ruby - Devise - Sign In with Ajax -
is here possibility modify devise sessionscontroller ajax communication?
edit
i found solution, , posted answers, thanks
1. generate devise controllers can modify it
rails g devise:controller 
now have controllers in app/controllers/[model] directory
2. edit routes.rb
let's set devise use our modified sessionscontroller
first add code (of course change :users devise model) config/routes.rb
devise_for :users, controllers: { sessions: 'users/sessions' } 3. modify sessions_controller.rb

find create method , change to
def create resource = user.find_for_database_authentication(email: params[:user][:email]) return invalid_login_attempt unless resource if resource.valid_password?(params[:user][:password]) sign_in :user, resource return render nothing: true end invalid_login_attempt end create new method after protected
def invalid_login_attempt set_flash_message(:alert, :invalid) render json: flash[:alert], status: 401 end 4. devise.rb
insert config/initializers/devise.rb
config.http_authenticatable_on_xhr = false config.navigational_formats = ["*/*", :html, :json] 5. invalid email or password message
insert new message config/locales/devise.en.yml under sessions
invalid: "invalid email or password." 
6. view
= form_for resource, url: session_path(:user), remote: true |f| = f.text_field :email = f.password_field :password = f.label :remember_me remember me = f.check_box :remember_me = f.submit value: 'sign in' :javascript $(document).ready(function() { //form id $('#new_user') .bind('ajax:success', function(evt, data, status, xhr) { //function called on status: 200 (for ex.) console.log('success'); }) .bind("ajax:error", function(evt, xhr, status, error) { //function called on status: 401 or 500 (for ex.) console.log(xhr.responsetext); }); }); important thing remote: true
the reason why using status 200 or 401 unlike {status: 'true'} less data size, faster , cleaner.
explanation
on signing in, these data in params
action: "create" commit: "sign in" controller: "users/sessions" user: { email: "test@test.cz" password: "123" remember_me: "0" } utf8: "✓" before signing, need authorize user.
resource = user.find_for_database_authentication(email: params[:user][:email]) user.find_for_database_authentication
if user found, resource filled like
created_at: "2015-05-29t12:48:04.000z" email: "test@test.cz" id: 1 updated_at: "2015-06-13t19:56:54.000z" otherwise be
null if user authenticated, validate password
if resource.valid_password?(params[:user][:password]) and sign in
sign_in :user, resource sources
helped me andreas lyngstad
Comments
Post a Comment