设计 - 使用 Ajax 登录 [英] Devise - Sign In with Ajax

查看:26
本文介绍了设计 - 使用 Ajax 登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是否有可能修改设计 SessionsController 以进行 ajax 通信?

编辑

我找到了解决方案,并将其发布到答案中,谢谢

解决方案

1.生成设计控制器以便我们可以修改它

rails g devise:controllers

现在我们在app/controllers/[model] 目录

中拥有所有控制器

2.编辑routes.rb

让我们设置 Devise 使用我们修改后的 SessionsController

首先将此代码(当然更改:users到您的设计模型)添加到config/routes.rb

devise_for :用户,控制器:{会话:'用户/会话'}

3.修改sessions_controller.rb

找到create方法,改成

def 创建资源 = User.find_for_database_authentication(email: params[:user][:email])除非资源,否则返回 invalid_login_attempt如果 resource.valid_password?(params[:user][:password])登录:用户,资源返回什么都不渲染:true结尾invalid_login_attempt结尾

保护

后创建新方法

def invalid_login_attemptset_flash_message(:alert,:invalid)渲染 json:flash[:alert],状态:401结尾

4.设计.rb

将其插入config/initializers/devise.rb

config.http_authenticable_on_xhr = falseconfig.navigational_formats = ["*/*", :html, :json]

5.无效的电子邮件或密码信息

sessions

下的 config/locales/devise.en.yml 中插入一条新消息

invalid: "无效的电子邮件或密码."

6.查看

= form_for 资源,url:session_path(:user),remote:true do |f|= f.text_field :email= f.password_field :密码= f.label :remember_me 做记得我= f.check_box :remember_me= f.submit value: '登录':javascript$(document).ready(function() {//表单ID$('#new_user').bind('ajax:success', function(evt, data, status, xhr) {//状态调用的函数:200(例如)console.log('成功');}).bind("ajax:error", function(evt, xhr, status, error) {//在状态上调用的函数:401 或 500(例如)控制台日志(xhr.responseText);});});

<块引用>

重要的事情远程:真实

我使用 status 200 或 401 与 {status: 'true'} 不同的原因是数据量更小,所以它更快更干净.

说明

登录时,您会在参数中获得这些数据

动作:创建"提交:登录"控制器:用户/会话"用户:{电子邮件:test@test.cz"密码:123"记住_我:0"}utf8:✓"

在签名之前,您需要对用户进行授权.

resource = User.find_for_database_authentication(email: params[:user][:email])

User.find_for_database_authentication

如果找到用户,资源将填充类似

created_at: "2015-05-29T12:48:04.000Z"电子邮件:test@test.cz"编号:1更新时间:2015-06-13T19:56:54.000Z"

否则会

null

如果用户通过身份验证,我们将验证他的密码

if resource.valid_password?(params[:user][:password])

最后登录

sign_in : 用户,资源

来源

SessionsController

帮助了我Andreas Lyngstad

Is here any possibility to modify devise SessionsController for ajax communication?

Edit

I found the solution, and posted it into answers, thanks

解决方案

1. Generate Devise controllers so we can modify it

rails g devise:controllers

Now we have all controllers in the app/controllers/[model] directory

2. Edit routes.rb

Let's set Devise to use our modified SessionsController

First add this code (of course change :users to your devise model) into config/routes.rb

devise_for :users, controllers: {
  sessions: 'users/sessions'
}

3. Modify sessions_controller.rb

Find the create method and change it 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 this into config/initializers/devise.rb

config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :json]

5. Invalid email or password message

Insert a new message into config/locales/devise.en.yml under the sessions

invalid: "Invalid email or password."

6. View

= form_for resource, url: session_path(:user), remote: true do |f|
  = f.text_field :email
  = f.password_field :password
  = f.label :remember_me do
    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 I am using status 200 or 401 unlike {status: 'true'} is less data size, so it is much faster and cleaner.

Explanation

On signing in, you get 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, you need to authorize the user.

resource = User.find_for_database_authentication(email: params[:user][:email])

User.find_for_database_authentication

If user is found, resource will be filled with something like

created_at: "2015-05-29T12:48:04.000Z"
email: "test@test.cz"
id: 1
updated_at: "2015-06-13T19:56:54.000Z"

Otherwise will be

null

If the user is authenticated, we are about to validate his password

if resource.valid_password?(params[:user][:password])

And finally sign in

sign_in :user, resource

Sources

SessionsController

Helped me Andreas Lyngstad

这篇关于设计 - 使用 Ajax 登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆