Devise 给项目添加权限验证系统


  1. 在我们之前的文章中我们已经介绍了一些登录和验证授权的解决方案,现在我们来介绍另外一个。最近,在ruby社区Devise越来越广泛的被采用来解决维护权限和验证。Devise源于Warden,而warden是一个基于Rack的验证权限gem,不过,使用devise实际并不需要任何关于warden的知识。   
  2.   
  3. 如果你之前有一些其他类似的维护验证权限功能的gem的使用经验的话,你会发现Devise的和他们的不同之处在于,提供了从页面到model的实现。相比而言,例如Authlogic就只实现了丢与model层的实现,这时你就要自己去处理view层实现。而Devise是基于Rails 引擎开发的所以就可以同时提供controllers和view的实现。从功能角度来看,Devise提供了11个方面的在维护和验证权限过程的功能模块,这些模块都是可配置的。例如,其中Rememberable模块是使用cookie保存用户的登录信息,Recoverable是用来处理用户重置口令的。可定制的模块使用可以很容易的根据自己的业务需求配置对应的相应功能模块。   


Devise : 简单引用

引用:

  1. gem 'devise'  
  2. rails generate devise:install  
  3. rails generate devise MODEL  

我们可以用的变量:
  1. before_filter :authenticate_member!  
  2.   
  3. member_signed_in?  
  4.   
  5. current_member  
  6.   
  7. member_session  

例如:
  1. class HomesController < ApplicationController  
  2.   before_filter :authenticate_user!, :except => [:show, :index]   
  3.   
  4.   def index  
  5.     if !user_signed_in?  
  6.       return redirect_to '/account/sign_in'  
  7.     end  
  8.     return redirect_to "/admin/index" if current_user.admin  
  9.   end  
  10.   
  11.   def show  
  12.       
  13.   end  
  14. end  

创建view模型:
  1. rails generate devise:views users  


下面开始:

1.gem

  1. gem 'devise'  

2.routes 

0> 运行 

rails generate devise MODEL
  1. devise_for :users,:path => 'account',   
  2.                   :controllers => {  
  3.                     :registrations => :account,  
  4.                     :sessions => :sessions  
  5.                   }  

1>db/migrate/......._devise_cretate_module
  1. class DeviseCreateUsers < ActiveRecord::Migration  
  2.   def change  
  3.     create_table(:usersdo |t|  
  4.       ## Database authenticatable  
  5.       t.string :email,              :null => false:default => ""  
  6.       t.string :encrypted_password:null => false:default => ""  
  7.   
  8.       ## Recoverable  
  9.       t.string   :reset_password_token  
  10.       ## Rememberable  
  11.       t.datetime :reset_password_sent_at  
  12.   
  13.       ## Rememberable  
  14.       t.datetime :remember_created_at  
  15.   
  16.       ## Trackable  
  17.       t.integer  :sign_in_count:default => 0  
  18.       t.datetime :current_sign_in_at  
  19.       t.datetime :last_sign_in_at  
  20.       t.string   :current_sign_in_ip  
  21.       t.string   :last_sign_in_ip  
  22.   
  23.       t.string :name, comment:"姓名"  
  24.       t.string :phone, comment:"电话"  
  25.       t.text :bio,comment:"用户介绍"  
  26.       t.boolean :receive_announcements,comment:"是否接收网店邮件信息",default: true  
  27.       t.references :shop  
  28.       t.string :avatar_image_uid  
  29.   
  30.       #增加用户权限  
  31.       t.boolean :admin, default: true  
  32.   
  33.       ## Confirmable  
  34.       # t.string   :confirmation_token  
  35.       # t.datetime :confirmed_at  
  36.       # t.datetime :confirmation_sent_at  
  37.       # t.string   :unconfirmed_email # Only if using reconfirmable  
  38.   
  39.       ## Lockable  
  40.       # t.integer  :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts  
  41.       # t.string   :unlock_token # Only if unlock strategy is :email or :both  
  42.       # t.datetime :locked_at  
  43.   
  44.       ## Token authenticatable  
  45.       t.string :authentication_token  
  46.   
  47.   
  48.       t.timestamps  
  49.     end  
  50.   
  51.     add_index :users:shop_id  
  52.     add_index :users, [:shop_id            , :email]        , :unique => true  
  53.     add_index :users:reset_password_token:unique => true  
  54.     # add_index :users, :confirmation_token,   :unique => true  
  55.     # add_index :users, :unlock_token,         :unique => true  
  56.     add_index :users:authentication_token:unique => true  
  57.   end  
  58. end  

2>app/models/module.rb
  1. class User < ActiveRecord::Base  
  2.   
  3.   belongs_to   :shop  
  4.   has_many     :articles  
  5.   has_many     :permissions    , dependent: :destroy  
  6.   
  7.   # Include default devise modules. Others available are:  
  8.   # :token_authenticatable, :confirmable,  
  9.   # :lockable, :timeoutable and :omniauthable  
  10.   devise :database_authenticatable:registerable,  
  11.          :recoverable:rememberable:trackable:validatable  
  12.   
  13.   # Setup accessible (or protected) attributes for your model  
  14.   attr_accessible :id:email:password:password_confirmation:remember_me:admin:name:shop_attributes:phone ,:bio:receive_announcements:avatar_image_  
  15.   # attr_accessible :title, :body  
  16.   
  17.   validates_presence_of :email  
  18.   validates :email, uniqueness: {scope: :shop_id}, format: {with: /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/ }, if:email_changed?  
  19.   validates_presence_of :passwordif:password_required?  
  20.   validates_confirmation_of :passwordif:password_required?  
  21.   
  22.   validates_length_of :password, within: 6..20, allow_blank: true  
  23.   # before_create :ensure_authentication_token # 生成login token,只使用一次  
  24.   
  25.   def is_admin?  
  26.     admin  
  27.   end  
  28.   
  29.   def has_right?(resource_code)  
  30.     #暂时不需要校验首页权限,目前没有很多数据内容  
  31.     return true if self.is_admin?  
  32.       
  33.     no_check_controller_array = ['account','users','kindeditor','photos','sessions',' ','oauth']     #不需要校验权限的控制器  
  34.     permissions = [all_resources.map(&:code) << no_check_controller_array].flatten  
  35.     resource_code.in?(permissions)  
  36.   end  
  37.   
  38.   def all_resources  
  39.     Rails.cache.fetch("all_resources_for_user_#{id}"do  
  40.       all_resources = self.permissions.all.map(&:resource)  
  41.     end  
  42.   end  
  43.   
  44.   def after_token_authentication # 登录后取消token  
  45.     self.authentication_token = nil  
  46.   end  
  47.   
  48.   def password_required? # copy from devise  
  49.     !persisted? || !password.nil? || !password_confirmation.nil?  
  50.   end  
  51.   
  52. end  



3.在controller中使用 

  1. class HomesController < ApplicationController  
  2.   before_filter :authenticate_user!, :except => [:show:index]   
  3.   
  4.   def index  
  5.     if !user_signed_in?  
  6.       return redirect_to '/account/sign_in'  
  7.     end  
  8.     return redirect_to "/admin/index" if current_user.admin  
  9.   end  
  10.   
  11.   def show  
  12.       
  13.   end  
  14. end  

4.生成 Devise view
  1. rails generate devise:views users  

5.rails s 运行试试


6. 重写 sessions 

  1. class SessionsController < Devise::SessionsController  
  2.   # layout Proc.new { |controller|  
  3.   #   if controller.request.headers['X-PJAX']  
  4.   #     return false  
  5.   #   end  
  6.   
  7.   
  8.   #   case controller.action_name  
  9.   #   when 'new'  
  10.   #     return 'auth'  
  11.   #   end  
  12.   # }  
  13.   
  14.   
  15.   def new  
  16.     super  
  17.     # 在这里添加其他逻辑  
  18.   end  
  19.   
  20.   
  21.   def create  
  22.     return super  
  23.   end  
  24. end  


7. 重写 registrations

  1. class AccountController < Devise::RegistrationsController  
  2.   def new  
  3.     super  
  4.   end  
  5.   
  6.    def create  
  7.     super  
  8.     # email = UserMailer.create_confirm("mxbeijingmi@163.com")  
  9.     # UserMailer.deliver(email)  
  10.     # UserMailer.confirm("menxu_work@163.com").deliver  
  11.     # UserMailer.welcome_email(params[:user]).deliver  
  12.     UserMailer.send_mail(nil).deliver  
  13.    end  
  14.   
  15.    def edit  
  16.     super  
  17.    end  
  18. end  


8. 其他的View 其他的就要慢慢来了其他定制 看文档:  https://github.com/plataformatec/devise
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值