Skip to content
Permalink
Browse files
Merge with jee2-user
  • Loading branch information
staplesc committed Nov 27, 2019
2 parents 717b3d6 + ad28ea9 commit 683a26262d4d44cdbe91e6daaa7aa1a1bdeac0d8
Show file tree
Hide file tree
Showing 11 changed files with 494 additions and 410 deletions.
@@ -0,0 +1,39 @@
#!/bin/bash
#found in https://www.reddit.com/r/bash/comments/8inq6i/validate_git_commit_message/, contributed by user frakman1
#rules based on https://chris.beams.io/posts/git-commit/#seven-rules

echo -e "\e[32m--- Checking Commit Message ---\e[0m";

cnt=0
while IFS='' read -r line || [[ -n "$line" ]]; do
cnt=$((cnt+1))
length=${#line}
if [ $cnt -eq 1 ]; then
# Checking if subject exceeds 50 characters
if [ $length -gt 50 ]; then
echo -e "\e[31m*** Subject line exceeds 50 characters ***\e[0m";
exit 1
fi
i=$(($length-1))
last_char=${line:$i:1}
# Last character must not have a punctuation
if [[ ! $last_char =~ [0-9a-zA-Z] ]]; then
echo -e "\e[31m*** Last character of subject line must not contain punctuation ***\e[0m";
exit 1
fi
elif [ $cnt -eq 2 ]; then
# Subject must be followed by a blank line
if [ $length -ne 0 ]; then
echo -e "\e[31m*** Current subject line follows a non-empty line. Subject lines should always be followed by a blank line ***\e[0m";
exit 1
fi
else
# Any line in body must not exceed 72 characters
if [ $length -gt 72 ]; then
echo -e "\e[31m*** Line \"$line\" exceeds 72 characters ***\e[0m";
exit 1
fi
fi
done < "$1"


@@ -3,3 +3,7 @@
set -e # using the options command to abort script at first error
echo "running the 'pre-commit' script"
./node_modules/.bin/eslint .
./node_modules/.bin/jest --coverage -o



@@ -1,5 +1,6 @@

# Assignment Template

This repository contains the base files for the assignment. You will need to create a _private duplicate_ in your module organisation. Carry out the following steps, taken from the [GitHub documentation](https://help.github.com/en/enterprise/2.16/user/articles/duplicating-a-repository):

Temporarily clone this repository to your development computer. This will create a directory on your computer called `temp` which contains the repository files:
@@ -42,7 +42,7 @@ const dbName = 'website.db'
*/
/*router.get('/', async ctx => {
try {
if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
//if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
await ctx.render('index')
@@ -100,9 +100,10 @@ router.post('/register', koaBody, async ctx => {
// call the functions in the module
const user = await new User(dbName)
await user.register(body.user, body.pass)
// await user.uploadPicture(path, type)
const {path, type} = ctx.request.files.avatar
await user.uploadPicture(path, type, body.user)
// redirect to the home page
ctx.redirect(`/?msg=new user "${body.name}" added`)
ctx.redirect(`/?msg=new user ${body.user} added`)
} catch(err) {
await ctx.render('error', {message: err.message})
}
@@ -2,59 +2,184 @@
'use strict'

const bcrypt = require('bcrypt-promise')
// const fs = require('fs-extra')
const mime = require('mime-types')
const sqlite = require('sqlite-async')
const saltRounds = 10

module.exports = class User {
/**
* Class representing the details of the user.
* */
class User {

/**
* Constructor for User table
* @constructor
* @param {} [dbName=':memory:'] database for the website
*/
constructor(dbName = ':memory:') {
return (async() => {
this.db = await sqlite.open(dbName)
// we need this table to store the user accounts
const sql = 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, pass TEXT);'
const sql = `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT,
password TEXT,
email TEXT,
location TEXT,
profileImg TEXT,
profileTxt TEXT,
registeredDate TEXT);`
await this.db.run(sql)
return this
})()
}

async register(user, pass) {
/**
* Register user with suitable username and password.
* @param {string} user - username
* @param {string} password
* @return {Promise<true>} registration confirmation
*/
async register(user, password) {
try {
if(user.length === 0) throw new Error('missing username')
if(pass.length === 0) throw new Error('missing password')
let sql = `SELECT COUNT(id) as records FROM users WHERE user="${user}";`
if(password.length === 0) throw new Error('missing password')
let sql = `SELECT COUNT(id) as records FROM users WHERE user='${user}';`
const data = await this.db.get(sql)
if(data.records !== 0) throw new Error(`username "${user}" already in use`)
pass = await bcrypt.hash(pass, saltRounds)
sql = `INSERT INTO users(user, pass) VALUES("${user}", "${pass}")`
password = await bcrypt.hash(password, saltRounds)
const currentDate = Date.now().toString()
sql = `INSERT INTO users(user, password, registeredDate) VALUES('${user}', '${password}', ${currentDate})`
await this.db.run(sql)
return true
} catch(err) {
throw err
}
}

async uploadPicture(path, mimeType) {
const extension = mime.extension(mimeType)
console.log(`path: ${path}`)
console.log(`extension: ${extension}`)
//await fs.copy(path, `public/avatars/${username}.${fileExtension}`)
}

/**
* Login user with existing username and password.
* @param {string} username
* @param {string} password
* @return {Promise<true>} login confirmation
*/
async login(username, password) {
try {
let sql = `SELECT count(id) AS count FROM users WHERE user="${username}";`
let sql = `SELECT count(id) AS count FROM users WHERE user='${username}';`
const records = await this.db.get(sql)
if(!records.count) throw new Error(`username "${username}" not found`)
sql = `SELECT pass FROM users WHERE user = "${username}";`
sql = `SELECT password FROM users WHERE user = '${username}';`
const record = await this.db.get(sql)
const valid = await bcrypt.compare(password, record.pass)
if(valid === false) throw new Error(`invalid password for account "${username}"`)
const valid = await bcrypt.compare(password, record.password)
if(valid === false) throw new Error(`invalid password for user "${username}"`)
return true
} catch(err) {
throw err
}
}

/**
* Check email syntax.
* @param {string} email
* @returns {Promise<true>} confirmation for proper email syntax
*/
async checkEmail(email) {
try{
if(email.length === 0) throw new Error('missing email')
if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) === false) throw new Error('email is invalid')
else return true
} catch(err) {
throw err
}
}

/**
* Add user email.
* @param {string} user
* @param {string} email
* @returns {Promise<true>} confirmation for adding user email
*/
async addEmail(user, email) {
try{
if(user.length === 0) throw new Error('missing username')
await this.checkEmail(email)
let sql = `SELECT COUNT(id) as records FROM users WHERE user='${user}';`
const data = await this.db.get(sql)
if(data.records === 0) throw new Error('username does not exist')
sql = `UPDATE users SET email = ('${email}') WHERE user = '${user}';`
await this.db.run(sql)
return true
} catch(err) {
throw err
}
}

/**
* Add user location.
* @param {string} user
* @param {string} location
* @returns {Promise<true>} confirmation for adding user location
*/
async addLocation(user, location) {
try{
if(user.length === 0) throw new Error('missing username')
if(location.length === 0) throw new Error('missing location')
let sql = `SELECT COUNT(id) as records FROM users WHERE user='${user}';`
const data = await this.db.get(sql)
if(data.records === 0) throw new Error('username does not exist')
sql = `UPDATE users SET location = '${location}' WHERE user = '${user}';`
await this.db.run(sql)
return true
} catch(err) {
throw err
}
}

/**
* Get all data of a selected user
* @param {string} username
* @returns {Promise<userData>}
*/
async getUser(username) {
try{
if(username.length === 0) throw new Error('username is missing')
let sql = `SELECT COUNT(id) as records FROM users WHERE user = '${username}'`
let data = await this.db.get(sql)
if(data.records === 0) throw new Error('username does not exist')
sql = `SELECT * FROM users WHERE user = '${username}'`
data = await this.db.get(sql)
return data
} catch(err) {
throw err
}
}

/**
* Get all data of all users
* @returns {Promise<userData[]>} array of data objects of all existing user
*/
async getAll() {
const sql = 'SELECT * FROM users;'
const data = await this.db.all(sql)
return data
}

/**
* Delete a user.
* @param {integer} key
* @returns {Promise<true>} confirmation for deleting user
*/
async delete(key) {
try{
if(key === undefined) throw new Error('missing id')
let sql = `SELECT COUNT(id) as records FROM users WHERE id=${key};`
const data = await this.db.get(sql)
if(data.records === 0) throw new Error(`user with id ${key} does not exist`)
sql = `DELETE FROM users WHERE id = ${key};`
await this.db.run(sql)
return true
} catch(err) {
throw err
}
}
}

module.exports = User

0 comments on commit 683a262

Please sign in to comment.