import { OAuth2UserAdapter, OAuth2User } from '@icynet/oauth2-provider'; import { Injectable } from '@nestjs/common'; import { Request } from 'express'; import { ParamsDictionary } from 'express-serve-static-core'; import { ParsedQs } from 'qs'; import { OAuth2ClientService } from 'src/modules/objects/oauth2-client/oauth2-client.service'; import { UserService } from 'src/modules/objects/user/user.service'; import { FormUtilityService } from 'src/modules/utility/services/form-utility.service'; @Injectable() export class UserAdapter implements OAuth2UserAdapter { constructor( private readonly userService: UserService, private readonly clientService: OAuth2ClientService, private readonly form: FormUtilityService, ) {} getId(user: OAuth2User): number { return user.id as number; } async fetchById(id: number): Promise { const find = await this.userService.getById(id); if (!find) { return null; } return { id: find.id, username: find.username, password: find.password, }; } async fetchByUsername(username: string): Promise { const find = await this.userService.getByUsername(username); if (!find) { return null; } return { id: find.id, username: find.username, password: find.password, }; } checkPassword(user: OAuth2User, password: string): Promise { return this.userService.comparePasswords(user.password, password); } async fetchFromRequest( req: Request>, ): Promise { return req.user; } async consented( userId: number, clientId: string, scope: string | string[], ): Promise { return this.clientService.hasAuthorized( userId, clientId, this.form.splitScope(scope), ); } async consent( userId: number, clientId: string, scope: string | string[], ): Promise { const client = await this.clientService.getById(clientId); const user = await this.userService.getById(userId); await this.clientService.createAuthorization( user, client, this.form.splitScope(scope), ); return true; } }