-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthController.js
79 lines (69 loc) · 2.13 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
71
72
73
74
75
76
77
78
79
require("dotenv").config();
const msalInstance = require("../msal");
const port = process.env.PORT || 5000;
exports.loginUser = async (req, res, next) => {
const authCodeUrlParameters = {
redirectUri: process.env.REDIRECT_URI,
responseMode: "form_post",
scopes: ["User.Read"],
};
msalInstance
.getAuthCodeUrl(authCodeUrlParameters)
.then((response) => {
res.json(response);
})
.catch((error) => {
next(error);
});
};
/**
* We parse the authorization code in this method and invoke the acquireTokenByCode on the MSAL instance.
* Setting set enableSpaAuthorizationCode to true will enable MSAL to acquire a second authorization code
* to be redeemed by your single-page application.
*/
exports.handleRedirectWithCode = (req, res, next) => {
const tokenRequest = {
code: req.body.code,
redirectUri: process.env.REDIRECT_URI,
enableSpaAuthorizationCode: true,
scopes: ["User.Read"],
};
msalInstance
.acquireTokenByCode(tokenRequest)
.then((response) => {
const { code } = response; //SPA authorization code
const {
sid, // session ID claim, used for non-hybrid
login_hint: loginHint, // new login_hint claim (used instead of sid or email)
preferred_username: preferredUsername,
} = response.idTokenClaims;
req.session.code = code;
req.session.loginHint = loginHint;
req.session.sid = sid;
req.session.referredUsername = preferredUsername;
req.session.authenticated = true;
const urlFrom = (urlObject) => String(Object.assign(new URL(`http://localhost:${port}`), urlObject));
res.redirect(
urlFrom({
protocol: "http",
pathname: "/",
search: "getCode=true",
})
);
})
.catch((err) => {
next(err);
});
};
exports.logoutUser = (req, res) => {
req.session.destroy((err) => {
res.status(200).json({ message: "success" });
});
};
exports.sendSPACode = (req, res) => {
if (req.session.authenticated) {
res.status(200).json({ ...req.session });
} else {
res.status(401).json({ message: "user is not authenticated" });
}
};