Files
app/ts/reception/classes.jwt.ts
T

101 lines
2.7 KiB
TypeScript

import * as plugins from '../plugins.js';
import { JwtManager } from './classes.jwtmanager.js';
import type { LoginSession } from './classes.loginsession.js';
/**
* a User is identified by its username or email.
* Both need to be unique and both can be changed.
*/
@plugins.smartdata.Manager()
export class Jwt extends plugins.smartdata.SmartDataDbDoc<Jwt, plugins.idpInterfaces.data.IJwt, JwtManager> {
// STATIC
public static async createJwtForRefreshToken(
jwtManagerInstance: JwtManager,
refreshTokenArg: string
): Promise<string | null> {
const sessionLookup =
await jwtManagerInstance.receptionRef.loginSessionManager.findLoginSessionByRefreshToken(
refreshTokenArg
);
if (!sessionLookup || sessionLookup.validationStatus !== 'current') {
return null;
}
return this.createJwtForLoginSession(jwtManagerInstance, sessionLookup.loginSession);
}
public static async createJwtForLoginSession(
jwtManagerInstance: JwtManager,
loginSession: LoginSession
): Promise<string | null> {
const user = await jwtManagerInstance.receptionRef.userManager.CUser.getInstance({
id: loginSession.data.userId,
});
if (!user) {
return null;
}
const validUntil = plugins.smarttime.ExtendedDate.fromMillis(
Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 1 })
);
const jwt = new Jwt();
jwt.id = plugins.smartunique.shortId();
jwt.data = {
userId: user.id,
sessionId: loginSession.id,
validUntil: validUntil.getTime(),
refreshEvery: 1000000,
refreshFrom: Date.now() + plugins.smarttime.getMilliSecondsFromUnits({ days: 0.5 }),
justForLooks: {
validUntilIsoString: validUntil.toISOString(),
}
};
await jwt.save();
const jwtString = await jwtManagerInstance.smartjwtInstance.createJWT({
id: jwt.id,
blocked: false,
data: jwt.data,
} as plugins.idpInterfaces.data.IJwt);
return jwtString;
}
// INSTANCE
@plugins.smartdata.unI()
public id: string;
@plugins.smartdata.svDb()
public blocked: boolean = false;
@plugins.smartdata.svDb()
public data: plugins.idpInterfaces.data.IJwt['data'];
public async block() {
this.blocked = true;
await this.save();
}
public async getLoginSession() {
if (this.data.sessionId) {
return this.manager.receptionRef.loginSessionManager.CLoginSession.getInstance({
id: this.data.sessionId,
});
}
if (!this.data.refreshToken) {
return null;
}
const sessionLookup =
await this.manager.receptionRef.loginSessionManager.findLoginSessionByRefreshToken(
this.data.refreshToken
);
if (!sessionLookup) {
return null;
}
return sessionLookup.loginSession;
}
}