Running with Ruby

Tag: authentication (page 1 of 2)

Ruby on Rails: RailsAdmin + HTTP Basic authentication

RailsAdmin is an awesome gem when you want to build a not-so-much custom admin panel. Unfortunately it’s not mentioned in documentation (or at least I couldn’t find it) how to use it with HTTP Basic authentication. Here is an example of how to do this (put this in your config/initializers/rails_admin.rb file):

RailsAdmin.config do |config|
  config.authenticate_with do
    authenticate_or_request_with_http_basic do |username, password|
      username == 'user' &&
      password == 'password'
    end
  end

  # Other config stuff should go here
end

You should also use gem like SettingsLogic for storing credentials like this:

RailsAdmin.config do |config|
  config.authenticate_with do
    authenticate_or_request_with_http_basic do |username, password|
      username == System::Settings.admin.username &&
      password == System::Settings.admin.password
    end
  end

  # Other config stuff should go here
end

Rails + Devise and remember_me (rememberable) by default

I’ve wanted to add an automatic remember_me for Devise by default (without a checkbox). First I’ve tried to do something like this:

def create
  params[:user].merge!(remember_me: true)
  super
end

Unfortunately it doesn’t seem to work. I have a rememberable strategy included in my User model, but still, remember_user_token cookie was not created. I don’t know why, even with remember_me option provided, it sets it to false. The easiest (and working) way to fix this, is to overwrite remember_me method, so it will always return true value.

# User of our portal
class User < ActiveRecord::Base

  devise :database_authenticatable, 
    :trackable, :encryptable, :confirmable, :recoverable,
    :registerable, :validatable, :lockable, :rememberable

  # @return [Boolean] user should be remembered when he logs in (with cookie)
  #   so he won't be asked to login again
  def remember_me
    true
  end
end

To be honest I didn’t have time to investigate it more deeply, so maybe there’s a better solution but this one works. After that, remember_user_token cookie is created and the session isn’t lost after user closes his browser.

Update

As Christoph mentioned in one of the comments, this is the “official” way to do this: , so probably there’s no better way ;)

Olderposts

Copyright © 2018 Running with Ruby

Theme by Anders NorenUp ↑