icynet-auth-server/src/modules/oauth2/oauth2.service.ts

65 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-03-09 18:37:04 +00:00
import { OAuth2AdapterModel, OAuth2Provider } from '@icynet/oauth2-provider';
import { Injectable } from '@nestjs/common';
import { OAuth2ClientService } from 'src/modules/objects/oauth2-client/oauth2-client.service';
import { AccessTokenAdapter } from './adapter/access-token.adapter';
import { ClientAdapter } from './adapter/client.adapter';
import { CodeAdapter } from './adapter/code.adapter';
2024-03-12 15:49:06 +00:00
import { JWTAdapter } from './adapter/jwt.adapter';
2022-03-09 18:37:04 +00:00
import { RefreshTokenAdapter } from './adapter/refresh-token.adapter';
import { UserAdapter } from './adapter/user.adapter';
2022-03-16 18:37:50 +00:00
const SCOPE_DESCRIPTION: Record<string, string> = {
email: 'Email address',
picture: 'Profile picture',
2022-03-16 18:37:50 +00:00
};
const ALWAYS_AVAILABLE = ['Username and display name'];
const ALWAYS_UNAVAILABLE = ['Password and other account settings'];
2022-03-09 18:37:04 +00:00
@Injectable()
2024-03-12 15:49:06 +00:00
export class OAuth2Service implements OAuth2AdapterModel {
public oauth = new OAuth2Provider(this, async (req, res, client, scope) => {
const fullClient = await this.clientService.getById(client.id as string);
let allowedScopes = [...ALWAYS_AVAILABLE];
let disallowedScopes = [...ALWAYS_UNAVAILABLE];
2022-03-09 18:37:04 +00:00
2024-03-12 15:49:06 +00:00
Object.keys(SCOPE_DESCRIPTION).forEach((item) => {
if (scope.includes(item)) {
allowedScopes.push(SCOPE_DESCRIPTION[item]);
} else {
disallowedScopes.push(SCOPE_DESCRIPTION[item]);
2022-08-27 10:53:37 +00:00
}
2024-03-12 15:49:06 +00:00
});
2022-08-27 10:53:37 +00:00
2024-03-12 15:49:06 +00:00
if (scope.includes('management')) {
allowedScopes = [
'Manage Icy Network on your behalf',
'Commit administrative actions to the extent of your user privileges',
];
disallowedScopes = null;
}
res.render('authorize', {
csrf: req.csrfToken(),
user: req.user,
client: fullClient,
allowedScopes,
disallowedScopes,
});
});
2022-03-09 18:37:04 +00:00
constructor(
public clientService: OAuth2ClientService,
2024-03-12 15:49:06 +00:00
public accessToken: AccessTokenAdapter,
public refreshToken: RefreshTokenAdapter,
public user: UserAdapter,
public client: ClientAdapter,
public code: CodeAdapter,
public jwt: JWTAdapter,
2022-03-09 18:37:04 +00:00
) {
2023-01-11 16:23:08 +00:00
if (!!process.env.DEBUG_OAUTH2) {
this.oauth.logger.setLogLevel('debug');
}
2022-03-09 18:37:04 +00:00
}
}