Rails API Forgot Password not Rendering View - ruby-on-rails

so i'm building a forgot password in my Rails API, i was able to send the reset password email, but when i go to the link, it gives me 204 No Content.
I'm using lvh.me to test my api subdomain in development
This is my passwords_controller.rb
class User::PasswordsController < Devise::PasswordsController
def create
puts params
self.resource = resource_class.send_reset_password_instructions(params)
if successfully_sent?(resource)
render json: {status: 'ok'}, status: :ok, location: after_sending_reset_password_instructions_path_for(resource_name)
else
render json: {error: ['Error occurred']}, status: :internal_server_error
end
end
# GET /user/password/edit?reset_password_token=blablabla
def edit
self.resource = resource_class.new
set_minimum_password_length
resource.reset_password_token = params[:reset_password_token]
end
# PUT /user/password
def update
self.resource = resource_class.reset_password_by_token(resource_params)
yield resource if block_given?
if resource.errors.empty?
resource.unlock_access! if unlockable?(resource)
if Devise.sign_in_after_reset_password
flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
set_flash_message!(:notice, flash_message)
resource.after_database_authentication
sign_in(resource_name, resource)
else
set_flash_message!(:notice, :updated_not_active)
end
respond_with resource, location: after_resetting_password_path_for(resource)
else
set_minimum_password_length
respond_with resource
end
end
protected
def after_resetting_password_path_for(resource)
Devise.sign_in_after_reset_password ? after_sign_in_path_for(resource) : new_session_path(resource_name)
end
# The path used after sending reset password instructions
def after_sending_reset_password_instructions_path_for(resource_name)
new_session_path(resource_name) if is_navigational_format?
puts new_session_path(resource_name) if is_navigational_format?
end
# Check if a reset_password_token is provided in the request
def assert_reset_token_passed
if params[:reset_password_token].blank?
set_flash_message(:alert, :no_token)
redirect_to new_session_path(resource_name)
end
end
# Check if proper Lockable module methods are present & unlock strategy
# allows to unlock resource on password reset
def unlockable?(resource)
resource.respond_to?(:unlock_access!) &&
resource.respond_to?(:unlock_strategy_enabled?) &&
resource.unlock_strategy_enabled?(:email)
end
def translation_scope
'devise.passwords'
end
end
The generated link looks like this: http://api.lvh.me:3000/user/password/edit?reset_password_token=blablabla
My controllers and views structure is:
controllers/user/passwords_controller.rb
views/user/passwords/edit.html.erb
My routes.rb for user looks like this:
constraints subdomain: 'api' do
scope module: 'user' do
devise_for :users,
path: '/user',
path_names: {
registration: 'signup',
sign_in: 'login',
sign_out: 'logout'
},
controllers: {
sessions: 'user/sessions',
registrations: 'user/registrations',
passwords: 'user/passwords'
}
end
end

Figured out that i had
class ApplicationController < ActionController::API which was keeping me from rendering Views, simply changing to
class ApplicationController < ActionController::Base resolved the issue

Related

Rails 5 Devise: Return JSON On sign_in Failure

Everything I seem to find on this issue is out of date and/or doesn't work.
GOAL: When a user tries to sign in via JSON from a mobile application and the username or password is wrong, I would like Rails to return JSON data so the errors can be displayed on the app.
So far I have done the following:
class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
skip_before_action :verify_authenticity_token
respond_to :json
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_flashing_format?
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, :location => after_sign_in_path_for(resource) do |format|
format.json {render :json => resource } # this code will get executed for json request
end
end
end
This works well on success, but I'm not sure what to do when it fails. Right now it returns an undefined method error:
undefined method `users_url' for #<Users::SessionsController:0x0000000195fa28>
You should take a look at this SO question that will point you in the right direction.
Basically you need to handle the login failure. You could do this:
class CustomFailure < Devise::FailureApp
def respond
if http_auth?
http_auth
elsif request.content_type == "application/json"
self.status = 401
self.content_type = "application/json"
self.response_body = {success: false, error: "Unauthorized"}.to_json
else
redirect
end
end
end
This handles JSON requests. I hope this helps!
Figured it out. CustomFailure never seemed to work, no matter how many things I tried. I was able to do this within the SessionsController via handle_failed_login:
class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
after_filter :handle_failed_login, :only => :new
skip_before_action :verify_authenticity_token
respond_to :json
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_flashing_format?
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, :location => after_sign_in_path_for(resource) do |format|
format.json {render :json => resource } # this code will get executed for json request
end
end
private
def handle_failed_login
if failed_login?
render json: { success: false, errors: ["Login Credentials Failed"] }, status: 401
end
end
def failed_login?
(options = env["warden.options"]) && options[:action] == "unauthenticated"
end
end

Gem mailcatcher - do not received emails

I create new user. After creating should received confirmation mail. but when i open mailcatcher(http://127.0.0.1:1080/)... nothing!
i use mailcatcher v. 0.5.12, Rails 3.2.22
In development.rb added:
# Don't care if the mailer can't send
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
config.action_mailer.raise_delivery_errors = true
What is wrong with settings? How check error? Please, help, thank you.
UPDATE
Confirmationcontroller:
class ConfirmationsController < Devise::ConfirmationsController
def new
super
resource.login = current_user.email if user_signed_in?
end
protected
def after_resending_confirmation_instructions_path_for(resource_name)
if user_signed_in?
home_path
else
new_session_path(resource_name)
end if is_navigational_format?
end
# The path used after confirmation.
def after_confirmation_path_for(resource_name, resource)
'/profile'
end
end
userscontrollers.rb:
# encoding: utf-8
class UsersController < ApplicationController
before_filter :require_admin, only: [:add_moderator, :remove_moderator, :destroy]
before_filter :require_moderator, only: [:edit, :update, :paid_on, :paid_off,
:ban, :unban]
before_filter :authenticate_user!, except: [:new, :create]
before_filter :load_user, only: [:show, :photos, :videos, :audios,
:buy_rating, :do_buy_rating,
:add_moderator, :remove_moderator,
:edit, :update, :paid_on, :paid_off, :ban, :unban, :destroy,
:add_funds, :mute, :unmute]
layout :determine_layout
def new
#user = User.new
#invite = Invite.find_by_code(session[:invite]) if session[:invite].present?
#user.email = #invite.email if #invite
end
def create
#user = User.new(params[:user])
raise ActiveRecord::RecordInvalid.new(#user) unless verify_recaptcha(model: #user, message: 'message')
#invite = Invite.find_by_code(session[:invite]) if session[:invite].present?
User.transaction do
#user.save!
#user.current_password = #user.password
#user.theme_ids = params[:user][:theme_ids]
#user.group_ids = [114, 130]
#user.save!
end
if #invite
#invite.new_user = #user
#invite.use!
end
redirect_to #user
rescue ActiveRecord::RecordInvalid
render :new
end
.........................................................
.........................................................
private
def determine_layout
return 'welcome' if %w(new create).include?(params[:action])
return 'dating' if params[:action]=='search'
'inner'
end
end
registrationscontroller.rb:
# encoding: utf-8
class RegistrationsController < Devise::RegistrationsController
def create
if verify_recaptcha
super
else
flash.delete :recaptcha_error
build_resource
resource.valid?
resource.errors.add(:base, :invalid_recaptcha)
# clean_up_passwords(resource)
render :new
end
rescue ActiveRecord::RecordNotUnique
render :new
end
def update
redirect_to '/settings'
end
# def update
# # required for settings form to submit when password is left blank
# if params[:user][:password].blank?
# params[:user].delete("password")
# params[:user].delete("current_password")
# end
#
# #user = User.find(current_user.id)
# if update_user
# set_flash_message :notice, :updated
# # Sign in the user bypassing validation in case his password changed
# sign_in #user, :bypass => true
# redirect_to after_update_path_for(#user)
# else
# render "edit"
# end
# end
def edit
redirect_to '/settings'
end
def destroy
current_password = params[:user].delete(:current_password)
if resource.valid_password?(current_password)
resource.mark_as_deleted!
render inline: "$('body').fadeOut(3000, function() { document.location = 'http://ya.ru'; })"
else
render inline: "$.flash.error('error')"
end
# Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
# set_flash_message :notice, :destroyed if is_navigational_format?
# respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
end
protected
def after_sign_up_path_for(resource)
'/profile'
end
end
Code was without Devise.mail_confirmation_instructions(#user).deliver. I realized, now all in fine

Devise sign up AJAX not working

I am trying to setup a registration form using devise and AJAX.
On a newly generated app it works perfectly but when I try and add it to a project, I do not have success
registration controller
https://gist.github.com/mosinski/8568126
my partial form:
https://gist.github.com/mosinski/8577429
my application.js:
https://gist.github.com/mosinski/8577480
my inicializer:
https://gist.github.com/mosinski/8577533
my application helper:
https://gist.github.com/mosinski/8577564
my form is partial in bootstrap modal.
The whole problem is that it not sending as js but as text/html why ?! ;]
1. Routes
Have you declared the custom controllers in your routes.rb file?
#config/routes.rb
devise_for :users, controllers: { sessions: "sessions", registrations: "registrations" }
2. Forms
Are you sure you're sending the request from your partial form?
Devise generates its own views (which you can typically find at /views/devise). If you're using the standard Devise forms, you'll be sending standard HTML mime-types, and so you'll have to ensure you're using your partial
That's all I can glean from your code currently! Of course we can discuss any fixes in the comments
Update
Here's our working registrations controller:
class RegistrationsController < DeviseController
prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]
before_filter :configure_permitted_parameters
prepend_view_path 'app/views/devise'
# GET /resource/sign_up
def new
build_resource({})
respond_with self.resource
end
# POST /resource
def create
build_resource(sign_up_params)
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_to do |format|
format.json { render :json => resource.errors, :status => :unprocessable_entity }
format.html { respond_with resource }
end
end
end
# GET /resource/edit
def edit
render :edit
end
# PUT /resource
# We need to use a copy of the resource because we don't want to change
# the current user in place.
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if update_resource(resource, account_update_params)
if is_navigational_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
set_flash_message :notice, flash_key
end
sign_in resource_name, resource, :bypass => true
respond_with resource, :location => after_update_path_for(resource)
else
clean_up_passwords resource
respond_with resource
end
end
# DELETE /resource
def destroy
resource.destroy
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message :notice, :destroyed if is_navigational_format?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
def cancel
expire_session_data_after_sign_in!
redirect_to new_registration_path(resource_name)
end
protected
# Custom Fields
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name,
:email, :password, :password_confirmation)
end
end
def update_needs_confirmation?(resource, previous)
resource.respond_to?(:pending_reconfirmation?) &&
resource.pending_reconfirmation? &&
previous != resource.unconfirmed_email
end
# By default we want to require a password checks on update.
# You can overwrite this method in your own RegistrationsController.
def update_resource(resource, params)
resource.update_with_password(params)
end
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
self.resource = resource_class.new_with_session(hash || {}, session)
end
# Signs in a user on sign up. You can overwrite this method in your own
# RegistrationsController.
def sign_up(resource_name, resource)
sign_in(resource_name, resource)
end
# The path used after sign up. You need to overwrite this method
# in your own RegistrationsController.
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource)
end
# The path used after sign up for inactive accounts. You need to overwrite
# this method in your own RegistrationsController.
def after_inactive_sign_up_path_for(resource)
respond_to?(:root_path) ? root_path : "/"
end
# The default url to be used after updating a resource. You need to overwrite
# this method in your own RegistrationsController.
def after_update_path_for(resource)
signed_in_root_path(resource)
end
# Authenticates the current scope and gets the current resource from the session.
def authenticate_scope!
send(:"authenticate_#{resource_name}!", :force => true)
self.resource = send(:"current_#{resource_name}")
end
def sign_up_params
devise_parameter_sanitizer.sanitize(:sign_up)
end
def account_update_params
devise_parameter_sanitizer.sanitize(:account_update)
end
end

RESTful login with devise (Rails 4)

How do I do RESTful sign-up and sign-in using devise in Ruby on Rails (I am using version 4)?
I could not find any documentation with regards to the parameters (e.g. email, password) that I should POST to the server.
It seems that RESTful login using JSON data (e.g. via AJAX) is not supported out of the box in the current version of devise - the default behavior is to send back a whole HTML page for any type of request made, instead of a JSON object for handling JSON request specifically.
Does this mean that I need to create/extend custom controller for handling user registration and login for RESTful apps using JSON? If so, please elaborate.
If you're using Devise, all of the RESTful actions have been provided through their forms & controller (if you browse to http://your-app.com/users/sign_up, you'll be able to register etc)
If you're looking to make your Devise handle JSON, you are correct in that it's not handled "out of the box", but fortunately, there is a way to do it:
Live Code
#config/routes (notice custom controllers)
devise_for :users, :path => '', :controllers => {:sessions => 'sessions', :registrations => 'registrations'}
#app/controllers/registrations_controller.rb
class RegistrationsController < DeviseController
prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]
before_filter :configure_permitted_parameters
prepend_view_path 'app/views/devise'
# GET /resource/sign_up
def new
build_resource({})
respond_with self.resource
end
# POST /resource
def create
build_resource(sign_up_params)
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_to do |format|
format.json { render :json => resource.errors, :status => :unprocessable_entity }
format.html { respond_with resource }
end
end
end
# GET /resource/edit
def edit
render :edit
end
# PUT /resource
# We need to use a copy of the resource because we don't want to change
# the current user in place.
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if update_resource(resource, account_update_params)
if is_navigational_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
set_flash_message :notice, flash_key
end
sign_in resource_name, resource, :bypass => true
respond_with resource, :location => after_update_path_for(resource)
else
clean_up_passwords resource
respond_with resource
end
end
# DELETE /resource
def destroy
resource.destroy
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message :notice, :destroyed if is_navigational_format?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
def cancel
expire_session_data_after_sign_in!
redirect_to new_registration_path(resource_name)
end
protected
# Custom Fields
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name,
:email, :password, :password_confirmation)
end
end
def update_needs_confirmation?(resource, previous)
resource.respond_to?(:pending_reconfirmation?) &&
resource.pending_reconfirmation? &&
previous != resource.unconfirmed_email
end
# By default we want to require a password checks on update.
# You can overwrite this method in your own RegistrationsController.
def update_resource(resource, params)
resource.update_with_password(params)
end
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
self.resource = resource_class.new_with_session(hash || {}, session)
end
# Signs in a user on sign up. You can overwrite this method in your own
# RegistrationsController.
def sign_up(resource_name, resource)
sign_in(resource_name, resource)
end
# The path used after sign up. You need to overwrite this method
# in your own RegistrationsController.
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource)
end
# The path used after sign up for inactive accounts. You need to overwrite
# this method in your own RegistrationsController.
def after_inactive_sign_up_path_for(resource)
respond_to?(:root_path) ? root_path : "/"
end
# The default url to be used after updating a resource. You need to overwrite
# this method in your own RegistrationsController.
def after_update_path_for(resource)
signed_in_root_path(resource)
end
# Authenticates the current scope and gets the current resource from the session.
def authenticate_scope!
send(:"authenticate_#{resource_name}!", :force => true)
self.resource = send(:"current_#{resource_name}")
end
def sign_up_params
devise_parameter_sanitizer.sanitize(:sign_up)
end
def account_update_params
devise_parameter_sanitizer.sanitize(:account_update)
end
end
This is probably excessive, but it works (try registering or logging in at http://firststop.herokuapp.com). You could probably achieve the same thing with this code (completely untested):
def create #-> completely untested & speculative
super do |format|
format.json { render :json => resource.errors, :status => :unprocessable_entity }
format.html { respond_with resource }
end
end
Login Code
class SessionsController < DeviseController
prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
prepend_before_filter :allow_params_authentication!, :only => :create
prepend_before_filter { request.env["devise.skip_timeout"] = true }
prepend_view_path 'app/views/devise'
# GET /resource/sign_in
def new
self.resource = resource_class.new(sign_in_params)
clean_up_passwords(resource)
respond_with(resource, serialize_options(resource))
end
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_to do |format|
format.json { render :json => {}, :status => :ok }
format.html { respond_with resource, :location => after_sign_in_path_for(resource) }
end
end
# DELETE /resource/sign_out
def destroy
redirect_path = after_sign_out_path_for(resource_name)
signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
set_flash_message :notice, :signed_out if signed_out && is_navigational_format?
# We actually need to hardcode this as Rails default responder doesn't
# support returning empty response on GET request
respond_to do |format|
format.all { head :no_content }
format.any(*navigational_formats) { redirect_to redirect_path }
end
end
protected
def sign_in_params
devise_parameter_sanitizer.sanitize(:sign_in)
end
def serialize_options(resource)
methods = resource_class.authentication_keys.dup
methods = methods.keys if methods.is_a?(Hash)
methods << :password if resource.respond_to?(:password)
{ :methods => methods, :only => [:password] }
end
def auth_options
{ :scope => resource_name, :recall => "#{controller_path}#new" }
end
end

How do I login a user with devise?

I have my rails application and I am running into a major issue with devise. I have a controller:
class Users::SessionsController < Devise::SessionsController
prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
include Devise::Controllers::InternalHelpers
def new
clean_up_passwords(build_resource)
respond_to do |format|
format.html { render :layout => "sessions" }
format.mobile
end
end
# POST /resource/sign_in
def create
resource = User.find_by_email(params[:user][:email])
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
set_flash_message :notice, :signed_in
sign_in_and_redirect(resource_name, resource)
end
end
The problem is it never logs the user in, it always stops at this line
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
I even put tons of loggers in the actual gem files to see if I could see anything off but nothing and I really have no idea how to fix this. If I comment this line out then the user gets logged in but fails if the email is not in the db and works for any password (which is definitely not the right solution)
How do I fix this?
UPDATE
this works but seems very hackish
# POST /resource/sign_in
def create
resource = User.find_by_email(params[:user][:email])
redirect_to(new_user_session_path, :notice => 'Invalid Email Address or Password. Password is case sensitive.') and return if resource.encrypted_password.blank?
bcrypt = BCrypt::Password.new(resource.encrypted_password)
password = BCrypt::Engine.hash_secret("#{params[:user][:password]}#{resource.class.pepper}", bcrypt.salt)
valid = Devise.secure_compare(password, resource.encrypted_password)
# resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
if valid
set_flash_message :notice, :signed_in
sign_in_and_redirect(resource_name, resource)
else
redirect_to(new_user_session_path, :notice => 'Invalid Email Address or Password. Password is case sensitive.') and return
end
end
If you want to sign in a user, use the sign_in helper inside your controller's action:
sign_in(:user, user)
resource = warden.authenticate!(:scope => resource_name)
sign_in(resource_name, resource)
I found this post useful for setting up a login for request specs.
https://makandracards.com/makandra/37161-rspec-devise-how-to-sign-in-users-in-request-specs
module DeviseRequestSpecHelpers
include Warden::Test::Helpers
def sign_in(resource_or_scope, resource = nil)
resource ||= resource_or_scope
scope = Devise::Mapping.find_scope!(resource_or_scope)
login_as(resource, scope: scope)
end
def sign_out(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
logout(scope)
end
end
Include it in your spec_helper
RSpec.configure do |config|
config.include DeviseRequestSpecHelpers, type: :request
end
And sign in as needed
sign_in create(:user, name: 'John Doe')
Here is how standard create actions works:
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message!(:notice, :signed_in)
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
end
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb#L18

Resources