Skip to content
Snippets Groups Projects
user.js 1.77 KiB
Newer Older
const express = require('express');

const userApp = express();

const libs = `${process.cwd()}/libs`;

const config = require(`${libs}/config`);

const log = require(`${libs}/log`)(module);

const User = require('../models/user');

const jwt = require('jwt-simple');

userApp.post('/', (req, res) => {
Lucas Gabriel Lima's avatar
Lucas Gabriel Lima committed
    if (!req.body.email || !req.body.password) {
        res.json({success: false, msg: 'Please pass email and password.'});
Lucas Gabriel Lima's avatar
Lucas Gabriel Lima committed
        var newUser = new User({
            email: req.body.email,
            password: req.body.password
        });const jwt = require('jwt-simple');
Lucas Gabriel Lima's avatar
Lucas Gabriel Lima committed
        // save the user
        newUser.save((err) => {
            if (err) {
                return res.json({success: false, msg: 'Email already in use.'});
            }
            res.json({success: true, msg: 'Successful created new user.'});
        });
    }
userApp.post('/authenticate', (req, res) => {
    User.findOne({
        email: req.body.email
    }, (err, user) => {
        if (err) throw err;

        if(!user){
            res.send({success: false, msg: 'Authentication failed. User not found.'});
        }
        else {
            user.comparePassword(req.body.password, (err, isMatch) => {
                if (isMatch && !err) {
                    var secret = config.get('mongodb:secret');

                    // if user is found and password is right create a token
                    var token = jwt.encode(user, secret);

                    //returns user info including token as json
                    res.json({success: true, token: 'JWT ' + token});
                }
                else {
                    res.send({success: false, msg: 'Authentication failed. Wrong password'});
                }
            })
        }
    })
})

module.exports = userApp;