Devise third-party authentication plugin

Source: Internet
Author: User
Tags i18n scalar

To install in a rails project:

#在Gemfile中添加, the current version 3.4.1gem ' devise ' installs it #然后只需bundle install. Bundle install# Initialize deviserails generate devise:install# Create a model that specifies the name of the. Rails generate devise user# will generate a migration file that can make some changes to the migration file ... rake db:migrate


Configure the default URL for the development environment:

#在开发环境中默认的url和生产环境可能有点不太一样: #在下面development的文件中, add the following line. Config/environments/development.rb config.action_mailer.default_url_options = {host: ' localhost ', port:3000}




Controller filtering and Helpers

Devise created some helpers in your controller and view

To establish control over user authentication, just add before_action (assuming your user model is users)

Before_action:authenticate_user

If your devise model is not user, replace "_user" to "_yourmodel", the same logic applies to the following command.



Verify that the user is logged on

User_signed_in?


The currently logged on user

Current_User


The range of sessions you can access

User_session


After a user has registered, confirm the account or update the password, devise will redirect a scope to the root path

For example: When using a: User resource, User_root_path will use it if it exists. Otherwise, the default root_path will be used

This root_path is defined in your routes.

ROOT to: "Home#index"

You can also overwrite after_sign_in_path_for and after_sign_out_path_for to your custom redirect hooks


Note: If your devise model is member not user, for example: Available Help methods ...

before_action:authenticate_member!  Member_signed_in? Current_member member_session




Configuration model

Devise can also support some options for configuration in your models

For example, you can choose the cost of the encryption algorithm

Devise:d atabase_authenticatable,: registerable,: confirmable,: Recoverable, Stretches:2

In addition to: stretches, you can define:P Epper,: encryptor,: Confirm_within,: remember_for,: timeout_in,: unlock_in. For more details, you can view the location of the initialization file created at Devise:install when

Config/initializers/devise.rb




Robust parameters

When you customize your view, you most always add new properties to the form. parameter handling from model controller removed in RAILS4

There are only three actions in devise, allowing any set of parameters to be passed to the model, so it needs to be processed.

Their names and the parameters allowed by default are:

Sign_in (devise::sessioncontroller#create) only allows authentication of keys (like email) sign_up (devise::registrationscontroller#create) Allow authentication of Keys:password and Password_confirmationaccount_update (devise::registrationscontroller#update) to allow authentication of key S:password, Password_confirmation and Current_password

If you want to allow additional parameters, you can use a simple filter before_action configuration in your controller

Class Applicationcontroller < Actioncontroller::base before_action:configure_permitted_parameters, if::d evise_  Controller? Protected def configure_permitted_parameters devise_parameter_sanitizer.for (: sign_up) <<: Username endend

The above code is a simple type that adds multiple fields to the parameter. But if you have a nested property (you should use accetps_nested_attributes_for), then you have to tell devise those are nested and types. Devise allows you to completely change the default design or customization.

Allow simple scalar values for username and email. Gca

def configure_permitted_parameters devise_parameter_sanitizer.for (: sign_in) {|u| U.permit (: username,: email)}end


If you have some check boxes, the user needs to choose. The browser will use those checkboxes as an array. This array is not a scalar allowed by a strong parameter, so you need to configure devise using the following method:

def configure_permitted_parameters devise_parameter_sanitizer.for (: sign_up) {|u| u.permit ({roles: []},: email,:p ASSW Ord,:p assword_confirmation)}end


If you have multiple devise models, you may want to create a model with different parameter handling.

In this case, it is recommended to inherit devise::P Arametersanitizer into your logic.

Class User::P Arametersanitizer < devise::P arametersanitizer def sign_in default_params.permit (: username,: email) EndEnd

Then configure your controller to use it:

Class Applicationcontroller < actioncontroller::base protected Def devise_parameter_sanitizer if resource_class = = User User::P arametersanitizer.new (user,: User, params) Else Super # Use the default one end EndEnd

The above example overrides the user allow parameter: username and: Email




Configuration view

Devise is an engine, and all views are packaged in gems. These views will help you get started, but you may need to change them after a while. If this is the case, you only need to go through the following generator and copy all the views to your application

Rails Generate Devise:views


If you have more than one devise model in your application (such as user and admin), you will find that all models use the same view. Thankfully, devise provides an easy way to customize the view. You need to configure Config.scoped_views = True in the config/initializers/devise.rb file.


Once configured, you will have the base view in such roles as Usrs/sessions/new and adminssessions/new. If the view is not found within this range, devise will use the default view Devise/sessions/new

You can also use the Builder to generate the view.

Rails Generate Devise:views Users


If you want to generate several views, like just the registerable and confirmable modules, you can generate them in a module list by using the-V flag

Rails Generate DEVISE:VIEWS-V Registrations confirmations




Configuring the Controller

If the level of custom views is not enough, you can customize each control by following these steps

1. Create a controller using the generator

Rails generate devise:controllers [scope]


If you specify users as a range, the controller will be created in the app/controllers/users/session controller looking like this ...

Class Users::sessionscontroller < Devise::sessionscontroller # get/resource/sign_in # def New # super # End: . end


2. Tell the route to use this controller

Devise_for:users, controllers: {session: "Users/sessions"}


3. Copy view from Devise/sessions to Users/sessions. Because control is changed, it cannot use the default view location Devise/sessions


4. Finally, change or extend the operation of the controller.

You can completely override a controller action

Class Users::sessionscontroller < Devise::sessionscontroller def Create # custom sign-in code EndEnd


Or you can simply add a new behavior:

Class Users::sessionscontroller < Devise::sessionscontroller def create super do |resource| Backgroundworker.trigger (Resource) End EndEnd

This is used to trigger background left or right or action log events:


Remember, devise uses flash messages to let the user know that the login succeeded or failed, devise expect your application to invoke Flash[:notice] and Flash[:alert]. Do not print the entire flash hash, just print the specific keys. In some cases, devise adds a: timeout key in Flash hash, this is not used to display. If you want to print the entire hash, remember to delete the key.



Configure Routing

The devise comes with a default route. If you need to customize them, you should use the Devise_for method to define them. It accepts several options: Class_name,:p Ath_prefix, and so on, which may include i18n changed path names

Devise_for:users, Path: "Auth", Path_names: {sign_in: ' login ', Sign_out:}

Be sure to check the details of the devise_for documentation


If you need more depth customization, such as allowing "/users/sign_in" outside of "/sign_in", all you have to do is create a normal route to wrap it in the Devise_scope router

Devise_scope:user do get ' sign_in ', to: ' Devise/sessions#new ' end

In this way, you tell devise to use the range in: User when "/sign_in" is accessed. Note that Devise_scope is also similar to your router alias



i18n

Devise uses Fluash messages in i18n, and combines flash keys with: Notice and: Alert. Customize your app and you can set up local files.

En:devise:sessions:signed_in: ' Signed in successfully. '


You can configure resource-based information to use the singular name in your configuration.

En:devise:sessions:user:signed_in: ' Welcome user, you is signed in. ' Admin:signed_in: ' H Ello admin! '


Devise mailer creating topic information using pattern matching

En:devise:mailer:confirmation_instructions:subject: ' Hello everybody! ' User_subject: ' Hello user! Please confirm your email ' reset_password_instructions:subject: ' Reset instructions '


This article is from the "Xiaofeng Moon" blog, make sure to keep this source http://kinda22.blog.51cto.com/2969503/1587991

Devise third-party authentication plugin

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.