Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.6 kB
1
Indexable
Never
// CAMINHO: SRC/CONTROLLERS/login.controller.ts

import { Request, Response } from 'express';
import * as jwt from 'jsonwebtoken';

import loginSrv from '../services/login.service';

const JWT_SECRET = process.env.JWT_SECRET || 'jwt_secret';

const loginController = async (req: Request, res: Response) => {
  const { email, password } = req.body;
  const { status, token, message } = await loginSrv.loginSrv(email, password);
  if (status !== 200) {
    return res.status(status).json({ message });
  }
  return res.status(status).json({ token });
};

const tokenVerify = (req: Request, res: Response) => {
  const { authorization } = req.headers;
  if (!authorization) {
    return res.status(401).json({ message: 'Token not found' });
  }

  const token = authorization.split(' ')[1];
  const checkTokenIsValid = jwt.verify(token, JWT_SECRET);

  if (!checkTokenIsValid) {
    return res.status(401).json({ message: 'Token must be a valid token' });
  }
};

const getRoleController = async (req: Request, res: Response) => {
  const { authorization } = req.headers;
  if (!authorization) {
    return res.status(401).json({ message: 'Token not found' });
  }

  tokenVerify(req, res);

  const token = authorization.split(' ')[1];

  const username = jwt.verify(token, process.env.JWT_SECRET as string) as { username: string };

  const role = await loginSrv.getRoleSrv(username.username);
  if (!role) {
    return res.status(401).json({ message: 'Token must be a valid token' });
  }
  return res.status(200).json({ role });
};

export default { loginController, getRoleController, tokenVerify };
Leave a Comment