icynet-auth-server/src/modules/oauth2/adapter/user.adapter.ts

87 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-09 18:37:04 +00:00
import { OAuth2UserAdapter, OAuth2User } from '@icynet/oauth2-provider';
2024-03-12 15:49:06 +00:00
import { Injectable } from '@nestjs/common';
2022-03-09 18:37:04 +00:00
import { Request } from 'express';
import { ParamsDictionary } from 'express-serve-static-core';
import { ParsedQs } from 'qs';
2024-03-12 15:49:06 +00:00
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';
2022-03-09 18:37:04 +00:00
2024-03-12 15:49:06 +00:00
@Injectable()
2022-03-09 18:37:04 +00:00
export class UserAdapter implements OAuth2UserAdapter {
2024-03-12 15:49:06 +00:00
constructor(
private readonly userService: UserService,
private readonly clientService: OAuth2ClientService,
private readonly form: FormUtilityService,
) {}
2022-03-09 18:37:04 +00:00
getId(user: OAuth2User): number {
return user.id as number;
}
async fetchById(id: number): Promise<OAuth2User> {
2024-03-12 15:49:06 +00:00
const find = await this.userService.getById(id);
2022-03-26 07:22:14 +00:00
if (!find) {
return null;
}
2022-03-09 18:37:04 +00:00
return {
id: find.id,
username: find.username,
password: find.password,
};
}
async fetchByUsername(username: string): Promise<OAuth2User> {
2024-03-12 15:49:06 +00:00
const find = await this.userService.getByUsername(username);
2022-03-26 07:22:14 +00:00
if (!find) {
return null;
}
2022-03-09 18:37:04 +00:00
return {
id: find.id,
username: find.username,
password: find.password,
};
}
checkPassword(user: OAuth2User, password: string): Promise<boolean> {
2024-03-12 15:49:06 +00:00
return this.userService.comparePasswords(user.password, password);
2022-03-09 18:37:04 +00:00
}
async fetchFromRequest(
req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>,
): Promise<OAuth2User> {
return req.user;
2022-03-09 18:37:04 +00:00
}
async consented(
userId: number,
clientId: string,
scope: string | string[],
): Promise<boolean> {
2024-03-12 15:49:06 +00:00
return this.clientService.hasAuthorized(
2022-03-20 14:50:12 +00:00
userId,
clientId,
2024-03-12 15:49:06 +00:00
this.form.splitScope(scope),
2022-03-20 14:50:12 +00:00
);
2022-03-09 18:37:04 +00:00
}
async consent(
userId: number,
clientId: string,
scope: string | string[],
): Promise<boolean> {
2024-03-12 15:49:06 +00:00
const client = await this.clientService.getById(clientId);
const user = await this.userService.getById(userId);
await this.clientService.createAuthorization(
2022-03-20 14:50:12 +00:00
user,
client,
2024-03-12 15:49:06 +00:00
this.form.splitScope(scope),
2022-03-20 14:50:12 +00:00
);
2022-03-09 18:37:04 +00:00
return true;
}
}