UNPKG

6.31 kBJavaScriptView Raw
1"use strict";
2/**
3 * This file is part of the @egodigital/egoose distribution.
4 * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
5 *
6 * @egodigital/egoose is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * @egodigital/egoose is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19const _ = require("lodash");
20const index_1 = require("../index");
21const index_2 = require("../http/index");
22/**
23 * Returns the information from 'https://graph.microsoft.com/v1.0/me'.
24 *
25 * @param {string | MicrosoftOAuthAccessToken} token The token.
26 *
27 * @return {Promise<false|MicrosoftMe>} The promise with the data or (false) if failed.
28 */
29async function getMicrosoftMe(token) {
30 let accessToken;
31 if (_.isObjectLike(token)) {
32 accessToken = token.access_token
33 .trim();
34 }
35 else {
36 accessToken = index_1.toStringSafe(token)
37 .trim();
38 }
39 try {
40 const RESPONSE = await index_2.GET('https://graph.microsoft.com/v1.0/me', {
41 headers: {
42 'Authorization': `Bearer ${accessToken}`
43 }
44 });
45 if (200 === RESPONSE.code) {
46 return JSON.parse((await RESPONSE.readBody())
47 .toString('utf8'));
48 }
49 }
50 catch (_a) { }
51 return false;
52}
53exports.getMicrosoftMe = getMicrosoftMe;
54/**
55 * Returns the login URL for Microsoft OAuth.
56 *
57 * @return {string} The login URL.
58 */
59function getMicrosoftOAuthLoginUrl() {
60 return `https://login.microsoftonline.com/${encodeURIComponent(process.env.MICROSOFT_OAUTH_TENANT_ID
61 .trim())}/oauth2/authorize?client_id=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_ID
62 .trim())}&response_type=code&redirect_uri=${encodeURIComponent(process.env.MICROSOFT_OAUTH_REDIRECT_URL
63 .trim())}&response_mode=query&resource=${encodeURIComponent('https://graph.microsoft.com')}`;
64}
65exports.getMicrosoftOAuthLoginUrl = getMicrosoftOAuthLoginUrl;
66/**
67 * Registers an Express instance for Microsoft OAuth.
68 *
69 * @param {express.Express | express.Router} hostOrRouter The host or router.
70 * @param {RegisterForMicrosoftOAuthOptions} opts The options.
71 */
72function registerForMicrosoftOAuth(hostOrRouter, opts) {
73 let redirectPath = index_1.toStringSafe(opts.redirectPath)
74 .trim();
75 if ('' === redirectPath) {
76 redirectPath = '/oauth/microsoft';
77 }
78 hostOrRouter.get(redirectPath, async function (req, res, next) {
79 try {
80 const CODE = index_1.toStringSafe(req.query['code'])
81 .trim();
82 if ('' !== CODE) {
83 const URL = `https://login.microsoftonline.com/${encodeURIComponent(process.env.MICROSOFT_OAUTH_TENANT_ID
84 .trim())}/oauth2/token`;
85 const BODY = Buffer.from(`grant_type=authorization_code` +
86 `&client_id=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_ID
87 .trim())}` +
88 `&code=${encodeURIComponent(CODE)}` +
89 `&redirect_uri=${encodeURIComponent(process.env.MICROSOFT_OAUTH_REDIRECT_URL
90 .trim())}` +
91 `&client_secret=${encodeURIComponent(process.env.MICROSOFT_OAUTH_CLIENT_SECRET
92 .trim())}&scope=${encodeURIComponent('https://graph.microsoft.com/user.read')}`, 'ascii');
93 const RESPONSE = await index_2.POST(URL, {
94 body: BODY,
95 headers: {
96 'Content-Length': '' + BODY.length,
97 'Content-Type': 'application/x-www-form-urlencoded'
98 }
99 });
100 if (200 === RESPONSE.code) {
101 const TOKEN = JSON.parse((await RESPONSE.readBody())
102 .toString('utf8'));
103 if (TOKEN) {
104 await Promise.resolve(opts.onAccessToken(TOKEN, req, res));
105 let onSuccess = opts.onSuccess;
106 if (!onSuccess) {
107 onSuccess = (req2, res2) => {
108 return res2.status(200)
109 .header('Content-type', 'text/plain; charset=utf-8')
110 .send(Buffer.from('Authorization succeeded. You can close the browser now.', 'utf8'));
111 };
112 }
113 return await Promise.resolve(onSuccess(req, res));
114 }
115 }
116 }
117 const ERROR = index_1.toStringSafe(req.query['error'])
118 .trim();
119 if ('' !== ERROR) {
120 const DESCRIPTION = index_1.toStringSafe(req.query['error_description']).trim();
121 let onError = opts.onError;
122 if (!onError) {
123 onError = (err, desc, req2, res2) => {
124 return res2.status(200)
125 .header('Content-type', 'text/plain; charset=utf-8')
126 .send(`Authorization error '${err}': '${desc}'`);
127 };
128 }
129 return await Promise.resolve(onError(ERROR, DESCRIPTION, req, res));
130 }
131 return res.status(400)
132 .send();
133 }
134 catch (e) {
135 let onServerError = opts.onServerError;
136 if (!onServerError) {
137 onServerError = (err, req2, res2) => {
138 return res2.status(500)
139 .send();
140 };
141 }
142 return await Promise.resolve(onServerError(e, req, res));
143 }
144 });
145}
146exports.registerForMicrosoftOAuth = registerForMicrosoftOAuth;
147//# sourceMappingURL=microsoft.js.map
\No newline at end of file