-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle-auth-hook.js
95 lines (86 loc) · 2.41 KB
/
google-auth-hook.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
95
"use strict";
/**
* Google OAath 2.0
*
* You should read Using OAuth 2.0 to Access Google APIs:
* https://developers.google.com/identity/protocols/OAuth2
*
* This example assumes that all users authenticating via
* google should have access. You would proably limit access
* to users you trust.
*
* The implementation assumes the following environement variables:
*
* - GOOGLE_CLIENT_ID
* - GOOGLE_CLIENT_SECRET
* - GOOGLE_CALLBACK_URL
*/
const { User, AuthenticationRequired } = require("unleash-server");
const passport = require("@passport-next/passport");
const GoogleOAuth2Strategy = require("@passport-next/passport-google-oauth2")
.Strategy;
const validEmails = (process.env.AUTHORIZED_EMAILS || "").split(",");
console.error(
"Valid emails for logging in to unleash with Google: ",
validEmails
);
passport.use(
new GoogleOAuth2Strategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL
},
(accessToken, refreshToken, profile, done) => {
if (validEmails.indexOf(profile.emails[0].value) > -1) {
done(
null,
new User({
name: profile.displayName,
email: profile.emails[0].value
})
);
} else {
done("You do not have permission to login", null);
}
}
)
);
function enableGoogleOauth(app) {
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
app.get(
"/api/admin/login",
passport.authenticate("google", { scope: ["email"] })
);
app.get(
"/api/auth/callback",
passport.authenticate("google", {
failureRedirect: "/api/admin/error-login"
}),
(req, res) => {
// Successful authentication, redirect to your app.
res.redirect("/");
}
);
app.use("/api/admin/", (req, res, next) => {
if (req.user) {
next();
} else {
return res
.status("401")
.json(
new AuthenticationRequired({
path: "/api/admin/login",
type: "custom",
message: `You have to identify yourself in order to use Unleash.
Click the button and follow the instructions.`
})
)
.end();
}
});
}
module.exports = enableGoogleOauth;