@koex/passport-oauth2
Version:
koex passport-oauth2
70 lines • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OauthStrategy = void 0;
const node_fetch_1 = require("node-fetch");
const qs = require("@zcorky/query-string");
const passport_1 = require("@koex/passport");
/**
* Oauth Passport Strategy
* which defined the authenticate(@S1) and callback flow(@S2),
* what you need do is to realize the following three methods,
* which will used in authenticate and callback flow.
* @Method getAuthorizeUrl(url, data): URL (@S1)
* @Method getAccessToken(url, data): Token (@S2)
* @Method getAccessUser(url, data): User (@S3)
*/
class OauthStrategy extends passport_1.Strategy {
constructor(oauthStrategyOptions, verify) {
super(verify);
this.oauthStrategyOptions = oauthStrategyOptions;
this.verify = verify;
this.utils = {
fetch: node_fetch_1.default,
qs,
};
}
/**
* @S1 Authenticate Flow
*
* @param ctx context
* @returns redirect to authorization url
*/
async authenticate(ctx) {
const { authorize_url, client_id, response_type, redirect_uri, scope, state, } = this.oauthStrategyOptions;
const data = {
client_id,
redirect_uri,
response_type,
scope,
state,
};
const auth_server_url = await this.getAuthorizeUrl(authorize_url, data);
ctx.redirect(auth_server_url);
}
/**
* @S2 Callback Flow
*
* @param ctx context
* @returns user profile
*/
async callback(ctx) {
const { token_url, user_profile_url, client_id, client_secret, redirect_uri, grant_type, scope, } = this.oauthStrategyOptions;
const code = ctx.query.code;
const accessTokenData = {
client_id,
client_secret,
redirect_uri,
grant_type,
scope,
code,
};
const token = await this.getAccessToken(token_url, accessTokenData);
return token;
}
async getProfile(ctx, token) {
const { user_profile_url } = this.oauthStrategyOptions;
return await this.getAccessUser(user_profile_url, token);
}
}
exports.OauthStrategy = OauthStrategy;
//# sourceMappingURL=strategy.js.map