Implementar modulo de Auth
This commit is contained in:
51
backend/src/modules/auth/auth.service.ts
Normal file
51
backend/src/modules/auth/auth.service.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import bcrypt from "bcrypt";
|
||||
import jwt from "jsonwebtoken";
|
||||
import userModel from "../user/user.model";
|
||||
|
||||
export class AuthService {
|
||||
|
||||
async login (
|
||||
userName:string,
|
||||
password:string
|
||||
){
|
||||
const user =
|
||||
await userModel.findOne({
|
||||
userName
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error("Usuario no encontrado");
|
||||
}
|
||||
|
||||
const validPassword =
|
||||
await bcrypt.compare(
|
||||
password,
|
||||
user.passwordHash
|
||||
);
|
||||
|
||||
if (!validPassword){
|
||||
throw new Error("Contraseña incorrecta");
|
||||
}
|
||||
|
||||
user.lastLogin = new Date();
|
||||
await user.save();
|
||||
|
||||
const token = jwt.sign(
|
||||
{
|
||||
|
||||
id:user._id,
|
||||
roleId: user.roleId
|
||||
},
|
||||
|
||||
process.env.JWT_SECRET as string,
|
||||
{
|
||||
expiresIn:"8h"
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
token,
|
||||
user
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user