Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var sqlite = require('sqlite3').verbose();
- var db = new sqlite.Database('../users.db');
- var bcrypt = require('bcrypt');
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var port = process.env.PORT || 3000;
- var path = require('path');
- var cookieParser = require('cookie-parser');
- var session = require('express-session');
- var cors = require('cors');
- app.use(cors());
- app.use(cookieParser());
- app.use(session({ secret: 'robbieisawesome', resave: true, saveUninitialized: true }));
- app.use(bodyParser.urlencoded({extended: true}));
- app.set('view engine', 'ejs');
- app.get('/', function(req, res) {
- var stat = 'You are not logged in.';
- if (req.session.userName) stat = 'You are logged in as ' + req.session.userName + '.';
- res.render('index', { status: stat });
- });
- app.post('/auth', function(req, res) {
- var user = req.body.user.toLowerCase();
- var pass = req.body.pass;
- var status = {type: 'auth', status: null};
- db.serialize();
- db.get('SELECT passhash FROM users WHERE username=?', user, function(err, row) {
- if (row) {
- if (bcrypt.compareSync(pass, row.passhash)) {
- req.session.user = user;
- res.redirect(301, '/');
- console.log('Account ' + user + ' authenticated successfully.');
- } else {
- res.writeHead(401, {'Content-Type': 'text/plain'});
- res.end('Password incorrect');
- console.log('Someone tried to log into the account ' + user + ' with an incorrect password.');
- }
- } else {
- res.writeHead(401, {'Content-Type': 'text/plain'});
- res.end('Nonexistent user');
- console.log('Someone tried to log into the nonexistent account ' + user + '.');
- }
- });
- });
- console.log('Authentication bound');
- app.post('/create', function(req, res) {
- var user = req.body.user.toLowerCase();
- var pass = req.body.pass;
- var salt = bcrypt.genSaltSync(10);
- var hash = bcrypt.hashSync(pass, salt);
- var status = {type: 'create', status: null};
- db.serialize();
- db.run('INSERT INTO users VALUES (?,?)', user, hash, function(err) {
- if (err) {
- res.writeHead(401, {'Content-Type': 'application/json'});
- status.status = 'exists';
- res.end(JSON.stringify(status));
- console.log('Someone attempted to create the already-existent account ' + user + '.');
- } else {
- res.writeHead(200, {'Content-Type': 'application/json'});
- status.status = 'success';
- res.end(JSON.stringify(status));
- console.log('The account ' + user + ' was created successfully.');
- }
- });
- });
- console.log('Registration bound');
- app.listen(port);
- console.log('Listening on *:' + port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement