Automatically set password for user - Devise - ruby-on-rails

Following this tutorial, I setup a simple registration system with devise, where a user enters their email address, they are sent a confirmation email, they click on it, it takes them to a form where they have to enter their password and complete the registration.
How do I skip that password form so that once the user clicks on the confirmation link in their email, their account is created? How can I automatically set simple password for all users?

Create a method in your user model to use it instead of the create method. Let's call it create_with_password
def self.create_with_password(attr={})
generated_password = attr[:first_name] + "123"
self.create(attr.merge(password: generated_password, password_confirmation: generated_password))
end
Override devise's registration controller to use your new method which generates the two necessary fields for devise password and password_confirmation using the first_name attribute in your user model for example then 123 like in John123
In your controller after your parameters are sanitized. You should call User.create_with_password(user_params)

Related

Update devise user password using a custom method

I am using Devise for authentication and trying to change the password of certain users to their date of birth using a method
def set_dob_password id
#user = User.find(id)
#user.update_attribute(password: #user.birth_date)
end
isn't working
. What is the best way of doing this ?
Of course it won't work! Devise stores encrypted passwords only in the DB. If you look at the users table you won't see a 'password' field but 'encrypted_password' column instead.
You first have to encrypt the password.
pw = BCrypt::Password.create(#user.birth_date)
#user.update_attribute(:encrypted_password, pw)
Make sure you have the 'bcrypt' gem first.
#user.update_attributes(password: params[:password], password_confirmation: params[:password_confirmation]). You need to update both password + password confirmation. So in your case replace parmas with user DoB.

Password encryption in Rails

I have User model and use Devise gem on it. In my application i have an admin user who can register other users (for example:clients). Then these users can log in by themselves with randomly generated password. (But no one can register by themselves, only admin can register users.)
When I am creating user from other user logged in, i.e admin user creates another user , i want to generate some random password, encrypt it, and save to database.
How to encrypt passwords, so that it will work with Devise authorization. I guess I have to use the same method as Devise?
I want something like that:
EDIT:
def create
#user = User.new(user_params)
# set #user.password to some random encrypted password
#user.save
end
So every created user will get some random password.
The reason i am asking this, is that i think that if my encryption/decription will not match what devise uses users will not be able to log in with their passwords, since when they log in their input is encrypted via devise's encryption.
If you are using Devise and you have :database_authenticable enabled, you don't need what you describe at all.
Devise encrypts automatically when it saves to the database and doesn't decrypt when it reads it back, however when you store it in the password field, it can be plain text, Devise will take care of it for you only when writing (so it will stay plain text until you save).
So in your controller to create new users you can just do the following:
def create
# I assume your form will pass a `params[:password]` in plain text too
#user = User.new(user_params)
#user.password_confirmation = params[:password]
#user.save
end
This should be enough for your purpose, don't need to match devise encryption
Update 1:
To generate a random password in addition, you can do something like:
require 'securerandom'
def create
# I assume your form will pass a `params[:password]` in plain text too
#password = SecureRandom.hex(16)
#user = User.new(user_params.to_h.merge(password: #password, password_confirmation: #password))
#user.save
# Remember to display `#password` in some way to the user
end
You should be having :database_authenticatable as one of the devise modules in your User model.
From Devise, it says
Database Authenticatable: encrypts and stores a password in the
database to validate the authenticity of a user while signing in. The
authentication can be done both through POST requests or HTTP Basic
Authentication.

Devise: Create user using only the Email address

How can I create a Signup using Devise where instead of the user entering both his email and password during sign up, all he needs to enter is an email and then get the Password generated through his email?
I'm trying to make sign up as simple as possible and I figured out that since devise is capable of sending out an activation email already, why not just piggy back on that and send a generated Password and confirm at the time of login?
Thanks for any help :)
You can use the Devise's friendly token in your controller:
password = Devise.friendly_token.first(8)
User.create(email: 'my#email.com', password: password, password_confirmation: password)
The friendly_token is a string containing A-Z, a-z, 0-9, “-” and “_”.
Source code here:
def self.friendly_token
SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
end
and here for more info:
def self.urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=") if !padding
s
end

Devise: after successful login hook

In my rails app, I am using devise for my authentication system. I have a situation in which I want to encrypt some data using a key that is based off of the user's password. The easiest way that I can think to do this is during a successful sign in, to generate the user's private key from their plain-text password (passed in from the login form) and store that in the user's session. I don't really want to ask the user to enter their password more than once.
Does devise provide a way to specify a callback function after a successful login? Or is there a better way to do this?
http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable#after_database_authentication-instance_method
In the user model where you're using devise create a after_database_authentication instance method.
Assume you have Devise resourse User with attribut password, then you can access user password after login in after_sign_in_path_for, which is called after sucessful login.
# app/control,lers/application_controller.rb
class ApplicationController < ActionController::Base
def after_sign_in_path_for(resource)
password = param[:user][:password]
do_cool_stuf_with_password(password)
#...
return url_for_root
end
end

Rails Devise: Set password reset token and redirect user

In my app for a certain use case I create a new user (programmatically set the password) and send them a confirmation email.
I would like them to be able to change their password immediately after confirming (without having to enter the system generated one which I don't want to send them)
In effect I would like
1) System creates a new user account with generated password.
2) System sends confirmation email.
3) User clicks confirmation and is redirected to enter in their password (effectively send them to a URL like below)
Change my password
Any help / pointers would be great.
A simple way to have just one step for users to confirm email address and set initial password using the link you proposed...
Send one email your app generates, including a reset_password_token, and consider user's possession of that token confirmation of the validity of that email address.
In system account generation code, assuming User model is set up with :recoverable and :database_authenticatable Devise modules...
acct = User.new
acct.password = User.reset_password_token #won't actually be used...
acct.reset_password_token = User.reset_password_token
acct.email = "user#usercompany.com" #assuming users will identify themselves with this field
#set other acct fields you may need
acct.save
Make the devise reset password view a little clearer for users when setting initial password.
views/devise/passwords/edit.html.erb
...
<%= "true" == params[:initial] ? "Set your password" : "Reset your password" %>
...
Generated Email
Hi <%= #user.name %>
An account has been generated for you.
Please visit www.oursite.com/users/password/edit?initial=true&reset_password_token=<%= #user.reset_password_token %> to set your password.
No need to include :confirmable Devise module in your User model, since accounts created by your app won't get accessed without the reset_password_token in the email.
Devise will handle the submit and clear the reset_password_token field.
See devise_gem_folder/lib/devise/models/recoverable.rb and database_authenticatable.rb for details on reset_password_token method and friends.
If you want to use Devise :confirmable module rather than this approach, see the Devise wiki page.
In Rails 4.1, the following modification of Anatortoise House's reply works:
user = User.new
user.password = SecureRandom.hex #some random unguessable string
raw_token, hashed_token = Devise.token_generator.generate(User, :reset_password_token)
user.reset_password_token = hashed_token
user.reset_password_sent_at = Time.now.utc
user.email = 'user#usercompany.com'
user.save!
# Use a mailer you've written, such as:
AccountMailer.set_password_notice(user, raw_token).deliver
The email view has this link:
www.oursite.com/users/password/edit?initial=true&reset_password_token=<%= #raw_token %>
Here is my snippet for mailer preview
class Devise::MailerPreview < ActionMailer::Preview
def reset_password_instructions
user = User.last
token = user.send(:set_reset_password_token)
Devise::Mailer.reset_password_instructions(user, token)
end
end
You can call
user.send(:set_reset_password_token)
It may not be stable, as it's a protected method but it can work for your case. Just cover it with a test.
(tested on Devise v. 3.4)

Resources