77 lines
1.8 KiB
TypeScript
77 lines
1.8 KiB
TypeScript
import { Inject, Injectable } from '@nestjs/common';
|
|
import { Repository } from 'typeorm';
|
|
import { OAuth2Client } from '../oauth2-client/oauth2-client.entity';
|
|
import { User } from '../user/user.entity';
|
|
import { OAuth2Token, OAuth2TokenType } from './oauth2-token.entity';
|
|
|
|
@Injectable()
|
|
export class OAuth2TokenService {
|
|
constructor(
|
|
@Inject('TOKEN_REPOSITORY')
|
|
private tokenRepository: Repository<OAuth2Token>,
|
|
) {}
|
|
|
|
public async insertToken(
|
|
token: string,
|
|
type: OAuth2TokenType,
|
|
client: OAuth2Client,
|
|
scope: string,
|
|
expiry: Date,
|
|
user?: User,
|
|
): Promise<OAuth2Token> {
|
|
const newToken = new OAuth2Token();
|
|
newToken.client = client;
|
|
newToken.token = token;
|
|
newToken.type = type;
|
|
newToken.scope = scope;
|
|
newToken.user = user;
|
|
newToken.expires_at = expiry;
|
|
|
|
await this.tokenRepository.save(newToken);
|
|
|
|
return newToken;
|
|
}
|
|
|
|
public async fetchByToken(
|
|
token: string,
|
|
type: OAuth2TokenType,
|
|
): Promise<OAuth2Token> {
|
|
return this.tokenRepository.findOne({
|
|
where: {
|
|
token,
|
|
type,
|
|
},
|
|
relations: ['client', 'user'],
|
|
});
|
|
}
|
|
|
|
public async fetchByUserIdClientId(
|
|
userId: number,
|
|
clientId: string,
|
|
type: OAuth2TokenType,
|
|
): Promise<OAuth2Token> {
|
|
return this.tokenRepository.findOne({
|
|
where: {
|
|
user: {
|
|
id: userId,
|
|
},
|
|
client: {
|
|
client_id: clientId,
|
|
},
|
|
type,
|
|
},
|
|
relations: ['client', 'user'],
|
|
});
|
|
}
|
|
|
|
public async wipeClientTokens(client: OAuth2Client): Promise<void> {
|
|
await this.tokenRepository.delete({
|
|
client: { id: client.id },
|
|
});
|
|
}
|
|
|
|
public async remove(token: OAuth2Token): Promise<void> {
|
|
await this.tokenRepository.remove(token);
|
|
}
|
|
}
|