2023-06-21 15:51:09 +02:00

70 lines
1.9 KiB
TypeScript

import jwt, { VerifyCallback } from "jsonwebtoken";
import BaseService from "@Services/BaseService";
import "reflect-metadata";
import { BackendVariables } from "@Common/config/variables/Variables";
import { Service } from "typedi";
type IdNotTokens = {
access_token: string;
id_token: string;
};
@Service()
export default class AuthService extends BaseService {
constructor(protected variables: BackendVariables) {
super();
}
/**
* @description : Get IdNot id_token and access_token
* @throws {Error} If jwt pair cannot be get
*/
public async getUserFromIdNotTokens(code: string) {
const tokens = await this.getIdNotTokens(code);
return jwt.decode(tokens.id_token);
}
private async getIdNotTokens(code: string): Promise<IdNotTokens> {
const url = new URL(
this.variables.IDNOT_CONNEXION_URL.concat("?") +
new URLSearchParams({
client_id: this.variables.IDNOT_CLIENT_ID,
client_secret: this.variables.IDNOT_CLIENT_SECRET,
redirect_uri: this.variables.IDNOT_REDIRECT_URL,
code: code,
grant_type: "authorization_code",
}),
);
try {
const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded",
});
const res = await fetch(url, {
method: "POST",
headers: headers,
});
const data = await res.json();
return data as IdNotTokens;
} catch (error) {
throw new Error();
}
}
public generateAccessToken(user: any) {
return jwt.sign({...user}, this.variables.ACCESS_TOKEN_SECRET, { expiresIn: "15m" });
}
public generateRefreshToken(user: any) {
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);
}
}