Simple Auth
SimpleAuth is an authentication library to be used when everything else is just too complicated.
This library only handles session. You have to implement the authentication strategy as you want (e.g. in-site authentication, OAuth, etc).
Installation
Just the following line to your Gemfile:
gem "simple_auth"
Then run rails generate simple_auth:install to copy the initializer file.
Usage
The initializer will install the required helper methods on your controller. So,
let's say you want to support user and admin authentication. You'll need to
specify the following scope.
# config/initializers/simple_auth.rb
SimpleAuth.setup do |config|
config.scopes = %i[user admin]
config.login_url = proc { login_path }
config.logged_url = proc { dashboard_path }
config.flash_message_key = :alert
config.install_helpers!
endSession is valid only when Controller#authorized_#{scope}? method returns
true, which is the default behavior. You can override these methods with your
own rules; the following example shows how you can authorize all e-mails from
@example.com to access the admin dashboard.
class Admin::DashboardController < ApplicationController
private
def authorized_admin?
current_user.email.match(/@example.com\z/)
end
endSo, how do you set up a new user session? That's really simple, actually.
class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by_email(params[:email])
if @user.try(:authenticate, params[:password])
SimpleAuth::Session.create(scope: "user", session: session, record: @user)
redirect_to return_to(dashboard_path)
else
flash[:alert] = "Invalid username or password"
render :new
end
end
def destroy
reset_session
redirect_to root_path
end
endFirst thing to notice is that SimpleAuth doesn't care about how you
authenticate. You could easily set up a different authentication strategy, e.g.
API tokens. The important part is assigning the record: and scope: options.
The return_to helper will give you the requested url (before the user logged
in) or the default url.
SimpleAuth uses GlobalID as the session
identifier. This allows using any objects that respond to #to_gid, including
namespaced models and POROs.
session[:user_id]
#=> gid://myapp/User/1If you need to locate a record using such value, you can do it by calling
GlobalID::Locator.locate(session[:user_id])
Finally, only ActiveRecord::RecordNotFound errors are trapped by SimpleAuth
(when ActiveRecord is available). If you locator raises a different exception,
add the error class to the list of known exceptions.
SimpleAuth::Session.record_not_found_exceptions << CustomNotFoundRecordErrorLogging out users
Logging out a user is just as simple; all you have to do is calling the regular
reset_session.
Restricting access
You can restrict access by using 2 macros. Use redirect_logged_#{scope} to
avoid rendering a page for logged user.
class SignupController < ApplicationController
before_action :redirect_logged_user
endUse require_logged_#{scope} to enforce authenticated access.
class DashboardController < ApplicationController
before_action :require_logged_user
end"So which helpers are defined?", you ask. Just three simple helpers.
#{scope}_logged_in? # e.g. user_logged_in? (available in controller & views)
current_#{scope} # e.g. current_user (available in controller & views)
#{scope}_session # e.g. user_session (available in controller & views)From your routes file
You can also restrict routes directly from your routes:
Rails.application.routes.draw do
authenticate :admin, ->(user) { user.admin? } do
mount Sidekiq::Web, at: "sidekiq"
end
endIn this case, :admin is the scope and the lambda will only be called whenever
there's a valid record associated with that record.
API Controllers
simple_auth supports ActionController::API-based controllers. Include the
SimpleAuth::ActionController::API module in your API controller:
class ApiController < ActionController::API
include SimpleAuth::ActionController::API
before_action :authenticate_via_token
before_action :require_logged_user
def index
render json: {message: "hello there"}
end
private def authenticate_via_token
user = User.find_by_api_token(id: request.headers["Authorization"])
return render(plain: "401 Unauthorized", status: :unauthorized) unless user
SimpleAuth::Session.create(scope: "user", session:, record: user)
end
endBy default, unauthorized requests receive a 401 Unauthorized plain text
response. You can override render_unauthorized_access(authorization) to
customize this behavior. The authorization object gives you access to
authorization.error_message, which contains the translated error message for
the failed authorization:
class ApiController < ActionController::API
include SimpleAuth::ActionController::API
private def render_unauthorized_access(authorization)
render json: {error: authorization.error_message}, status: :unauthorized
end
endNote
SimpleAuth::ActionController::API defines a stub session object that's just
a hash, so the user record can be resolved across multiple calls within the
same request.
Translations
These are the translations you'll need:
---
en:
simple_auth:
user:
unlogged_in: "You need to be logged in"
unauthorized: "You don't have permission to access this page"If you don't set these translations, a default message will be used.
To display the error message, use something like <%= flash[:alert] %>. If you
want to use a custom key, say :error, use the configuration file
config/initializers/simple_auth.rb to define the new key:
# config/initializers/simple_auth.rb
SimpleAuth.setup do |config|
# ...
config.flash_message_key = :error
# ...
endMaintainer
Contributors
Contributing
For more details about how to contribute, please read https://github.com/fnando/simple_auth/blob/main/CONTRIBUTING.md.
License
The gem is available as open source under the terms of the MIT License. A copy of the license can be found at https://github.com/fnando/simple_auth/blob/main/LICENSE.md.
Code of Conduct
Everyone interacting in the simple_auth project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.