Skip to content
Permalink
Browse files
Correct mirroring
  • Loading branch information
pastorpv committed Nov 4, 2019
1 parent f4ae1a4 commit c53781439d648c372234c966b3f6c7da2451a02d
Show file tree
Hide file tree
Showing 19 changed files with 8,668 additions and 0 deletions.
@@ -0,0 +1,74 @@

{
"env": {
"es6": true,
"jasmine": true,
"node": true,
"browser": true,
"jest": true
},
"parserOptions": {
"ecmaVersion": 8
},
"rules": {
"arrow-body-style": "error",
"arrow-spacing": ["warn", {"before": true, "after": true}],
"brace-style": "error",
"camelcase": ["error", {"properties": "never"}],
"complexity": ["error", 5],
"eol-last": "warn",
"eqeqeq": "error",
"func-call-spacing": ["error", "never"],
"global-require": "error",
"handle-callback-err": "warn",
"indent": ["warn", "tab", {"SwitchCase": 1}],
"key-spacing": ["error", {"beforeColon": false, "afterColon": true}],
"linebreak-style": ["warn", "unix"],
"max-depth": ["error", 3],
"max-len": ["warn", { "code": 120, "tabWidth": 4 }],
"max-lines": ["warn", {"max": 150, "skipBlankLines": true, "skipComments": true}],
"max-lines-per-function": ["error", 20],
"max-nested-callbacks": ["error", 4],
"max-params": ["error", 5],
"max-statements": ["error", 20],
"no-cond-assign": "error",
"no-dupe-args": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": "warn",
"no-empty-function": "error",
"no-multiple-empty-lines": "warn",
"no-extra-parens": "error",
"no-func-assign": "error",
"no-irregular-whitespace": "error",
"no-magic-numbers": ["warn", {"ignore": [-1, 0, 1]}],
"no-multi-spaces": "warn",
"no-multi-str": "off",
"no-unexpected-multiline": "error",
"no-unreachable": "error",
"no-self-assign": "error",
"no-trailing-spaces": "warn",
"no-undef": "error",
"no-unused-vars": "warn",
"no-var": 2,
"prefer-arrow-callback": "warn",
"prefer-const": "error",
"prefer-template": "error",
"quotes": ["warn", "single"],
"semi": ["warn", "never"],
"space-before-blocks": ["error", { "functions": "always", "keywords": "always", "classes": "always" }],
"space-before-function-paren": ["error", "never"],
"strict": ["error", "global"],
"yoda": "error"
},
"overrides": [{
"files": [ "*.test.js", "*.spec.js", "*.steps.js" ],
"rules": {
"global-require": "off",
"max-lines-per-function": "off",
"max-lines": "off",
"max-statements": "off",
"no-magic-numbers": "off"
}
}]
}
@@ -0,0 +1,5 @@
#!/bin/sh

set -e # using the options command to abort script at first error
echo "running the 'post-commit' script"
./node_modules/.bin/markdownlint --ignore node_modules .
@@ -0,0 +1,5 @@
#!/bin/sh

set -e # using the options command to abort script at first error
echo "running the 'pre-commit' script"
./node_modules/.bin/eslint .
@@ -0,0 +1,33 @@

{
"line-length": false,
"no-inline-html": {
"allowed_elements": [
"a", "br"
]
},
"header-increment": true,
"ul-style": {
"style": "dash"
},
"ul-start-left": true,
"no-trailing-spaces": {
"br_spaces": 0
},
"no-hard-tabs": true,
"no-reversed-links": true,
"no-multiple-blanks": true,
"no-missing-space-atx": true,
"no-multiple-space-atx": true,
"blanks-around-headers": true,
"header-start-left": true,
"no-duplicate-header": true,
"single-h1": true,
"blanks-around-fences": true,
"blanks-around-lists": true,
"no-bare-urls": true,
"no-space-in-emphasis": true,
"no-space-in-code": true,
"no-space-in-links": true,
"fenced-code-language": true
}
@@ -0,0 +1,27 @@

{
"version": "0.2.0",
"configurations": [

{
"type": "node",
"request": "attach",
"name": "Attach by Process ID",
"processId": "${command:PickProcess}"
},
{
"type": "node",
"request": "launch",
"name": "Jest",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"protocol": "inspector",
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
}
]
}
@@ -0,0 +1,24 @@

# 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:

`git clone https://github.coventry.ac.uk/web/template-dynamic-websites.git temp`

Create a new **private** repository in the module organisation on the GitHub server and copy the _clone url_ to the clipboard (the one that begins with `https://` and ends in `.git`. The repository name should be your username (the one you use to log into the University computers).

Mirror Push to this new repository, replacing xxx with the url from the clipboard making sure you are _in_ the `temp/` directory:

`cd temp/ && git push --mirror xxx`

Once you are sure the code is in your new repository, delete the temporary local repository.

`cd .. && rm -rf temp/`
Your private repository on GitHub will now contain a complete copy of this template including the commits that were already made. You can now start your assignment by carrying out the following steps:

Clone your private repository

Change your [local config settings](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup). This is a vital step otherwise your commits won't show on the GitHub _graph_ and your grade will be affected.

Start working on the assignment. Remember to install all the dependencies listed in the `package.json` file.
107 index.js
@@ -0,0 +1,107 @@
#!/usr/bin/env node

//Routes File

'use strict'

/* MODULE IMPORTS */
const Koa = require('koa')
const Router = require('koa-router')
const views = require('koa-views')
const staticDir = require('koa-static')
const bodyParser = require('koa-bodyparser')
const koaBody = require('koa-body')({multipart: true, uploadDir: '.'})
const session = require('koa-session')
//const jimp = require('jimp')

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

const app = new Koa()
const router = new Router()

/* CONFIGURING THE MIDDLEWARE */
app.keys = ['darkSecret']
app.use(staticDir('public'))
app.use(bodyParser())
app.use(session(app))
app.use(views(`${__dirname}/views`, { extension: 'handlebars' }, {map: { handlebars: 'handlebars' }}))

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

/**
* The secure home page.
*
* @name Home Page
* @route {GET} /
* @authentication This route requires cookie-based authentication.
*/
router.get('/', 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')
} catch(err) {
await ctx.render('error', {message: err.message})
}
})

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

/**
* 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
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`)
} 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.post('/login', 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...')
} catch(err) {
await ctx.render('error', {message: err.message})
}
})

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

app.use(router.routes())
module.exports = app.listen(port, async() => console.log(`listening on port ${port}`))
@@ -0,0 +1,19 @@
'use strict'

module.exports = {
displayName: 'test',
verbose: true,
collectCoverage: true,
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
statements: 0
}
},
testPathIgnorePatterns: [
'/node_modules/',
'/__tests__/fixtures/',
]
}
@@ -0,0 +1,22 @@

{
"tags": {
"allowUnknownTags": true,
"dictionaries": ["jsdoc","closure"]
},
"source": {
"include": [ "." ],
"exclude": [ "node_modules" ],
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins": ["jsdoc-route-plugin"],
"templates": {
"cleverLinks": false,
"monospaceLinks": false
},
"opts": {
"destination": "docs/jsdoc",
"recurse": true
}
}
@@ -0,0 +1,60 @@

'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 {

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);'
await this.db.run(sql)
return this
})()
}

async register(user, pass) {
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}";`
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}")`
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}`)
}

async login(username, password) {
try {
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}";`
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}"`)
return true
} catch(err) {
throw err
}
}

}

0 comments on commit c537814

Please sign in to comment.