Skip to content
Permalink
f2e37868de
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
74 lines (62 sloc) 1.84 KB
//Routes File
'use strict'
/* MODULE IMPORTS */
const Router = require('koa-router')
const koaBody = require('koa-body')({multipart: true, uploadDir: '.'})
const router = new Router()
const dbUsers = './databases/users.db'
/* IMPORT CUSTOM MODULES */
const User = require('../modules/user')
router.get('/', async ctx => {
try {
const auth = ctx.session.authorised
const user = await new User(dbUsers)
const authenticated = user.checkAuth(auth)
if(authenticated !== 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})
}
})
router.get('/register', async ctx => await ctx.render('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(dbUsers)
await user.register(body.user, body.pass, body.auth)
// 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(dbUsers)
await user.login(body.user, body.pass)
const auth = await user.getAuth(body.user)
ctx.session.authorised = auth.auth
return ctx.render('mainmenu')
} 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')
})
module.exports = router