Search code examples
ruby-on-railsrubyverification

has_secure_password and email verification


has_secure_password in rails works well for signing up users by checking :password and :password_confirmation then logging a :password_digest field in the database. However, if I want to be able to verify the email address (by sending an email confirmation) how would I be able to do this with rails?


Solution

  • Generally to verify an email address, you send an email to the concerned email address ( with a link ) and the user clicks a link / verifies it. The link generally contains a token used to uniquely identify that email address. So you can add a verification_token field to your model, may be add verification_email_sent_at and verified_at fields as well, to keep track and use a controller action

       def verify_email
         @user = User.find_by_verification_token(params[:verification_token])
         if @user
            @user.verification_token = nil
            @user.verification_email_sent_at = nil
            @user.verified_at = Time.now
            @user.save
            # above lines can be part of method like @user.verify!
            redirect_to "/"
         else
            ...
         end
       end
    

    Also I'd strongly suggest instead of building your authentication solution take a look at

    https://github.com/plataformatec/devise

    Its pretty simple to use.