forked from ilya-v-trofimov/s3-site-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
88 lines (75 loc) · 2.19 KB
/
main.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
'use strict';
const { OAuth2Client } = require('google-auth-library');
const GOOGLE_CLIENT_ID = '<enter your client id here>';
const client = new OAuth2Client(GOOGLE_CLIENT_ID);
function getRedirect(page){
return {
status: '302',
statusDescription: 'Login',
headers: {
location: [{
key: 'Location',
value: page,
}],
},
};
}
function getResponse(code, descr) {
return {
status: code,
statusDescription: descr,
};
}
exports.auth = function (event, context, callback) {
log('auth', event);
log('context', context);
log('process.env', process.env);
const cfrequest = event.Records[0].cf.request;
const headers = cfrequest.headers;
if (!headers.authorization) {
log('auth', {msg: "no auth header"});
const response = getRedirect('main.html');
log('RESPONSE', response);
callback(null, response);
return;
}
const token = headers.authorization[0].value.slice(7);
verify(token)
.then(() => {
log('auth', {msg: 'Successful verification'});
delete cfrequest.headers.authorization;
log('RESPONSE', cfrequest);
callback(null, cfrequest);
})
.catch((err) => {
const response = getResponse(err.httpCode, err.message);
log('RESPONSE', response);
callback(null, response);
});
};
async function verify(token) {
let ticket;
try {
ticket = await client.verifyIdToken({
idToken: token,
audience: GOOGLE_CLIENT_ID + '.apps.googleusercontent.com'
});
} catch (err) {
log('ERROR', err);
throw generateError('401', err.message, 'unauthorized.html');
}
if (ticket.payload.hd !== '<enter your company email domain here>') {
throw generateError('403', 'Forbidden!', 'forbidden.html');
}
return true;
}
function generateError(code, message, html){
const err = new Error();
err.httpCode = code;
err.message = message;
err.htmlPage = html;
return err;
}
function log(label, json){
console.log(`[${label}]\n` + JSON.stringify(json));
}