-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
94 lines (75 loc) · 2.32 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 Router = require('express');
const bodyParser = require('body-parser');
const { OAuth2Client } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { AuthenticationError } = require('apollo-server-express');
const cors = require('cors');
let { JWT_SECRET } = process.env;
if (!JWT_SECRET) {
if (process.env.NODE_ENV !== 'production') {
JWT_SECRET = 'tempjwtsecretfordevonly';
console.log('Missing env var JWT_SECRET. Using unsafe dev secret');
} else {
console.log('Missing env var JWT_SECRET. Authentication disabled');
}
}
const routes = new Router();
routes.use(bodyParser.json());
const origin = process.env.UI_SERVER_ORIGIN || 'http://localhost:8000';
routes.use(cors({ origin, credentials: true }));
function getUser(req) {
const token = req.cookies.jwt;
if (!token) return { signedIn: false };
try {
const credentials = jwt.verify(token, JWT_SECRET);
return credentials;
} catch (error) {
return { signedIn: false };
}
}
routes.post('/signin', async (req, res) => {
if (!JWT_SECRET) {
res.status(500).send('Missing JWT_SECRET. Refusing to authenticate');
}
const googleToken = req.body.google_token;
if (!googleToken) {
res.status(400).send({ code: 400, message: 'Missing Token' });
return;
}
const client = new OAuth2Client();
let payload;
try {
const ticket = await client.verifyIdToken({ idToken: googleToken });
payload = ticket.getPayload();
} catch (error) {
res.status(403).send('Invalid credentials');
}
const { given_name: givenName, name, email } = payload;
const credentials = {
signedIn: true, givenName, name, email,
};
const token = jwt.sign(credentials, JWT_SECRET);
res.cookie('jwt', token, { httpOnly: true, domain: process.env.COOKIE_DOMAIN });
res.json(credentials);
});
routes.post('/signout', async (req, res) => {
res.clearCookie('jwt');
res.json({ status: 'ok' });
});
routes.post('/user', (req, res) => {
res.json(getUser(req));
});
function mustBeSignedIn(resolver) {
return (root, args, { user }) => {
if (!user || !user.signedIn) {
throw new AuthenticationError('You must be signed in');
}
return resolver(root, args, { user });
};
}
function resolveUser(_, args, { user }) {
return user;
}
module.exports = {
routes, getUser, mustBeSignedIn, resolveUser,
};