Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.7 kB
2
Indexable
Never
// CONTROLLER MEU OVO

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 invalidTokenMsg = 'Token must be a valid token';

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];

  try {
    jwt.verify(token, JWT_SECRET);
  } catch (err) {
    return res.status(401).json({ message: invalidTokenMsg });
  }
};

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];

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

    const role = await loginSrv.getRoleSrv(username.username);
    if (!role) {
      return res.status(401).json({ message: invalidTokenMsg });
    }

    return res.status(200).json({ role });
  } catch (err) {
    return res.status(401).json({ message: invalidTokenMsg });
  }
};

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