Skip to content

Commit

Permalink
feat: add required functions
Browse files Browse the repository at this point in the history
  • Loading branch information
DevNono committed Aug 20, 2023
1 parent 0efa496 commit ee070d4
Show file tree
Hide file tree
Showing 16 changed files with 97 additions and 52 deletions.
4 changes: 2 additions & 2 deletions src/controllers/admin/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { NextFunction, Request, Response } from 'express';
import { login } from '../../../utils/login';
import { loginAccount } from '../../../utils/login';

export default [
// Middlewares

// Controller
async (request: Request, response: Response, next: NextFunction) => {
await login(request, response, next, true);
await loginAccount(request, response, next, true);
},
];
21 changes: 21 additions & 0 deletions src/controllers/admin/partners/getPartners.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextFunction, Request, Response } from 'express';
import { fetchPartners } from '../../../operations/partner';
import { success } from '../../../utils/responses';
import { Permission } from '../../../types';
import { hasPermission } from '../../../middlewares/authentication';

export default [
// Middlewares
...hasPermission(Permission.anim),

// Controller
async (request: Request, response: Response, next: NextFunction) => {
try {
const result = await fetchPartners();

return success(response, result);
} catch (error) {
return next(error);
}
},
];
2 changes: 2 additions & 0 deletions src/controllers/admin/partners/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import { Router } from 'express';
import updatePartner from './updatePartner';
import addPartner from './addPartner';
import removePartner from './removePartner';
import getPartners from './getPartners';

const router = Router();

router.get('/', getPartners);
router.post('/', addPartner);
router.patch('/:partnerId', updatePartner);
router.delete('/:partnerId', removePartner);
Expand Down
14 changes: 9 additions & 5 deletions src/controllers/admin/settings/updateSetting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,26 @@ export default [
try {
let result;
switch (request.params.setting) {
case 'login':
case 'login': {
result = await setLoginAllowed(request.body.value === 'true');
break;
case 'shop':
}
case 'shop': {
result = await setShopAllowed(request.body.value === 'true');
break;
case 'trombi':
}
case 'trombi': {
result = await setDisplayTrombi(request.body.value === 'true');
break;
default:
}
default: {
return notFound(response, Error.NotFound);
}
}

return success(response, result);
} catch (error) {
return next(error);
}
},
];
];
21 changes: 21 additions & 0 deletions src/controllers/admin/tournaments/getTournaments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextFunction, Request, Response } from 'express';
import { success } from '../../../utils/responses';
import { fetchTournaments } from '../../../operations/tournament';
import { hasPermission } from '../../../middlewares/authentication';
import { Permission } from '../../../types';

export default [
// Middlewares
...hasPermission(Permission.anim),

// Controller
async (request: Request, response: Response, next: NextFunction) => {
try {
const result = await fetchTournaments();

return success(response, result);
} catch (error) {
return next(error);
}
},
];
2 changes: 2 additions & 0 deletions src/controllers/admin/tournaments/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Router } from 'express';
import updateTournament from './updateTournament';
import getTournaments from './getTournaments';

const router = Router();

router.get('/', getTournaments);
router.patch('/:tournamentId', updateTournament);

export default router;
5 changes: 3 additions & 2 deletions src/controllers/admin/upload/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Router } from 'express';
import multer = require('multer');
import uploadFile from './uploadFile';

const router = Router();
const multer = require('multer');

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const upload = multer({ storage });

router.post('/', upload.single('file'), uploadFile);

Expand Down
14 changes: 6 additions & 8 deletions src/controllers/admin/upload/uploadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,25 @@ import { success } from '../../../utils/responses';
import { Permission } from '../../../types';
import { uploadFile } from '../../../operations/upload';

const multer = require('multer');

// Allow to upload a file to an external API
export default [
// Middlewares
...hasPermission(Permission.anim),
validateBody(
Joi.object({
name: Joi.string().required(),
path: Joi.string().required(),
name: Joi.string().required(),
path: Joi.string().required(),
}),
),

// Controller
async (request: Request, response: Response, next: NextFunction) => {
try {
const result = await uploadFile(request.file, request.body.path, request.body.name);
const result = await uploadFile(request.file, request.body.path, request.body.name);

return success(response, result);
return success(response, result);
} catch (error) {
return next(error);
return next(error);
}
},
];
];
4 changes: 2 additions & 2 deletions src/controllers/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { isNotAuthenticated } from '../../middlewares/authentication';
import { validateBody } from '../../middlewares/validation';
import { Error as ResponseError } from '../../types';
import * as validators from '../../utils/validators';
import { login } from '../../utils/login';
import { loginAccount } from '../../utils/login';

export default [
// Middlewares
Expand All @@ -18,6 +18,6 @@ export default [

// Controller
async (request: Request, response: Response, next: NextFunction) => {
await login(request, response, next);
await loginAccount(request, response, next);
},
];
2 changes: 1 addition & 1 deletion src/middlewares/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default [
) {
return next();
}

return unsupportedMediaType(response, Error.UnsupportedMediaType);
},

Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { getRequestInfo } from '../utils/users';
export const isLoginAllowed = async (request: Request, response: Response, next: NextFunction) => {
const login = (await fetchSetting('login')).value;
const { user } = getRequestInfo(response);
if (login || (user.permissions && user.permissions.length !== 0)) {

if (login || (user.permissions && user.permissions.length > 0)) {
return next();
}
return forbidden(response, Error.LoginNotAllowed);
Expand Down
6 changes: 1 addition & 5 deletions src/operations/partner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ import database from '../services/database';

export const fetchPartners = (): PrismaPromise<Partner[]> => database.partner.findMany();

export const addPartner = (partner: {
name: string;
link: string;
display?: boolean;
}): PrismaPromise<Partner> =>
export const addPartner = (partner: { name: string; link: string; display?: boolean }): PrismaPromise<Partner> =>
database.partner.create({
data: {
id: nanoid(),
Expand Down
2 changes: 1 addition & 1 deletion src/operations/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ const setSettingAllowed = (id: string, allowed: boolean): PrismaPromise<Setting>

export const setLoginAllowed = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('login', allowed);
export const setShopAllowed = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('shop', allowed);
export const setDisplayTrombi = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('trombi', allowed);
export const setDisplayTrombi = (allowed: boolean): PrismaPromise<Setting> => setSettingAllowed('trombi', allowed);
32 changes: 16 additions & 16 deletions src/operations/upload.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import axios from "axios";
import env from "../utils/env";
import axios from 'axios';
import env from '../utils/env';

// Operations for file upload
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const uploadFile = async (file: any, path: string, name: string) => {
const fileBlob = new Blob([file.buffer], { type: file.mimetype });

const fileBlob = new Blob([file.buffer], { type: file.mimetype });
const formData = new FormData();
formData.append('file', fileBlob, file.originalname);
formData.append('path', path);
formData.append('name', name);

const formData = new FormData();
formData.append('file', fileBlob, file.originalname);
formData.append('path', path);
formData.append('name', name);
const result = await axios.post(`${env.front.website}/uploads/files/api`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${env.upload.token}`,
},
});

const result = await axios.post(`${env.front.website}/uploads/files/api`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
'Authorization': `Bearer ${env.upload.token}`
},
});

return result.data;
return result.data;
};
12 changes: 6 additions & 6 deletions src/utils/login.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { NextFunction, Request, Response } from 'express';
import bcrpyt from 'bcryptjs';
import { filterUser } from './filters';
import { forbidden, success, unauthenticated } from './responses';
import { generateToken } from './users';
import { fetchUser } from '../operations/user';
import { Error as ResponseError, UserType } from '../types';
import bcrpyt from 'bcryptjs';
import * as validators from './validators';

export async function login(request: Request, response: Response, next: NextFunction, admin = false) {
try {
export async function loginAccount(request: Request, response: Response, next: NextFunction, admin = false) {
try {
const { login, password } = request.body;

// Fetch the user depending on the email or the username
Expand Down Expand Up @@ -43,10 +43,10 @@ export async function login(request: Request, response: Response, next: NextFunc
if (!isPasswordValid) {
return unauthenticated(response, ResponseError.InvalidCredentials);
}

// If admin check that the user has any permissions
if (admin && (!user.permissions || user.permissions.length === 0)) {
return forbidden(response, ResponseError.LoginNotAllowed);
return forbidden(response, ResponseError.LoginNotAllowed);
}

const token = generateToken(user);
Expand All @@ -58,4 +58,4 @@ export async function login(request: Request, response: Response, next: NextFunc
} catch (error) {
return next(error);
}
};
}
4 changes: 2 additions & 2 deletions tests/discord.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { decode } from 'querystring';
import axios from 'axios';
// import axios from 'axios';
import nock from 'nock';
import type {
DiscordAuthorizationData,
Expand Down Expand Up @@ -150,7 +150,7 @@ const computeRateLimitHeader = (enforceRateLimit = false): nock.ReplyHeaders =>
const listen = () => {
// eslint-disable-next-line global-require
// TODO: fix this for nexts versions of axios
//axios.defaults.adapter = require('axios/lib/adapters/http');
// axios.defaults.adapter = require('axios/lib/adapters/http');
nock('https://discord.com/api/v9')
.persist()

Expand Down

0 comments on commit ee070d4

Please sign in to comment.