icynet-auth-server/src/modules/features/oauth2/adapter/code.adapter.ts

80 lines
2.0 KiB
TypeScript

import { OAuth2CodeAdapter, OAuth2Code } from '@icynet/oauth2-provider';
import { OAuth2TokenType } from 'src/modules/objects/oauth2-token/oauth2-token.entity';
import { OAuth2Service } from '../oauth2.service';
export class CodeAdapter implements OAuth2CodeAdapter {
constructor(private _service: OAuth2Service) {}
ttl = 3600;
async create(
userId: number,
clientId: string,
scope: string | string[],
ttl: number,
): Promise<string> {
const client = await this._service.clientService.getById(clientId);
const user = await this._service.userService.getById(userId);
const accessToken = this._service.token.generateString(64);
// Standardize scope value
const scopes = (
!Array.isArray(scope) ? this._service.splitScope(scope) : scope
).join(' ');
const expiresAt = new Date(Date.now() + ttl * 1000);
this._service.tokenService.insertToken(
accessToken,
OAuth2TokenType.CODE,
client,
scopes,
expiresAt,
user,
);
return accessToken;
}
async fetchByCode(code: string | OAuth2Code): Promise<OAuth2Code> {
const findBy = typeof code === 'string' ? code : code.code;
const find = await this._service.tokenService.fetchByToken(
findBy,
OAuth2TokenType.CODE,
);
return {
...find,
code: find.token,
client_id: find.client.client_id,
user_id: find.user.id,
};
}
async removeByCode(code: string | OAuth2Code): Promise<boolean> {
const findBy = typeof code === 'string' ? code : code.code;
const find = await this._service.tokenService.fetchByToken(
findBy,
OAuth2TokenType.CODE,
);
this._service.tokenService.remove(find);
return true;
}
getUserId(code: OAuth2Code): string {
return code.user_id as string;
}
getClientId(code: OAuth2Code): string {
return code.client_id as string;
}
getScope(code: OAuth2Code): string {
return code.scope;
}
checkTTL(code: OAuth2Code): boolean {
return code.expires_at.getTime() > Date.now();
}
}