Adonis JS - Hashing Password

I went through

and a few more.

It should be pretty simple, but I don't know why I can't figure it out. I want to use the Adonis Authentication tool during login. To do this, I need to hash passwords before saving. I'm stuck here.

View

<h1>Sign up</h1>
{{ form.open({url: '/addNew', action: 'UserController.addNewUser'}) }}

{{ csrfField }}

<div class="field">
{{ form.label('username', 'Choose a username') }}
{{ form.text('username') }}
</div>

<div class="field">
{{ form.label('email', 'Enter email address') }}
{{ form.text('email') }}
</div>

<div class="field">
{{ form.label('password', 'Choose a strong password') }}
{{ form.password('password') }}
</div>

<div class="button">
{{ form.submit('Sign Up') }}
</div>

{{ form.close() }}

Controller: UserController

'use strict'

const Database = use('Database')
const User = use('App/Model/User')
const user = new User()

class UserController {

* index (request, response) {
 const users = yield Database.select('*').from('users')
 response.json(users)
}

* addNewUser (request, response){

 user.name = request.input('username')
 user.email = request.input('email')
 user.password = request.input('password')
 user.entry = "Lorem Ipsum";

//Insert into database
  const userId = yield Database
 .insert({name: user.name, email: user.email, password: user.password, entry: user.entry})
 .into('users')

 response.json(userId)
 }
}
module.exports = UserController

Model: User

'use strict'

const Lucid = use('Lucid')


class User extends Lucid {

static boot () {
   super.boot()
   this.addHook('beforeCreate', 'User.encryptPassword')
  }
}


module.exports = User

Hook: User

'use strict'

const Hash = use('Hash')
const User = exports = module.exports = {}

User.encryptPassword = function * (next) {
  this.password = yield Hash.make(request.input('password'))
  yield next
}

Thank!

+4
source share
2 answers

Model . Database?

, , .

* addNewUser (request, response) {
  const user = new User()
  user.name = request.input('username')
  user.email = request.input('email')
  user.password = request.input('password')
  user.entry = "Lorem Ipsum";
  yield user.save()
  response.json(user.id)
}

request. , .

Hook

'use strict'

const Hash = use('Hash')
const User = exports = module.exports = {}

User.encryptPassword = function * (next) {
   this.password = yield Hash.make(this.password)
   yield next
}

http://adonisjs.com/docs/3.1/database-hooks#_basic_example

+1

, . . , . , :

: UserController → addNewUser()

user.name = request.input('username')
user.email = request.input('email')
const pswd = request.input('password')
user.password = yield Hash.make(pswd)

. , Hash.make . encryption Adonis . : Hashed $2a $10 $. , , !

0

Source: https://habr.com/ru/post/1661532/


All Articles