繁体   English   中英

Rails Devise通过身份验证令牌查找用户

[英]Rails Devise find user by authentication token

我正在尝试这样做:

类NotesController <ApplicationController

定义指数

@user = User.find_by_authentication_token(params [:token])

@notes = @ user.notes

...

但是我遇到一个错误:

Started POST "/api/login" for 10.0.0.4 at 2013-07-22 13:20:43 +0300
Processing by Api::LoginController#login as JSON
  Parameters: {"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}, "login"=>{"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'pp@pp.pp' LIMIT 1
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 200 OK in 119ms (Views: 0.0ms | ActiveRecord: 3.0ms)


Started GET "/notes?token=GFRWkkLCq3xQx5rTRTFp" for 10.0.0.4 at 2013-07-22 13:20:44 +0300
Processing by NotesController#index as JSON
  Parameters: {"token"=>"GFRWkkLCq3xQx5rTRTFp", "note"=>{}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `notes' for nil:NilClass):
  app/controllers/notes_controller.rb:7:in `index'

如您所见,代码

User.find_by_authentication_token(params[:token])

不断返回nil。

弄清楚了:问题是我忘记了使用方法user.ensure_authentication_token后的保存(提交)用户。

def login
    user = User.find_for_database_authentication(:email => params[:user][:email])
    if user.nil?
      render :json => {:result => 'ERROR'}
    else
      if user.valid_password?(params[:user][:password])
        user.ensure_authentication_token
        user.save
        render :json => {:result => user.authentication_token}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM