-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathauthController.js
70 lines (55 loc) · 2.21 KB
/
authController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const getGraphClient = require('../utils/graphClient');
const { handleAnyClaimsChallenge, setClaims } = require('../utils/claimUtils');
const {
msalConfig,
REDIRECT_URI,
POST_LOGOUT_REDIRECT_URI,
GRAPH_ME_ENDPOINT
} = require('../authConfig');
const AuthProvider = require("../auth/AuthProvider");
const authProvider = new AuthProvider({
msalConfig: msalConfig,
redirectUri: REDIRECT_URI,
postLogoutRedirectUri: POST_LOGOUT_REDIRECT_URI,
});
exports.loginUser = async (req, res, next) => {
let postLoginRedirectUri;
let scopesToConsent;
if (req.query && req.query.postLoginRedirectUri) {
postLoginRedirectUri = decodeURIComponent(req.query.postLoginRedirectUri);
}
if (req.query && req.query.scopesToConsent) {
scopesToConsent = decodeURIComponent(req.query.scopesToConsent);
}
return authProvider.login(req, res, next, { postLoginRedirectUri, scopesToConsent });
}
exports.handleRedirect = async (req, res, next) => {
return authProvider.handleRedirect(req, res, next);
}
exports.logoutUser = async (req, res, next) => {
return authProvider.logout(req, res, next);
}
exports.getAccount = async (req, res, next) => {
const account = authProvider.getAccount(req, res, next);
res.status(200).json(account);
}
exports.getProfile = async (req, res, next) => {
if (!authProvider.isAuthenticated(req, res, next)) {
return res.status(401).json({ error: 'unauthorized' });
}
try {
const tokenResponse = await authProvider.acquireToken(req, res, next, { scopes: ['User.Read']});
const graphResponse = await getGraphClient(tokenResponse.accessToken).api('/me').responseType('raw').get();
const graphData = await handleAnyClaimsChallenge(graphResponse);
res.status(200).json(graphData);
} catch (error) {
if (error.name === 'ClaimsChallengeAuthError') {
setClaims(req.session, msalConfig.auth.clientId, GRAPH_ME_ENDPOINT, error.payload);
return res.status(401).json({ error: error.name });
}
if (error.name === 'InteractionRequiredAuthError') {
return res.status(401).json({ error: error.name, scopes: error.payload });
}
next(error);
}
}