89 lines
2.0 KiB
TypeScript
89 lines
2.0 KiB
TypeScript
import createHttpError from "http-errors";
|
|
import { AuthMessages } from "../messages";
|
|
import jwt from "jsonwebtoken";
|
|
import dotenv from "dotenv";
|
|
import User from "../../../models/User";
|
|
import { JWT_SECRET } from "../../../core/constants";
|
|
import Role from "../../../models/Role";
|
|
import Permission from "../../../models/Permission";
|
|
dotenv.config();
|
|
|
|
class AuthServiceClass {
|
|
async login(username: string, password: string) {
|
|
try {
|
|
const user = await User.findOne({
|
|
where: {
|
|
nationalCode: username,
|
|
mobile: password,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
throw createHttpError.Unauthorized(
|
|
AuthMessages.error.login.incorrectData,
|
|
);
|
|
}
|
|
|
|
const token = jwt.sign(
|
|
{
|
|
id: user.id,
|
|
roleId: user.roleId,
|
|
},
|
|
JWT_SECRET,
|
|
{ expiresIn: "1d" },
|
|
);
|
|
|
|
return token;
|
|
} catch (error) {
|
|
console.log(error);
|
|
throw createHttpError.InternalServerError(
|
|
AuthMessages.error.login.loginFailed,
|
|
);
|
|
}
|
|
}
|
|
async Me(req:any) {
|
|
const userId = req.user?.id;
|
|
|
|
if (!userId) {
|
|
throw new createHttpError.Unauthorized("کاربر احراز هویت نشده است");
|
|
}
|
|
|
|
const user = await User.findByPk(userId, {
|
|
attributes: ["id", "fullname", "mobile", "roleId"],
|
|
include: [
|
|
{
|
|
model: Role,
|
|
as: "role",
|
|
attributes: ["id", "name"],
|
|
include: [
|
|
{
|
|
model: Permission,
|
|
as: "permissions",
|
|
attributes: ["name"],
|
|
through: { attributes: [] },
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
if (!user) {
|
|
throw new createHttpError.NotFound("کاربر پیدا نشد");
|
|
}
|
|
|
|
const permissions = user.role?.permissions?.map((p: any) => p.name) || [];
|
|
|
|
return {
|
|
id: user.id,
|
|
fullname: user.fullname,
|
|
mobile: user.mobile,
|
|
role: user.role?.name,
|
|
permissions,
|
|
};
|
|
}
|
|
}
|
|
|
|
const AuthService = new AuthServiceClass();
|
|
|
|
export default AuthService;
|