Devise adds a permission verification system to the Project

Source: Internet
Author: User
In our previous article, we have introduced some login and authorization verification solutions. Now we will introduce another solution. Recently, devise has been widely used in the Ruby community to maintain permissions and verify permissions. Devise originated from Warden, and warden is a rack-based permission verification gem. However, using devise does not actually require any knowledge about warden. If you have some other gem usage experience similar to maintaining the permission verification function, you will find that devise differs from them in that it provides implementation from the page to the model. In contrast, for example, authlogic only implements the implementation of the lost and model layers, and you need to process the view layer implementation on your own. Devise is developed based on the rails engine, so it can provide both controllers and view implementations. From a functional perspective, devise provides 11 functional modules for maintaining and verifying permissions. These modules are configurable. For example, the rememberable module uses cookies to store user login information, and recoverable is used to process user password reset. Customizable modules allow you to easily configure corresponding functional modules based on your business needs.

Devise: simple reference

Reference:

gem 'devise'rails generate devise:installrails generate devise MODEL

Variables we can use:

before_filter :authenticate_member!member_signed_in?current_membermember_session

For example:

class HomesController < ApplicationController  before_filter :authenticate_user!, :except => [:show, :index]   def index    if !user_signed_in?      return redirect_to '/account/sign_in'    end    return redirect_to "/admin/index" if current_user.admin  end  def show      endend

Create a view model:

rails generate devise:views users

Start as follows:

1. Gem

gem 'devise'

2. Routes

0> RUN

rails generate devise MODEL

  devise_for :users,:path => 'account',                     :controllers => {                      :registrations => :account,                      :sessions => :sessions                    }

1> dB/migrate/... _ devise_cretate_module

Class devisecreateusers <activerecord: Migration def change create_table (: Users) Do | T |## database authenticatable T. string: email,: null => false,: default => "" T. string: encrypted_password,: null => false,: default => "" # recoverable T. string: reset_password_token # rememberable T. datetime: reset_password_sent_at # rememberable T. datetime: remember_created_at # trackable T. integer: sign_in_count,: default => 0 T. datetime: current_sign_in_at T. datetime: last_sign_in_at T. string: current_sign_in_ip T. string: last_sign_in_ip T. string: name, comment: "name" T. string: Phone, comment: "phone" T. text: bio, comment: "User Introduction" T. boolean: receive_announcements, comment: "whether to receive online shop mail information", default: true t. references: Shop T. string: avatar_image_uid # Add User permission T. boolean: Admin, default: True ## confirmable # T. string: confirmation_token # T. datetime: confirmed_at # T. datetime: confirmation_sent_at # T. string: unconfirmed_email # Only if using reconfirmable # lockable # T. integer: failed_attempts,: default => 0 # Only if Lock Strategy is: failed_attempts # T. string: unlock_token # Only if unlock strategy is: email or: Both # T. datetime: locked_at # token authenticatable T. string: authentication_token T. timestamps end add_index: users,: shop_id add_index: users, [: shop_id,: email],: Unique => true add_index: users,: reset_password_token,: Unique => true # add_index: users,: confirmation_token,: Unique => true # add_index: users,: unlock_token,: Unique => true add_index: users,: authentication_token,: Unique => true endend

2> APP/models/module. Rb

Class user <activerecord: Base belongs_to: Shop has_sions: articles has_sions: permissions, dependent: Destroy # include default devise modules. others available are: #: Unlock,: confirmable, #: lockable,: timeoutable and: omniauthable devise: database_authenticatable,: registerable,: recoverable,: rememberable,: trackable ,: validatable # setup accessible (or protected) attributes f Or your model attr_accessible: ID,: email,: Password,: password_confirmation,: remember_me,: Admin,: name,: shop_attributes,: Phone,: bio,: receive_announcements ,: avatar_image _ # attr_accessible: title,: Body validates_presence_of: email validates: email, uniqueness: {scope: shop_id}, format: {: /\ A [^ @] + @ ([^ @ \.] + \.) + [^ @ \.] + \ Z/}, if: email_changed? Validates_presence_of: Password, if: password_required? Validates_confirmation_of: Password, if: password_required? Validates_length_of: Password, within: 6 .. 20, allow_blank: true # before_create: ensure_authentication_token # generate a login token and use only one def is_admin? Admin end def has_right? (Resource_code) # You do not need to verify the homepage permission for the moment. Currently, there is not much data to return true if self. is_admin? No_check_controller_array = ['account', 'users', 'kindeditor ', 'photos', 'session ','', 'oauth'] # controller permissions = [all_resources.map (&: Code) <no_check_controller_array] that does not require permission verification. flatten resource_code.in? (Permissions) end def all_resources rails. cache. fetch ("all_resources_for_user _ # {ID}") Do all_resources = self. permissions. all. map (&: Resource) end def after_token_authentication # cancel token self after logon. authentication_token = nil end def password_required? # Copy from devise! Persisted? |! Password. nil? |! Password_confirmation.nil? Endend

3. Use in Controller

class HomesController < ApplicationController  before_filter :authenticate_user!, :except => [:show, :index]   def index    if !user_signed_in?      return redirect_to '/account/sign_in'    end    return redirect_to "/admin/index" if current_user.admin  end  def show      endend

4. Generate devise View

rails generate devise:views users

5. Try running rails S.

6. Override sessions

Class sessionscontroller <devise: sessionscontroller # layout Proc. new {| controller | # If controller. request. headers ['x-pjax '] # Return false # End # Case Controller. action_name # When 'new' # Return 'auth' # End #} def new super # add other logic here: End def create return Super endend

7. Rewrite registrations

class AccountController < Devise::RegistrationsController  def new    super  end   def create    super    # email = UserMailer.create_confirm("mxbeijingmi@163.com")    # UserMailer.deliver(email)    # UserMailer.confirm("menxu_work@163.com").deliver    # UserMailer.welcome_email(params[:user]).deliver    UserMailer.send_mail(nil).deliver   end   def edit    super   endend

8. Other views. Other views are coming soon.

See other custom documents:
Https://github.com/plataformatec/devise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.