85 lines
2.2 KiB
TypeScript
85 lines
2.2 KiB
TypeScript
import { IsBoolean, IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
|
|
import * as jsonwebtoken from "jsonwebtoken";
|
|
import { config } from './config';
|
|
import { User } from './models/entities/User';
|
|
|
|
export class JwtCreator {
|
|
public static createRefresh(user: User, expiry_timestamp?: number) {
|
|
if (!expiry_timestamp) { expiry_timestamp = Math.floor(Date.now() / 1000) + 10 * 36000; }
|
|
return jsonwebtoken.sign({
|
|
refreshtokencount: user.refreshTokenCount,
|
|
userid: user.id,
|
|
exp: expiry_timestamp
|
|
}, config.jwt_secret)
|
|
}
|
|
|
|
public static createAccess(user: User, expiry_timestamp?: number) {
|
|
if (!expiry_timestamp) { expiry_timestamp = Math.floor(Date.now() / 1000) + 10 * 36000; }
|
|
return jsonwebtoken.sign({
|
|
userdetails: new JwtUser(user),
|
|
exp: expiry_timestamp
|
|
}, config.jwt_secret)
|
|
}
|
|
}
|
|
|
|
class JwtUser {
|
|
@IsInt()
|
|
id: number;
|
|
|
|
@IsUUID(4)
|
|
uuid: string;
|
|
|
|
@IsOptional()
|
|
@IsEmail()
|
|
email?: string;
|
|
|
|
@IsOptional()
|
|
@IsString()
|
|
username?: string;
|
|
|
|
@IsString()
|
|
@IsNotEmpty()
|
|
firstname: string;
|
|
|
|
@IsString()
|
|
@IsOptional()
|
|
middlename?: string;
|
|
|
|
@IsString()
|
|
@IsNotEmpty()
|
|
lastname: string;
|
|
|
|
permissions: string[];
|
|
|
|
@IsBoolean()
|
|
enabled: boolean;
|
|
|
|
@IsInt()
|
|
@IsNotEmpty()
|
|
refreshTokenCount?: number;
|
|
|
|
@IsString()
|
|
@IsOptional()
|
|
profilePic?: string;
|
|
|
|
public constructor(user: User) {
|
|
this.id = user.id;
|
|
this.firstname = user.firstname;
|
|
this.middlename = user.middlename;
|
|
this.lastname = user.lastname;
|
|
this.username = user.username;
|
|
this.email = user.email;
|
|
this.refreshTokenCount = user.refreshTokenCount;
|
|
this.uuid = user.uuid;
|
|
this.profilePic = user.profilePic;
|
|
this.permissions = this.getPermissions(user);
|
|
}
|
|
|
|
public getPermissions(user: User): string[] {
|
|
let returnPermissions: string[] = new Array<string>();
|
|
for (let permission of user.permissions) {
|
|
returnPermissions.push(permission.toString());
|
|
}
|
|
return returnPermissions;
|
|
}
|
|
} |