Skip to content
Permalink
Browse files
Merge pull request #1 from 5001CEM-1920SEPJAN/one-last-hope3
One last hope3
  • Loading branch information
sarkarj committed Dec 2, 2019
2 parents fe39314 + 0965d59 commit 2041344a3cae908cea2db07dfcd41ddf4ef49f76
Show file tree
Hide file tree
Showing 53 changed files with 4,357 additions and 1,580 deletions.
@@ -0,0 +1,2 @@
/node_modules
/docs
@@ -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



@@ -25,3 +25,5 @@ trace/

*.codio
*.c9

.vscode/

This file was deleted.

@@ -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:
128 index.js
@@ -16,6 +16,16 @@ const session = require('koa-session')

/* IMPORT CUSTOM MODULES */
const User = require('./modules/user')
const Article = require('./modules/article')

/* IMPORT ROUTE MODULES */
const editPost = require('./routes/edit.post')
const categoriesTagGet = require('./routes/categories.tag.get')
const uploadPost = require('./routes/upload.post')
const releasePost = require('./routes/release.post')
const get = require('./routes/get')
const loginGetPost = require('./routes/login.get.post')
const registerPost = require('./routes/register.post')

const app = new Koa()
const router = new Router()
@@ -29,78 +39,120 @@ app.use(views(`${__dirname}/views`, { extension: 'handlebars' }, {map: { handleb

const defaultPort = 8080
const port = process.env.PORT || defaultPort
const dbName = 'website.db'
const dbName = 'database.db'

/**
* The secure home page.
*
* @name Home Page
* @route {GET} /
* @authentication This route requires cookie-based authentication.
*/
router.get('/', async ctx => {
router.get('/', async ctx => await get(ctx, dbName))

router.get('/articles/:id', async ctx => {
try {
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')
const id = ctx.params.id
const article = await new Article(dbName)
const data = await article.get(id)
const loggedIn = true
if(ctx.session.authorised) await ctx.render('articlepage', {article: data, loggedIn: loggedIn})
else await ctx.render('articlepage', data)
} catch(err) {
await ctx.render('error', {message: err.message})
ctx.body = err.message
console.log(err)
}
})

router.get('/edit/:id', async ctx => {
try {
const id = ctx.params.id
const article = await new Article(dbName)
const data = await article.get(id)
await ctx.render('editarticle', data)
} catch(err) {
ctx.body = err.message
console.log(err)
}
})

router.post('/edit', koaBody, async ctx => await editPost(ctx, dbName))

router.get('/categories/:tag', async ctx => await categoriesTagGet(ctx, dbName))

/**
* The user registration page.
*
* @name Register Page
* @route {GET} /register
*/
router.get('/register', async ctx => await ctx.render('register'))

router.get('/register', async ctx => {
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
await ctx.render('loginpage')
})

/**
* The script to process new user registrations.
*
* @name Register Script
* @route {POST} /register
*/
router.post('/register', koaBody, async ctx => {
try {
// extract the data from the request
router.post('/register', koaBody, async ctx => await registerPost(ctx, dbName))

router.get('/login', async ctx => {
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
if(ctx.query.user) data.user = ctx.query.user
await ctx.render('loginpage', data)
})

router.post('/login', async ctx => await loginGetPost(ctx, dbName))

router.get('/logout', async ctx => {
ctx.session.authorised = null
ctx.redirect('/?msg=you are now logged out')
})

router.get('/account', async ctx => {
const user = await new User(dbName)
if(ctx.session.authorised === true) {
const data = await user.getUser(ctx.session.user)
console.log(data)
await ctx.render('accountpage', {account: data})
} else await ctx.render('accountpage')
})

router.post('/account', koaBody, async ctx => {
try{
const body = ctx.request.body
console.log(body)
// call the functions in the module
const user = await new User(dbName)
await user.register(body.user, body.pass)
// await user.uploadPicture(path, type)
// redirect to the home page
ctx.redirect(`/?msg=new user "${body.name}" added`)
if(body.email !== undefined) await user.addEmail(ctx.session.user, body.email)
if(body.location !== undefined) await user.addLocation(ctx.session.user, body.location)
ctx.redirect('/account')
} catch(err) {
await ctx.render('error', {message: err.message})
}
})

router.get('/login', async ctx => {
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
if(ctx.query.user) data.user = ctx.query.user
await ctx.render('login', data)
})
router.get('/upload', async ctx => await ctx.render('articleUpload'))

router.post('/login', async ctx => {
router.post('/upload', koaBody, async ctx => await uploadPost(ctx, dbName))

router.get('/admin', async ctx => {
try {
const body = ctx.request.body
const user = await new User(dbName)
await user.login(body.user, body.pass)
ctx.session.authorised = true
return ctx.redirect('/?msg=you are now logged in...')
const article = await new Article(dbName)
const data = await article.getUnreleased()
await ctx.render('adminHome', {articles: data})
} catch(err) {
console.error(err.message)
await ctx.render('error', {message: err.message})
}
})

router.get('/logout', async ctx => {
ctx.session.authorised = null
ctx.redirect('/?msg=you are now logged out')
router.post('/release', koaBody, async ctx => await releasePost(ctx, dbName))

router.post('/login', async ctx => {
try {
return ctx.redirect('/upload')
} catch(err) {
await ctx.render('error', {message: err.message})
}
})

app.use(router.routes())
@@ -0,0 +1,107 @@

'use strict'

const Database = require('sqlite-async')

class Article {

constructor(dbName = ':memory:') {
return (async() => {
this.db = await Database.open(dbName)
const sql = `CREATE TABLE IF NOT EXISTS Articles (
"article_id" INTEGER PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL,
"summary" TEXT,
"content" NVARCHAR NOT NULL,
"written_date" DATE NOT NULL,
"author" TEXT,
"image_url" TEXT,
"tag" TEXT,
"released" INTEGER,
"rating" INTEGER);`
await this.db.run(sql)
return this
})()
}

async upload(title, summary, content, tag, username) {
try{
if(title === null) throw new Error('Please enter a title for your article')
else if(summary === null) throw new Error('Please enter a summary for your article')
else if(content === null) throw new Error('Where is the content? Please Enter some text in the content box')
const date = await new Date()
const fullDate = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
let sql = `INSERT INTO Articles(title, summary, content, written_date, tag, released, author)
VALUES("${title}", "${summary}", "${content}", "${fullDate}", "${tag}", 0, "${username}")`
await this.db.run(sql)
sql = 'SELECT last_insert_rowid() as id'
const result = await this.db.get(sql)
sql = `UPDATE Articles SET image_url = "articleImages/${result.id}.png" WHERE article_id = ${result.id};`
await this.db.run(sql)
return result.id
} catch(err) {
throw err
}
}

async reupload(id, title, summary, content, tag) {
try{
if(title === null) throw new Error('Please enter a title for your article')
else if(summary === null) throw new Error('Please enter a summary for your article')
else if(content === null) throw new Error('Where is the content? Please Enter some text in the content box')
const date = await new Date()
const fullDate = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
let sql = `UPDATE Articles SET title = "${title}", summary = "${summary}", content = "${content}",
written_date = "${fullDate}", tag = "${tag}", released = 0
WHERE article_id = ${id};`
await this.db.run(sql)
sql = `UPDATE Articles SET image_url = "articleImages/${id}.png" WHERE article_id = ${id};`
await this.db.run(sql)
return true
} catch(err) {
throw err
}
}

async release(id) {
const query = `UPDATE Articles SET released = 1 WHERE article_id = ${id};`
await this.db.run(query)
}

async get(id) {
try{
const data = await this.db.get(`SELECT * FROM Articles WHERE article_id = '${id}';`)
if(data === undefined) throw new Error('This article does not exist')
return data
} catch(err) {
throw err
}
}

async getByTag(tag) {
const data = await this.db.all(`SELECT * FROM Articles WHERE tag = '${tag}';`)
Array.prototype.reverse.call(data)
return data
}

async getUnreleased() {
const data = await this.db.all('SELECT * FROM Articles WHERE released = 0;')
Array.prototype.reverse.call(data)
return data
}

async search(searchQuery) {
let sql = 'SELECT * FROM Articles WHERE released = 1;'
if(searchQuery !== undefined && searchQuery.q !== undefined) {
sql = `SELECT * FROM Articles
WHERE upper(title) LIKE upper("%${searchQuery.q}%") AND released = 1
OR upper(summary) LIKE upper("%${searchQuery.q}%") AND released = 1
OR upper(content) LIKE upper("%${searchQuery.q}%") AND released = 1
OR upper(author) LIKE upper("%${searchQuery.q}%") AND released = 1;`
}
const data = await this.db.all(sql)
Array.prototype.reverse.call(data)
return data
}
}
module.exports = Article

0 comments on commit 2041344

Please sign in to comment.