import jwt, { VerifyCallback } from "jsonwebtoken"; import BaseService from "@Services/BaseService"; import { BackendVariables } from "@Common/config/variables/Variables"; import { Service } from "typedi"; import UsersService from "@Services/super-admin/UsersService/UsersService"; import CustomersService from "@Services/super-admin/CustomersService/CustomersService"; import { ECustomerStatus } from "@prisma/client"; import { Customer } from "le-coffre-resources/dist/Notary"; import bcrypt from "bcrypt"; enum PROVIDER_OPENID { idNot = "idNot", } export interface ICustomerJwtPayload { customerId: string; email: string; iat?: number; exp?: number; } export interface IdNotJwtPayload { sub: string; profile_idn: string; entity_idn: string; } export interface IUserJwtPayload { userId: string; openId: { providerName: PROVIDER_OPENID; userId: string | number; }; office_Id: string; role: string; rules: string[]; iat?: number; exp?: number; } @Service() export default class AuthService extends BaseService { constructor(protected variables: BackendVariables, private userService: UsersService, private customerService: CustomersService) { super(); } public async getCustomerJwtPayload(customers: Customer[]): Promise { for (const customer of customers) { if (customer.status === ECustomerStatus["PENDING"]) { customer.status = ECustomerStatus["VALIDATED"]; await this.customerService.update(customer.uid!, customer); } } return { customerId: customers[0]!.uid!, email: customers[0]!.contact!.email, }; } public async getUserJwtPayload(id: string, providerName: PROVIDER_OPENID = PROVIDER_OPENID.idNot): Promise { const user = await this.userService.getByProvider(providerName, id); if (!user) return null; const rules: string[] = []; user.role.rules.forEach((rule) => { rules.push(rule.name); }); if (user.office_role) { user.office_role.rules.forEach((rule) => { if (!rules.includes(rule.name)) { rules.push(rule.name); } }); } return { userId: user.uid, openId: { providerName: providerName, userId: user.idNot }, office_Id: user.office_membership.uid, role: user.role.name, rules: rules, }; } public generateAccessToken(user: any): string { return jwt.sign({ ...user }, this.variables.ACCESS_TOKEN_SECRET, { expiresIn: "15m" }); } public generateRefreshToken(user: any): string { return jwt.sign({ ...user }, this.variables.REFRESH_TOKEN_SECRET, { expiresIn: "1h" }); } public verifyAccessToken(token: string, callback?: VerifyCallback) { return jwt.verify(token, this.variables.ACCESS_TOKEN_SECRET, callback); } public verifyRefreshToken(token: string, callback?: VerifyCallback) { return jwt.verify(token, this.variables.REFRESH_TOKEN_SECRET, callback); } public comparePassword(password: string, hash: string): Promise { return bcrypt.compare(password, hash); } public hashPassword(password: string): Promise { return bcrypt.hash(password, 10); } }