0

I'm trying to apply the technique here to manually generate a password with devise and save it along with other attributes.

I'm using

password = "iamben"
@user = User.new(first_name: "Ben", email: "ben@mail.com", encrypted_password: password).encrypted_password
@user.save

NoMethodError (undefined method `save' for "iamben":String)

I am not sure why it doesn't work. I also tried a couple of other attempts

@user = User.new(first_name: "Ben", email: "ben@mail.com", encrypted_password: password.encrypted_password)

and

@user = User.new(first_name: "Ben", email: "ben@mail.com", encrypted_password: encrypted_password(password))

Sorry, it's probably something very simple I am doing incorrectly

stevec
  • 41,291
  • 27
  • 223
  • 311
  • That's a seven year old post. Note that this technique will also require you to do your own encryption for login as well so the bytes match. If you are set on doing this, suggest you look at https://github.com/heartcombo/devise-encryptable. – dbugger Aug 12 '20 at 19:30
  • @dbugger I have to admit, I don’t even know if it’s hashing and encrypting or just hashing. I have used bcrypt in the past without issue and understand what’s going on there. But i think the issue above is that my syntax is incorrect? – stevec Aug 12 '20 at 19:34
  • Don't think it is a syntax issue, it's "the API has changed in 7 years" issue. If you dig through the devise code, there is probably no direct route to set the encrypted password through the user object. Check out what devise actually does for to store the password. https://www.freecodecamp.org/news/how-does-devise-keep-your-passwords-safe-d367f6e816eb/#:~:text=Devise%20uses%20Bcrypt%20to%20securely,of%20your%20users'%20passwords%E2%80%9D. It is not as simple as hashing the password. – dbugger Aug 12 '20 at 19:45
  • @dbugger that article suggests devise simply appends a salt and hashes the password + salt 2^n times. Seems like I can do all this easily simply using bcrypt. Two things still seem weird 1. Seems odd devise doesn’t have some easy way to do what I’m attempting above, and 2. Why did devise creators use the word ‘encrypt’ when there is no encryption whatsoever (hashing yes, encryption no). Not that I can find anyway – stevec Aug 12 '20 at 19:58
  • Old nomenclature likely. In the database_authenicatable class, there is this comment... `# For legacy reasons, we use `encrypted_password` to store the hashed_password`. – dbugger Aug 12 '20 at 20:04
  • 1
    @dbugger wow, good observation. Thanks for the help/info – stevec Aug 12 '20 at 20:08

1 Answers1

0

I had a few points of confusion, but the answer essentially boils down to what we find here.

Simply

  1. find the user record whose password you want to change (e.g. user = User.where(email: "ben@mail.com")
  2. user.password = "123abc"
  3. user.save
  4. That's it! That user's password is now 123abc
stevec
  • 41,291
  • 27
  • 223
  • 311