103 lines
2.7 KiB
TypeScript
103 lines
2.7 KiB
TypeScript
import {
|
|
OAuth2AccessTokenAdapter,
|
|
OAuth2AccessToken,
|
|
} from '@icynet/oauth2-provider';
|
|
import { OAuth2TokenType } from 'src/modules/objects/oauth2-token/oauth2-token.entity';
|
|
import { Injectable } from '@nestjs/common';
|
|
import { OAuth2ClientService } from 'src/modules/objects/oauth2-client/oauth2-client.service';
|
|
import { UserService } from 'src/modules/objects/user/user.service';
|
|
import { TokenService } from 'src/modules/utility/services/token.service';
|
|
import { FormUtilityService } from 'src/modules/utility/services/form-utility.service';
|
|
import { OAuth2TokenService } from 'src/modules/objects/oauth2-token/oauth2-token.service';
|
|
|
|
@Injectable()
|
|
export class AccessTokenAdapter implements OAuth2AccessTokenAdapter {
|
|
constructor(
|
|
private readonly clientService: OAuth2ClientService,
|
|
private readonly userService: UserService,
|
|
private readonly token: TokenService,
|
|
private readonly form: FormUtilityService,
|
|
private readonly tokenService: OAuth2TokenService,
|
|
) {}
|
|
|
|
public ttl = 604800;
|
|
|
|
getToken(token: OAuth2AccessToken): string {
|
|
return token.token;
|
|
}
|
|
|
|
async create(
|
|
userId: number,
|
|
clientId: string,
|
|
scope: string | string[],
|
|
ttl: number,
|
|
): Promise<string> {
|
|
const client = await this.clientService.getById(clientId);
|
|
const user = await this.userService.getById(userId);
|
|
const accessToken = this.token.generateString(64);
|
|
|
|
// Standardize scope value
|
|
const scopes = (
|
|
!Array.isArray(scope) ? this.form.splitScope(scope) : scope
|
|
).join(' ');
|
|
|
|
const expiresAt = new Date(Date.now() + ttl * 1000);
|
|
|
|
this.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.tokenService.fetchByToken(
|
|
findBy,
|
|
OAuth2TokenType.ACCESS_TOKEN,
|
|
);
|
|
|
|
if (!find) {
|
|
return null;
|
|
}
|
|
|
|
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.tokenService.fetchByUserIdClientId(
|
|
userId,
|
|
clientId,
|
|
OAuth2TokenType.ACCESS_TOKEN,
|
|
);
|
|
|
|
return {
|
|
...find,
|
|
client_id: find.client.client_id,
|
|
user_id: find.user.id,
|
|
};
|
|
}
|
|
}
|