-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
143 lines (132 loc) · 4.13 KB
/
Copy pathapp.js
File metadata and controls
143 lines (132 loc) · 4.13 KB
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
const bcrypt = require("bcrypt");
// require jwt (jasonwebtoken)
const jwt = require("jsonwebtoken");
// require database connection
const dbConnect = require("./db/dbConnect");
// importing/requiring usermodel
const user = require("./db/userModel");
// execute database connection
dbConnect();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const auth = require("./auth");
// Handle CORS Errors
// curb cores Error by addding a header here
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
next();
});
// body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (request, response, next) => {
response.json({ message: "Hey! This is your server response!" });
next();
});
// Creating register Endpoint
app.post("/register", (request, response) => {
// Hashing the password before saving the email and password
bcrypt
.hash(request.body.password, 10)
.then((hashedpassword) => {
// create a new user instance and collect the data
const user = new User({
email: request.body.email,
password: hashedpassword,
});
// Saving the new user
user
.save()
// return the success if the new user is added to the database
.then((result) => {
response.status(201).send({
message: "User created Successfully.",
result,
});
})
// catch error if the new user wasn't added successfully
.catch((error) => {
response.status(500).send({
message: "Error Creating user",
error,
});
});
})
// catch erro if the password has isn't successful
.catch((e) => {
response.status(500).send({
message: "Password was not hashed successfully",
e,
});
});
});
// Creating Login Endpoint
app.post("/login", (request, response) => {
// Checking if the email that the user enters on login exists
// Using a then...catch... block to check if the email search
// above was successful or not. If it is unsuccessful, capture
// that in the catch block. If successful, compare the password
// entered with the hashed password in the database.
User.findOne({ email: request.body.email })
.then((user) => {
bcrypt
.compare(request.body.password, user.password)
.then((passwordCheck) => {
// check if password matches
if (!passwordCheck) {
return response.status(400).send({
message: "Passwords does not match",
error,
});
}
// if the password matches, generate a random token with the
// jwt.sign() function. It takes 3 parameters:
// jwt.sign(payload, secretOrPrivateKey, [options, callback])
// Read more: https://www.npmjs.com/package/jsonwebtoken#usage
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
// return success response
response.status(200).send({
message: "Login Successful",
email: user.email,
token,
});
})
.catch((error) => {
response.status(400).send({
message: "Passwords does not match",
error,
});
});
})
.catch((e) => {
response.status(404).send({
message: "Email not found",
e,
});
});
});
// free endpoint
app.get("/free-endpoint", (request, response) => {
response.json({ message: "You are free to access me anytime" });
});
// authentication endpoint
app.get("/auth-endpoint", auth, (request, response) => {
response.json({ message: "You are authorized to access me" });
});
module.exports = app;