-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.js
101 lines (90 loc) · 2.76 KB
/
test.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
96
97
98
99
100
101
const express = require('express')
const serverless = require('serverless-http')
const app = express()
const bodyParser = require('body-parser')
const validator = require('express-validator')
const {check, validationResult} = require('express-validator/check')
const AWS = require('aws-sdk')
const keys = require('../config/keys')
const axios = require('axios')
const s3 = new AWS.S3({
accessKeyId: keys.accessKeyId,
secretAccessKey: keys.secretAccessKey,
})
const S3Params = {
Bucket: 'data-store-blog',
Key: 'users/users.json',
}
const router = express.Router()
app.use(bodyParser.json())
app.use(validator())
const validate = () => [
check('firstName', 'first name doesnt exists').exists(),
check('lastName', 'first name doesnt exists').exists(),
check('email', 'Invalid email')
.exists()
.isEmail(),
]
const emailAlreadyExists = (data, email) => data[email]
router.post('/', validate(), (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) return res.status(422).json({errors: errors.array()})
const {firstName, lastName, email, token} = req.body
axios
.post(
`https://www.google.com/recaptcha/api/siteverify?secret=${
keys.secretRecaptcha
}&response=${token}`,
{},
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
},
},
)
.then(result => {
if (result.data.success) {
s3.getObject(S3Params, function(err, data) {
if (err)
return res
.status(500)
.json({error: 'Has occurred an error, please try later.'})
let object = JSON.parse(data.Body.toString())
if (emailAlreadyExists(object, email)) {
return res.status(422).json({error: 'Email already exists.'})
}
const newDataobject = Object.assign({}, object, {
[email]: {firstName, lastName, email},
})
s3.putObject(
{
Bucket: S3Params['Bucket'],
Key: S3Params['Key'],
Body: JSON.stringify({
...newDataobject,
}),
ContentType: 'application/json',
},
function(err, data) {
res
.status(200)
.json({message: 'Your information has been saved.'})
},
)
})
} else {
return res
.status(422)
.json({error: 'Captcha verification failed. Try again.'})
}
})
.catch(err => {
return res
.status(500)
.json({error: 'Has occurred an error, please try later.'})
})
})
// path must route to lambda
app.use('/.netlify/functions/test', router)
module.exports = app
module.exports.handler = serverless(app)