【问题标题】:how to authenticate the user with warden/devise without password?如何在没有密码的情况下使用 Warden/devise 对用户进行身份验证?
【发布时间】:2021-02-18 11:22:03
【问题描述】:

在我的应用程序中登录时,用户将只提供电子邮件,不需要密码。我想使用 devise/warden 对其进行身份验证。

class Users::SessionsController < Devise::SessionsController
  include ExpireExistingToken

  def new
    super
  end

  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?
    resource.update(language: Constant::SUPPORTED_LANGUAGES.key(params['locale'])) if params['locale'].present?
    resource.send_otp(force_expire: true) if resource.email_verified?
    respond_with resource, location: after_sign_in_path_for(resource)
    flash.delete(:notice)
  end

  def destroy
    session.delete(:is_otp_verified)
    super
  end
end
# frozen_string_literal: true

# Responsible for token expiration
module ExpireExistingToken
  extend ActiveSupport::Concern

  included do
    before_action :remove_existing_token, only: :new
  end

  protected

  def remove_existing_token
    uuid = session[:uuid]
    usr = User.find_by(uuid: uuid) if uuid
    return unless usr
    usr.send(:clear_reset_password_token)
    usr.save
    session.delete(:uuid)
  end
end

我试图覆盖valid_password?在用户模型中,但它不起作用。请帮我解决这个问题。

【问题讨论】:

  • 您可以使用sign_in(user)手动登录用户。
  • 嗨@Vishal,我尝试手动登录,它正在工作。我只是怀疑它会不会有任何并发​​症?其实我在 ROR 中是个幼稚的人,所以请不要介意。
  • @Vishal,将 self.resource =warden.authenticate!(auth_options) 替换为 self.resource = User.find_by(email: params[:user][:email])
  • 不,不会有问题。这取决于你的业务逻辑你想怎么做。例如,您注册时没有密码,但她/他将如何为他们创建密码?
  • 好的,非常感谢@Vishal。

标签: ruby-on-rails ruby devise warden


【解决方案1】:

您可以尝试覆盖Devise 密码验证方法并在保存过程中返回false。如果您只想针对特定资源或功能禁用它,则需要在保存期间从表单发送virtual attribute

class User < ActiveRecord::Base
  attr_accessor :skip_validation  

  protected

  def password_required?
    return false if skip_validation
    super
  end
end

【讨论】:

  • 我尝试了上述解决方案,但没有成功。 warden.authenticate!(auth_options),总是返回 401 未授权访问。即使在覆盖password_required之后?方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 2022-06-10
  • 2016-12-15
  • 2019-02-28
  • 2016-02-19
相关资源
最近更新 更多