-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
94 lines (81 loc) · 2.39 KB
/
auth.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const express= require('express');
const graph = require('./graph');
const router = express.Router();
router.get('/signin',
async(req, res)=> {
const urlParameters = {
scopes: process.env.OAUTH_SCOPES.split(','),
redirectUri: process.env.OAUTH_REDIRECT_URI
};
try {
const authUrl = await req.app.locals
.msalClient.getAuthCodeUrl(urlParameters);
res.redirect(authUrl);
}
catch (error) {
console.log(`Error: ${error}`);
req.flash('error_msg', {
message: 'Error getting auth URL',
debug: JSON.stringify(error, Object.getOwnPropertyNames(error))
});
res.redirect('/');
}
}
);
router.get('/callback',
async (req, res)=> {
const tokenRequest = {
code: req.query.code,
scopes: process.env.OAUTH_SCOPES.split(','),
redirectUri: process.env.OAUTH_REDIRECT_URI
};
try {
const response = await req.app.locals
.msalClient.acquireTokenByCode(tokenRequest);
// Save the user's homeAccountId in their session
req.session.userId = response.account.homeAccountId;
console.log("2.", req.session.userId)
const user = await graph.getUserDetails(
req.app.locals.msalClient,
req.session.userId
);
// Add the user to user storage
req.app.locals.users[req.session.userId] = {
displayName: user.displayName,
email: user.mail || user.userPrincipalName,
timeZone: user.mailboxSettings.timeZone
};
console.log(req.session)
} catch(error) {
req.flash('error_msg', {
message: 'Error completing authentication',
debug: JSON.stringify(error, Object.getOwnPropertyNames(error))
});
}
res.redirect('/');
}
);
router.get('/signout',
async function(req, res) {
console.log(req.locals)
// Sign out
if (req.session.userId) {
// Look up the user's account in the cache
const accounts = await req.app.locals.msalClient
.getTokenCache()
.getAllAccounts();
const userAccount = accounts.find(a => a.homeAccountId === req.session.userId);
// Remove the account
if (userAccount) {
req.app.locals.msalClient
.getTokenCache()
.removeAccount(userAccount);
}
}
// Destroy the user's session
req.session.destroy(function (err) {
res.redirect('/');
});
}
);
module.exports = router;