import { ResourceNotFoundException } from '@nestjs.pro/common/dist/exceptions/ResourceNotFoundException'; import { Random } from '@nestjs.pro/common/dist/utilities/Random'; import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Organization } from '@tco.ai/models/dist/RBAC/Organization'; import { Token } from '@tco.ai/models/dist/RBAC/Token'; import { TokenCreate } from '@tco.ai/models/dist/RBAC/TokenCreate'; import { TokenRepository } from '@tco.ai/models/dist/RBAC/TokenRepository'; import { User } from '@tco.ai/models/dist/RBAC/User'; @Injectable() export class TokensService { public constructor(@InjectRepository(TokenRepository) private readonly tokenRepository: TokenRepository) { } public getByToken(token: string): Promise { return new Promise(async (resolve, reject) => { const entity = await this.tokenRepository.findOne({ where: { token }, relations: [ 'user' ] }); if (entity) { resolve(entity); } else { reject(new ResourceNotFoundException('could not locate token')); } }); } /** * Create a new api token. * * @param {User} principal * @param tokenCreate * * @return {Promise} */ public async create(principal: User, tokenCreate: TokenCreate): Promise { const token = new Token(); token.organization = principal.organization; token.user = principal; token.token = Random.getRandomCryptoString(100); token.name = tokenCreate.name; token.description = tokenCreate.description; await this.tokenRepository.save(token); return this.getByToken(token.token); } /** * Delete an api token by it's id and owning organization. * * @param {string} id * @param {Organization} organization * * @return {Promise} */ public async deleteByIdAndOrganization(id: string, organization: Organization): Promise { return (await this.tokenRepository.delete({ id, organization })).affected > 0; } /** * Search across all api tokens. * * @param {Organization} organization * * @return {Promise>} */ public search(organization: Organization): Promise> { return this.tokenRepository.find({ where: { organization } }); } }