Skip to content

Instantly share code, notes, and snippets.

@sergeysova
Last active June 5, 2017 00:45
Show Gist options
  • Save sergeysova/803d6e9fdb2c42c6652dbf3aa437df39 to your computer and use it in GitHub Desktop.
Save sergeysova/803d6e9fdb2c42c6652dbf3aa437df39 to your computer and use it in GitHub Desktop.
import express from 'express'
import { createRest } from 'createrest'
import { createRestExpress } from 'createrest-express'
import { AuthController } from 'controllers'
const app = express()
const routes = createRest(r => {
r.resources('auth', AuthController, { methodNames: { create: 'login' } })
})
app.use(createRestExpress(routes))
app.listen(7000)
export class LoginContext {
constructor(manager) {
this.user = manager
this.model = null
}
async loginWith(email, password) {
try {
const valid = await this.manager.validateCredentials(email, password)
if (valid) {
this.model = await this.manager.findByEmail(email)
}
return valid
}
catch (error) {
return false
}
}
}
import { LoginContext } from 'contexts'
import { UserManager } from 'managers'
import { User } from 'models'
export class AuthController {
beforeEach(req, res, next) {
if (req.user) {
return res.redirect('/')
}
next()
}
async login(req, res, next) {
const ctx = new LoginContext(new UserManager(User))
if (await ctx.loginWith(req.params.email, req.params.password)) {
req.user = ctx.model
next()
}
else {
next(new Error('InvalidCredentials'))
}
}
}
export class UserManager {
constructor(user) {
this.user = user
}
findByEmail(email) {
return this.model.where({ email }).execute()
}
async validateCredentials(email, password) {
try {
const user = await this.findByEmail(email)
return superhash.validatePassword(appSecret, user.salt, user.hashedPassword, password)
}
catch (e) {
throw Error.InvalidData()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment