-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
74 lines (63 loc) · 1.77 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
const { OAuth2Client } = require("google-auth-library");
const User = require("./models/user");
const socketManager = require("./server-socket");
// create a new OAuth client used to verify google sign-in
// TODO: replace with your own CLIENT_ID
const CLIENT_ID =
"280530756657-h7idsmk4f3vahmglar41qkf79ch1g9lt.apps.googleusercontent.com";
const client = new OAuth2Client(CLIENT_ID);
// accepts a login token from the frontend, and verifies that it's legit
function verify(token) {
return client
.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
})
.then((ticket) => ticket.getPayload());
}
// gets user from DB, or makes a new account if it doesn't exist yet
function getOrCreateUser(user) {
// the "sub" field means "subject", which is a unique identifier for each user
return User.findOne({ googleid: user.sub }).then((existingUser) => {
if (existingUser) return existingUser;
const newUser = new User({
name: user.name,
googleid: user.sub,
});
return newUser.save();
});
}
function login(req, res) {
verify(req.body.token)
.then((user) => getOrCreateUser(user))
.then((user) => {
// persist user in the session
req.session.user = user;
res.send(user);
})
.catch((err) => {
console.log(`Failed to log in: ${err}`);
res.status(401).send({ err });
});
}
function logout(req, res) {
req.session.user = null;
res.send({});
}
function populateCurrentUser(req, res, next) {
// simply populate "req.user" for convenience
req.user = req.session.user;
next();
}
function ensureLoggedIn(req, res, next) {
if (!req.user) {
return res.status(401).send({ err: "not logged in" });
}
next();
}
module.exports = {
login,
logout,
populateCurrentUser,
ensureLoggedIn,
};