百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
B

banken

> 后端框架
开源

适用于 Rails 的简单而轻量级的授权库

269 stars0 点赞8 次浏览
访问官网GitHub

工具介绍

适用于 Rails 的简单而轻量级的授权库

Simple and lightweight authorization library for Rails inspired by Pundit. Banken provides a set of helpers which restricts what resources a given user is allowed to access.

In first, Look this tutorial:

  • Tutorial
  • Tutorial (Japanese)

========

What's the difference between Banken and Pundit?

  • The difference between Banken and Pundit
  • The difference between Banken and Pundit (Japanese)

Installation

ruby
gem "banken"

Include Banken in your application controller:

ruby
# app/controllers/application_controller.rb
class ApplicationController 
  

If you are using namespace in your controller and policy, you can access the policy passing string like 'admin/posts' as a second argument. Below calls Admin::PostsLoyalty.

erb

  

Ensuring loyalties are used

Banken adds a method called verify_authorized to your controllers. This method will raise an exception if authorize! has not yet been called. You should run this method in an after_action to ensure that you haven't forgotten to authorize the action. For example:

ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  after_action :verify_authorized, except: :index
end

If you're using verify_authorized in your controllers but need to conditionally bypass verification, you can use skip_authorization. These are useful in circumstances where you don't want to disable verification for the entire action, but have some cases where you intend to not authorize.

ruby
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def show
    record = Record.find_by(attribute: "value")
    if record.present?
      authorize! record
    else
      skip_authorization
    end
  end
end

If you need to perform some more sophisticated logic or you want to raise a custom exception you can use the two lower level method banken_authorization_performed? which return true or false depending on whether authorize! have been called, respectively.

Just plain old Ruby

As you can see, Banken doesn't do anything you couldn't have easily done yourself. It's a very small library, it just provides a few neat helpers. Together these give you the power of building a well structured, fully working authorization system without using any special DSLs or funky syntax or anything.

Remember that all of the loyalty is just plain Ruby classes, which means you can use the same mechanisms you always use to DRY things up. Encapsulate a set of permissions into a module and include them in multiple loyalties. Use alias_method to make some permissions behave the same as others. Inherit from a base set of permissions. Use metaprogramming if you really have to.

Generator

Use the supplied generator to generate loyalties:

bash
rails g banken:loyalty posts

Closed systems

In many applications, only logged in users are really able to do anything. If you're building such a system, it can be kind of cumbersome to check that the user in a loyalty isn't nil for every single permission.

We suggest that you define a filter that redirects unauthenticated users to the login page. As a secondary defence, if you've defined an ApplicationLoyalty, it might be a good idea to raise an exception if somehow an unauthenticated user got through. This way you can fail more gracefully.

ruby
# app/loyalties/application_loyalty.rb
class ApplicationLoyalty
  def initialize(user, record)
    raise Banken::NotAuthorizedError, "must be logged in" unless user
    @user = user
    @record = record
  end
end

Rescuing a denied Authorization in Rails

Banken raises a Banken::NotAuthorizedError you can rescue_from in your ApplicationController. You can customize the user_not_authorized method in every controller.

ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  include Banken

  rescue_from Banken::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized
    flash[:alert] = "You are not authorized to perform this action."
    redirect_to(request.referrer || root_path)
  end
end

Creating custom error messages

NotAuthorizedErrors provide information on what query (e.g. :create?), what controller (e.g. PostsController), and what loyalty (e.g. an instance of PostsLoyalty) caused the error to be raised.

One way to use these query, record, and loyalty properties is to connect them with I18n to generate error messages. Here's how you might go about doing that.

ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  rescue_from Banken::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized(exception)
    loyalty_name = exception.loyalty.class.to_s.underscore

    flash[:error] = t "#{loyalty_name}.#{exception.query}", scope: "banken", default: :default
    redirect_to(request.referrer || root_path)
  end
end
yaml
en:
  banken:
    default: 'You cannot perform this action.'
    posts_loyalty:
      update?: 'You cannot edit this post!'
      create?: 'You cannot create posts!'

Of course, this is just an example. Banken is agnostic as to how you implement your error messaging.

Customize Banken user

In some cases your controller might not have access to current_user, or your current_user is not the method that should be invoked by Banken. Simply define a method in your controller called banken_user.

ruby
def banken_user
  User.find_by_other_means
end

Additional context

Banken strongly encourages you to model your application in such a way that the only context you need for authorization is a user object and a domain model that you want to check authorization for. If you find yourself needing more context than that, consider whether you are authorizing the right domain model, maybe another domain model (or a wrapper around multiple domain models) can provide the context you need.

Banken does not allow you to pass additional arguments to loyalties for precisely this reason.

However, in very rare cases, you might need to authorize based on more context than just the currently authenticated user. Suppose for example that authorization is dependent on IP address in addition to the authenticated user. In that case, one option is to create a special class which wraps up both user and IP and passes it to the loyalty.

ruby
class UserContext
  attr_reader :user, :ip

  def initialize(user, ip)
    @user = user
    @ip = ip
  end
end

# app/controllers/application_controller.rb
class ApplicationController
  include Banken

  def banken_user
    UserContext.new(current_user, request.ip)
  end
end

Strong parameters

In Rails 4 (or Rails 3.2 with the strong_parameters gem), mass-assignment protection is handled in the controller. With Banken you can control which attributes a user has access to update via your loyalties. You can set up a permitted_attributes method in your loyalty like this:

ruby
# app/loyalties/posts_loyalty.rb
class PostsLoyalty < ApplicationLoyalty
  def permitted_attributes
    if user.admin? || user.owner_of?(post)
      [:title, :body, :tag_list]
    else
      [:tag_list]
    end
  end
end

You can now retrieve these attributes from the loyalty:

ruby
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def update
    @post = Post.find(params[:id])
    if @post.update_attributes(post_params)
      redirect_to @post
    else
      render :edit
    end
  end

  private

  def post_params
    params.require(:post).permit(loyalty(@post).permitted_attributes)
  end
end

However, this is a bit cumbersome, so Banken provides a convenient helper method:

ruby
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def update
    @post = Post.find(params[:id])
    if @post.update_attributes(permitted_attributes(@post))
      redirect_to @post
    else
      render :edit
    end
  end
end

License

Licensed under the MIT license, see the separate LICENSE.txt file.

Issues· 2 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyauthorizationbankenrails

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架