rubyonrails if语句验证检查

mfuanj7w  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(271)

所以我是rubyonrails新手,我对if语句有个问题,基本上我要检查的是sql数据库中是否存在登录电子邮件地址的确认令牌。如果它确实回退了一条消息,您的电子邮件将无法验证。单击电子邮件中的链接后,它将删除数据库中的令牌。然后您可以继续登录。我不能让它为我的生活工作。除了验证检查,其他一切都正常。谢谢你的帮助!!!

def authenticate(email, password)
   command = AuthenticateUser.call(email, password)
   user = User.find_by email:(email)
   confirmationtoken = 
   User.find_by_confirmation_token(params[:confirmation_token].to_s)
   if user.present? && confirmationtoken.present?
     render json: {error: 'Email not verified' }, status: :unauthorized
   elsif command.success?
     render json: {
       access_token: command.result,
       message: 'Login Successful'
     }
     else
       render json: { error: command.errors }, status: :unauthorized
     end
   end
ruarlubt

ruarlubt1#

您只需检查用户的 confirmation_token 属性已设置:

user = User.find_by(email: email)
if user && user.confirmation_token.present?
  # ...
elsif command.success?
  # ...
else
  # ...
end
``` `user.confirmation_token.present?` 可以缩短为 `user.confirmation_token?` 
gwbalxhn

gwbalxhn2#

我认为这将有助于清理您的逻辑,因为没有必要做两次用户查找。查找用户和使用对象可能会引起安全问题。。如果用户在系统中,让authenticateuser找到用户并获得成功。当你发送一封电子邮件时,只需在电子邮件中建立一个按钮,链接到一个端点,该端点将验证电子邮件并将确认令牌设置为nil。

def authenticate(email, password)
   command = AuthenticateUser.call(email, password)
   has_confirmation_token = 
   User.find_by_confirmation_token(params[:confirmation_token]).present?
   if !has_confirmation_token && !command.success?
     render json: {error: 'Email not verified' }, status: :unauthorized
   elsif command && command.success?
     render json: {
       access_token: command.result,
       message: 'Login Successful'
     }
     else
       render json: { error: command.errors }, status: :unauthorized
     end
   end

相关问题