Skip to content

Commit

Permalink
chore: fix authentication in social-network example (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharygolba authored Sep 10, 2016
1 parent bbbe317 commit e4966fd
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 33 deletions.
8 changes: 2 additions & 6 deletions examples/social-network/app/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class UsersController extends Controller {
'password'
];

async login({
login({
params: {
data: {
attributes: {
Expand All @@ -19,11 +19,7 @@ class UsersController extends Controller {
}
}
}) {
const user = await User.findByEmail(email);

if (user) {
return await user.authenticate(password);
}
return User.authenticate(email, password);
}
}

Expand Down
26 changes: 12 additions & 14 deletions examples/social-network/app/models/user.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { Model } from 'lux-framework';

import {
encryptPassword,
comparePassword
} from 'app/utils/password';
import bcrypt from 'bcrypt-as-promised';

class User extends Model {
static hasMany = {
Expand Down Expand Up @@ -38,13 +34,8 @@ class User extends Model {

static hooks = {
async beforeSave(user) {
const { id, password, dirtyAttributes } = user;

if ((typeof id !== 'number') && password || dirtyAttributes.has('password')) {

Object.assign(user, {
password: encryptPassword(password)
});
if (user.isNew || user.dirtyAttributes.has('password')) {
user.password = await bcrypt.hash(user.password, 10);
}
}
};
Expand All @@ -63,8 +54,15 @@ class User extends Model {
}
};

authenticate(password) {
return comparePassword(password, this.password);
static async authenticate(email, password) {
const user = await this.findByEmail(email);

if (user) {
return await bcrypt
.compare(password, user.password)
.then(() => user)
.catch(bcrypt.MISMATCH_ERROR, () => false);
}
}
}

Expand Down
11 changes: 0 additions & 11 deletions examples/social-network/app/utils/password.js

This file was deleted.

4 changes: 2 additions & 2 deletions examples/social-network/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
"dependencies": {
"babel-core": "6.14.0",
"babel-preset-lux": "1.2.0",
"bcrypt-as-promised": "1.1.0",
"knex": "0.11.10",
"lux-framework": "1.0.0-rc.7",
"sqlite3": "3.1.4",
"bcrypt-as-promised": "1.1.0"
"sqlite3": "3.1.4"
},
"devDependencies": {
"faker": "3.1.0"
Expand Down

0 comments on commit e4966fd

Please sign in to comment.