Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.4 kB
1
Indexable
Never
// LOGIN SIVICO

import { compare } from 'bcryptjs';
import { sign } from 'jsonwebtoken';
import Users from '../database/models/Users.model';

const notFilledErrMsg = 'All fields must be filled';
const invalidCredErrMsg = 'Invalid email or password';

const genToken = (username: string) => {
  const token = sign({ username }, process.env.JWT_SECRET as string, {
    expiresIn: '4h',
  });
  return token;
};

const validateEmail = (email: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

const loginSrv = async (email: string, password: string) => {
  if (!email || !password) {
    return { status: 400, message: notFilledErrMsg };
  }

  if (!validateEmail(email)) {
    return { status: 401, message: invalidCredErrMsg };
  }

  const user = await Users.findOne({ where: { email } });
  if (!user) {
    return { status: 401, message: invalidCredErrMsg };
  }

  const passwordMatch = await compare(password, user.password);
  if (!passwordMatch || password.length < 6) {
    return { status: 401, message: invalidCredErrMsg };
  }

  const token = genToken(user.username);

  return { status: 200, token };
};

const getRoleSrv = async (username: string) => {
  const user = await Users.findOne({ where: { username } });
  if (!user) {
    return null;
  }
  return user.role;
};

export default { loginSrv, genToken, getRoleSrv };
Leave a Comment