GithubHelp home page GithubHelp logo

rbcas / casino-activerecord_authenticator Goto Github PK

View Code? Open in Web Editor NEW
18.0 3.0 60.0 449 KB

Provides mechanism to use ActiveRecord as an authenticator for CASino.

License: MIT License

Ruby 100.00%

casino-activerecord_authenticator's Introduction

casino-activerecord_authenticator Build Status Coverage Status

Provides mechanism to use ActiveRecord as an authenticator for CASino.

ActiveRecord supports many SQL databases such as MySQL, PostgreSQL, SQLite, ...

To use the ActiveRecord authenticator, configure it in your cas.yml:

authenticators:
  my_company_sql:
    authenticator: "ActiveRecord"
    options:
      connection:
        adapter: "mysql2"
        host: "localhost"
        username: "casino"
        password: "secret"
        database: "users"
      table: "users"
      username_column: "username"
      password_column: "password"
      pepper: "suffix of the password"            # optional
      extra_attributes:
        email: "email_database_column"
        fullname: "displayname_database_column"

Configuration examples for the connection part for other databases can be found here.

Contributing to casino-activerecord_authenticator

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
  • Fork the project.
  • Start a feature/bugfix branch.
  • Commit and push until you are happy with your contribution.
  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright

Copyright (c) 2013 Nils Caspar. See LICENSE.txt for further details.

casino-activerecord_authenticator's People

Contributors

gmoore avatar hasanen avatar luxflux avatar moustafasamir avatar nirnanaaa avatar pencil avatar trekdemo avatar ukasiu avatar willglynn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

casino-activerecord_authenticator's Issues

How to handle active/inactive users?

I have a user table with an inactive attribute. If a user is set as inactive, I don't want to authenticate them, even if the password is valid.

Do you have a recommendation for how to handle this?

My thought was to override the validate method:

if valid_password?(password, password_from_database) && active_for_authentication?(user)

And write an active_for_authentication? private method with the appropriate check:

def active_for_authentication?(user)
  !user.inactive
end

Does that make the most sense?

undefined method `underscore' for nil:NilClass

When I tried to access mysql active record got following error "undefined method `underscore' for nil:NilClass"

config/cas.yml

development:
  <<: *defaults
  authenticators:
    my_company_sql:
    authenticator: "ActiveRecord"
    options:
      connection:
        adapter: "mysql2"
        host: "localhost"
        username: "user"
        password: "password"
        database: "my_casino"
      table: "users"
      username_column: "username"
      password_column: "password"

Update Rubygems

The gemspec in this repository allows for ActiveRecord allows for Activrecord 4.1 but the rubygems version restricts it to ~> 3.2.12.

EDIT: It turns out I can't use ActiveRecord 4.2 with the gemspec in this repository.

Adding support for plaintext passwords?

I am curious as to why plaintext passwords aren't supported currently. I understand from a policy perspective that encrypted passwords should be promoted and used to encourage better security overall. But I have a use case where the data stored in MS SQL Server 2008 DB has passwords in plaintext. Eventually, the plan is the migrate the passwords through a hash digest but for now support for plaintext passwords is necessary.

Any technical reason why support for plaintext passwords isn't included currently?

Login with Devise

I just cloned CASinoAPP and changed Gemfile to casino3:

source 'https://rubygems.org'

gem 'rails', '4.1.0'

group :assets do
  gem 'sass-rails'
  gem 'coffee-rails'
  gem 'uglifier'
  gem 'therubyracer'
end

gem 'casino', '3.0.0.pre.1'
gem 'casino-activerecord_authenticator', :github => 'rbCAS/casino-activerecord_authenticator', :branch => 'casino3'

gem 'whenever', :require => false

group :sqlite do
  gem 'sqlite3'
end

group :mysql do
  gem 'mysql2'
end

group :postgres do
  gem 'pg'
end

group :development do
  gem 'capistrano', '~> 2.15'
end 

then edited my cas.yml to connect to my postgre database with devise:

production:
  frontend:
    sso_name: 'Acceptto SSO'
    footer_text: 'All rights reserved by Acceptto'
  authenticators:

########################################
# SQL (ActiveRecord authenticator)
########################################
    my_company_sql_database:
      authenticator: "ActiveRecord"
      options:
        connection:
          host: localhost
          adapter: postgresql
          database: m2m_development
          encoding: unicode
          pool: 5
          username: acceptto
          password: vesper
        table: "users"
        username_column: "email"
        password_column: "encrypted_password"
        extra_attributes:
          email: "email"
          fullname: "email"

After starting the server and trying to login I get this log message in Terminal:

Started POST "/login" for 127.0.0.1 at 2014-05-11 12:49:06 +0430
Processing by CASino::SessionsController#create as HTML
  Parameters: {"utf8"=>"โœ“", "authenticity_token"=>"052B5FNnci1HKSJis7BKn1c8jZU70Mq+bh+dsOZAYqU=", "lt"=>"LT-13997963103773-LzfYWg0YEThYA8kPyd6Kw9X0N09bPHMWx2SM5jxB", "username"=>"[email protected]", "password"=>"[FILTERED]", "rememberMe"=>"1", "button"=>""}
  CASino::LoginTicket Load (0.8ms)  SELECT  "casino_login_tickets".* FROM "casino_login_tickets"  WHERE "casino_login_tickets"."ticket" = 'LT-13997963103773-LzfYWg0YEThYA8kPyd6Kw9X0N09bPHMWx2SM5jxB' LIMIT 1
Login ticket 'LT-13997963103773-LzfYWg0YEThYA8kPyd6Kw9X0N09bPHMWx2SM5jxB' successfully validated
  SQL (1.3ms)  DELETE FROM "casino_login_tickets" WHERE "casino_login_tickets"."id" = 14
   (0.3ms)  BEGIN
  CASino::LoginTicket Exists (0.6ms)  SELECT  1 AS one FROM "casino_login_tickets"  WHERE "casino_login_tickets"."ticket" = 'LT-13997963466853-t4HTBMOgx8sHv7xzT9imSsactLrY7lusc4ZKCAyK' LIMIT 1
  SQL (0.7ms)  INSERT INTO "casino_login_tickets" ("created_at", "ticket", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["created_at", "2014-05-11 08:19:06.687807"], ["ticket", "LT-13997963466853-t4HTBMOgx8sHv7xzT9imSsactLrY7lusc4ZKCAyK"], ["updated_at", "2014-05-11 08:19:06.687807"]]
   (0.5ms)  COMMIT
Created login ticket 'LT-13997963466853-t4HTBMOgx8sHv7xzT9imSsactLrY7lusc4ZKCAyK'
  Rendered /Users/mani/.rvm/gems/ruby-1.9.3-p194@casinoapp/gems/casino-3.0.0.pre.1/app/views/casino/application/_messages.html.erb (0.1ms)
  Rendered /Users/mani/.rvm/gems/ruby-1.9.3-p194@casinoapp/gems/casino-3.0.0.pre.1/app/views/casino/application/_footer.html.erb (0.2ms)
  Rendered /Users/mani/.rvm/gems/ruby-1.9.3-p194@casinoapp/gems/casino-3.0.0.pre.1/app/views/casino/sessions/new.html.erb within layouts/application (6.6ms)
Completed 403 Forbidden in 23ms (Views: 13.1ms | ActiveRecord: 4.1ms)

it seems like login ticket validates successfully but then I get a 403 Forbidden in sessions/new.html and I get a Incorrect username or password message on the view. this is my /config/initializers/devise.rb config file on my development machine:

Devise.setup do |config|
  config.secret_key = '561e47b4fc7d7b3f6f33245db32c151b58a0365647c46dcf7c03807ebe968779a5b3ebb5ccf6f03d0e34161349eb8ea9d52ee6db8c3b76e1bff3058241e40e2f'
  config.mailer_sender = '[email protected]'
  config.mailer = 'Devise::Mailer'
  require 'devise/orm/active_record'
  config.case_insensitive_keys = [ :email ]
  config.strip_whitespace_keys = [ :email ]
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 10

  # Setup a pepper to generate the encrypted password.
  # config.pepper = 'dc78514f85063bae46f6c59eca0fbcaf77058ae4184948d795dfdd7baf84f49b46be247fa3c0f2830d70b3f0c621d3cf0616d8fb52e4dcd9774075da162d4ac5'
  config.reconfirmable = true

  config.password_length = 8..128

  config.reset_password_within = 6.hours

  config.sign_out_via = :delete
end

as you can see pepper line is commented (default config for devise). Also my password is 'eybaba13' which is in database with this format in encrypted_password field:
$2a$10$I0wEDn3LomuW06WsYUYIyOr5Qe5fqfqdt07dXDTz2AtEEiSqeyfHK

Any Idea how to fix it?

Improve the Authenticator ?

I don't like this code:

  def valid_password?(password, password_from_database)
    return false if password_from_database.blank?
    magic = password_from_database.split('$')[1]
    case magic
    when /\A2a?\z/
      valid_password_with_bcrypt?(password, password_from_database)
    when /\AH\z/, /\AP\z/
      valid_password_with_phpass?(password, password_from_database)
    else
      valid_password_with_unix_crypt?(password, password_from_database)
    end
  end

It can be helpful and works, but I do not like it... I think we can improve, If we refactor it to something like:

class PasswordEncryptor
  # Return the password hash and salt that must be stored on user's record.
  #
  #   PasswordEncryptor.encrypt("test")
  #   #=> {:hash => "abc...", :salt => "salt123"}
  def self.encrypt(password)
    salt = encryptor.hexdigest(rand.to_s)
    hash = hasher(password, salt)

    {:salt => salt, :hash => hash}
  end

  # Password must the plain text version.
  # Salt must be the salt stored on the user record.
  #
  #   PasswordEncryptor.hasher("marmot", "salt123")
  def self.hasher(password, salt)
    encryptor.hexdigest("#{salt}Lol:)#{password}")
  end

  # Return the encryptor adapter. Must always respond to
  # the +hexdigest+ method.
  def self.encryptor
    Digest::SHA1 #Can be others or a delegator
  end
end

class Authenticator
  def self.authenticate(username, password)
    user = User.find_by_user(username) 

    return unless user actual_hash = PasswordEncryptor.hasher(password, user.password_salt)

    return user if user.password_hash == actual_hash
  end
end

What do you think about the idea?

I can provide a PR ;)

Testing with the same database

Hi,

There might a bug related to caching or database connection when the same table is used for authenticator and for the main app.

Assuming we have a class model Account with "email" and "encrypted_password" fields and we use a table "accounts" to store those. We also specify the the same table for the authenticator:

test:
  <<: *defaults
  authenticators:
    users:
      options:
        url: "postgres://localhost/auth_test"
        table: "accounts"
        username_column: "email"
        password_column: "encrypted_password"

Then there is a simple test:

require 'rails_helper'

RSpec.describe "User log in", type: :feature do
  let!(:account) { Account.create!(email: 'test@example', password: 'secret') }

  scenario "user who has an account logs into the app" do
    visit '/'

    fill_in 'Username', with: account.email
    fill_in 'Password', with: 'secret'
    click_button 'Login'

    expect(page).to have_content 'You are currently logged in as [email protected]'
  end
end

Which is failing with "Incorrect username/passoword" message. What happens is that when the authenticator tries to fetch the record here:

user = @model.send("find_by_#{@options[:username_column]}!", username)

it gets 0 results. Even though there is that account record in the table that was during the test. If I debug and do

::Account.count
# => 1
@model.count
# => 0
@model.create(email: "123", encrypted_password: "123")
# => ... (creates an actual record)
@model.count
# => 1
::Account.count
# => 2

# At this point If I do SQL queries through ::Account I get both records,
# but when doing SQL query from @model then I only get one record.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.