-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (90 loc) · 3.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
require('dotenv').config();
const express = require('express');
const app = express()
const auth = express.Router()
const bcrypt = require('bcryptjs');
const { connect } = require('http2');
const path = require('path');
const { errors, queryResult } = require('pg-promise');
const { isNull } = require('util');
const pgp = require('pg-promise')();
const db = pgp({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: true }
});
const PORT = process.env.PORT || 8080
const saltRounds = 10;
// DATABASE CONFIG
db.query("CREATE TABLE IF NOT EXISTS users ( \
Username varchar(50) NOT NULL UNIQUE, \
Password varchar(60) NOT NULL);"
);
// DEVELOPERS SHOULD ADD CODE HERE
// DEVELOPERS CODE ENDS HERE
app.use(express.static(path.join(__dirname, 'public')))
.use(express.urlencoded())
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.use('/img',express.static(path.join(__dirname, 'public/images')))
.use('/js',express.static(path.join(__dirname, 'public/js')))
.use('/css',express.static(path.join(__dirname, 'public/stylesheets')))
// ROUTING EXAMPLES
.get('/', (req, res) => res.render('pages/index', { title: 'Home' }))
.get('/help', (req, res) => res.render('pages/help', { title: 'Help' }))
// DEVELOPERS ADD OWN ROUTING
// ROUTING ENDS HERE
.use('/auth', auth)
.listen(PORT, () => console.log(`Listening on ${PORT}`))
// AUTH functions to handle HTTP requests that go to https://localhost:PORT/auth
// Login User function
// Return Values:
// null: if matching user does not exist
// object: returns the correct user
async function loginUser(username, password) {
return bcrypt.hash('1', saltRounds).then(async (fakeHash) => {
return db.one(`SELECT Username, Password FROM users WHERE Username='${username}'`).then(async (user) => {
return bcrypt.compare(password, user.password).then(async (loggedIn) => {
if (loggedIn) { return user } else { return null }
})
}).catch(async error => {
console.log(error.message || error)
return await bcrypt.compare('2', fakeHash).then(async () => { return null })
})
})
}
// Login page methods
auth.get('/login', (req, res) => res.render('pages/auth/login', { title: 'Login' }))
auth.post('/login', async (req, res) => {
await loginUser(req.body.username, req.body.password).then((user) => {
if (user) {
res.render(
'pages/auth/login', { title: 'Login Successful!', currentuser: user.username }) // use this to redirect the user to a homepage, etc.
} else {
res.send("The username and password provided do not match our records.")
}
})
})
// Register User function
// Return Values:
// Bool: True if user successfully registered, false if not!
async function registerUser(username, password) {
return db.none(`SELECT * FROM users WHERE Username='${username}'`).then(async () => {
return bcrypt.hash(password, saltRounds).then(async (hashedPass) => {
return db.query(`INSERT INTO users VALUES ('${username}', '${hashedPass}')`).then(async () => { return true })
})
}).catch(error => {
console.log(error.message || error)
return false
})
}
// Register page methods
auth.get('/register', (req, res) => res.render('pages/auth/register', { title: 'Register' }))
auth.post('/register', async (req, res) => {
if (await registerUser(req.body.username, req.body.password)) {
newUser = req.body.username;
res.render(
'pages/auth/register', { title: 'Registration Successful!', newUser: newUser })
} else {
res.send(`User "${req.body.username}" already exists.`)
}
});