Create user
This commit is contained in:
27
src/middlewares/ensureAdmin.ts
Normal file
27
src/middlewares/ensureAdmin.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { verify } from 'jsonwebtoken';
|
||||
import admin from '../config/admin';
|
||||
|
||||
import authConfig from '../config/auth';
|
||||
|
||||
import AppError from '../errors/AppError';
|
||||
|
||||
interface TokenPayload {
|
||||
iat: number;
|
||||
exp: number;
|
||||
sub: string;
|
||||
}
|
||||
|
||||
export default function ensureAdmin(
|
||||
request: Request,
|
||||
response: Response,
|
||||
next: NextFunction,
|
||||
): void {
|
||||
const adminToken = request.admin_token;
|
||||
|
||||
if (admin.key != adminToken) {
|
||||
throw new AppError('You don\'t have permission to perform this action.', 401);
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
49
src/middlewares/ensureAuthenticated.ts
Normal file
49
src/middlewares/ensureAuthenticated.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { verify } from 'jsonwebtoken';
|
||||
|
||||
import authConfig from '../config/auth';
|
||||
|
||||
import AppError from '../errors/AppError';
|
||||
|
||||
interface TokenPayload {
|
||||
iat: number;
|
||||
exp: number;
|
||||
sub: string;
|
||||
}
|
||||
|
||||
export default function ensureAuthenticated(
|
||||
request: Request,
|
||||
response: Response,
|
||||
next: NextFunction,
|
||||
): void {
|
||||
// validação do token JWT
|
||||
|
||||
// pegando o valor do header
|
||||
const authHeader = request.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
throw new AppError('JWT token is missing.', 401);
|
||||
}
|
||||
|
||||
// formato do valor do header: "Bearer insert_token_here"
|
||||
|
||||
const [, token] = authHeader.split(' ');
|
||||
|
||||
try {
|
||||
const decoded = verify(token, authConfig.jwt.secret);
|
||||
|
||||
const { sub } = decoded as TokenPayload;
|
||||
|
||||
// sub -> id_user
|
||||
// ou seja, o JWT informa o uuid do usuário sozinho
|
||||
// isso ajuda a economizar linhas
|
||||
// TODO, mas é a melhor prática de segurança?
|
||||
request.user = {
|
||||
id_user: sub,
|
||||
};
|
||||
|
||||
return next();
|
||||
} catch {
|
||||
throw new AppError('Invalid JWT token', 401);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user