-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (62 loc) · 1.93 KB
/
server.js
File metadata and controls
68 lines (62 loc) · 1.93 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
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const User = require("./models/User");
var mongoDB = process.env.MONGO_URL || "mongodb://localhost:27017/data_viz";
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true,})
.then(() => console.log("connected to database"))
.catch(() => console.error("error : ", err))
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post("https://data-visualization-maker-tool.herokuapp.com/signup", async(req, res, next) => {
const newUser = new User({
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 10)
})
await newUser.save(err => {
if (err) {
return res.status(400).json({
title: "error",
error: "email in use"
})
}
return res.status(200).json({
title: "signup success"
})
})
})
app.post("https://data-visualization-maker-tool.herokuapp.com/loginUser", (req, res, next) => {
User.findOne({ email: req.body.email }, (err, user) => {
if (err) return res.status(500).json({
title: "server error",
error: err
})
if (!user) {
return res.status(401).json({
title: "user not found",
error: "invalid credentials"
})
}
if (!bcrypt.compareSync(req.body.password, user.password)) {
return res.status(401).json({
tite: "login failed",
error: "invalid credentials"
})
}
let token = jwt.sign({ userId: user._id}, "secretkey");
return res.status(200).json({
title: "login sucess",
token: token
})
})
})
const port = process.env.PORT || 5000;
app.listen(port, (err) => {
if (err) return console.log(err);
console.log("server running on port " + port);
})