Files
hounam-submit-form-backend/src/modules/auth/service/auth.service.ts
2026-05-26 16:00:09 +03:30

85 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import createHttpError from "http-errors";
import { Controller } from "../../../core/controller/main.controller";
import { User } from "../../../models/User";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { Role } from "../../../models/Role";
import { Applicant } from "../../../models/Applicant";
import { Identity } from "../../../models/Identity";
import { authErrorMessages } from "../messages/auth.messages";
class AuthServiceClass extends Controller {
async usersLogin(email: string, password: string) {
try {
// ۱. پیدا کردن کاربر به همراه نقش
const user = await User.findOne({
where: { email },
include: [
{
model: Role,
as: "role",
},
],
});
if (!user)
throw new createHttpError.Unauthorized("ایمیل یا رمز عبور اشتباه است.");
// ۲. چک کردن پسورد
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch)
throw new createHttpError.Unauthorized("ایمیل یا رمز عبور اشتباه است.");
// ۳. صدور توکن
const token = jwt.sign(
{ userId: user.id },
process.env.JWT_SECRET || "secret",
{ expiresIn: "24h" }, // طول عمر توکن
);
return {
token,
user: { id: user.id, fullname: user.fullname, role: user },
};
} catch (err) {
throw new createHttpError.InternalServerError("خطای سرور");
}
}
async applicantLogin(nationalCode: string) {
try {
const identity = await Identity.findOne({
where: { nationalCode },
include: [
{
model: Applicant,
as: "applicant",
},
],
});
if (!identity?.applicantId) {
throw new createHttpError.NotFound(
authErrorMessages.notFound.applicant,
);
}
const token = jwt.sign(
{ userId: identity.applicantId },
process.env.JWT_SECRET || "secret",
{ expiresIn: "24h" }, // طول عمر توکن
);
return {
token,
applicant: { id: identity.applicantId, fullname: `${identity.firstName} ${identity.lastName}`, role: identity },
};
} catch (error) {
throw new createHttpError.InternalServerError("خطای سرور");
}
}
}
const AuthService = new AuthServiceClass();
export default AuthService;