forked from huseyinbabal/token-based-auth-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
120 lines (108 loc) · 3.3 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
// Required Modules
var express = require("express");
var morgan = require("morgan");
var bodyParser = require("body-parser");
var jwt = require("jsonwebtoken");
var mongoose = require("mongoose");
var app = express();
var port = process.env.PORT || 3001;
var User = require('./models/User');
// Connect to DB
mongoose.connect(process.env.MONGO_URL);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
app.post('/authenticate', function(req, res) {
User.findOne({email: req.body.email, password: req.body.password}, function(err, user) {
if (err) {
res.json({
type: false,
data: "Error occured: " + err
});
} else {
if (user) {
res.json({
type: true,
data: user,
token: user.token
});
} else {
res.json({
type: false,
data: "Incorrect email/password"
});
}
}
});
});
app.post('/signin', function(req, res) {
User.findOne({email: req.body.email, password: req.body.password}, function(err, user) {
if (err) {
res.json({
type: false,
data: "Error occured: " + err
});
} else {
if (user) {
res.json({
type: false,
data: "User already exists!"
});
} else {
var userModel = new User();
userModel.email = req.body.email;
userModel.password = req.body.password;
userModel.save(function(err, user) {
user.token = jwt.sign(user, process.env.JWT_SECRET);
user.save(function(err, user1) {
res.json({
type: true,
data: user1,
token: user1.token
});
});
})
}
}
});
});
app.get('/me', ensureAuthorized, function(req, res) {
User.findOne({token: req.token}, function(err, user) {
if (err) {
res.json({
type: false,
data: "Error occured: " + err
});
} else {
res.json({
type: true,
data: user
});
}
});
});
function ensureAuthorized(req, res, next) {
var bearerToken;
var bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== 'undefined') {
var bearer = bearerHeader.split(" ");
bearerToken = bearer[1];
req.token = bearerToken;
next();
} else {
res.send(403);
}
}
process.on('uncaughtException', function(err) {
console.log(err);
});
// Start Server
app.listen(port, function () {
console.log( "Express server listening on port " + port);
});