Adding Login Functionality
// routes/users.js const express = require('express'); const vdict = require('../config'); const router = express.Router(); const usersdb = require('../models/usersdb') router.get('/', function(req, res, next){ if(req.session.user) res.send('dashboard'); else res.redirect('/users/login'); }); router.get('/login', function(req, res, next){ res.render('login', vdict); }); router.post('/login', function(req, res, next){ usersdb.users.findOne({username:req.body.username}, function (err, user){ if (err) return console.error(err); if(user){ if(usersdb.bcrypt.compareSync(req.body.password, user.password)){ req.session.user = user.username; vdict.message = ''; res.send('dashboard'); }else{ vdict.message = 'ពាក្យសំងាត់មិនត្រឹមត្រូវទេ'; res.redirect('/users/login'); } }else{ vdict.message = 'ឈ្មោះអ្នកប្រើប្រាស់មិនត្រឹមត្រូវទេ'; res.redirect('/users/login'); } }); }); module.exports = router;
// models/usersdb.js class Usersdb{ constructor(){ const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const usersSchema = new mongoose.Schema({ username: {type: String, required: true}, password: {type: String, required: true}, email: {type: String, required: true}, role: {type: String, required: true}, date: {type: Date, required: true} }); const users = mongoose.model('users', usersSchema); this.users = users; this.bcrypt = bcrypt; users.findOne(function (err, user){ if (err) return console.error(err); if(!user){ const hash = bcrypt.hashSync('password', 12); const root = new users({username:'root', password:hash, email:'root@multimedia.com', role:'Admin', date: new Date()}); root.save(function (err, root){ if (err) return console.error(err); }); } }); } checkUser(user){ } }//end class module.exports = new Usersdb();
<!--views/index.ejs--> <%- include('partials/head') %> <%- include('partials/header') %> <link rel='stylesheet' href='/stylesheets/index.css' /> <link rel='stylesheet' href='/stylesheets/login.css' /> <script src='/javascripts/utility.js'></script> <section class="login region"> <form id="login" action="/users/login" method="post"> <span>ឈ្មោះអ្នកប្រើប្រាស់ៈ</span><input type="text" name="username" required /> <span>ពាក្យសំងាត់ៈ</span><input type="text" name="password" required /> <span></span><input type="submit" value="បញ្ជូន" /> </form> <div style="text-align:center;" class="message"><%- message %></div> </section> <%- include('partials/footer.ejs') %>
/* public/stylesheets/login.css */ .login{ background:lightgrey; border-radius:3px; max-width:450px; } #login{ display:grid; grid-template-columns: 30% auto; grid-gap:5px; margin:30px auto 0; padding:20px; } #login span{ text-align:right; } #login input[type=text]{ padding:0 5px; } #login input[type=submit]{ font:14px/1.5 OdorMeanChey; }
GitHub: "https://github.com/Sokhavuth/multimedia
Heroku: https://khmerweb-multimedia.herokuapp.com/
Comments
Post a Comment