@tpointurier/ally-microsoft
Version:
An ally driver for Microsoft
85 lines (84 loc) • 2.81 kB
JavaScript
import { Oauth2Driver } from '@adonisjs/ally';
export class MicrosoftDriver extends Oauth2Driver {
config;
authorizeUrl;
accessTokenUrl;
userInfoUrl = 'https://graph.microsoft.com/v1.0/me';
codeParamName = 'code';
errorParamName = 'error';
stateCookieName = 'microsoft_oauth_state';
stateParamName = 'state';
scopeParamName = 'scope';
scopesSeparator = ' ';
constructor(ctx, config) {
super(ctx, config);
this.config = config;
const tenantId = this.config.tenantId || 'common';
this.authorizeUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize`;
this.accessTokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
this.loadState();
}
configureRedirectRequest(request) {
request.scopes(this.config.scopes || ['openid']);
request.param('response_type', 'code');
}
configureAccessTokenRequest(request) {
request
.header('Content-Type', 'application/x-www-form-urlencoded')
.field('grant_type', 'authorization_code')
.field('client_id', this.config.clientId)
.field('client_secret', this.config.clientSecret)
.field('redirect_uri', this.config.callbackUrl)
.field('code', this.ctx.request.input(this.codeParamName));
}
/**
* Find if the current error code is for access denied
*/
accessDenied() {
const error = this.getError();
if (!error) {
return false;
}
return error === 'access_denied';
}
/**
* Returns details for the authorized user
*/
async user(callback) {
const accessToken = await this.accessToken(callback);
const user = await this.getUserInfo(accessToken.token, callback);
return {
...user,
token: accessToken,
};
}
/**
* Finds the user by the access token
*/
async userFromToken(token, callback) {
const user = await this.getUserInfo(token, callback);
return {
...user,
token: { token: token, type: 'bearer' },
};
}
/**
* Fetches the user info from the Twitch API
*/
async getUserInfo(accessToken, callback) {
const request = this.getAuthenticatedRequest(this.userInfoUrl, accessToken);
if (typeof callback === 'function') {
callback(request);
}
return await request.get();
}
/**
* Returns the HTTP request with the authorization header set
*/
getAuthenticatedRequest(url, token) {
const request = this.httpClient(url);
request.header('Authorization', `Bearer ${token}`);
request.parseAs('json');
return request;
}
}