2023-08-17 11:28:30 +02:00

97 lines
2.8 KiB
TypeScript

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 ContactService from "../ContactService";
import { ECustomerStatus } from "@prisma/client";
enum PROVIDER_OPENID {
idNot = "idNot",
}
interface ICustomerJwtPayload {
customerId: string;
email: string;
}
interface IUserJwtPayload {
userId: string;
openId: {
providerName: PROVIDER_OPENID;
userId: string | number;
};
office_Id: string;
role: string;
rules: string[];
}
@Service()
export default class AuthService extends BaseService {
constructor(protected variables: BackendVariables, private userService: UsersService, private customerService: CustomersService, private contactService: ContactService) {
super();
}
public async getCustomerJwtPayload(email:string): Promise<ICustomerJwtPayload | null> {
const contact = await this.contactService.getByEmail(email);
if (!contact) return null;
const customer = await this.customerService.getByUid(contact.customers!.uid, { contact: true });
if (!customer) return null;
if(customer.status === ECustomerStatus["PENDING"]) {
customer.status = ECustomerStatus["VALIDATED"];
this.customerService.update(customer.uid, customer);
}
return {
customerId: customer.uid,
email: contact.email,
};
}
public async getUserJwtPayload(id: string, providerName: PROVIDER_OPENID = PROVIDER_OPENID.idNot): Promise<IUserJwtPayload | null> {
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: "1h" });
}
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);
}
}