Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
2
Indexable
Never
const accountmodel = require('../../models/account')
const bcrypt = require('bcrypt');
const saltRounds = 10;
const salt = bcrypt.genSaltSync(saltRounds);

// session handler
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const app = express();
app.use(session({
    secret: 'keyboard cat',
    saveUninitialized: true, 
    resave: true, 
    cookie: { secure: true },
    store: MongoStore.create({ 
        mongoUrl: 'mongodb://localhost/toy_store_dev',
        ttl: 3 * 60 * 60, // 60 seconds * 60 minutes * 3 hours
     })
  }));


class registercontroller {
    // [post] /action/register
    register(req, res, next){
       var user = req.body.username
       var pass =  req.body.password
       const hash = bcrypt.hashSync(pass, salt);
        accountmodel.findOne({ username:user})
            .then(data=> {
                if(data){
                    res.json('already exitsed user')
                }
                else{
                    accountmodel.create({
                               username : user,
                               password : hash // store hash password in database
                           })
                }
            })
            .then(data=> {
                res.json("success created an account");
            })
            .catch(err=> {
                res.status(500).json("failed to create an account");
            })
    }
    //[post] /action/login
    login(req, res,next){
        var user = req.body.username;
        var pass = req.body.password;
        const hash = bcrypt.hashSync(pass, salt);
        var check = bcrypt.compareSync(pass, hash); // true
        if(check){
            accountmodel.findOne({ username:user})
        .then(data=> {
            if(data){
                res.json(data);
                //req.session.isAuth = true;
                res.redirect('/adminmanage');

            }
            else{
                res.status(300).json('account khong dung');
            }
        })
        .catch(err => {
            res.json('co loi ben server');
        })
        }
    }
}
module.exports = new registercontroller();