I'm trying to make a login mechanism with jwt but as I'm a newbie, I'm not sure if I'm doing right.
I already made my server.js which looks like this :
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const path = require('path');
require('dotenv').config();
var cors = require('cors');
const app = express();
const port = process.env.PORT || 8600;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
});
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
const adRoutes = require('./routes/adRoutes.js');
app.use('/Advertisements', adRoutes);
const comRoutes = require('./routes/comRoutes.js');
app.use('/Companies', comRoutes);
const userRoutes = require('./routes/userRoutes.js');
app.use('/Users', userRoutes);
const appRoutes = require('./routes/appRoutes.js');
app.use('/Applications', appRoutes);
const appAuth = require('./routes/loginRoutes.js');
let refreshTokens = [];
app.use('/auth', appAuth);
app.get('/api', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
});
app.post('/auth/token', (req, res) => {
const refrechToken = req.body.token;
if (refrechToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refrechToken)) return res.sendStatus(403);
jwt.verify(refrechToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
}
)
});
app.post('/auth/login', (req, res) => {
const email = req.body.email;
const password = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
const accessToken = generateAccessToken({ email: email });
const refreshToken = jwt.sign(email, process.env.REFRESH_TOKEN_SECRET);
refreshTokens.push(refreshToken);
res.json({ accessToken: accessToken, refreshToken: refreshToken });
});
app.delete('/auth/logout', (req, res) => {
refreshTokens = refreshTokens.filter(token => token !== req.body.token);
res.sendStatus(204);
});
function generateAccessToken(email) {
return jwt.sign(email, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1800s' });
}
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.listen(port)
And I have a login mechanism that works on Postman but without jwt like this :
const express = require('express');
const router = express.Router();
const path = require('path');
const CryptoJS = require('crypto-js');
const UserController = require('../controllers/userController.js');
var con = require("../config.js");
const { log } = require('console');
router.get('/', function(request, response) {
response.sendFile(path.join(__dirname, '../../front', 'login.html'));
});
router.post('/register', (req, res) => {
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
req.body.password = hashedPassword;
UserController.create(req, res);
});
router.post('/login', function(req, res) {
const email = req.body.email;
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
email_ = "\"" + email + "\"";
password_ = "\"" + hashedPassword + "\"";
if (email == "" || hashedPassword == ""){
res.send('Please enter Email and/or Password !');
}
else{
var sql = "SELECT * FROM User WHERE email = " + email_;
con.query(sql, function (err, result) {
if (err) throw err;
if (result.length == 0){
res.send('Incorrect Email !');
}
else{
if (result[0].password == hashedPassword){
req.session.email = result[0].email;
res.send('Login successful!');
}
else{
res.send("Incorrect Password !");
}
}
});
}
});
router.get('/check', function(req, res) {
if (req.session.email) {
console.log(req.session.email);
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.send('Logout successful!');
});
I want to 1. login with token, 2. auto-filled profile using the token and 3. logout system
So that I could make them and that it works on the website, let me know not exact codes but just a mechanism or functions that I need please.
Here's my config.js if you need :
const mysql = require("mysql");
const con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "DB name",
port: "port"
});
con.connect((err) => {
if(err)
{
console.warn("Error in connection: " + err.message);
}
});
module.exports = con;
Related
I have installed express-session before initializing passport yet the passport authenticate doesn't works and it simply redirects to the failureRedirect url without any errors or messages.
i have checked that passport initializing works perfectly just authentication is not working
my index.js file
const ejs = require("ejs");
const url = require("url");
const session = require("express-session");
const cookieParser = require('cookie-parser')
const flash = require('connect-flash');
const toastr = require('express-toastr');
const Profile = require('./models/Profile.js');
const passport = require("passport");
const { customAlphabet } = require('nanoid');
const express = require("express"),
path = require('path')
const app = express();
const port = 3000;
const { Notyf } = require('notyf')
const { connect } = require('mongoose');
const LocalStrategy = require('passport-local');
const MemoryStore = require("memorystore")(session);
const methodOverride = require('method-override')
connect(process.env.mongodb);
const initializePassport = require('./utils/passport-config.js')
initializePassport(
passport,
email => Profile.find({ email_id: email }),
id => Profile.find({ user_id: email })
)
var bodyParser = require('body-parser');
app.use(cookieParser());
app.use(
session({
store: new MemoryStore({ checkPeriod: 86400000 }),
secret: "##%#&^$^$%#$^$&%#$%##$%$^%&$%^#$%##$%#E%#%#$FEErfgr3g#%GT%536c53cc6%5%tv%4y4hrgrggrgrgf4n",
resave: false,
saveUninitialized: false,
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(toastr());
app.use('/assets', express.static(path.join(__dirname, 'assets')))
app.use('/scripts', express.static(path.join(__dirname, 'node_modules')))
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
}),
);
const checkAuth = (req, res, next) => {
try {
if (req.isAuthenticated()) return next();
req.session.backURL = req.url;
res.redirect("/login");
} catch (e) {
console.log(e)
}
};
app.get('/', async function(req, res){
res.render('index.ejs', { url: req.url })
});
app.get('/login', async function(req, res){
if (req.session.backURL) {
req.session.backURL = req.session.backURL;
} else if (req.headers.referer) {
const parsed = url.parse(req.headers.referer);
if (parsed.hostname === app.locals.domain) {
req.session.backURL = parsed.path;
}
} else {
req.session.backURL = "/";
}
res.render('login.ejs', { url: req.url })
});
app.get('/signup', async function(req, res){
res.render('signup.ejs', { url: req.url })
});
app.get('/newshop', async function(req, res){
res.render('shopcreate.ejs', { url: req.url })
});
app.get('/profile', async function(req, res){
res.render('profile.ejs', { url: req.url })
});
app.get('/settings', async function(req, res){
res.render('settings.ejs', { url: req.url })
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
}), async (
err,
req,
res,
next,
) => {
try {
await console.log(req)
if (req.session.backURL) {
const backURL = req.session.backURL;
req.session.backURL = null;
res.redirect(backURL);
} else {
res.redirect('/');
}
} catch(e) {
console.log(e)
}
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
my passport-config.js file -
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
console.log(email)
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, { message: 'User not found' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
I have an express application set up to use a filesystem which contains a folder for each user.
app.use(express.static(mainFolder));
The problem is that I can't seem to restrict users from viewing each others files.
In account A, I have a folder for photos
mainFolder > AccountA > Photos > thePhoto.png
However, After I log into account B I can access this photo by typing in
localhost:8080/AccountA/Photos/thePhoto.png
I have already created a middleware to check that the user is logged in and this stops anyone not logged in from viewing the photo. Now I need a to restrict each user from viewing other accounts files/photos etc.
I am aware that I could do
app.use(express.static(mainFolder/accountA));
However I would have to this for each user. Could I put this in the authentication route so that after a user has authenticated the app uses this file?
I have also looked at How to serve user specific static content in Express.js and this does not help.
Here is the code for my middleware:
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next()
} else if(req.url != "/login" && req.url != "/register" && req.url != "/register?" && req.originalUrl != "/register?" ){
res.redirect('/login');
} else if(req.url === "/login" || req.url === "/register" || req.url === "/register?" || req.originalUrl === "register"){
return next()
}
}
Here is my app.js
//------------------------------------------------------
// STORAGE SITE SERVER SIDE
//------------------------------------------------------
// Matthew Haywood
var path = require("path")
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var fs = require("fs-extra");
var methodOverride = require("method-override");
var passport = require("passport");
var session = require('express-session')
var flash = require('express-flash');
var bcrypt = require('bcryptjs');
var csv = require('csv-parser');
var schedule = require('node-schedule');
const { exec } = require('child_process');
var sanitizer = require('sanitize')();
var os = require('os-utils');
var addScheduledWorkflowFromFile = require('./routes/workflow/workflowRoutes').addScheduledWorkflowFromFile;
var middleware = require("./middleware/index");
var workflowRoutes = require('./routes/workflow/workflowRoutes').router;
var storageRoutes = require('./routes/storage/storageRoutes').router;
var codeRoutes = require('./routes/code/codeRoutes').router;
global.testFolder;
//Configure the app based on whether its development or production
if (process.env.NODE_ENV === 'production') {
testFolder = '/media/pi/ELEMENTS\ B/';
string_len = 22;
production_flag = true
}
if (process.env.NODE_ENV === 'development') {
testFolder = '/Users/matthaywood/Desktop/StorageSite/StorageSite/public/'
string_len = 59;
}
//PASSPORT SETUP
const initializePassport = require('./passport-config');
const { stdout, allowedNodeEnvironmentFlags } = require("process");
const { timeStamp } = require("console");
const { ResultWithContext } = require("express-validator/src/chain");
initializePassport(
passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(flash())
app.use(session({
secret: "Once again rusty is the cutest dog",
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride("_method"));
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
next();
});
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next()
} else if(req.url != "/login" && req.url != "/register" && req.url != "/register?" && req.originalUrl != "/register?" ){
res.redirect('/login');
} else if(req.url === "/login" || req.url === "/register" || req.url === "/register?" || req.originalUrl === "register"){
return next()
}
}
function checkUser(req,res,next){
if(req.body.currentPath != undefined){
console.log('CheckUser function ' + req.body.currentPath)
var endDir = req.body.currentPath.replace(testFolder, '');
var user = endDir.split('/')[1]
if(user == req.user.name){
console.log("USER " + user + " AUTHORISED FOR " + req.body.currentPath + " DIRECTORY")
return next()
} else {
res.redirect("/Unauthorised");
return "Failed";
}
} else {
next();
}
}
app.use(checkAuthenticated);
app.use(checkUser);
global.users = [];
global.scheduledWorkflows = []
//LOAD USERS IN FROM JSON FILE
var loadedData = JSON.parse(fs.readFileSync("users.json"))
console.log(loadedData.Users)
users = loadedData.Users
addScheduledWorkflowFromFile()
app.use(express.static(__dirname + "/public"));
app.use('/modules', express.static("modules"));
app.use("/", workflowRoutes);
app.use("/", storageRoutes);
app.use("/", codeRoutes);
//----------------------------------------------------------
// ROUTES
//----------------------------------------------------------
app.get("/", function (req, res) {
res.render("clusterHome.ejs");
})
//Settings Route for displaying current connected HDD
app.get("/settings", function (req, res) {
res.render("settings.ejs");
})
//--------------------------------------------------------------------
// ROUTES FOR USERS AND LOGIN
//--------------------------------------------------------------------
//Register
app.get("/register", function (req, res) {
res.render("register.ejs");
})
app.post("/register", function (req, res) {
var password = req.body.password;
// var name = sanitizer.value(req.body.name,String);
var name = req.body.name;
// var email = sanitizer.value(req.body.email,String);
var email = req.body.email;
var the_hash;
console.log('CREATING NEW ACCOUNT')
bcrypt.hash(password, 10, function (err, hash) {
console.log(err)
the_hash = hash;
the_id = Date.now().toString();
users.push({
id: the_id,
name: name,
email: email,
password: hash
})
fs.mkdirSync(testFolder + name);
fs.mkdirSync(testFolder + name + "/" + "Workflows");
fs.mkdirSync(testFolder + name + "/Workflows/Logs" );
fs.mkdirSync(testFolder + name + "/" + "Code");
var data = JSON.parse(fs.readFileSync("users.json"))
data.Users.push({
id: the_id,
name: name,
email: email,
password: hash
})
data = JSON.stringify(data, null, 2)
fs.writeFileSync("users.json", data)
passport.authenticate('local')(req, res, function () {
res.redirect("/");
})
if (err) {
console.log(err)
res.redirect('/register');
}
})
})
//----------------------------------------------------------
// LOGIN/LOGOUT ROUTES
//----------------------------------------------------------
app.get("/login", function (req, res) {
res.render("login.ejs");
})
app.post("/login", passport.authenticate('local'), function (req, res) {
app.use(express.static(testFolder+"/"+req.user.name));
res.redirect("/");
})
//Logout
app.delete("/logout", function (req, res) {
req.logOut();
res.redirect('/login')
})
//Unauthorised Route
app.get("/unauthorized", function(req, res){
res.render("unauthorised.ejs");
})
//----------------------------------------------------------
// LOG ROUTES
//----------------------------------------------------------
app.get("/logs", function (req, res) {
res.render("logs.ejs")
})
app.get("/logs/get-data", function (req, res) {
os.cpuUsage(function (v) {
res.status(200).send({ cpuUsage: v })
});
})
//----------------------------------------------------------
// AUTO GIT PULL SCHEDULE
//----------------------------------------------------------
//Only run this job if in production to pull from github
if (process.env.NODE_ENV === 'production') {
const job = schedule.scheduleJob('*/5 * * * *', function () {
exec('git pull', (err, stdout, stderr) => {
if (err) {
console.log(err);
} else {
console.log("Pulling from git repository")
console.log(stdout)
//Restart server if git has pulled changes
if(!stdout.includes("Already up to date.")){
process.exit(1)
}
}
})
})
}
function serverLog(string){
//function used to log to a file
}
app.listen("8080");
my problem is that I want to access to the user who is logged in. All users are saved in a database and then SELECTED into a variable.
In the passport-config-js I am checking the login by comparing the email and the hashed password. So I hope you all can help me, I need this for a school project.
severs.js
const express = require('express');
const app = express();
const bcrypt = require('bcrypt');
const passport = require('passport');
const flash = require('express-flash');
const session = require('express-session');
const methodOverride = require('method-override');
const initializePassport = require('./passport-config');
initializePassport(
passport,
email => users.find(user => user["email"] === email),
id => users.find(user => user["id"] === id)
)
const users = [];
app.set('view-engine', 'ejs');
app.use(express.urlencoded({extended: false}))
app.use(flash());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride('_method'));
app.use(express.static("public"))
app.get('/' , checkAuthenticated,(req, res) => {
res.render('startseite.ejs')
})
app.get('/login', checkNotAuthenticated ,(req, res) =>{
res.render('login.ejs');
})
app.post('/login', checkNotAuthenticated ,passport.authenticate('local',
{
successRedirect: '/startseite',
failureRedirect: '/login',
failureFlash: true
})
)
app.get('/startseite',checkAuthenticated,(req, res) =>{
res.render('startseite.ejs', {email: req.body.email});
console.log(req.body);
})
app.post('/register', checkNotAuthenticated,async (req, res, next) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
let newUser = {
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
}
if(users.length){
for(let i = 0; i < users.length; i+
if(req.body.email === users[i].email){
console.log(users[i].email + " email already taken");
alert("Email already taken");
res.render('/register');
}
}
}
let sql = `INSERT INTO Players (email, name, password) VALUES ('${newUser.email}', '${newUser.name}', '${newUser.password}')`;
connection.query(sql, (err, result) =>{
if(err) throw err;
console.log("User with email: " + newUser.email + " inserted")
allPlayers();
});
res.redirect('/login');
} catch {
res.redirect('/register');
}
//console.log(users);
})
app.delete('/startseite', (req, res) =>{
req.logOut();
res.redirect('/login');
})
function checkAuthenticated(req, res, next) {
if(req.isAuthenticated()){
return next()
}
res.redirect('/login');
}
function checkNotAuthenticated(req, res, next) {
if(req.isAuthenticated()){
return res.redirect('/');
}
next();
}
function allPlayers(){
let userList = query("*");
userList
.then()
.then((values) =>{
let i = 0;
while(values[i] != null){
users.push(values[i]);
i++;
}
//console.log(users);
})
}
allPlayers();
app.listen(3000);
passport-config.js
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const {connection, select, query} = require('./db');
function initialize(passport, getUserByEmail, getUserById){
const authenticateUser = async (email, password, done) =>{
const user = getUserByEmail(email);
if(user == null){
return done(null, false, {message: 'email or password incorrect'});
}
try {
if(await bcrypt.compare(password, user.password)) {
return done(null, user);
} else {
return done(null, false, {message: 'email or password incorrect'})
}
} catch(e) {
return done(e)
}
}
passport.use(new LocalStrategy({usernameField: 'email'},
authenticateUser));
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {return done(null, getUserById(id))})
}
module.exports = initialize;
I'm learning Node.js and I'm finding some troubles with redirecting the user to an :id path. I would like to print there his username.
So to make an overview it is a landing page with a form where I ask for an Alias and an email. When user clicks submit I'd like to move him to /:id path to print its' username.
My code is the following:
var express = require("express"),
app = express(),
request = require("request"),
mongoose = require("mongoose"),
bodyParser = require("body-parser");
app.set("view engine", "ejs")
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost/Scape_Room", {useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new mongoose.Schema({
email: String,
alias: String,
});
var user = mongoose.model ("user",userSchema);
app.get("/", function(req, res){
res.render("index")
})
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect("/start/:id")
}
})
})
app.get("/start/:id", function(req,res){
user.findById(req.params.id, function(err, foundUser){
if(err){
console.log(err)
} else{
res.render("startPoint", {user:foundUser})
}
})
})
app.listen(3000, function(err){
console.log("Server listening")
})
error is the following: { CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "user"
I've tried:
- to change the path to :_id
- added start/ into the route
When you are using the redirect() method, you must pass a real route url not an id.
const express = require("express")
const request = require("request");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs")
app.use(express.static("public"));
mongoose.connect("mongodb://localhost/Scape_Room", { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
email: String,
alias: String,
});
const user = mongoose.model("user", userSchema);
app.get("/", function (req, res) {
res.render("index");
});
app.post("/newuser", function (req, res) {
const { name, email } = req.body;
if (!name || !email) {
return res.end();
}
const newUser = { name: name, email: email }
user.create(newUser, function (err, newlyUser) {
if (err) {
console.log(err);
return res.end();
}
if (!newlyUser) {
console.log("Couldn't save user!");
return res.end();
}
if (!newlyUser.id) {
console.log("No user id found");
return res.end();
}
res.redirect(`/start/${newlyUser.id}`);
});
});
app.get("/start/:id", function (req, res) {
user.findById(req.params.id, function (err, user) {
if (err) {
console.log(err);
} else {
res.render("startPoint", { user });
}
})
})
app.listen(3000, function (err) {
console.log("Server listening")
});
Use something like below
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect(`/start/${newlyUser._id}`)
}
})
})
I am trying to remove the # sign on the URL using html5mode by stating the location provider html5mode to true
$locationProvider.html5Mode(true);
I also did configured my server.js file to serve my static files and my index.html as below
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
port = process.env.PORT || 8080;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen('8080');
console.log('The magic happens on port 8080');
At this point, everything works fine from localhost:8080 to other navigation such as localhost:8080/login even when I refreshed the page, it is still working fine.
It it not working during any API fetch statement is being called. Below is my routes.js
route.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db);
User = require('./models/user.js')(db);
module.exports = function(app) {
app.route('/api/user')
.get(function(req, res, next) {
User.find(function(err, user){
if(err)
res.json(err);
res.json(user);
});
})
.post(function(req, res, next) {
var error_return = [{response:'User Existed'},{response:'Invalid Username or Password'},{response:'Server Error'}];
if(req.body.type === "local"){
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
newUser.save(function(error, result){
if(error)
res.json(error_return[2]);
res.json({response:result});
});
return;
}
res.json(error_return[0]);
});
}else if(req.body.type === "login"){
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)){
res.json(error_return[1]);
return;
}
res.json({response:user});
});
}
});
};
Previously before enabling html5mode, my files in require('./app/routes.js')(app); is running smoothly, after enabling, it is not even being called. Have I missing something in my code?
All your requests are going to public/index.html right now.
Modify your code to allow /api/ requests to go to the routes
app.use('/api', bodyParser.json(), require('./app/routes.js'));
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.listen('8080');
console.log('The magic happens on port 8080');
routes.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db),
User = require('./models/user.js')(db),
router = require('express').Router();
module.exports = router;
router.route('/user')
.get(function (req, res, next) {
User.find(function (err, user) {
if (err) res.json(err);
res.json(user);
});
})
.post(function (req, res, next) {
var error_return = [{
response: 'User Existed'
}, {
response: 'Invalid Username or Password'
}, {
response: 'Server Error'
}];
if (req.body.type === "local") {
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
newUser.save(function (error, result) {
if (error) res.json(error_return[2]);
res.json({
response: result
});
});
return;
}
res.json(error_return[0]);
});
} else if (req.body.type === "login") {
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)) {
res.json(error_return[1]);
return;
}
res.json({
response: user
});
});
}
});