Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flash messages #40

Merged
merged 3 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,20 @@ const path = require('path'); // Core Node.js module to handle and transform fil
const cookieParser = require('cookie-parser'); // Middleware to parse and set cookies in request objects
const logger = require('morgan'); // HTTP request logger middleware for node.js
const session = require('express-session');
var flash = require('connect-flash');

// DB Modules
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/minitwit.db'); // todo This needs to be set up in an init function with error handling instead
const fs = require('fs');
const sqlFilePath = path.join(__dirname, 'db', 'schema.sql');
const sql = fs.readFileSync(sqlFilePath, 'utf8');

const flash = require('connect-flash');


// Initialize database schema
const db = require('./db/database');

db.initSchema()
.then(() => {
console.log('Database schema initialized successfully.');
})
.catch((err) => {
console.error('Error initializing database schema:', err);
});


// Import routers for different paths
Expand Down
33 changes: 33 additions & 0 deletions db/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const sqlite3 = require('sqlite3').verbose();
const fs = require('fs');
const path = require('path');

class Database {
constructor() {
if (!Database.instance) {
this.db = new sqlite3.Database('./db/minitwit.db');
Database.instance = this;
}
return Database.instance;
}

getDb() {
return this.db;
}

async initSchema() {
const sqlFilePath = path.join(__dirname, 'schema.sql');
const sql = fs.readFileSync(sqlFilePath, 'utf8');
return new Promise((resolve, reject) => {
this.db.exec(sql, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}

module.exports = new Database();
31 changes: 18 additions & 13 deletions routes/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ var router = express.Router();
const bcrypt = require('bcrypt');
const sqlite3 = require('sqlite3').verbose();
var session = require('express-session');
const db = require('../db/database');

router.use(session({
secret: 'devving-and-opssing',
Expand All @@ -16,18 +17,22 @@ router.use(function (req, res, next) {
next();
})

// Database connection
let db = new sqlite3.Database('./db/minitwit.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the minitwit.db');
}
});
// If user is logged in, return id and username from session, otherwise empty user
// Use the returned value to populate views
function getUserCredentialsFromSession(req) {
if (req.session.username) {
return {
user: {
id: req.session.username.id,
username: req.session.username.username
}
}
} return { user: {} }
}

/* GET login page. */
router.get('/', function (req, res) {
const g = { user: req.session.username };
const g = getUserCredentialsFromSession(req);
res.render('login', { title: 'Login', g: g });
});

Expand All @@ -42,13 +47,13 @@ router.post('/', (req, res, next) => {

// Check user in DB
const sql = 'SELECT * FROM user WHERE username = ?';
db.get(sql, [username], (err, user) => {
db.getDb().get(sql, [username], (err, user) => {
if (err) {
console.error(err.message);
return res.status(500).send('Server error');
}
if (!user) {
req.flash('error', 'Invalid username or password');
req.flash('error', 'Invalid username');
res.redirect('/login');
} else {
bcrypt.compare(password, user.pw_hash, (err, result) => {
Expand All @@ -65,8 +70,8 @@ router.post('/', (req, res, next) => {
req.flash('success', 'You were logged in');
return res.redirect('/');
} else {
// Passwords dont match
return res.status(400).send('Invalid username or password');
req.flash('error', 'Invalid password');
return res.redirect('/login');
}
});
}
Expand Down
62 changes: 57 additions & 5 deletions routes/register.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,37 @@
var express = require('express');
var router = express.Router();
const bcrypt = require('bcrypt');
const session = require('express-session');
const UserService = require('../services/userService');
const userService = new UserService();

router.use(session({
secret: 'devving-and-opssing',
resave: false,
saveUninitialized: true
}));


router.use(function (req, res, next) {
res.locals.success_messages = req.flash('success');
res.locals.error_messages = req.flash('error');
next();
})

function getUserCredentialsFromSession(req) {
if (req.session.username) {
return {
user: {
id: req.session.username.id,
username: req.session.username.username
}
}
} return { user: {} }
}

/* GET register page. */
router.get('/', function (req, res, next) {
const g = { user: req.session.username };
const g = getUserCredentialsFromSession(req);
res.render('register', { title: 'Register', g: g });
});

Expand All @@ -25,7 +50,29 @@ const validateEmail = (email) => {
};

router.post('/', async function (req, res, next) {
const { username, email, password } = req.body;
const { username, email, password, password2 } = req.body;

const validEmail = validateEmail(email);

if (password != password2) {
req.flash('error', 'The two passwords do not match')
return res.redirect('/register')
}

if (!username) {
req.flash('error', 'You have to enter a username')
return res.redirect('/register')
}

if (!validEmail) {
req.flash('error', 'You have to enter a valid email address')
return res.redirect('/register')
}

if (!password) {
req.flash('error', 'You have to enter a password')
return res.redirect('/register')
}

const validEmail = validateEmail(email);

Expand All @@ -38,15 +85,20 @@ router.post('/', async function (req, res, next) {
const emailExists = await userService.getUserIdByEmailIfExists(email);
const usernameExists = await userService.getUserIdByUsernameIfExists(username);

if (emailExists || usernameExists) {
req.flash('error', 'User already exists');
if (emailExists) {
req.flash('error', 'That email is taken');
return res.redirect('/register')
}

if (usernameExists) {
req.flash('error', 'The username is already taken')
return res.redirect('/register')
}

const hashedPassword = await bcrypt.hash(password, 10);
await userService.registerUser(username, email, hashedPassword);

req.flash('success', 'You were registered, please login')
req.flash('success', 'You were successfully registered and can login now')
return res.redirect('/login');
} catch (err) {
console.error(err);
Expand Down
Loading