设想remember_me!不工作

时间:2015-06-15 03:36:03

标签: ruby-on-rails-4 devise

我的sessions_controller.rb文件中包含以下代码:

module V1
  class Users::SessionsController < Devise::SessionsController

    # POST /sign_in
    def new
      user = User.find_by_email(params[:user][:email]) if params[:user] 
      if user && user.valid_password?(params[:user][:password])
        sign_in(:user, user)
        current_user.remember_me!
        head 200
      else
        render status: 200, json: {errors: ["Incorrect email / username or password."]}.as_json
      end
    end

    # ...

  end
end

上述代码似乎运行正常,但是,在登录并访问我的/posts路线后,我收到错误消息告诉我“您需要先登录或注册才能继续。”

我的应用程序的结构:

controllers
├── v1
|   ├── users
|   |   ├── registrations_controller.rb
|   |   ├── sessions_controller.rb
|   |   ├── api_controller.rb
|   ├── posts_controller.rb
application_controller.rb

在我的帖子控制器中,我设置了before_action :authenticate_v1_user!。我正在使用rails来构建API,我正在通过从名为Postman的工具发送请求来测试上述路由。我也尝试过使用我的AngularJS应用程序(在与API不同的子域上)。当我刚刚通过向/sign_in发送正确的凭据登录时,为什么我会收到错误告诉我登录。是否有特殊注意事项,因为这只是一个API?

修改

我的user.rb文件:

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :email, presence: true, uniqueness: true
  validates :password, confirmation: true, presence: true
  validates :password_confirmation, presence: true
end

我的routes.rb文件:

Rails.application.routes.draw do
  devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations" }
  devise_scope :user do
    post "sign_in", to: "v1/users/sessions#new"
    delete "sign_out", to: "v1/users/sessions#destroy"
    post "register", to: "v1/users/registrations#create"
  end

  namespace :v1, defaults: {format: 'json'} do
    devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations" }
    # Routes for posts
    get 'posts(/index)', :to => 'posts#index'
    post 'posts/create'
    delete 'posts/:id', :to => 'posts#destroy'
    get 'posts/show'
    put 'posts/:id', :to => 'posts#update'
  end
end

0 个答案:

没有答案