2019-09-14 19:03:38 +00:00
|
|
|
import Staff from '../staff/model.mjs'
|
|
|
|
import Jwt from '../jwt.mjs'
|
|
|
|
import * as google from './google.mjs'
|
2019-09-15 01:53:38 +00:00
|
|
|
import * as security from './security.mjs'
|
|
|
|
import AuthHelper from './helper.mjs'
|
2019-02-20 16:10:37 +00:00
|
|
|
|
|
|
|
export default class AuthRoutes {
|
|
|
|
constructor(opts = {}) {
|
|
|
|
Object.assign(this, {
|
2019-09-15 01:53:38 +00:00
|
|
|
helper: opts.helper || new AuthHelper(),
|
2019-02-20 16:10:37 +00:00
|
|
|
Staff: opts.Staff || Staff,
|
|
|
|
jwt: opts.jwt || new Jwt(),
|
|
|
|
google: opts.google || google,
|
2019-09-15 01:53:38 +00:00
|
|
|
security: opts.security || security,
|
2019-02-20 16:10:37 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* POST /api/login - Authenticate a user using social login
|
|
|
|
*
|
|
|
|
* @body {string} token - The google token to authenticate
|
|
|
|
* @returns
|
|
|
|
*
|
|
|
|
* { token: 'Authentication token' }
|
|
|
|
*/
|
|
|
|
async login(ctx) {
|
|
|
|
let output = await google.getProfile(ctx.request.body.token)
|
|
|
|
|
|
|
|
if (output.email_verified !== 'true') ctx.throw(422, 'Email was not verified with google')
|
|
|
|
if (!output.email) ctx.throw(422, 'Email was missing from google response')
|
|
|
|
|
|
|
|
let level = 1
|
|
|
|
let staff = await this.Staff
|
|
|
|
.query({ where: { email: output.email }})
|
|
|
|
.fetch({ require: false })
|
|
|
|
|
|
|
|
if (staff && staff.id && staff.get('level')) {
|
|
|
|
level = staff.get('level')
|
|
|
|
}
|
|
|
|
|
2019-10-02 18:47:20 +00:00
|
|
|
ctx.body = { token: this.jwt.createToken(staff.id, output.email, level) }
|
2019-02-20 16:10:37 +00:00
|
|
|
}
|
2019-09-15 01:53:38 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* POST /api/login/user - Authenticate a user using password login
|
|
|
|
*
|
|
|
|
* @body {string} username - Username
|
|
|
|
* @body {string} password - Password
|
|
|
|
* @returns
|
|
|
|
*
|
|
|
|
* { token: 'Authentication token' }
|
|
|
|
*/
|
|
|
|
async loginUser(ctx) {
|
|
|
|
this.security.isValidLogin(ctx, ctx.request.body)
|
|
|
|
|
|
|
|
let token = await this.helper.loginStaff(ctx)
|
|
|
|
|
|
|
|
ctx.body = { token }
|
|
|
|
}
|
2019-02-20 16:10:37 +00:00
|
|
|
}
|