oauth2-provider/src/controller/tokens/clientCredentials.ts

44 lines
1.1 KiB
TypeScript

import { ServerError, InvalidScope } from '../../model/error';
import { OAuth2, OAuth2Client, OAuth2TokenResponse } from '../../model/model';
/**
* Issue client access token
* @param oauth2 - OAuth2 instance
* @param client - Client
* @param wantScope - Requested scopes
* @returns Access token
*/
export async function clientCredentials(
oauth2: OAuth2,
client: OAuth2Client,
wantScope: string | string[]
): Promise<OAuth2TokenResponse> {
let scope: string[] = [];
const resObj: OAuth2TokenResponse = {
token_type: 'bearer',
};
scope = oauth2.model.client.transformScope(wantScope);
if (!oauth2.model.client.checkScope(client, scope)) {
throw new InvalidScope('Client does not allow access to this scope');
}
oauth2.logger.debug('Scope check passed', scope);
try {
resObj.access_token = await oauth2.model.accessToken.create(
null,
oauth2.model.client.getId(client),
scope,
oauth2.model.accessToken.ttl
);
} catch (err) {
throw new ServerError('Failed to call accessToken.create function');
}
resObj.expires_in = oauth2.model.accessToken.ttl;
return resObj;
}