构建API服务器2

1. 实现unauthenticated!方法

class Api::V1::BaseController < ApplicationController
+ def unauthenticated!
+   api_error(status: 401)
+ end
end

2. 增加授权

+gem 'pundit'
$ bundle install

修改app/controllers/api/v1/base_controller.rb

class Api::V1::BaseController < ApplicationController
 + include Pundit
end
$ rails g pundit:install
create app/policies/application_policy.rb

将policies目录放到rails的自动加载路径中:
修改config/application.rb

module BuildAnApiRailsDemo
 class Application < Rails::Application
+ config.autoload_paths << Rails.root.join('app/policies')
 end
end

创建和user相关的权限机制

$ rails g pundit:policy user

修改app/policies/user_policy.rb

class UserPolicy < ApplicationPolicy
 def show?
   return true
 end

 def create?
   return true
 end

 def update?
   return true if user.admin?
   return true if record.id == user.id
 end

 def destroy?
   return true if user.admin?
   return true if record.id == user.id
 end

 class Scope < ApplicationPolicy::Scope
   def resolve
     scope
   end
 end
end

使用UserPolicy
修改app/controller/api/users_controller.rb

class Api::V1::UsersController < Api::V1::BaseController
 def update
 @user = User.find(params[:id])
+  return api_error(status: 403) if !UserPolicy.new(current_user, @user).update?
   @user.update_attributes(update_params)
 end
end

你可能感兴趣的:(构建API服务器2)