LoginSignup
0
0

More than 3 years have passed since last update.

【Rails6】devise_auth_tokenを用いたOmniauthのSNS認証でパスワードのバリデーションを突破する方法

Posted at

Omniauthを用いたSNS認証を実装している際にパスワードがバリデーションに引っかかる事象が発生。
具体的には

  • パスワードが英大文字、英小文字、数字の混合であること
  • パスワードが6文字以上20文字以下であること

これらのバリデーションに引っかかった。
その時の解決法をメモ

結論…set_random_passwordメソッドをオーバーライドし、修正

より、devise_auth_tokenの一次ソースを参照していた際にset_random_passwordメソッドを発見。
こいつがパスワードを自動生成していたようだ。

元のメソッドでは

 def set_random_password
   # set crazy password for new oauth users. this is only used to prevent
   # access via email sign-in.
   p = SecureRandom.urlsafe_base64(nil, false)
   @resource.password = p
   @resource.password_confirmation = p
 end

このようになっているが、このpって値が上記バリデーションに引っかかる仕様となっていた。

これをオーバーライドし以下のように修正。英小文字、英大文字、数字を必ず含む形式にしている。

def set_random_password
  # パスワードのバリデーション突破のためにオーバーライド
  random_password = SecureRandom.alphanumeric(10) + [*'A'..'Z'].sample(1).join + [*'a'..'z'].sample(1).join + [*'0'..'9'].sample(1).join
  @resource.password = random_password
  @resource.password_confirmation = random_password
end

これにて解決

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0