87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import {
|
|
OAuth2AccessTokenAdapter,
|
|
OAuth2AccessToken,
|
|
} from '@icynet/oauth2-provider';
|
|
import { OAuth2TokenType } from 'src/modules/objects/oauth2-token/oauth2-token.entity';
|
|
import { OAuth2Service } from '../oauth2.service';
|
|
|
|
export class AccessTokenAdapter implements OAuth2AccessTokenAdapter {
|
|
constructor(private _service: OAuth2Service) {}
|
|
|
|
public ttl = 3600;
|
|
|
|
getToken(token: OAuth2AccessToken): string {
|
|
return token.token;
|
|
}
|
|
|
|
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.ACCESS_TOKEN,
|
|
client,
|
|
scopes,
|
|
expiresAt,
|
|
user,
|
|
);
|
|
|
|
return accessToken;
|
|
}
|
|
|
|
async fetchByToken(
|
|
token: string | OAuth2AccessToken,
|
|
): Promise<OAuth2AccessToken> {
|
|
const findBy = typeof token === 'string' ? token : token.token;
|
|
const find = await this._service.tokenService.fetchByToken(
|
|
findBy,
|
|
OAuth2TokenType.ACCESS_TOKEN,
|
|
);
|
|
|
|
return {
|
|
...find,
|
|
client_id: find.client.client_id,
|
|
user_id: find.user.id,
|
|
};
|
|
}
|
|
|
|
checkTTL(token: OAuth2AccessToken): boolean {
|
|
return new Date() < token.expires_at;
|
|
}
|
|
|
|
getTTL(token: OAuth2AccessToken): number {
|
|
return token.expires_at.getTime() - Date.now();
|
|
}
|
|
|
|
async fetchByUserIdClientId(
|
|
userId: number,
|
|
clientId: string,
|
|
): Promise<OAuth2AccessToken> {
|
|
const find = await this._service.tokenService.fetchByUserIdClientId(
|
|
userId,
|
|
clientId,
|
|
OAuth2TokenType.ACCESS_TOKEN,
|
|
);
|
|
|
|
return {
|
|
...find,
|
|
client_id: find.client.client_id,
|
|
user_id: find.user.id,
|
|
};
|
|
}
|
|
}
|