Last active
January 2, 2019 21:06
-
-
Save jordanbyron/5876360 to your computer and use it in GitHub Desktop.
Custom authentication strategy for Devise with login screens, routes, and no database_authenticatable - Full writeup: http://blog.jordanbyron.com/post/54013166913/devise-authentication-strategy-without
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module AuthApp | |
class CustomAuthentication < Devise::Strategies::Authenticatable | |
# This check is run before +authenticate!+ is called to determine if this | |
# authentication strategy is applicable. In this case we only try to authenticate | |
# if the login and password are present | |
# | |
def valid? | |
login && password | |
end | |
def authenticate! | |
# Perform your custom authorization check here | |
# | |
if login == 'Hax0r' && password == '1337' | |
user = User.where(login: login.downcase).first_or_create | |
success! user # Tell devise we have a winner, and give it a User | |
else | |
fail! "Sorry, your username or password is incorrect" | |
end | |
end | |
private | |
def login | |
(params[:user] || {})[:login] | |
end | |
def password | |
(params[:user] || {})[:password] | |
end | |
end | |
end | |
# The first parameter is the name of the strategy you'll use in your model | |
# | |
# class User | |
# devise :awesome_auth, :rememberable | |
# end | |
# | |
# The second parameter is the class of the strategy. It must live inside a | |
# module because (See next comment block) | |
# | |
Warden::Strategies.add :awesome_auth, AuthApp::CustomAuthentication | |
# We need to add the module to devise below. The magic juice to get | |
# routes and sessions working also happens in this line with the | |
# :controller and :route keys. | |
# | |
Devise.add_module :auth_app, :strategy => true, :controller => :sessions, | |
:route => :session |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!
Devise.add_module
was the missing piece I didn't see documented elsewhere.