2021-11-29 18:15:21 +01:00
|
|
|
import { ADMIN_SOCKETS_TOKEN, SECRET_KEY } from "../Enum/EnvironmentVariable";
|
|
|
|
import Jwt from "jsonwebtoken";
|
2021-12-01 10:12:07 +01:00
|
|
|
import { InvalidTokenError } from "../Controller/InvalidTokenError";
|
2020-11-13 18:00:22 +01:00
|
|
|
|
2021-07-27 16:37:01 +02:00
|
|
|
export interface AuthTokenData {
|
|
|
|
identifier: string; //will be a email if logged in or an uuid if anonymous
|
2021-11-15 12:30:25 +01:00
|
|
|
accessToken?: string;
|
2021-07-27 16:37:01 +02:00
|
|
|
}
|
2021-10-28 14:53:07 +02:00
|
|
|
export interface AdminSocketTokenData {
|
|
|
|
authorizedRoomIds: string[]; //the list of rooms the client is authorized to read from.
|
|
|
|
}
|
2021-07-27 16:37:01 +02:00
|
|
|
export const tokenInvalidException = "tokenInvalid";
|
|
|
|
|
2020-11-13 18:00:22 +01:00
|
|
|
class JWTTokenManager {
|
2021-10-28 14:53:07 +02:00
|
|
|
public verifyAdminSocketToken(token: string): AdminSocketTokenData {
|
|
|
|
return Jwt.verify(token, ADMIN_SOCKETS_TOKEN) as AdminSocketTokenData;
|
|
|
|
}
|
|
|
|
|
2021-11-15 12:30:25 +01:00
|
|
|
public createAuthToken(identifier: string, accessToken?: string) {
|
|
|
|
return Jwt.sign({ identifier, accessToken }, SECRET_KEY, { expiresIn: "30d" });
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
|
|
|
|
2021-08-15 22:51:06 +02:00
|
|
|
public verifyJWTToken(token: string, ignoreExpiration: boolean = false): AuthTokenData {
|
2021-07-27 16:37:01 +02:00
|
|
|
try {
|
2021-08-15 22:51:06 +02:00
|
|
|
return Jwt.verify(token, SECRET_KEY, { ignoreExpiration }) as AuthTokenData;
|
2021-07-27 16:37:01 +02:00
|
|
|
} catch (e) {
|
2021-12-01 10:12:07 +01:00
|
|
|
if (e instanceof Error) {
|
|
|
|
// FIXME: we are loosing the stacktrace here.
|
|
|
|
throw new InvalidTokenError(e.message);
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const jwtTokenManager = new JWTTokenManager();
|