first commit
This commit is contained in:
84
src/modules/auth/service/auth.service.ts
Normal file
84
src/modules/auth/service/auth.service.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user