设计 - 使用 Ajax 登录

Devise - Sign In with Ajax

是否有可能为 ajax 通信修改设计 SessionsController

编辑

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

1。生成 Devise 控制器,以便我们对其进行修改

rails g devise:controllers

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

中拥有所有控制器

2。编辑 routes.rb

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

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

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

3。修改sessions_controller.rb

找到create方法改成

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

受保护

后创建新方法
def invalid_login_attempt
  set_flash_message(:alert, :invalid)
  render json: flash[:alert], status: 401
end

4。 devise.rb

将其插入 config/initializers/devise.rb

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

5。无效的电子邮件或密码消息

下的 config/locales/devise.en.yml 中插入一条新消息
invalid: "Invalid email or password."

6。查看

= 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

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

说明

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

action: "create"
commit: "Sign in"
controller: "users/sessions"
user: {
  email: "test@test.cz"
  password: "123"
  remember_me: "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"
email: "test@test.cz"
id: 1
updated_at: "2015-06-13T19:56:54.000Z"

否则会

null

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

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

最后登录

sign_in :user, resource

来源

SessionsController

帮助了我 Andreas Lyngstad