-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
134 lines (118 loc) · 4.31 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
//server.js
//==================================--BASE SETUP--============================
//LOAD PACKAGES-------------------------------
var express = require ('express'); //EXPRESS Package
var app = express(); //define our app using express
var bodyParser = require('body-parser');// get body-parser
var morgan = require('morgan'); //use to see requests
var mongoose = require('mongoose') //for working with mongoDB
var config = require('./config'); //get config file
var path = require('path');
var jwt = require('jsonwebtoken');
var User = require(__dirname + '/server//models/user.js');
app.use(morgan('dev')); //HTTP logger
//==================================--APP--====================================
var superSecret = config.secret;
// APP CONFIGURATION------------------------------------------
// use body parser to grab information from POST
app.use(bodyParser.urlencoded({ extended:true}));
app.use(bodyParser.json());
// configure app to handle CORS requests
app.use(function(req,res,next){
res.setHeader('Access-Control-Allow-Orgin','*');
res.setHeader('Access-Control-Allow-Method','GET,POST');
res.setHeader('Access-Control-Allow-Headers','X-Request-With,content-type,\Authorization');
next();
});
//==================================--DB--====================================
mongoose.connect('mongodb://ervijjustyy:vija7898@ds019746.mlab.com:19746/vijjusty');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log('MONGO: successfully connected to db');
});
// set static files location
// used for requests that frontend will make
app.use(express.static(__dirname + '/public'));
//=========================--ROUTES/API--====================================
//API ROUTES
var apiRoutes = require(__dirname + '/server/routes/api')(app,express);
//REGISTER ROUTES----------------------------------------
app.use('/api',apiRoutes); //all /api routes
// MAIN CATCHALL ROUTE-----------------------------------------------------
// SEND USERS TO FRONTEND -------------------------------------------------
// has to be registered after API ROUTES
// set up our one route to the index.html file
// route for the home page
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
//=============================== /authenticate =========================
app.post('/authenticate',function(req, res){
//find the user
//select the name, username and password explicitly
User.findOne({
username: req.body.username
}).select('name username password').exec(function(err,user){
if(err) throw err;
//no user with that username was found
if(!user){
res.json({
success:false,
message:'Authencation failed. User not found.'
});
}else if (user){
//check if password matches
var validPassword = user.comparePassword(req.body.password);
if(!validPassword){
res.json({
success: false,
message: 'Authencation failed. Wrong password.'
});
}else{
//if user is found and password is right
//create a token
var token = jwt.sign({
name: user.name,
username: user.username
}, superSecret , {
expiresIn: 86400 // (24hrs)
// expires in 3600 * 24 = c (24 hours)
});
//return json object, information including token as JSON
res.json({
name: user.name,
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
//================================= /register =============================
app.route('/register')
//create a user (accessed at POST http://localhost:8080/api/register)
.post(function(req,res) {
//create a new instance of the User model
var user = new User();
//set the users information (comes from the request)
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
//save the user and check for errors
user.save(function(err){
if (err){
//duplicate entry
if(err.code == 11000)
return res.json({success: false,
message: 'A user with that\ username already exists.'});
else
return res.send(err);
}
res.json({ message:'User created!' });
});
});
//=========================--START THE SERVER---=========================
app.listen(config.port);
console.log("Magic happens on port" + config.port);