Authentication in Rails

0

If you want to roll out your own authentication in Rails this should get you going

/app/controllers/concerns/authenticate.rb
module Authenticate
  extend ActiveSupport::Concern

  protected
  def logged_in?
    current_user != nil
  end

  def current_user
    @current_user ||= (login_from_session || nil)
  end

  def current_user=(user)
    session[:user_id] = user.id
    @current_user = user
  end

  def login_required
    logged_in? || access_denied
  end

  def access_denied
    respond_to do |format|
      format.html do
        store_location
        redirect_to signin_url
      end
    end
  end

  def store_location
    session[:return_to] = request.url
  end

  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end

  def login_from_session
    User.find(session[:user_id]) if session[:user_id]
  end 

  included do
    helper_method :current_user, :logged_in?
  end
end

include this in your application controller

/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include Authenticate
end

Then you can require that a user has to be logged in like this

class TopicsController < ApplicationController
  before_action :login_required, except: [:index, show]
end

It gives you helpers logged_in? and current_user you can use in your views

<% if logged_in? %>
    <%= link_to current_user.username, user_path(current_user) %>
<% else %>

  • 0 posts
  • 0 subtopics
  • 10 months ago by vince