定制devise 非常简单,user.valid_password?(params[:passwd]) 就可以了.

访问量: 1664

步骤

1. 把对应的controller, view 从gem path中copy过来。

2. 各种修改。

3. 记得务必把prepend_before_action :allow_params_authentication!, only: :create   ( session controller中)  这句话注释掉。

它会让代码自动走验证的逻辑。太奇葩了。

4. 验证用户的时候,valid_password? 是关键.

5. 增加routes.rb

  devise_for :managers, controllers: {
    registrations: 'managers/registrations',
    passwords: 'managers/passwords',
    sessions: 'managers/sessions'
  }

下面是登录的部分代码作为例子:

class Managers::SessionsController < DeviseController
  prepend_before_action :require_no_authentication, only: [:new, :create]
  prepend_before_action :verify_signed_out_user, only: :destroy
  prepend_before_action(only: [:create, :destroy]) { request.env["devise.skip_timeout"] = true }

  # GET /resource/sign_in
  def new 
    Rails.logger.info "--- hihihi , in new"
    self.resource = resource_class.new(sign_in_params)
  end 

  # POST /resource/sign_in
  def create
    manager = Manager.where('email = ?', params[:manager][:email]).first
    if manager.blank?
      redirect_to :back, alert: '用户名不存在。请立刻联系管理员。多次尝试失败会上报风控系统' and return
    end 

    if manager.blank? || !manager.valid_password?(params[:manager][:password])
      redirect_to :back, alert: '邮箱与密码不匹配' and return
    end 

    if manager.valid_password? params[:manager][:password]
      sign_in manager
      redirect_to after_sign_in_path_for(manager), notice: '欢迎您!'
    else
      redirect_to :back, alert: '邮箱与密码不匹配'
    end 
  end 

视图部分:

<%= form_for(resource, as: resource_name, url: session_path(resource_name), :html => {class: "devise-form"}) do |f| %>
  <fieldset>
    <div class="field">
      <%= f.label :email, '邮箱', :for=>"email"  %><br />
      <%= f.email_field :email, autofocus: true, id: 'email', class: 'form-control' %>
    </div>
    <div class="field">
      <%= f.label :password, '密码', :for=>"password" %><br />
      <%= f.password_field :password, autocomplete: "off", id: 'password', class: 'form-control' %>
    </div>
    <div class="field">
      <%= f.label :otp_code, 'Google验证码', :for=>"otp_code" %><br />
      <%= text_field_tag :otp_code, '', autocomplete: "off", id: 'password', class: 'form-control' %>
    </div>
    <span class="divider"></span>
    <div class="actions">
      <%= f.submit "登录", class: 'btn btn-primary' %>
    </div>
  <fieldset>
<% end %>

订阅/RSS Feed

Subscribe

分类/category