Last active
June 5, 2017 00:45
-
-
Save sergeysova/803d6e9fdb2c42c6652dbf3aa437df39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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