-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
96 lines (86 loc) · 2.46 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
const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const user = require("./models/users");
const database_url = process.env.DBURL;
const JWT_secret = process.env.JWT;
try {
mongoose.connect(database_url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
} catch (error) {
console.log("Moongoose connection error");
}
const app = express();
app.use(express.static("public"));
app.use(express.json());
//user login ....................
app.post("/api/login", async (req, res) => {
const { username, password } = req.body;
const User = await user.findOne({ user_id: username }).lean();
console.log(User);
if (!User) {
return res.json({ status: "error", error: "Invalid username/password" });
}
if (await bcrypt.compare(password, User.password)) {
const token = jwt.sign(
{
id: User._id,
username: User.user_name,
},
JWT_secret
);
return res.json({ status: "ok", data: token });
}
res.json({ status: "error", error: "Invalid username/password" });
});
// user registration................
app.post("/api/register", async (req, res) => {
const { name, username, password: plainTextPassword } = req.body;
console.log(name, username, plainTextPassword);
if (!username || typeof username !== "string") {
return res.json({
status: "error",
error: "Invalid username!",
});
}
if (!plainTextPassword || typeof plainTextPassword !== "string") {
return res.json({
status: "error",
error: "Invalid password!",
});
}
if (plainTextPassword.length < 5) {
return res.json({
status: "error",
error: "Password too small",
});
}
const password = await bcrypt.hash(plainTextPassword, 15);
try {
const response = await user.create({
user_id: username,
password: password,
user_name: name,
});
res.json({ status: "ok" });
console.log(` User created successfully --${response}`);
} catch (error) {
console.log(JSON.stringify(error));
if (error.code === 11000) {
// console.log('Email already registered!')
return res.json({
status: 409,
error: "Email already registered!",
});
}
throw error;
}
});
app.listen(process.env.PORT, () => {
console.log(`The server is up and running on port http://localhost:${process.env.PORT}`);
});