-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_auth.js
92 lines (82 loc) · 2.16 KB
/
server_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
const passport = require('passport');
const Auth0Strategy = require('passport-auth0');
const fetch = require('node-fetch');
/**
* Retrieves all user information from retailplanet backend
*
* @param accessToken Token of the current user to retrieve information for
*/
function retrieveUserInfo(accessToken) {
return fetch(`${process.env.BACKEND_URL}/profile`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then(pResult => pResult.json());
}
/**
* Convert Tokens to a User-Profile
*/
const tokenToProfile = async (accessToken, refreshToken, extraParams, profile, done) => {
const { id, name, nickname, _json: { email } } = profile;
const user = {
profile: {
id,
name,
username: nickname,
email,
},
tokens: {
accessToken,
refreshToken,
},
info: {},
};
retrieveUserInfo(accessToken)
.then((pResult) => {
user.info = {
...pResult,
};
delete user.info.id;
delete user.info.avatar;
})
.catch(console.log)
.finally(() => done(null, user));
};
/**
* Strategy which connects to our OAuth-Provider
*/
const authStrategy = new Auth0Strategy({
state: true,
domain: process.env.OAUTH_URL,
clientID: process.env.OAUTH_CLIENTID,
clientSecret: process.env.OAUTH_SECRET,
callbackURL: `${process.env.BASEURL}/login`,
scope: 'openid email profile',
}, tokenToProfile);
/**
* Initializes Authentication in Express-App
*
* @param pExpressApp App
*/
function auth(pExpressApp) {
passport.use('auth0', authStrategy);
pExpressApp.use(passport.initialize());
pExpressApp.use(passport.session());
pExpressApp.get('/login', passport.authenticate('auth0', {
audience: 'api.retailplanet.io',
session: true,
successReturnToOrRedirect: '/',
failureRedirect: '/',
}));
pExpressApp.get('/logout', (req, res) => {
req.logout();
res.redirect(`https://${process.env.OAUTH_URL}/v2/logout?client_id=${process.env.OAUTH_CLIENTID}&returnTo=${process.env.BASEURL}`);
});
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
}
module.exports = auth;