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

95 lines
2.3 KiB
TypeScript

import {
OAuth2RefreshTokenAdapter,
OAuth2RefreshToken,
} from '@icynet/oauth2-provider';
import { OAuth2TokenType } from 'src/modules/objects/oauth2-token/oauth2-token.entity';
import { OAuth2Service } from '../oauth2.service';
export class RefreshTokenAdapter implements OAuth2RefreshTokenAdapter {
constructor(private _service: OAuth2Service) {}
invalidateOld = false;
async create(
userId: number,
clientId: string,
scope: string | string[],
): 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() + 3.154e7 * 1000);
this._service.tokenService.insertToken(
accessToken,
OAuth2TokenType.REFRESH_TOKEN,
client,
scopes,
expiresAt,
user,
);
return accessToken;
}
async fetchByToken(
token: string | OAuth2RefreshToken,
): Promise<OAuth2RefreshToken> {
const findBy = typeof token === 'string' ? token : token.token;
const find = await this._service.tokenService.fetchByToken(
findBy,
OAuth2TokenType.REFRESH_TOKEN,
);
return {
...find,
client_id: find.client.client_id,
user_id: find.user.id,
};
}
async removeByUserIdClientId(
userId: number,
clientId: string,
): Promise<boolean> {
const find = await this._service.tokenService.fetchByUserIdClientId(
userId,
clientId,
OAuth2TokenType.REFRESH_TOKEN,
);
await this._service.tokenService.remove(find);
return true;
}
async removeByRefreshToken(token: string): Promise<boolean> {
const find = await this._service.tokenService.fetchByToken(
token,
OAuth2TokenType.REFRESH_TOKEN,
);
await this._service.tokenService.remove(find);
return true;
}
getUserId(code: OAuth2RefreshToken): number {
return code.user_id as number;
}
getClientId(code: OAuth2RefreshToken): string {
return code.client_id as string;
}
getScope(code: OAuth2RefreshToken): string {
return code.scope;
}
}