UNPKG

@egodigital/egoose

Version:

Helper classes and functions for Node.js 10 or later.

147 lines 6.31 kB
"use strict"; /** * This file is part of the @egodigital/egoose distribution. * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/) * * @egodigital/egoose is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 3. * * @egodigital/egoose is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ Object.defineProperty(exports, "__esModule", { value: true }); const _ = require("lodash"); const index_1 = require("../index"); const index_2 = require("../http/index"); /** * Returns the information from 'https://graph.microsoft.com/v1.0/me'. * * @param {string | MicrosoftOAuthAccessToken} token The token. * * @return {Promise<false|MicrosoftMe>} The promise with the data or (false) if failed. */ async function getMicrosoftMe(token) { let accessToken; if (_.isObjectLike(token)) { accessToken = token.access_token .trim(); } else { accessToken = index_1.toStringSafe(token) .trim(); } try { const RESPONSE = await index_2.GET('https://graph.microsoft.com/v1.0/me', { headers: { 'Authorization': `Bearer ${accessToken}` } }); if (200 === RESPONSE.code) { return JSON.parse((await RESPONSE.readBody()) .toString('utf8')); } } catch { } return false; } exports.getMicrosoftMe = getMicrosoftMe; /** * Returns the login URL for Microsoft OAuth. * * @return {string} The login URL. */ function getMicrosoftOAuthLoginUrl() { return `https://login.microsoftonline.com/${encodeURIComponent(process.env.MICROSOFT_OAUTH_TENANT_ID .trim())}/oauth2/authorize?client_id=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_ID .trim())}&response_type=code&redirect_uri=${encodeURIComponent(process.env.MICROSOFT_OAUTH_REDIRECT_URL .trim())}&response_mode=query&resource=${encodeURIComponent('https://graph.microsoft.com')}`; } exports.getMicrosoftOAuthLoginUrl = getMicrosoftOAuthLoginUrl; /** * Registers an Express instance for Microsoft OAuth. * * @param {express.Express | express.Router} hostOrRouter The host or router. * @param {RegisterForMicrosoftOAuthOptions} opts The options. */ function registerForMicrosoftOAuth(hostOrRouter, opts) { let redirectPath = index_1.toStringSafe(opts.redirectPath) .trim(); if ('' === redirectPath) { redirectPath = '/oauth/microsoft'; } hostOrRouter.get(redirectPath, async function (req, res, next) { try { const CODE = index_1.toStringSafe(req.query['code']) .trim(); if ('' !== CODE) { const URL = `https://login.microsoftonline.com/${encodeURIComponent(process.env.MICROSOFT_OAUTH_TENANT_ID .trim())}/oauth2/token`; const BODY = Buffer.from(`grant_type=authorization_code` + `&client_id=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_ID .trim())}` + `&code=${encodeURIComponent(CODE)}` + `&redirect_uri=${encodeURIComponent(process.env.MICROSOFT_OAUTH_REDIRECT_URL .trim())}` + `&client_secret=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_SECRET .trim())}&scope=${encodeURIComponent('https://graph.microsoft.com/user.read')}`, 'ascii'); const RESPONSE = await index_2.POST(URL, { body: BODY, headers: { 'Content-Length': '' + BODY.length, 'Content-Type': 'application/x-www-form-urlencoded' } }); if (200 === RESPONSE.code) { const TOKEN = JSON.parse((await RESPONSE.readBody()) .toString('utf8')); if (TOKEN) { await Promise.resolve(opts.onAccessToken(TOKEN, req, res)); let onSuccess = opts.onSuccess; if (!onSuccess) { onSuccess = (req2, res2) => { return res2.status(200) .header('Content-type', 'text/plain; charset=utf-8') .send(Buffer.from('Authorization succeeded. You can close the browser now.', 'utf8')); }; } return await Promise.resolve(onSuccess(req, res)); } } } const ERROR = index_1.toStringSafe(req.query['error']) .trim(); if ('' !== ERROR) { const DESCRIPTION = index_1.toStringSafe(req.query['error_description']).trim(); let onError = opts.onError; if (!onError) { onError = (err, desc, req2, res2) => { return res2.status(200) .header('Content-type', 'text/plain; charset=utf-8') .send(`Authorization error '${err}': '${desc}'`); }; } return await Promise.resolve(onError(ERROR, DESCRIPTION, req, res)); } return res.status(400) .send(); } catch (e) { let onServerError = opts.onServerError; if (!onServerError) { onServerError = (err, req2, res2) => { return res2.status(500) .send(); }; } return await Promise.resolve(onServerError(e, req, res)); } }); } exports.registerForMicrosoftOAuth = registerForMicrosoftOAuth; //# sourceMappingURL=microsoft.js.map