简体   繁体   English

具有常规授权和API的Rails Devise

[英]Rails Devise with regular authorization and API

On my project devise provides user registration/authentication for admin panel. 在我的项目中,devise为管理面板提供了用户注册/身份验证。 I need to add API method which will sign_in user and return JSON with status + session cookie. 我需要添加将登录用户并返回带有状态+会话cookie的JSON的API方法。

routes.rb routes.rb

devise_for :user, :controllers => {sessions: 'sessions'}

Session Controller 会话控制器

class SessionsController < Devise::SessionsController
  skip_before_filter :verify_authenticity_token

  def create
    resource = warden.authenticate!(:scrope => resource_name, :recall => "#{controller_path}#failure")
    sign_in(resource_name, resource)

    respond_to do |format|
      format.html { respond_with resource, :location => after_sign_in_path_for(resource) }
      format.json { render json: {:success => 1}}
    end
  end

If I will post data to user/sign_in.json, it will render {"success": 1} which is exactly that I need. 如果我将数据发布到user / sign_in.json,它将呈现{“ success”:1},这正是我所需要的。

But the question is how to move user/sign_in.json on some custom url such as /api/sign_in ? 但是问题是如何在一些自定义网址(例如/ api / sign_in)上移动user / sign_in.json?

Surround the route in a namespace: 将路由包围在名称空间中:

namespace :api do
  devise_for :user, :controllers => {sessions: 'sessions'}
end

Did it like that: 这样吗:

api_controller.rb api_controller.rb

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

    if resource.nil?
      render :json=> {:success => 0, :error => "No Such User"}, :status=>401
    else
      if resource.valid_password?(params[:user][:password])
        sign_in(:user, resource)
        render :json=> {:success => 1}
      else
        render :json=> {:success => 0, :error => "Wrong Password"}, :status=>401
      end
    end 
  end

routes.rb routes.rb

namespace :api do
    namespace :v1 do
      get :sign_in, :to => 'api#create_session'
    end
  end

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

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