-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
213 lines (188 loc) · 6.04 KB
/
server.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const PORT = process.env.PORT || 8080;
const { Pool } = require("pg");
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
ssl: {
require: true,
rejectUnauthorized: true,
},
});
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Sign In
app.use("/login", async (req, res) => {
const { username, password } = req.body;
// validate password
const validatePassword = (password) => {
if (password.length < 6) {
return "Password must be at least 7 character long";
} else if (!/[a-z]/.test(password)) {
return "Password must contain at least one lowercase letter";
} else if (!/[A-Z]/.test(password)) {
return "Password must contain al least one uppercase letter";
} else if (!/\d/.test(password)) {
return "Password must contain at least one number";
} else if (!/[!@#$%^&*]/.test(password)) {
return "Password must contain at least one special character";
} else {
// if password is valid return nothing
return password;
}
};
const validatedPassword = validatePassword(password);
try {
const user = await pool.query(
`SELECT user_id, firstname, lastname, password FROM accounts WHERE username = $1`,
[username]
);
if (user.rows.length === 0) {
res.status(401).json({ error: "Invalid username" });
return;
}
const storedHash = user.rows[0].password;
const passwordMatch = await bcrypt.compare(validatedPassword, storedHash);
if (!passwordMatch) {
res.status(401).json({ error: "Invalid password" });
return;
} else {
const token = jwt.sign(
{
id: user.rows[0].user_id,
firstname: user.rows[0].firstname,
lastname: user.rows[0].lastname,
},
process.env["jwtPrivateKey"] // env is objec [xxx] you are accessing the key of the object
);
res.status(200).json({
// JWT
token,
user: {
id: user.rows[0].user_id,
firstname: user.rows[0].firstname,
lastname: user.rows[0].lastname,
},
});
}
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
//Sign Up
app.use("/signup", async (req, res) => {
const { firstname, lastname, username, password, email } = req.body;
const validatePassword = (password) => {
if (password.length < 6) {
return "Password must be at least 7 character long";
} else if (!/[a-z]/.test(password)) {
return "Password must contain at least one lowercase letter";
} else if (!/[A-Z]/.test(password)) {
return "Password must contain al least one uppercase letter";
} else if (!/\d/.test(password)) {
return "Password must contain at least one number";
} else if (!/[!@#$%^&*]/.test(password)) {
return "Password must contain at least one special character";
} else {
// if password is valid return nothing
return password;
}
};
const validatedPassword = validatePassword(password);
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(validatedPassword, salt);
try {
const user = await pool.query(
`insert into accounts (firstname, lastname,username,password,email) values ($1,$2,$3,$4,$5)`,
[firstname, lastname, username, hashedPassword, email]
);
if (user.rowCount > 0) {
res.status(200).json({ message: "You sign up successfully" });
} else {
res.status(500).json({ message: "Try again registration failed" });
}
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.get("/words/:selectedYears", async (req, res) => {
const selectedYears = req.params.selectedYears;
try {
const allWords = await pool.query(
`SELECT word_id, ${selectedYears} FROM spelling_table`
);
res.status(200).json(allWords.rows);
} catch (err) {
console.error(err);
res.status(500).send(err);
}
});
app.post("/session-Record", async (req, res) => {
const {
userId,
correctSpeltWords,
wrongSpeltWords,
countedCorrectWords,
countedWrongWords,
session_accuracy_percentage,
} = req.body;
console.log(req.body);
try {
// write the insert query
const sessionRecord = await pool.query(
`insert into sessions (user_id,correctWordsList,wrongWordsList,number_of_correct_words,number_of_incorrect_words,session_accuracy_percentage) values ($1,$2,$3,$4,$5,$6)`,
[
userId,
correctSpeltWords,
wrongSpeltWords,
countedCorrectWords,
countedWrongWords,
session_accuracy_percentage,
]
);
sessionRecord.rowCount > 0
? res.status(200).json({ message: "Session recorded successfully" })
: res.status(500).json({ message: "Session Not recorded" });
} catch (error) {
console.error(error);
}
});
app.get("/sessions_data", async (req, res) => {
try {
const getData = await pool.query(`select * from sessions`);
const sessionsData = getData.rows;
res.status(200).json(sessionsData);
} catch (error) {
console.error(error);
res.status(500).json({ error: error });
}
});
app.get("/overall_progress_data/:userId", async (req, res) => {
const userId = +req.params.userId;
console.log(userId);
const userOverallProgressRecord = await pool.query(
`select session_id, session_accuracy_percentage from sessions where user_id = $1`,
[userId]
);
userOverallProgressRecord.rowCount > 0
? res.status(200).send(userOverallProgressRecord.rows)
: res.status(500).json({ message: "record not found" });
try {
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});
app.listen(PORT, () => console.log(`Server is running on ${PORT}`));