I did read manuals about access to current user via everyauth. It's say, that I can read current user info from: req.user on my server, everyauth.user and user on my views, but they are undefined. But if I'm try get access from, for example, everyauth.twitter or everyauth.facebook, I'm get user info from this social networks.
I'm want, when get user from database (find or create by social data) it's must save in session variable, like currentUser, and i can get it in helpers and in other databare requests.
My app.js code:
var express = require('express')
, everyauth = require('everyauth')
, Promise = everyauth.Promise
, util = require('util')
, mongoose = require('mongoose')
, routes = require('./routes')
, _ = require('underscore')
mongoose.connect('mongodb://127.0.0.1/base');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
// Everyauth settings above that app.configure
everyauth.twitter
.consumerKey('secretKey')
.consumerSecret('secret')
.findOrCreateUser(function (session, accessToken, accessTokenSecret, twitterUserData){
var promise = this.Promise();
User.findOrCreateByUidAndNetwork(twitterUserData.id, 'twitter', twitterUserData, promise);
return promise;
})
.redirectPath('/')
everyauth.facebook
.appId("secretId")
.appSecret("secret")
.findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
var promise = this.Promise();
User.findOrCreateByUidAndNetwork(fbUserMetadata.id, 'facebook', fbUserMetadata, promise);
return promise;
})
.redirectPath('/');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret:'blablabla'}));
app.use(everyauth.middleware()); // Yes, i'm use it
app.use(express.methodOverride());
app.use(app.router); // And it
app.use(express['static'](__dirname + '/public'));
});
everyauth.helpExpress(app); // And this above that routes
app.dynamicHelpers({
currentUser: function (req, res){
return req.user; //it's empty!
}
})
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
require("./controllers/user");
app.listen(80);
And user Scheme:
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var UserSchema = new Schema({
"uid":{type:String},
"name":{type:String},
"network":{type:String},
"profile":{}
});
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
And user find or create function:
this.findOrCreateByUidAndNetwork = function(uid, network, profile, promise) {
User.find({uid: uid, network: network}, function(err, users) {
if(err) throw err;
if(users.length > 0) {
promise.fulfill(users[0]);// <-- what i want:)
} else {
var user = new User();
user.network = network;
user.uid = uid;
user.profile = profile;
user.name = profile.first_name || profile.name;
user.save(function(err) {
if (err) throw err;
promise.fulfill(user);
});
}
});
};
Thanks, for watching my question. Best regards, Asci
Possibly a little late, but for anyone who needs an answer to this -
On Everyauth's Github page it specifies that "To access the user, configure everyauth.everymodule.findUserById". So for example (again quoting bnoguchi) -
everyauth.everymodule
.findUserById( function (id, callback) {
yourApi.fetchUserById(id, function (err, user) {
if (err) return callback(err);
callback(null, user);
});
// or more succinctly, if your api sends a user to the callback with function signature function (err, user):
// yourApi.fetchUserById(id, callback);
});
Related
I am trying to set up a MEAN (mongodb, express, nodejs, angular6(CLI)) app. Trying to post user signup form data to mongo database, but its throwing an error. It is my first MEAN app, trying to learn.
Do I miss something here?
Error: Route.post() requires callback functions but got a [object Undefined]
server.js
Here is server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var app = express();
var api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static(path.join(__dirname + '/dist/meanshopcart')));
app.use('/api', api);
app.post('/sign-up', api.signup);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/meanshopcart/index.html'));
});
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
//app.listen(port, function(){
// console.log("Server is running..!!");
//});
server.listen(port, function(err){
if(err){
return console.log('something bad happened', err);
}
console.log("Server is running..!!");
});
Routes Folder(routes/api.js)
my routes folder ./server/routes/api.js
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/users');
const db = 'mongodb://localhost:27017/meanshopapp';
mongoose.connect(db, function(err){
console.log("mongo connection done");
if(err){
console.log("Error.."+err);
}
});
router.get('/', (req, res)=>{
console.log("get api ");
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
res.send(users);
});
exports.signup = function(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = router;
Model
this is my user schema user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name : { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
phoneNo: { type: Number },
address: { type: String }
});
module.exports = mongoose.model('user', userSchema, 'users');
You are using exports and module.exports.
Either you should follow #dimagolovin's answer
OR
module.exports = {router};
and use
`app.use('/api', api.router);
app.post('/sign-up', api.signup);`
Try to change the follwing in ./server/routes/api.js
function signup(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = {router, signup};
It should do the work
I am having problems trying to access the "DB" database object that is created when the MongoDB client module connects to my MongoDB database.
At the moment I am getting an error stating that, within data.js, 'db' is not defined. I understand why this is - the db object is not being "passed" through to the router and then subsequently through to the controller.
What is the best way to do this?
I have tried to pass the "db" object through to the router (dataRoutes.js) but I cannot figure how to make this accessible to the controller (data.js). Could someone please help?
Please note I have not included the other routes and controllers but they simply submit a Form via the POST method to /data/submit . The controller below is meant to write this form data to the MongoDB database.
Here is the relevant code:
app.js
var express = require('express');
var path = require('path')
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var app = express();
var routes = require('./routes/index');
var dataRoutes = require('./routes/dataRoutes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
MongoClient.connect("mongodb://localhost:27017/m101", function(err, db) {
if(err) throw err;
console.log("Successfully connected to MongoDB.");
app.use('/', routes); // Use normal routes for wesbite
app.use('/data', dataRoutes);
app.get('/favicon.ico', function(req, res) {
res.send(204);
});
app.use(function(req, res, next) {
var err = new Error('Oops Page/Resource Not Found!');
err.status = 404;
next(err); //Proceed to next middleware
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
// update the error responce, either with the error status
// or if that is falsey use error code 500
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.use(function(err, req, res, next) {
console.log('Error');
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Express server listening on port %s.", port);
});
});
dataRoutes.js
// router
var express = require('express');
var router = express.Router();
// controller references
var ctrlsData = require('../controllers/data');
router.post('/submit', ctrlsData.submit);
module.exports = router;
data.js
var MongoClient = require('mongodb').MongoClient;
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.submit = function(req, res) {
var title = req.body.title;
var year = req.body.year;
var imdb = req.body.imdb;
/*
console.log('submitted');
console.log(req.body);
sendJsonResponse(res, 201, {title,year,imdb});
*/
var title = req.body.title;
var year = req.body.year;
var imdb = req.body.imdb;
if ((title == '') || (year == '') || (imdb == '')) {
sendJsonResponse(res, 404, {
"message": "Title, Year and IMDB Reference are all required."
});
} else {
db.collection('movies').insertOne(
{ 'title': title, 'year': year, 'imdb': imdb },
function (err, r) {
if (err) {
sendJsonResponse(res, 400, err);
} else {
sendJsonResponse(res, 201, "Document inserted with _id: " + r.insertedId + {title,year,imdb});
}
}
);
}
};
Create a db variable that reference mongodb in app.js :
MongoClient.connect("mongodb://localhost:27017/m101", function(err, db) {
app.db = db;
//.....
});
In data.js, access db from req.app :
module.exports.submit = function(req, res) {
req.app.db.collection('movies').insertOne({ 'title': title, 'year': year, 'imdb': imdb },
function(err, r) {}
)
};
The accepted answer isn't quite correct. You shouldn't attach custom objects to the app object. That's what app.locals is for. Plus, the accepted answer will fail when using Typescript.
app.locals.db = db;
router.get('/foo', (req) => {
req.app.locals.db.insert('bar');
});
Sure, it's longer. But you get the assurance that future updates to ExpressJS will not interfere with your object.
I understand that the answer of #Bertrand is functional, but it is not usually recommended. The reason being that, from a software point of view, you should have a better separation in your software.
app.js
var express = require('express');
var path = require('path')
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var app = express();
var routes = require('./routes/index');
var dataRoutes = require('./routes/dataRoutes');
var DB = require('./db.js');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
DB.Init("mongodb://localhost:27017/m101")
.then(() => {
console.log("Successfully connected to MongoDB.");
app.use('/', routes); // Use normal routes for wesbite
app.use('/data', dataRoutes);
app.get('/favicon.ico', function(req, res) {
res.send(204);
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Express server listening on port %s.", port);
});
})
.catch((e) => {
console.log("Error initializing db");
});
db.js
var _db = null;
module.exports = {
Init: (url) => {
return new Promise((resolve, reject) => {
if (!url)
reject("You should provide a URL");
MongoClient.connect("mongodb://localhost:27017/m101", function(err, db) {
if(err) reject(err);
_db = db;
resolve(); // Or resolve(db) if you wanna return the db object
});
});
},
Submit: (req, res, next) => {
// Whatever goes. You have access to _db here, too!
}
};
in data.js
var DB = require('../db.js');
router.post('/submit', DB.submit);
Finally, even this answer can be improved as you are not usually advised to wait for the DB to connect, otherwise, you are losing the advantage of using ASync procs.
Consider something similar to here in app.js:
Promise.resolve()
.then(() => {
// Whatever DB stuff are
// DB.Init ?
})
.then(() => {
// Someone needs routing?
})
...
.catch((e) => {
console.error("Ther app failed to start");
console.error(e);
});
I understand that in the last sample, you can not instantly query DB as it may not have connected yet, but this is a server, and users are usually expected to wait for your DB to init. However, if you wanna more proof solution, consider implementing something yourself in DB.submit to wait for the connect. Or, you can also use something like mongoose.
I am trying to implement login through OAuth 2.0, however I can't make my sessions persist, it seems right after a users has been authenticated their session is gone. Also, the app seems to get stuck in routes/bnetauth.js at the redirect in the callback function.
These are the files where I use passport
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
//TOOLS
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session'); //Persistant sessions
var passport = require('passport');
//REQUIRE MODELS
require('./models/News');
require('./models/Application');
//REQUIRE ROUTES
var bnetauth = require('./routes/bnetauth')(passport);
var api = require('./routes/api');
var public = require('./routes/public');
var admin = require('./routes/admin');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/karatechop');
require('./config/passport')(passport);
var app = express();
app.use(express.static('views'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'ilovescotchscotchyscotchscotch', // session secret
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
//Use Routes
app.use('/auth', bnetauth)
app.use('/api', api);
app.use('/admin', admin);
app.use('/', public);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
});
module.exports = app;
routes/bnetauth.js (Logging in through battle.net, hence the bnetauth name)
var express = require('express');
var router = express.Router();
module.exports = function(passport) {
router.get('/bnet',
passport.authenticate('bnet'));
router.get('/bnet/callback',
passport.authenticate('bnet', {
failureRedirect: '/' }),
function(req, res, next){
console.log('Authenticated: ' + req.isAuthenticated())
####THIS IS WHERE IT GETS STUCK####
res.redirect('https://localhost:3000/');
});
config/passport.js
var BnetStrategy = require('passport-bnet').Strategy;
var BNET_ID = 'hidden'
var BNET_SECRET = 'hidden'
var User = require('../models/user')
// expose this function to our app using module.exports
module.exports = function(passport) {
console.log('Entering passport')
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log('Serializing')
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('Deserializing')
done(err, user);
});
});
passport.use(new BnetStrategy({
clientID: BNET_ID,
clientSecret: BNET_SECRET,
region: 'eu',
callbackURL: "https://localhost:3000/auth/bnet/callback"
}, function(accessToken, refreshToken, profile, done) {
console.log(profile)
console.log(accessToken)
User.findOne({id: profile.id}, function(err, user){
console.log("Trying!")
if(err)
return done(err);
if(user) {
return done(null, user);
} else {
var newUser = new User();
newUser.id = profile.id,
newUser.token = accessToken,
newUser.battle_tag = profile.battletag
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
}));
};
return router;
}
I found the solution to my problem!
The problem was in my serialize and deserialize functions in config/passport.js
On my user model, I had two forms of ids.
The _id applied by mongo
The id that I save from the users object passed back to me from battle.net (this is the ID of the user on battle.net).
In serialize, the id that would be used when serializing the user to the session would be the battle.net id (since I was calling user.id and not user._id
Then, in the deserialize when extracting data from the user object, I was using mongo's findById function, which uses the ._id (which is totally different from .id in my user's object, hence it returned 'undefined'.
Changing the .id to ._id in the serialize function solved my problem, and sessions are now working and are persistent.
I am creating a single page application using JavaScript(JQuery) and need to store large video files which size exceed 16Mb. I found that need to use GridFS supporting large files. As I am the new one to MongoDB I am not sure how to use GridFS. There are some good tutorials on creating applications using Node.js, MongoDB and Express but cant find any describing how to use GridFS with MongoDB (not mongoose), Express and Node.js. I managed to put up stuff for uploading files in the BSON-document size limit of 16MB. This is what I have:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var Grid = require('gridfs-stream');
var db = monk('localhost:27017/elearning');
var gfs = Grid(db, mongo);
var routes = require('./routes/index');
var users = require('./routes/users');
var courses = require('./routes/courses');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/courses', courses);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And, for example, the courses file is as the following:
var express = require('express');
var router = express.Router();
/* GET courses listing */
router.get('/courselist', function(req, res) {
var db = req.db;
var collection = db.get('courselist');
collection.find({},{},function(e,docs){
res.json(docs);
})
});
/* POST courses data */
router.post('/courselist', function(req, res) {
var db = req.db;
var collection = db.get('courselist');
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
/* Delete courses data */
router.delete('/courselist/:id', function(req, res) {
var db = req.db;
var collection = db.get('courselist');
var userToDelete = req.params.id;
collection.remove({ '_id' : userToDelete }, function(err) {
res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
});
});
module.exports = router;
I would be extremely grateful for your help, if you could tell how should I edit above files in order to utilize GridFS and be able to get, upload and delete video and picture files from my elearning database.
You can do direct uploading without using mongoose using gridfs-stream as simple as:
var express = require('express'),
mongo = require('mongodb'),
Grid = require('gridfs-stream'),
db = new mongo.Db('node-cheat-db', new mongo.Server("localhost", 27017)),
gfs = Grid(db, mongo),
app = express();
db.open(function (err) {
if (err) return handleError(err);
var gfs = Grid(db, mongo);
console.log('All set! Start uploading :)');
});
//POST http://localhost:3000/file
app.post('/file', function (req, res) {
var writeStream = gfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
//GET http://localhost:3000/file/[mongo_id_of_file_here]
app.get('/file/:fileId', function (req, res) {
gfs.createReadStream({
_id: req.params.fileId // or provide filename: 'file_name_here'
}).pipe(res);
});
app.listen(process.env.PORT || 3000);
for complete files and running project:
Clone node-cheat direct_upload_gridfs, run node app followed by npm install express mongodb gridfs-stream.
OR
Follow baby steps at Node-Cheat Direct Upload via GridFS README.md
Very late but I found previous answer outdated. I'm posting this because this might help newbies like me. To run it, please follow previous answers guide. All credit goes to #ZeeshanHassanMemon.
var express = require('express'),
mongoose = require('mongoose'),
Grid = require('gridfs-stream'),
app = express();
Grid.mongo = mongoose.mongo;
conn = mongoose.createConnection('mongodb://localhost/node-cheat-db');
conn.once('open', function () {
var gfs = Grid(conn.db);
app.set('gridfs', gfs);
console.log('all set');
});
//POST http://localhost:3000/file
app.post('/file', function (req, res) {
var gridfs = app.get('gridfs');
var writeStream = gridfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
//GET http://localhost:3000/file/[mongo_id_of_file_here]
app.get('/file/:fileId', function (req, res) {
var gridfs = app.get('gridfs');
gridfs.createReadStream({
_id: req.params.fileId // or provide filename: 'file_name_here'
}).pipe(res);
});
app.listen(process.env.PORT || 3000);
So I'm following the following Egghead.io guide:
https://egghead.io/lessons/angularjs-finalizing-jwt-authentication-with-angularjs
With a twist, I am trying to incorporate a MongoDB to retrieve my users. I have everything working so far, except the last part where he states that the /me route should just return req.user and it should be fine on refreshes. I don't get that. What I do get is blank user returned from my server.
My server code is setup like this:
var jwtSecret = 'fjkdlsajfoew239053/3uk';
app.use(cors());
app.use(bodyParser.json());
app.use(expressJwt({ secret: jwtSecret }).unless({ path: [ '/login' ]}));
app.use(compression());
app.use(express.static(__dirname + '/client'));
app.get('/', function(req, res){
res.render(__dirname + '/client/bundle.js');
});
app.get('/me', function (req, res) {
res.send(req.user);
});
... setup for user schema and other boring stuff ...
function authenticate(req, res, next) {
var body = req.body;
if (!body.username || !body.password) {
res.status(400).end('Must provide username or password');
}
//do salting, hashing, etc here yo
User.findOne({ username: body.username }, function(err, user){
if (user === null || body.password !== user.password) {
res.status(401).end('Username or password incorrect');
}else{
req.user = user;
next();
}
});
}
// ROUTES
app.post('/login', authenticate, function (req, res, next) {
var token = jwt.sign({
username: req.user.username
}, jwtSecret);
res.send({
token: token,
user: req.user
});
});
app.listen(process.env.PORT || 5000);
And my controller (Client-side) handling the basic authentication is:
module.exports = function($scope, $state, $modal, UserFactory) {
var vm = this;
$scope.$state = $state;
$scope.sign_in = false;
$scope.open = function () {
var $modalInstance = $modal.open({
templateUrl: 'suggestion-modal.html',
controller: 'modalCtrl'
});
};
// initialization
UserFactory.getUser().then(function success(response) {
vm.user = response.data;
});
function login(username, password) {
UserFactory.login(username, password).then(function success(response) {
vm.user = response.data.user;
}, handleError);
}
function logout() {
UserFactory.logout();
vm.user = null;
}
function handleError(response) {
alert('Error: ' + response.data);
}
vm.login = login;
vm.logout = logout;
};
Can anyone catch the bug I'm not seeing here? Basically I have a JWT on the client when I'm logged in but my initialization on the client controller is not recognizing that I'm logged in (it's not setting the user object to anything). It's kinda strange.
So my solution ended up taking into account Kent's help and a little brainstorming. It looked like the following. Note, apparently middleware ordering in express matters a lot since after changing when Express-jwt got loaded made a huge difference in whether or not the authentication headers were checked on initial directory load on the client (which if they were angular wouldn't load and the whole app broke). Cheers!
'use strict';
var faker = require('faker');
var cors = require('cors');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compression = require('compression');
var express = require('express');
var bcrypt = require('bcrypt');
var connectLiveReload = require('connect-livereload');
var jwt = require('jsonwebtoken');
var app = express();
var jwtSecret = 'fjkdlsajfoew239053/3uk';
app.use(cors());
app.use(bodyParser.json());
app.use(compression());
app.use(express.static(__dirname + '/client'));
// app.get('/', function(req, res){
// res.render(__dirname + '/client/bundle.js');
// });
app.use(expressJwt({ secret: jwtSecret }).unless({ path: ['/login']}));
app.get('/me', function (req, res) {
res.send(req.user);
});
...schema stuff...
// UTIL FUNCTIONS
function authenticate(req, res, next) {
var body = req.body;
if (!body.username || !body.password) {
res.status(400).end('Must provide username or password');
}
//do salting, hashing, etc here yo
User.findOne({ username: body.username }, function(err, user){
if (user === null || body.password !== user.password) {
res.status(401).end('Username or password incorrect');
}else{
req.user = user;
next();
}
});
}
// ROUTES
app.post('/login', authenticate, function (req, res, next) {
var token = jwt.sign({
username: req.body.username
}, jwtSecret);
res.send({
token: token,
user: req.user
});
});
// app.use(connectLiveReload()); figure out whats wrong with this later and get livereload working
app.listen(process.env.PORT || 5000);