-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth-signup.js
94 lines (82 loc) · 2.03 KB
/
auth-signup.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
"use strict"
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const User = require("./models/user");
const MONGO_URI = process.env.MONGO_URI;
const JWT_SECRET = process.env.JWT_SECRET;
let connection = null;
const connectDB = () => {
if (connection && mongoose.connection.readyState === 1) return;
mongoose.connect(MONGO_URI, { }).then(
conn => {
connection = conn;
}
);
};
module.exports.handler = async (event, context) => {
const { id: userId, name: userName } = JSON.parse(event.body);
console.log(userId);
console.log(userName);
if(typeof userId == "undefined" || userId == "" || userId == null || typeof userName == "undefined" || userName == "" || userName == null)
return {
statusCode: "400",
body: JSON.stringify({
"message": "Bad Request",
})
};
connectDB();
try {
const existingUser = await User.findOne({ id: userId }).populate("friends");
if (existingUser)
return {
statusCode: "409",
body: JSON.stringify({
"message": "Duplicated User",
})
};
const zeroArray = Array(9).fill(0);
const newUser = await User.create({
id: userId,
name: userName,
animal: zeroArray,
emoji: zeroArray,
color: zeroArray,
first: zeroArray,
now: zeroArray,
});
if(newUser){
const token = jwt.sign(
{
id: userId,
name: userName,
},
JWT_SECRET,
{
expiresIn: "30m",
}
);
return {
statusCode: "201",
body: JSON.stringify({
"message": "New User Created",
"data": {
"id": userId,
"name": userName,
"token": token,
}
})
};
}
else{
throw new Error('Failed to Create New User');
}
} catch (err) {
console.log(err);
return {
statusCode: "400",
body: JSON.stringify({
"message": "Bad Request",
})
};