2023-10-13 13:35:49 +00:00
|
|
|
import { CookieOptions } from 'express';
|
|
|
|
import { ExpressRequest, ExpressResponse } from './Express';
|
|
|
|
import ObjectID from 'Common/Types/ObjectID';
|
|
|
|
import Dictionary from 'Common/Types/Dictionary';
|
2023-10-13 12:25:38 +00:00
|
|
|
|
2023-10-13 13:35:49 +00:00
|
|
|
export default class CookieUtil {
|
2023-10-13 12:25:38 +00:00
|
|
|
// set cookie with express response
|
|
|
|
|
2023-10-13 13:35:49 +00:00
|
|
|
public static setCookie(
|
|
|
|
res: ExpressResponse,
|
|
|
|
name: string,
|
|
|
|
value: string,
|
|
|
|
options: CookieOptions
|
|
|
|
): void {
|
2023-10-13 12:25:38 +00:00
|
|
|
res.cookie(name, value, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
// get cookie with express request
|
|
|
|
|
2023-10-13 13:35:49 +00:00
|
|
|
public static getCookie(
|
|
|
|
req: ExpressRequest,
|
|
|
|
name: string
|
|
|
|
): string | undefined {
|
2023-10-13 12:25:38 +00:00
|
|
|
return req.cookies[name];
|
|
|
|
}
|
|
|
|
|
|
|
|
// delete cookie with express response
|
|
|
|
|
2023-10-13 13:35:49 +00:00
|
|
|
public static removeCookie(res: ExpressResponse, name: string): void {
|
2023-10-13 12:25:38 +00:00
|
|
|
res.clearCookie(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
// get all cookies with express request
|
2023-10-13 13:35:49 +00:00
|
|
|
public static getAllCookies(req: ExpressRequest): Dictionary<string> {
|
2023-10-13 18:45:24 +00:00
|
|
|
return req.cookies || {};
|
2023-10-13 12:25:38 +00:00
|
|
|
}
|
|
|
|
|
2023-10-13 13:35:49 +00:00
|
|
|
public static getUserTokenKey(id?: ObjectID): string {
|
|
|
|
if (!id) {
|
|
|
|
return `user-token`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return `user-token-${id.toString()}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static getUserSSOKey(id: ObjectID): string {
|
|
|
|
return `${this.getSSOKey()}${id.toString()}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static getSSOKey(): string {
|
|
|
|
return `sso-`;
|
|
|
|
}
|
2023-10-13 18:12:28 +00:00
|
|
|
|
|
|
|
// delete all cookies.
|
|
|
|
public static removeAllCookies(
|
|
|
|
req: ExpressRequest,
|
|
|
|
res: ExpressResponse
|
|
|
|
): void {
|
|
|
|
const cookies: Dictionary<string> = this.getAllCookies(req);
|
|
|
|
for (const key in cookies) {
|
|
|
|
this.removeCookie(res, key);
|
|
|
|
}
|
|
|
|
}
|
2023-10-13 13:35:49 +00:00
|
|
|
}
|