Skip to content
Browse files

Updated code with authlogic

  • Loading branch information...
1 parent 5e03831 commit 63cac211a514a8f931c1d2990415c05f4368add7 @binarylogic committed
Showing with 37 additions and 2,975 deletions.
  1. +21 −18 app/controllers/application.rb
  2. +1 −1 app/controllers/user_sessions_controller.rb
  3. +3 −3 app/controllers/users_controller.rb
  4. +2 −1 app/views/layouts/application.html.erb
  5. +1 −2 app/views/user_sessions/new.html.erb
  6. +3 −0 config/environment.rb
  7. +1 −0 db/migrate/20081103171327_create_users.rb
  8. +5 −8 test/functional/users_controller_test.rb
  9. +0 −8 vendor/plugins/authlogic/.gitignore
  10. +0 −62 vendor/plugins/authlogic/CHANGELOG.rdoc
  11. +0 −20 vendor/plugins/authlogic/MIT-LICENSE
  12. +0 −37 vendor/plugins/authlogic/Manifest
  13. +0 −328 vendor/plugins/authlogic/README.rdoc
  14. +0 −15 vendor/plugins/authlogic/Rakefile
  15. +0 −1 vendor/plugins/authlogic/init.rb
  16. +0 −30 vendor/plugins/authlogic/lib/authlogic.rb
  17. +0 −297 vendor/plugins/authlogic/lib/authlogic/active_record/acts_as_authentic.rb
  18. +0 −56 vendor/plugins/authlogic/lib/authlogic/active_record/authenticates_many.rb
  19. +0 −28 vendor/plugins/authlogic/lib/authlogic/active_record/scoped_session.rb
  20. +0 −34 vendor/plugins/authlogic/lib/authlogic/controller_adapters/abstract_adapter.rb
  21. +0 −28 vendor/plugins/authlogic/lib/authlogic/controller_adapters/merb_adapter.rb
  22. +0 −31 vendor/plugins/authlogic/lib/authlogic/controller_adapters/rails_adapter.rb
  23. +0 −26 vendor/plugins/authlogic/lib/authlogic/session/active_record_trickery.rb
  24. +0 −458 vendor/plugins/authlogic/lib/authlogic/session/base.rb
  25. +0 −72 vendor/plugins/authlogic/lib/authlogic/session/callbacks.rb
  26. +0 −241 vendor/plugins/authlogic/lib/authlogic/session/config.rb
  27. +0 −18 vendor/plugins/authlogic/lib/authlogic/session/errors.rb
  28. +0 −101 vendor/plugins/authlogic/lib/authlogic/session/scopes.rb
  29. +0 −18 vendor/plugins/authlogic/lib/authlogic/sha512_crypto_provider.rb
  30. +0 −56 vendor/plugins/authlogic/lib/authlogic/version.rb
  31. +0 −213 vendor/plugins/authlogic/test/active_record_acts_as_authentic_test.rb
  32. +0 −28 vendor/plugins/authlogic/test/active_record_authenticates_many_test.rb
  33. +0 −5 vendor/plugins/authlogic/test/fixtures/companies.yml
  34. +0 −17 vendor/plugins/authlogic/test/fixtures/employees.yml
  35. +0 −3 vendor/plugins/authlogic/test/fixtures/projects.yml
  36. +0 −19 vendor/plugins/authlogic/test/fixtures/users.yml
  37. +0 −142 vendor/plugins/authlogic/test/test_helper.rb
  38. +0 −12 vendor/plugins/authlogic/test/user_session_active_record_trickery_test.rb
  39. +0 −316 vendor/plugins/authlogic/test/user_session_base_test.rb
  40. +0 −144 vendor/plugins/authlogic/test/user_session_config_test.rb
  41. +0 −19 vendor/plugins/authlogic/test/user_session_scopes_test.rb
  42. +0 −17 vendor/plugins/authlogic/test_libs/aes128_crypto_provider.rb
  43. +0 −22 vendor/plugins/authlogic/test_libs/mock_controller.rb
  44. +0 −6 vendor/plugins/authlogic/test_libs/mock_cookie_jar.rb
  45. +0 −5 vendor/plugins/authlogic/test_libs/mock_request.rb
  46. +0 −9 vendor/plugins/authlogic/test_libs/ordered_hash.rb
View
39 app/controllers/application.rb
@@ -3,36 +3,39 @@
class ApplicationController < ActionController::Base
helper :all
- filter_parameter_logging :password, :confirm_password
+ helper_method :current_user_session, :current_user
+ filter_parameter_logging :password, :confirm_password
- before_filter :load_user
-
- private
- def load_user
- @user_session = UserSession.find
- @current_user = @user_session && @user_session.record
- end
-
- def require_user
- unless @current_user
+ private
+ def current_user_session
+ return @current_user_session if defined?(@current_user_session)
+ @current_user_session = UserSession.find
+ end
+
+ def current_user
+ return @current_user if defined?(@current_user)
+ @current_user = current_user_session && current_user_session.record
+ end
+
+ def require_user
+ unless current_user
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to new_user_session_url
return false
end
- end
-
- def require_no_user
- if @current_user
+ end
+
+ def require_no_user
+ if current_user
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to account_url
return false
end
end
-
- def store_location
- return if @prevent_store_location == true
+
+ def store_location
session[:return_to] = request.request_uri
end
View
2 app/controllers/user_sessions_controller.rb
@@ -17,7 +17,7 @@ def create
end
def destroy
- @user_session.destroy
+ current_user_session.destroy
flash[:notice] = "Logout successful!"
redirect_back_or_default new_user_session_url
end
View
6 app/controllers/users_controller.rb
@@ -20,9 +20,9 @@ def show
@user = @current_user
end
- def edit
- @user = @current_user
- end
+ def edit
+ @user = @current_user
+ end
def update
@user = @current_user # makes our views "cleaner" and more consistent
View
3 app/views/layouts/application.html.erb
@@ -6,6 +6,7 @@
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title><%= controller.controller_name %>: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
+ <%= javascript_include_tag :defaults %>
</head>
<body>
@@ -16,7 +17,7 @@
<br />
-<% if !@current_user %>
+<% if !current_user %>
<%= link_to "Register", new_account_path %> |
<%= link_to "Log In", new_user_session_path %>
<% else %>
View
3 app/views/user_sessions/new.html.erb
@@ -1,8 +1,7 @@
<h1>Login</h1>
-<%= error_messages_for "user_session", :header_message => nil %>
-
<% form_for @user_session, :url => user_session_path do |f| %>
+ <%= f.error_messages %>
<%= f.label :login %><br />
<%= f.text_field :login %><br />
<br />
View
3 config/environment.rb
@@ -25,11 +25,14 @@
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "aws-s3", :lib => "aws/s3"
+ config.gem :authlogic
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+ #config.plugin_paths += ["#{RAILS_ROOT}/../../Libs"]
+ #config.plugins = [:authlogic]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
View
1 db/migrate/20081103171327_create_users.rb
@@ -4,6 +4,7 @@ def self.up
t.string :login
t.string :crypted_password
t.string :password_salt
+ #t.string :openid
t.string :remember_token
t.integer :login_count
t.datetime :last_request_at
View
13 test/functional/users_controller_test.rb
@@ -1,12 +1,7 @@
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
- test "should get index" do
- get :index
- assert_response :success
- assert_not_nil assigns(:users)
- end
-
+=begin
test "should get new" do
get :new
assert_response :success
@@ -19,12 +14,13 @@ class UsersControllerTest < ActionController::TestCase
assert_redirected_to user_path(assigns(:user))
end
-
+=end
test "should show user" do
- get :show, :id => users(:one).id
+ get :show
assert_response :success
end
+=begin
test "should get edit" do
get :edit, :id => users(:one).id
assert_response :success
@@ -42,4 +38,5 @@ class UsersControllerTest < ActionController::TestCase
assert_redirected_to users_path
end
+=end
end
View
8 vendor/plugins/authlogic/.gitignore
@@ -1,8 +0,0 @@
-.DS_Store
-*.log
-*.sqlite3
-pkg/*
-coverage/*
-doc/*
-benchmarks/*
-
View
62 vendor/plugins/authlogic/CHANGELOG.rdoc
@@ -1,62 +0,0 @@
-== 1.0.1 released 2008-11-05
-
-* Moved Rack standards into abstract_adapter for the controllers.
-
-== 1.0.0 released 2008-11-05
-
-* Checked for blank login counts, if a default wasnt set in the migrations.
-* Added check for database table in acts_as_authentic to avoid errors in initial setup.
-* Completely rewrote tests to be more conventional and thorough tests, removed test_app.
-* Modified how validations work so that a validate method was added as well as callbacks for that method.
-* Extracted scope support into its own module to help organize code better.
-* Added in salt for encryption, just like hashes and removed :crypto_provider_type option for acts_as_authentic.
-* Added merb adapters.
-* Improved documentation throughout.
-
-== 0.10.4 released 2008-10-31
-
-* Changed configuration to use inheritable attributes
-* Cleaned up requires to be in their proper files
-* Added in scope support.
-
-== 0.10.3 released 2008-10-31
-
-* Instead of raising an error when extra fields are passed in credentials=, just ignore them.
-* Added remember_me config option to set the default value.
-* Only call credential methods if an argument was passed.
-* More unit tests
-* Hardened automatic session updating. Also automatically log the user in if they change their password when logged out.
-
-== 0.10.2 released 2008-10-24
-
-* Added in stretches to the default Sha512 encryption algorithm.
-* Use column_names instead of columns when determining if a column is present.
-* Improved validation callbacks. after_validation should only be run if valid? = true. Also clear errors before the "before_validation" callback.
-
-== 0.10.1 released 2008-10-24
-
-* Sessions now store the "remember token" instead of the id. This is much safer and guarantees all "sessions" that are logged in are logged in with a valid password. This way stale sessions can't be persisted.
-* Bumped security to Sha512 from Sha256.
-* Remove attr_protected call in acts_as_authentic
-* protected_password should use pasword_field configuration value
-* changed magic state "inactive" to "active"
-
-== 0.10.0 released 2008-10-24
-
-* Do not allow instantiation if the session has not been activated with a controller object. Just like ActiveRecord won't let you do anything without a DB connection.
-* Abstracted controller implementation to allow for rails, merb, etc adapters. So this is not confined to the rails framework.
-* Removed create and update methods and added save, like ActiveRecord.
-* after_validation should be able to change the result if it adds errors on callbacks.
-* Completed tests.
-
-== 0.9.1 released 2008-10-24
-
-* Changed scope to id. Makes more sense to call it an id and fits better with the ActiveRecord model.
-* Removed saving_from_session flag, apparently it is not needed.
-* Fixed updating sessions to make more sense and be stricter.
-* change last_click_at to last_request_at
-* Only run "after" callbacks if the result is successful.
-
-== 0.9.0 released 2008-10-24
-
-* Initial release.
View
20 vendor/plugins/authlogic/MIT-LICENSE
@@ -1,20 +0,0 @@
-Copyright (c) 2007 Ben Johnson of Binary Logic (binarylogic.com)
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
37 vendor/plugins/authlogic/Manifest
@@ -1,37 +0,0 @@
-CHANGELOG.rdoc
-init.rb
-lib/authlogic/active_record/acts_as_authentic.rb
-lib/authlogic/active_record/authenticates_many.rb
-lib/authlogic/active_record/scoped_session.rb
-lib/authlogic/controller_adapters/abstract_adapter.rb
-lib/authlogic/controller_adapters/merb_adapter.rb
-lib/authlogic/controller_adapters/rails_adapter.rb
-lib/authlogic/session/active_record_trickery.rb
-lib/authlogic/session/base.rb
-lib/authlogic/session/callbacks.rb
-lib/authlogic/session/config.rb
-lib/authlogic/session/errors.rb
-lib/authlogic/session/scopes.rb
-lib/authlogic/sha512_crypto_provider.rb
-lib/authlogic/version.rb
-lib/authlogic.rb
-Manifest
-MIT-LICENSE
-Rakefile
-README.rdoc
-test/active_record_acts_as_authentic_test.rb
-test/active_record_authenticates_many_test.rb
-test/fixtures/companies.yml
-test/fixtures/employees.yml
-test/fixtures/projects.yml
-test/fixtures/users.yml
-test/test_helper.rb
-test/user_session_active_record_trickery_test.rb
-test/user_session_base_test.rb
-test/user_session_config_test.rb
-test/user_session_scopes_test.rb
-test_libs/aes128_crypto_provider.rb
-test_libs/mock_controller.rb
-test_libs/mock_cookie_jar.rb
-test_libs/mock_request.rb
-test_libs/ordered_hash.rb
View
328 vendor/plugins/authlogic/README.rdoc
@@ -1,328 +0,0 @@
-= Authlogic
-
-Authlogic is a framework agnostic object based authentication solution that handles all of the non sense for you. It's as easy as ActiveRecord is with a database. Put simply, its the Chuck Norris of authentication solutions for rails, merb, etc.
-
-The last thing we need is another authentication solution, right? That's what I thought until I tried out some of the current solutions in both rails and merb. None of them felt right. They were either too complicated, bloated, littered my application with tons of code, or were just confusing. This is not the simple / elegant ruby we all fell in love with. We need a "ruby like" authentication solution. Authlogic is my attempt to satisfy that need...
-
-Let's take a rails application, wouldn't it be nice to keep your app up to date with the latest and greatest security techniques with a simple update of a plugin?
-
-What if you could have authentication up and running in minutes without having to run a generator? All because it's simple, like everything else.
-
-What if creating a user session could be as simple as...
-
- UserSession.create(params[:user_session])
-
-What if your user sessions controller could look just like your other controllers...
-
- class UserSessionsController < ApplicationController
- def new
- @user_session = UserSession.new
- end
-
- def create
- @user_session = UserSession.new(params[:user_session])
- if @user_session.save
- redirect_to account_url
- else
- render :action => :new
- end
- end
-
- def destroy
- @user_session.destroy
- end
- end
-
-Look familiar? If you didn't know any better, you would think UserSession was an ActiveRecord model. I think that's pretty cool, because it fits nicely into the RESTful development pattern, a style we all know and love. What about the view...
-
- <% form_for @user_session do |f| %>
- <%= f.error_messages %>
- <%= f.label :login %><br />
- <%= f.text_field :login %><br />
- <br />
- <%= f.label :password %><br />
- <%= f.password_field :password %><br />
- <br />
- <%= f.submit "Login" %>
- <% end %>
-
-Or how about persisting the session...
-
- class ApplicationController
- before_filter :load_user
-
- protected
- def load_user
- @user_session = UserSession.find
- @current_user = @user_session && @user_session.record
- end
- end
-
-Authlogic makes this a reality. This is just the tip of the ice berg. Keep reading to find out everything Authlogic can do.
-
-== Helpful links
-
-* <b>Documentation:</b> http://authlogic.rubyforge.org
-* <b>Authlogic setup tutorial:</b> http://www.binarylogic.com/2008/11/3/tutorial-authlogic-basic-setup
-* <b>Live example of the setup tutorial above (with source):</b> http://authlogic_example.binarylogic.com
-* <b>Bugs / feature suggestions:</b> http://binarylogic.lighthouseapp.com/projects/18752-authlogic
-
-== Install and use
-
-Install the gem / plugin
-
- $ sudo gem install authlogic
- $ cd vendor/plugins
- $ sudo gem unpack authlogic
-
-Or as a plugin
-
- script/plugin install git://github.com/binarylogic/authlogic.git
-
-=== Create your session
-
-Lets assume you are setting up a session for your User model.
-
-Create your user_session.rb file:
-
- # app/models/user_session.rb
- class UserSession < Authgasm::Session::Base
- # configuration here, just like ActiveRecord, or in an initializer
- # See Authgasm::Session::Config::ClassMethods for more details
- end
-
-=== Ensure proper database fields
-
-The user model needs to have the following columns. The names of these columns can be changed with configuration. Better yet, Authgasm tries to guess these names by checking for the existence of common names. See Authgasm::Session::Config::ClassMethods for more details, but chances are you won't have to specify any configuration for your field names, even if they aren't the same names as below.
-
- t.string :login, :null => false
- t.string :crypted_password, :null => false
- t.string :password_salt, :null => false # not needed if you are encrypting your pw instead of using a hash algorithm
- t.string :remember_token, :null => false
- t.integer :login_count # This is optional, it is a "magic" column, just like "created_at". See below for a list of all magic columns.
-
-=== Set up your model
-
-Make sure you have a model that you will be authenticating with. For this example let's say you have a User model:
-
- class User < ActiveRecord::Base
- acts_as_authentic # for options see documentation: Authgasm::ActsAsAuthentic::ClassMethods
- end
-
-The options for acts_as_authentic are based on the UserSession configuration. So if you specified configuration for your UserSession model you should not have to specify any options for acts_as_authentic, unless you want them to be different.
-
-Done! Now go use it just like you would with any other ActiveRecord model. Either glance at the code at the beginning of this readme or check out the tutorial (see above in "helpful links") for a more detailed walk through.
-
-== Magic Columns
-
-Just like ActiveRecord has "magic" columns, such as: created_at and updated_at. Authlogic has its own "magic" columns too:
-
- Column name Description
- login_count Increased every time an explicit login is made. This will *NOT* increase if logging in by a session, cookie, or basic http auth
- last_request_at Updates every time the user logs in, either by explicitly logging in, or logging in by cookie, session, or http auth
- current_login_at Updates with the current time when an explicit login is made.
- last_login_at Updates with the value of current_login_at before it is reset.
- current_login_ip Updates with the request remote_ip when an explicit login is made.
- last_login_ip Updates with the value of current_login_ip before it is reset.
-
-== Magic States
-
-Authlogic tries to check the state of the record before creating the session. If your record responds to the following methods and any of them return false, validation will fail:
-
- Method name Description
- active? Is the record marked as active?
- approved? Has the record been approved?
- confirmed? Has the record been conirmed?
-
-What's neat about this is that these are checked upon any type of login. When logging in explicitly, by cookie, session, or basic http auth. So if you mark a user inactive in the middle of their session they wont be logged back in next time they refresh the page. Giving you complete control.
-
-Need Authlogic to check your own "state"? No problem, check out the hooks section below. Add in a before_validation to do your own checking. The sky is the limit.
-
-== Hooks / Callbacks
-
-Just like ActiveRecord you can create your own hooks / callbacks so that you can do whatever you want when certain actions are performed. Here they are:
-
- before_create
- after_create
- before_destroy
- after_destroy
- before_save
- after_save
- before_update
- after_update
- before_validation
- after_validation
-
-== Multiple Sessions / Session Identifiers
-
-You're asking: "why would I want multiple sessions?". Take this example:
-
-You have an app where users login and then need to re-login to view / change their billing information. Similar to how Apple's me.com works. What you could do is have the user login with their normal session, then have an entirely new session that represents their "secure" session. But wait, this is 2 users sessions. No problem:
-
- # regular user session
- @user_session = UserSession.new
- @user_session.id
- # => nil
-
- # secure user session
- @secure_user_session = UserSession.new(:secure)
- @secure_user_session.id
- # => :secure
-
-This will keep everything separate. The :secure session will store its info in a separate cookie, separate session, etc. Just set the id and you are good to go. Need to retrieve the session?
-
- @user_session = UserSession.find
- @secure_user_session = UserSession.find(:secure)
-
-For more information on ids checkout Authlogic::Session::Base#initialize
-
-== Scoping
-
-Scoping with authentication is a little tricky because it can come in many different flavors:
-
-1. Accounts have many users, meaning users can only belong to one account at a time.
-2. Accounts have and belong to many users, meaning a user can belong to more than one account.
-3. Users access their accounts via subdomains.
-4. Users access their accounts by selecting their account and storing their selection, *NOT* using subdomains. Maybe you store their selection in a session, cookie, or the database. It doesn't matter.
-
-Now mix and match the above, it can get pretty hairy. Fear not, because Authlogic is designed in a manner where it doesn't care how you do it, all that you have to do is break it down. When scoping a session there are 3 parts you might want to scope:
-
-1. The model (the validations, etc)
-2. The session (finding the record)
-3. The cookies (the names of the session key and cookie)
-
-I will describe each below, in order.
-
-=== Scoping your model
-
-This scopes your login field validation, so that users are allowed to have the same login, just not in the same account.
-
- # app/models/user.rb
- class User < ActiveRecord::Base
- acts_as_authentic :scope => :account_id
- end
-
-=== Scoping your session
-
-When the session tries to validate it searches for a record. You want to scope that search. No problem...
-
-The goal of Authlogic was to not try and introduce anything new. As a result I came up with:
-
- @account.user_sessions.find
- @account.user_sessions.create
- @account.user_sessions.build
- # ... etc
-
-This works just like ActiveRecord, so it should come natural. Here is how you get this functionality:
-
- class Account < ActiveRecord::Base
- authenticates_many :user_sessions
- end
-
-=== Scoping cookies
-
-What's neat about cookies is that if you use sub domains they automatically scope their self. Meaning if you create a cookie in whatever.yourdomain.com it will not exist in another.yourdomain.com. So if you are using subdomains to scope your users, you don't have to do anything.
-
-But what if you *don't* want to separate your cookies by subdomains? You can accomplish this by doing:
-
- ActionController::Base.session_options[:session_domain] = ‘.mydomain.com’
-
-If for some reason the above doesn't work for you, do some simple Google searches. There are a million blog posts on this.
-
-Now let's look at this from the other angle. What if you are *NOT* using subdomains, but still want to separate cookies for each account. Simple, set the :scope_cookies option for authenticate_many:
-
- class Account < ActiveRecord::Base
- authenticates_many :user_sessions, :scope_cookies => true
- end
-
-Done, Authlogic will give each cookie a unique name depending on the account.
-
-With the above information you should be able to scope your sessions any way you want. Just mix and match the tools above to accomplish this. Also check out the documentation on Authlogic::ActiveRecord::AuthenticatesMany.
-
-== Errors
-
-The errors in Authlogic work JUST LIKE ActiveRecord. In fact, it uses the exact same ActiveRecord errors class. Use it the same way:
-
- class UserSession
- before_validation :check_if_awesome
-
- private
- def check_if_awesome
- errors.add(:login, "must contain awesome") if login && !login.include?("awesome")
- errors.add_to_base("You must be awesome to log in") unless record.awesome?
- end
- end
-
-== Automatic Session Updating
-
-This is one of my favorite features that I think is pretty cool. It's things like this that make a library great and let you know you are on the right track.
-
-Just to clear up any confusion, Authlogic does not store the plain id in the session. It stores a token. This token changes with the password, this way stale sessions can not be persisted.
-
-That being said...What if a user changes their password? You have to re-log them in with the new password, recreate the session, etc, pain in the ass. Or what if a user creates a new user account? You have to do the same thing. Here's an even better one: what if a user is in the admin area and changes his own password? There might even be another place passwords can change. It shouldn't matter, your code should be written in a way where you don't have to remember to do this.
-
-Instead of updating sessions all over the place, doesn't it make sense to do this at a lower level? Like the User model? You're saying "but Ben, models can't mess around with sessions and cookies". True...but Authlogic can, and you can access Authlogic just like a model. I know in most situations it's not good practice to do this but I view this in the same class as sweepers, and feel like it actually is good practice here. User sessions are directly tied to users, they should be connected on the model level.
-
-Fear not, because the acts_as_authentic method you call in your model takes care of this for you, by adding an after_save callback to automatically keep the session up to date. You don't have to worry about it anymore. Don't even think about it. Let your UsersController deal with users, not users *AND* sessions. *ANYTIME* the user changes his password in *ANY* way, his session will be updated.
-
-Here is basically how this is done....
-
- class User < ActiveRecord::Base
- after_save :maintain_sessions!
- after_update :update_sessions!
-
- private
- def maintain_sessions!
- # If we aren't logged in at all and the password was changed, go ahead and log the user in
- # If we are logged in and the password has change, update the sessions
- end
- end
-
-Obviously there is a little more to it than this, but hopefully this clarifies any confusion. Lastly, this can be altered / disabled via a configuration option. Just set :session_ids => nil when calling acts_as_authentic.
-
-When things come together like this I think its a sign that you are doing something right. Put that in your pipe and smoke it!
-
-== Framework agnostic (Rails, Merb, etc.)
-
-I designed Authlogic to be framework agnostic, meaning it doesn't care what framework you use it in. Right out of the box it supports rails and merb. I have not had the opportunity to use other frameworks, but the only thing stopping Authlogic from being used in other frameworks is a simple adapter. Check out controller_adapters/rails_adapter, or controller_adapters/merb_adapter.
-
-Since pretty much all of the frameworks in ruby follow the Rack conventions, the code should be very similar across adapters. You're saying "but Ben, why not just hook into Rack and avoid the need for controller adapters all together?". It's not that simple, because rails doesn't inherit from the Rack::Request class, plus there are small differences between how rack is implemented in each framework. Authlogic has to hook into your controller with a before_filter anyways, so it can "activate" itself. Why not just use the controller object?
-
-The point in all of this rambling is that implementing Authlogic is as simple as creating an adapter. I created both the rails and merb adapters in under 10 minutes. If you have an adapter you created and would like to add please let me know and I will add it into the source.
-
-== How it works
-
-Interested in how all of this all works? Basically a before_filter is automatically set in your controller which lets Authlogic know about the current controller object. This "activates" Authlogic and allows Authlogic to set sessions, cookies, login via basic http auth, etc. If you are using your framework in a multiple thread environment, don't worry. I kept that in mind and made this thread safe.
-
-From there it is pretty simple. When you try to create a new session the record is authenticated and then all of the session / cookie magic is done for you. The sky is the limit.
-
-== What's wrong with the current solutions?
-
-You probably don't care, but I think releasing the millionth authentication solution for a framework that has been around for over 4 years requires a little explanation.
-
-I don't necessarily think the current solutions are "wrong", nor am I saying Authlogic is the answer to your prayers. But, to me, the current solutions were lacking something. Here's what I came up with...
-
-=== Generators are messy
-
-Generators have their place, and it is not to add authentication to an app. It doesn't make sense. Generators are meant to be a starting point for repetitive tasks that have no sustainable pattern. Take controllers, the set up is the same thing over and over, but they eventually evolve to a point where there is no clear cut pattern. Trying to extract a pattern out into a library would be extremely hard, messy, and overly complicated. As a result, generators make sense here.
-
-Authentication is a one time set up process for your app. It's the same thing over and over and the pattern never really changes. The only time it changes is to conform with newer / stricter security techniques. This is exactly why generators should not be an authentication solution. Generators add code to your application, once code crosses that line, you are responsible for maintaining it. You get to make sure it stays up with the latest and greatest security techniques. And when the plugin you used releases some major update, you can't just re-run the generator, you get to sift through the code to see what changed. You don't really have a choice either, because you can't ignore security updates.
-
-Using a library that hundreds of other people use has it advantages. Probably one of the biggest advantages if that you get to benefit from other people using the same code. When Bob in California figures out a new awesome security technique and adds it into Authlogic, you get to benefit from that with a single update. The catch is that this benefit is limited to code that is not "generated" or added into your app. As I said above, once code is "generated" and added into your app, it's your responsibility.
-
-Lastly, there is a pattern here, why clutter up all of your applications with the same code over and over?
-
-=== Limited to a single authentication
-
-I recently had an app where you could log in as a user and also log in as an employee. I won't go into the specifics of the app, but it made the most sense to do it this way. So I had two sessions in one app. None of the current solutions I found easily supported this. They all assumed a single session. One session was messy enough, adding another just put me over the edge and eventually forced me to write Authlogic. Authlogic can support 100 different sessions easily and in a clean format. Just like an app can support 100 different models and 100 different records of each model.
-
-=== Too presumptuous
-
-A lot of them forced me to name my password column as "this", or the key of my cookie had to be "this". They were a little too presumptuous. I am probably overly picky, but little details like that should be configurable. This also made it very hard to implement into an existing app.
-
-=== Disclaimer
-
-I am not trying to "bash" any other authentication solutions. These are just my opinions, formulate your own opinion. I released Authlogic because it has made my life easier and I enjoy using it, hopefully it does the same for you.
-
-
-Copyright (c) 2008 Ben Johnson of [Binary Logic](http://www.binarylogic.com), released under the MIT license
View
15 vendor/plugins/authlogic/Rakefile
@@ -1,15 +0,0 @@
-require 'rubygems'
-require 'echoe'
-
-require File.dirname(__FILE__) << "/lib/authlogic/version"
-
-Echoe.new 'authlogic' do |p|
- p.version = Authlogic::Version::STRING
- p.author = "Ben Johnson of Binary Logic"
- p.email = 'bjohnson@binarylogic.com'
- p.project = 'authlogic'
- p.summary = "Framework agnostic object based authentication solution that handles all of the non sense for you. It's as easy as ActiveRecord is with a database."
- p.url = "http://github.com/binarylogic/authlogic"
- p.dependencies = %w(activesupport activerecord)
- p.include_rakefile = true
-end
View
1 vendor/plugins/authlogic/init.rb
@@ -1 +0,0 @@
-require "authlogic"
View
30 vendor/plugins/authlogic/lib/authlogic.rb
@@ -1,30 +0,0 @@
-require "active_support"
-
-require File.dirname(__FILE__) + "/authlogic/version"
-
-require File.dirname(__FILE__) + "/authlogic/controller_adapters/abstract_adapter"
-require File.dirname(__FILE__) + "/authlogic/controller_adapters/rails_adapter" if defined?(Rails)
-require File.dirname(__FILE__) + "/authlogic/controller_adapters/merb_adapter" if defined?(Merb)
-
-require File.dirname(__FILE__) + "/authlogic/sha512_crypto_provider"
-
-require File.dirname(__FILE__) + "/authlogic/active_record/acts_as_authentic"
-require File.dirname(__FILE__) + "/authlogic/active_record/authenticates_many"
-require File.dirname(__FILE__) + "/authlogic/active_record/scoped_session"
-
-require File.dirname(__FILE__) + "/authlogic/session/active_record_trickery"
-require File.dirname(__FILE__) + "/authlogic/session/callbacks"
-require File.dirname(__FILE__) + "/authlogic/session/config"
-require File.dirname(__FILE__) + "/authlogic/session/errors"
-require File.dirname(__FILE__) + "/authlogic/session/scopes"
-require File.dirname(__FILE__) + "/authlogic/session/base"
-
-module Authlogic
- module Session
- class Base
- include ActiveRecordTrickery
- include Callbacks
- include Scopes
- end
- end
-end
View
297 vendor/plugins/authlogic/lib/authlogic/active_record/acts_as_authentic.rb
@@ -1,297 +0,0 @@
-module Authlogic
- module ActiveRecord # :nodoc:
- # = Acts As Authentic
- # Provides the acts_as_authentic method to include in your models to help with authentication. See method below.
- module ActsAsAuthentic
- # Call this method in your model to add in basic authentication madness that your authlogic session expects.
- #
- # === Methods
- # For example purposes lets assume you have a User model.
- #
- # Class method name Description
- # User.crypto_provider The class that you set in your :crypto_provider option
- # User.forget_all! Finds all records, loops through them, and calls forget! on each record. This is paginated to save on memory.
- # User.unique_token returns unique token generated by your :crypto_provider
- #
- # Named Scopes
- # User.logged_in Find all users who are logged in, based on your :logged_in_timeout option.
- # User.logged_out Same as above, but logged out.
- #
- # Isntace method name
- # user.password= Method name based on the :password_field option. This is used to set the password. Pass the *raw* password to this.
- # user.confirm_password= Confirms the password, needed to change the password.
- # user.valid_password?(pass) Determines if the password passed is valid. The password could be encrypted or raw.
- # user.reset_password! Basically resets the password to a random password using only letters and numbers.
- # user.logged_in? Based on the :logged_in_timeout option. Tells you if the user is logged in or not.
- # user.forget! Changes their remember token, making their cookie and session invalid. A way to log the user out withouth changing their password.
- #
- # === Options
- #
- # * <tt>session_class:</tt> default: "#{name}Session",
- # This is the related session class. A lot of the configuration will be based off of the configuration values of this class.
- #
- # * <tt>crypto_provider:</tt> default: Authlogic::Sha512CryptoProvider,
- # This is the class that provides your encryption. By default Authlogic provides its own crypto provider that uses Sha512 encrypton.
- #
- # * <tt>login_field:</tt> default: options[:session_class].login_field,
- # The name of the field used for logging in, this is guess based on what columns are in your db. Only specify if you aren't using:
- # login, username, or email
- #
- # * <tt>login_field_type:</tt> default: options[:login_field] == :email ? :email : :login,
- # Tells authlogic how to validation the field, what regex to use, etc. If the field name is email it will automatically use email,
- # otherwise it uses login.
- #
- # * <tt>login_field_regex:</tt> default: if email then typical email regex, otherwise typical login regex.
- # This is used in validates_format_of for the login_field.
- #
- # * <tt>login_field_regex_message:</tt> the message to use when the validates_format_of for the login field fails.
- #
- # * <tt>password_field:</tt> default: options[:session_class].password_field,
- # This is the name of the field to set the password, *NOT* the field the encrypted password is stored.
- #
- # * <tt>crypted_password_field:</tt> default: depends on which columns are present,
- # The name of the database field where your encrypted password is stored. If the name of the field is different from any of the following
- # you need to specify it with this option: crypted_password, encrypted_password, password_hash, pw_hash
- #
- # * <tt>password_salt_field:</tt> default: depends on which columns are present,
- # This is the name of the field in your database that stores your password salt. If the name of the field is different from any of the
- # following then you need to specify it with this option: password_salt, pw_salt, salt
- #
- # * <tt>remember_token_field:</tt> default: options[:session_class].remember_token_field,
- # This is the name of the field your remember_token is stored. The remember token is a unique token that is stored in the users cookie and
- # session. This way you have complete control of when session expire and you don't have to change passwords to expire sessions. This also
- # ensures that stale sessions can not be persisted. By stale, I mean sessions that are logged in using an outdated password. If the name
- # of the field is anything other than the following you need to specify it with this option: remember_token, remember_key, cookie_token,
- # cookie_key
- #
- # * <tt>scope:</tt> default: nil,
- # This scopes validations. If all of your users belong to an account you might want to scope everything to the account. Just pass :account_id
- #
- # * <tt>logged_in_timeout:</tt> default: 10.minutes,
- # This is really just a nifty feature to tell if a user is logged in or not. It's based on activity. So if the user in inactive longer than
- # the value you pass here they are assumed "logged out".
- #
- # * <tt>session_ids:</tt> default: [nil],
- # The sessions that we want to automatically reset when a user is created or updated so you don't have to worry about this. Set to [] to disable.
- # Should be an array of ids. See the Authlogic::Session documentation for information on ids. The order is important.
- # The first id should be your main session, the session they need to log into first. This is generally nil. When you don't specify an id
- # in your session you are really just inexplicitly saying you want to use the id of nil.
- def acts_as_authentic(options = {})
- # If we don't have a database, skip all of this, solves initial setup errors
- begin
- column_names
- rescue Exception
- return
- end
-
- # Setup default options
- begin
- options[:session_class] ||= "#{name}Session".constantize
- rescue NameError
- raise NameError.new("You must create a #{name}Session class before a model can act_as_authentic. If that is not the name of the class pass the class constant via the :session_class option.")
- end
-
- options[:crypto_provider] ||= Sha512CryptoProvider
- options[:crypto_provider_type] ||= options[:crypto_provider].respond_to?(:decrypt) ? :encryption : :hash
- options[:login_field] ||= options[:session_class].login_field
- options[:login_field_type] ||= options[:login_field] == :email ? :email : :login
- options[:password_field] ||= options[:session_class].password_field
- options[:crypted_password_field] ||=
- (column_names.include?("crypted_password") && :crypted_password) ||
- (column_names.include?("encrypted_password") && :encrypted_password) ||
- (column_names.include?("password_hash") && :password_hash) ||
- (column_names.include?("pw_hash") && :pw_hash) ||
- :crypted_password
- options[:password_salt_field] ||=
- (column_names.include?("password_salt") && :password_salt) ||
- (column_names.include?("pw_salt") && :pw_salt) ||
- (column_names.include?("salt") && :salt) ||
- :password_salt
- options[:remember_token_field] ||= options[:session_class].remember_token_field
- options[:logged_in_timeout] ||= 10.minutes
- options[:session_ids] ||= [nil]
-
- # Validations
- case options[:login_field_type]
- when :email
- validates_length_of options[:login_field], :within => 6..100
- email_name_regex = '[\w\.%\+\-]+'
- domain_head_regex = '(?:[A-Z0-9\-]+\.)+'
- domain_tld_regex = '(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)'
- options[:login_field_regex] ||= /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i
- options[:login_field_regex_message] ||= "should look like an email address."
- validates_format_of options[:login_field], :with => options[:login_field_regex], :message => options[:login_field_regex_message]
- else
- validates_length_of options[:login_field], :within => 2..100
- options[:login_field_regex] ||= /\A\w[\w\.\-_@ ]+\z/
- options[:login_field_regex_message] ||= "use only letters, numbers, spaces, and .-_@ please."
- validates_format_of options[:login_field], :with => options[:login_field_regex], :message => options[:login_field_regex_message]
- end
-
- validates_uniqueness_of options[:login_field], :scope => options[:scope]
- validates_uniqueness_of options[:remember_token_field]
- validate :validate_password
- validates_numericality_of :login_count, :only_integer => :true, :greater_than_or_equal_to => 0, :allow_nil => true if column_names.include?("login_count")
-
- if column_names.include?("last_request_at")
- named_scope :logged_in, lambda { {:conditions => ["last_request_at > ?", options[:logged_in_timeout].ago]} }
- named_scope :logged_out, lambda { {:conditions => ["last_request_at is NULL or last_request_at <= ?", options[:logged_in_timeout].ago]} }
- end
-
- before_save :get_session_information, :if => :update_sessions?
- after_save :maintain_sessions!, :if => :update_sessions?
-
- # Attributes
- attr_writer "confirm_#{options[:password_field]}"
- attr_accessor "tried_to_set_#{options[:password_field]}"
-
- # Class methods
- class_eval <<-"end_eval", __FILE__, __LINE__
- def self.unique_token
- # Force using the Sha512 because all that we are doing is creating a unique token, a hash is perfect for this
- Authlogic::Sha512CryptoProvider.encrypt(Time.now.to_s + (1..10).collect{ rand.to_s }.join)
- end
-
- def self.crypto_provider
- #{options[:crypto_provider]}
- end
-
- def self.forget_all!
- # Paginate these to save on memory
- records = nil
- i = 0
- begin
- records = find(:all, :limit => 50, :offset => i)
- records.each { |record| record.forget! }
- i += 50
- end while !records.blank?
- end
- end_eval
-
- # Instance methods
- if column_names.include?("last_request_at")
- class_eval <<-"end_eval", __FILE__, __LINE__
- def logged_in?
- !last_request_at.nil? && last_request_at > #{options[:logged_in_timeout].to_i}.seconds.ago
- end
- end_eval
- end
-
- class_eval <<-"end_eval", __FILE__, __LINE__
- def #{options[:password_field]}=(pass)
- return if pass.blank?
- self.tried_to_set_#{options[:password_field]} = true
- @#{options[:password_field]} = pass
- self.#{options[:remember_token_field]} = self.class.unique_token
- self.#{options[:password_salt_field]} = self.class.unique_token
- self.#{options[:crypted_password_field]} = crypto_provider.encrypt(@#{options[:password_field]} + #{options[:password_salt_field]})
- end
-
- def valid_#{options[:password_field]}?(attempted_password)
- return false if attempted_password.blank? || #{options[:crypted_password_field]}.blank? || #{options[:password_salt_field]}.blank?
- attempted_password == #{options[:crypted_password_field]} ||
- (crypto_provider.respond_to?(:decrypt) && crypto_provider.decrypt(#{options[:crypted_password_field]}) == attempted_password + #{options[:password_salt_field]}) ||
- (!crypto_provider.respond_to?(:decrypt) && crypto_provider.encrypt(attempted_password + #{options[:password_salt_field]}) == #{options[:crypted_password_field]})
- end
- end_eval
-
- class_eval <<-"end_eval", __FILE__, __LINE__
- def #{options[:password_field]}; end
- def confirm_#{options[:password_field]}; end
-
- def crypto_provider
- self.class.crypto_provider
- end
-
- def forget!
- self.#{options[:remember_token_field]} = self.class.unique_token
- save_without_session_maintenance(false)
- end
-
- def reset_#{options[:password_field]}!
- chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
- newpass = ""
- 1.upto(10) { |i| newpass << chars[rand(chars.size-1)] }
- self.#{options[:password_field]} = newpass
- self.confirm_#{options[:password_field]} = newpass
- save_without_session_maintenance(false)
- end
- alias_method :randomize_password!, :reset_password!
-
- def save_without_session_maintenance(*args)
- @skip_session_maintenance = true
- result = save(*args)
- @skip_session_maintenance = false
- result
- end
-
- protected
- def update_sessions?
- !@skip_session_maintenance && #{options[:session_class]}.activated? && !#{options[:session_ids].inspect}.blank? && #{options[:remember_token_field]}_changed?
- end
-
- def get_session_information
- # Need to determine if we are completely logged out, or logged in as another user
- @_sessions = []
- @_logged_out = true
-
- #{options[:session_ids].inspect}.each do |session_id|
- session = #{options[:session_class]}.find(*[session_id].compact)
- if session
- if !session.record.blank?
- @_logged_out = false
- @_sessions << session if session.record == self
- end
- end
- end
- end
-
- def maintain_sessions!
- if @_logged_out
- create_session!
- elsif !@_sessions.blank?
- update_sessions!
- end
- end
-
- def create_session!
- # We only want to automatically login into the first session, since this is the main session. The other sessions are sessions
- # that need to be created after logging into the main session.
- session_id = #{options[:session_ids].inspect}.first
-
- # If we are already logged in, ignore this completely. All that we care about is updating ourself.
- next if #{options[:session_class]}.find(*[session_id].compact)
-
- # Log me in
- args = [self, session_id].compact
- #{options[:session_class]}.create(*args)
- end
-
- def update_sessions!
- # We found sessions above, let's update them with the new info
- @_sessions.each do |stale_session|
- stale_session.unauthorized_record = self
- stale_session.save
- end
- end
-
- def tried_to_set_password?
- tried_to_set_password == true
- end
-
- def validate_password
- if new_record? || tried_to_set_#{options[:password_field]}?
- if @#{options[:password_field]}.blank?
- errors.add(:#{options[:password_field]}, "can not be blank")
- else
- errors.add(:confirm_#{options[:password_field]}, "did not match") if @confirm_#{options[:password_field]} != @#{options[:password_field]}
- end
- end
- end
- end_eval
- end
- end
- end
-end
-
-ActiveRecord::Base.extend Authlogic::ActiveRecord::ActsAsAuthentic
View
56 vendor/plugins/authlogic/lib/authlogic/active_record/authenticates_many.rb
@@ -1,56 +0,0 @@
-module Authlogic
- module ActiveRecord
- # = Authenticates Many
- #
- # This allows you to scope your authentication. For example, let's say all users belong to an account, you want to make sure only users
- # that belong to that account can actually login into that account. Simple, just do:
- #
- # class Account < ActiveRecord::Base
- # authenticates_many :user_sessions
- # end
- #
- # Now you can scope sessions just like everything else in ActiveRecord:
- #
- # @account.user_sessions.new(*args)
- # @account.user_sessions.create(*args)
- # @account.user_sessions.find(*args)
- # # ... etc
- #
- # For more information on scopes check out the scopes section in the README.
- module AuthenticatesMany
- # Allows you set essentially set up a relationship with your sessions. See module definition above for more details.
- #
- # === Options
- #
- # * <tt>session_class:</tt> default: "#{name}Session",
- # This is the related session class.
- #
- # * <tt>relationship_name:</tt> default: options[:session_class].klass_name.underscore.pluralize,
- # This is the name of the relationship you want to use to scope everything. For example an Account has many Users. There should be a relationship
- # called :users that you defined with a has_many. The reason we use the relationship is so you don't have to repeat yourself. The relatonship
- # could have all kinds of custom options. So instead of repeating yourself we essentially use the scope that the relationship creates.
- #
- # * <tt>find_options:</tt> default: nil,
- # By default the find options are created from the relationship you specify with :relationship_name. But if you want to override this and
- # manually specify find_options you can do it here. Specify options just as you would in ActiveRecord::Base.find.
- #
- # * <tt>scope_cookies:</tt> default: false
- # By the nature of cookies they scope theirself if you are using subdomains to access accounts. If you aren't using subdomains you need to have
- # separate cookies for each account, assuming a user is logging into mroe than one account. Authlogic can take care of this for you by
- # prefixing the name of the cookie and sessin with the model id. You just need to tell Authlogic to do this by passing this option.
- def authenticates_many(name, options = {})
- options[:session_class] ||= name.to_s.classify.constantize
- options[:relationship_name] ||= options[:session_class].klass_name.underscore.pluralize
- class_eval <<-"end_eval", __FILE__, __LINE__
- def #{name}
- find_options = #{options[:find_options].inspect} || #{options[:relationship_name]}.scope(:find)
- find_options.delete_if { |key, value| ![:conditions, :include, :joins].include?(key.to_sym) || value.nil? }
- @#{name} ||= Authlogic::ActiveRecord::ScopedSession.new(#{options[:session_class]}, find_options, #{options[:scope_cookies] ? "self.class.model_name.underscore + '_' + self.send(self.class.primary_key).to_s" : "nil"})
- end
- end_eval
- end
- end
- end
-end
-
-ActiveRecord::Base.extend Authlogic::ActiveRecord::AuthenticatesMany
View
28 vendor/plugins/authlogic/lib/authlogic/active_record/scoped_session.rb
@@ -1,28 +0,0 @@
-module Authlogic
- module ActiveRecord
- class ScopedSession # :nodoc:
- attr_accessor :klass, :find_options, :id
-
- def initialize(klass, find_options, id)
- self.klass = klass
- self.find_options = find_options
- self.id = id
- end
-
- [:create, :create!, :find, :new].each do |method|
- class_eval <<-"end_eval", __FILE__, __LINE__
- def #{method}(*args)
- klass.with_scope(scope_options) do
- klass.#{method}(*args)
- end
- end
- end_eval
- end
-
- private
- def scope_options
- {:find_options => find_options, :id => id}
- end
- end
- end
-end
View
34 vendor/plugins/authlogic/lib/authlogic/controller_adapters/abstract_adapter.rb
@@ -1,34 +0,0 @@
-module Authlogic
- module ControllerAdapters # :nodoc:
- # = Abstract Adapter
- # Allows you to use Authlogic in any framework you want, not just rails. See tha RailsAdapter for an example of how to adapter Authlogic to work with your framework.
- class AbstractAdapter
- attr_accessor :controller
-
- def initialize(controller)
- self.controller = controller
- end
-
- def authenticate_with_http_basic(&block)
- @auth = Rack::Auth::Basic::Request.new(controller.request.env)
- if @auth.provided? and @auth.basic?
- black.call(*@auth.credentials)
- else
- false
- end
- end
-
- def cookies
- controller.cookies
- end
-
- def request
- controller.request
- end
-
- def session
- controller.session
- end
- end
- end
-end
View
28 vendor/plugins/authlogic/lib/authlogic/controller_adapters/merb_adapter.rb
@@ -1,28 +0,0 @@
-module Authlogic
- module ControllerAdapters
- # = Merb Adapter
- # Adapts authlogic to work with merb. The point is to close the gap between what authlogic expects and what the merb controller object
- # provides. Similar to how ActiveRecord has an adapter for MySQL, PostgreSQL, SQLite, etc.
- class MerbAdapter < AbstractAdapter
- # = Merb Implementation
- # Lets Authlogic know about the controller object, AKA "activates" authlogic.
- module MerbImplementation
- def self.included(klass) # :nodoc:
- klass.before :activate_authlogic
- end
-
- private
- def activate_authlogic
- Authlogic::Session::Base.controller = MerbAdapter.new(self)
- end
- end
- end
- end
-end
-
-# make sure we're running inside Merb
-if defined?(Merb::Plugins)
- Merb::BootLoader.before_app_loads do
- Merb::Controller.send(:include, Authlogic::ControllerAdapters::MerbAdapter::MerbImplementation)
- end
-end
View
31 vendor/plugins/authlogic/lib/authlogic/controller_adapters/rails_adapter.rb
@@ -1,31 +0,0 @@
-module Authlogic
- module ControllerAdapters
- # = Rails Adapter
- # Adapts authlogic to work with rails. The point is to close the gap between what authlogic expects and what the rails controller object
- # provides. Similar to how ActiveRecord has an adapter for MySQL, PostgreSQL, SQLite, etc.
- class RailsAdapter < AbstractAdapter
- def authenticate_with_http_basic(&block)
- controller.authenticate_with_http_basic(&block)
- end
-
- def cookies
- controller.send(:cookies)
- end
-
- # = Rails Implementation
- # Lets Authlogic know about the controller object, AKA "activates" authlogic.
- module RailsImplementation
- def self.included(klass) # :nodoc:
- klass.prepend_before_filter :activate_authlogic
- end
-
- private
- def activate_authlogic
- Authlogic::Session::Base.controller = RailsAdapter.new(self)
- end
- end
- end
- end
-end
-
-ActionController::Base.send(:include, Authlogic::ControllerAdapters::RailsAdapter::RailsImplementation)
View
26 vendor/plugins/authlogic/lib/authlogic/session/active_record_trickery.rb
@@ -1,26 +0,0 @@
-module Authlogic
- module Session
- # = ActiveRecord Trickery
- #
- # Authlogic looks like ActiveRecord, sounds like ActiveRecord, but its not ActiveRecord. That's the goal here. This is useful for the various rails helper methods such as form_for, error_messages_for, etc.
- # These helpers exptect various methods to be present. This adds in those methods into Authlogic.
- module ActiveRecordTrickery
- def self.included(klass) # :nodoc:
- klass.extend ClassMethods
- klass.send(:include, InstanceMethods)
- end
-
- module ClassMethods # :nodoc:
- def human_attribute_name(attribute_key_name, options = {})
- attribute_key_name.humanize
- end
- end
-
- module InstanceMethods # :nodoc:
- def new_record?
- new_session?
- end
- end
- end
- end
-end
View
458 vendor/plugins/authlogic/lib/authlogic/session/base.rb
@@ -1,458 +0,0 @@
-module Authlogic
- module Session # :nodoc:
- # = Base
- #
- # This is the muscle behind Authlogic. For detailed information on how to use this please refer to the README. For detailed method explanations see below.
- class Base
- include Config
-
- class << self
- # Returns true if a controller have been set and can be used properly. This MUST be set before anything can be done. Similar to how ActiveRecord won't allow you to do anything
- # without establishing a DB connection. By default this is done for you automatically, but if you are using Authlogic in a unique way outside of rails, you need to assign a controller
- # object to Authlogic via Authlogic::Session::Base.controller = obj.
- def activated?
- !controller.blank?
- end
-
- def controller=(value) # :nodoc:
- controllers[Thread.current] = value
- end
-
- def controller # :nodoc:
- controllers[Thread.current]
- end
-
- def reset_controllers!
- @@controllers = {}
- end
-
- # A convenince method. The same as:
- #
- # session = UserSession.new
- # session.create
- def create(*args)
- session = new(*args)
- session.save
- end
-
- # Same as create but calls create!, which raises an exception when authentication fails
- def create!(*args)
- session = new(*args)
- session.save!
- end
-
- # A convenience method for session.find_record. Finds your session by session, then cookie, and finally basic http auth. Perfect for that global before_filter to find your logged in user:
- #
- # before_filter :load_user
- #
- # def load_user
- # @user_session = UserSession.find
- # @current_user = @user_session && @user_session.record
- # end
- #
- # Accepts a single parameter as the id. See initialize for more information on ids. Lastly, how it finds the session can be modified via configuration.
- def find(id = nil)
- args = [id].compact
- session = new(*args)
- return session if session.find_record
- nil
- end
-
- def klass # :nodoc:
- @klass ||=
- if klass_name
- klass_name.constantize
- else
- nil
- end
- end
-
- def klass_name # :nodoc:
- @klass_name ||=
- if guessed_name = name.scan(/(.*)Session/)[0]
- @klass_name = guessed_name[0]
- end
- end
-
- private
- def controllers
- @@controllers ||= {}
- end
- end
-
- attr_accessor :login_with, :new_session
- attr_reader :record, :unauthorized_record
- attr_writer :id
-
- # You can initialize a session by doing any of the following:
- #
- # UserSession.new
- # UserSession.new(login, password)
- # UserSession.new(:login => login, :password => password)
- # UserSession.new(User.first)
- #
- # If a user has more than one session you need to pass an id so that Authlogic knows how to differentiate the sessions. The id MUST be a Symbol.
- #
- # UserSession.new(:my_id)
- # UserSession.new(login, password, :my_id)
- # UserSession.new({:login => loing, :password => password}, :my_id)
- # UserSession.new(User.first, :my_id)
- #
- # Ids are rarely used, but they can be useful. For example, what if users allow other users to login into their account via proxy? Now that user can "technically" be logged into 2 accounts at once.
- # To solve this just pass a id called :proxy, or whatever you want. Authlogic will separate everything out.
- def initialize(*args)
- raise NotActivated.new(self) unless self.class.activated?
-
- create_configurable_methods!
-
- self.id = args.pop if args.last.is_a?(Symbol)
-
- case args.first
- when Hash
- self.credentials = args.first
- when String
- send("#{login_field}=", args[0]) if args.size > 0
- send("#{password_field}=", args[1]) if args.size > 1
- self.remember_me = args[2] if args.size > 2
- else
- self.unauthorized_record = args.first
- self.remember_me = args[1] if args.size > 1
- end
- end
-
- # Your login credentials in hash format. Usually {:login => "my login", :password => "<protected>"} depending on your configuration.
- # Password is protected as a security measure. The raw password should never be publicly accessible.
- def credentials
- {login_field => send(login_field), password_field => "<Protected>"}
- end
-
- # Lets you set your loging and password via a hash format. This is "params" safe. It only allows for 3 keys: your login field name, password field name, and remember me.
- def credentials=(values)
- return if values.blank? || !values.is_a?(Hash)
- values.symbolize_keys!
- [login_field.to_sym, password_field.to_sym, :remember_me].each do |field|
- next if !values.key?(field)
- send("#{field}=", values[field])
- end
- end
-
- # Resets everything, your errors, record, cookies, and session. Basically "logs out" a user.
- def destroy
- errors.clear
- @record = nil
- controller.cookies.delete cookie_key
- controller.session[session_key] = nil
- true
- end
-
- # The errors in Authlogic work JUST LIKE ActiveRecord. In fact, it uses the exact same ActiveRecord errors class. Use it the same way:
- #
- # === Example
- #
- # class UserSession
- # before_validation :check_if_awesome
- #
- # private
- # def check_if_awesome
- # errors.add(:login, "must contain awesome") if login && !login.include?("awesome")
- # errors.add_to_base("You must be awesome to log in") unless record.awesome?
- # end
- # end
- def errors
- @errors ||= Errors.new(self)
- end
-
- # Attempts to find the record by session, then cookie, and finally basic http auth. See the class level find method if you are wanting to use this in a before_filter to persist your session.
- def find_record
- return record if record
- find_with.each do |find_method|
- if send("valid_#{find_method}?")
- if record.class.column_names.include?("last_request_at")
- record.last_request_at = Time.now
- record.save_without_session_maintenance(false)
- end
- return record
- end
- end
- nil
- end
-
- # Allows you to set a unique identifier for your session, so that you can have more than 1 session at a time. A good example when this might be needed is when you want to have a normal user session
- # and a "secure" user session. The secure user session would be created only when they want to modify their billing information, or other sensative information. Similar to me.com. This requires 2
- # user sessions. Just use an id for the "secure" session and you should be good.
- #
- # You can set the id a number of ways:
- #
- # session = Session.new(:secure)
- # session = Session.new("username", "password", :secure)
- # session = Session.new({:username => "username", :password => "password"}, :secure)
- # session.id = :secure
- #
- # Just be sure and set your id before you validate / create / update your session.
- def id
- @id
- end
-
- def inspect # :nodoc:
- details = {}
- case login_with
- when :unauthorized_record
- details[:unauthorized_record] = "<protected>"
- else
- details[login_field.to_sym] = send(login_field)
- details[password_field.to_sym] = "<protected>"
- end
- "#<#{self.class.name} #{details.inspect}>"
- end
-
- # Similar to ActiveRecord's new_record? Returns true if the session has not been saved yet.
- def new_session?
- new_session != false
- end
-
- def remember_me # :nodoc:
- return @remember_me if @set_remember_me
- @remember_me ||= self.class.remember_me
- end
-
- # Accepts a boolean as a flag to remember the session or not. Basically to expire the cookie at the end of the session or keep it for "remember_me_until".
- def remember_me=(value)
- @set_remember_me = true
- @remember_me = value
- end
-
- # Allows users to be remembered via a cookie.
- def remember_me?
- remember_me == true || remember_me == "true" || remember_me == "1"
- end
-
- # When to expire the cookie. See remember_me_for configuration option to change this.
- def remember_me_until
- return unless remember_me?
- remember_me_for.from_now
- end
-
- # Creates / updates a new user session for you. It does all of the magic:
- #
- # 1. validates
- # 2. sets session
- # 3. sets cookie
- # 4. updates magic fields
- def save
- if valid?
- update_session!
- controller.cookies[cookie_key] = {
- :value => record.send(remember_token_field),
- :expires => remember_me_until
- }
-
- record.login_count = (record.login_count.blank? ? 1 : record.login_count + 1) if record.respond_to?(:login_count)
-
- if record.respond_to?(:current_login_at)
- record.last_login_at = record.current_login_at if record.respond_to?(:last_login_at)
- record.current_login_at = Time.now
- end
-
- if record.respond_to?(:current_login_ip)
- record.last_login_ip = record.current_login_ip if record.respond_to?(:last_login_ip)
- record.current_login_ip = controller.request.remote_ip
- end
-
- record.save_without_session_maintenance(false)
-
- self.new_session = false
- self
- end
- end
-
- # Same as save but raises an exception when authentication fails
- def save!
- result = save
- raise SessionInvalid.new(self) unless result
- result
- end
-
- # Sometimes you don't want to create a session via credentials (login and password). Maybe you already have the record. Just set this record to this and it will be authenticated when you try to validate
- # the session. Basically this is another form of credentials, you are just skipping username and password validation.
- def unauthorized_record=(value)
- self.login_with = :unauthorized_record
- @unauthorized_record = value
- end
-
- # Returns if the session is valid or not. Basically it means that a record could or could not be found. If the session is valid you will have a result when calling the "record" method. If it was unsuccessful
- # you will not have a record.
- def valid?
- errors.clear
- if valid_credentials?
- validate
- return true if errors.empty?
- end
-
- self.record = nil
- false
- end
-
- # Tries to validate the session from information from a basic http auth, if it was provided.
- def valid_http_auth?
- controller.authenticate_with_http_basic do |login, password|
- if !login.blank? && !password.blank?
- send("#{login_field}=", login)
- send("#{password_field}=", password)
- result = valid?
- if result
- update_session!
- self.new_session = false
- return result
- end
- end
- end
-
- false
- end
-
- # Tries to validate the session from information in the cookie
- def valid_cookie?
- if cookie_credentials
- self.unauthorized_record = search_for_record("find_by_#{remember_token_field}", cookie_credentials)
- result = valid?
- if result
- update_session!
- self.new_session = false
- return result
- end
- end
-
- false
- end
-
- # Tries to validate the session from information in the session
- def valid_session?
- if session_credentials
- self.unauthorized_record = search_for_record("find_by_#{remember_token_field}", session_credentials)
- result = valid?
- if result
- self.new_session = false
- return result
- end
- end
-
- false
- end
-
- # Overwite this method to add your own validation, or use callbacks: before_validation, after_validation
- def validate
- end
-
- private
- def controller
- self.class.controller
- end
-
- def cookie_credentials
- controller.cookies[cookie_key]
- end
-
- def create_configurable_methods!
- return if respond_to?(login_field) # already created these methods
-
- self.class.class_eval <<-"end_eval", __FILE__, __LINE__
- attr_reader :#{login_field}
-
- def #{login_field}=(value)
- self.login_with = :credentials
- @#{login_field} = value
- end
-
- def #{password_field}=(value)
- self.login_with = :credentials
- @#{password_field} = value
- end
-
- def #{password_field}; end
-
- private
- # The password should not be accessible publicly. This way forms using form_for don't fill the password with the attempted password. The prevent this we just create this method that is private.
- def protected_#{password_field}
- @#{password_field}
- end
- end_eval
- end
-
- def klass
- self.class.klass
- end
-
- def klass_name
- self.class.klass_name
- end
-
- def record=(value)
- @record = value
- end
-
- def search_for_record(method, value)
- begin
- klass.send(method, value)
- rescue Exception
- raise method.inspect + " " + value.inspect
- end
- end
-
- def session_credentials
- controller.session[session_key]
- end
-
- def update_session!
- controller.session[session_key] = record && record.send(remember_token_field)
- end
-
- def valid_credentials?
- unchecked_record = nil
-
- case login_with
- when :credentials
- errors.add(login_field, "can not be blank") if send(login_field).blank?
- errors.add(password_field, "can not be blank") if send("protected_#{password_field}").blank?
- return false if errors.count > 0
-
- unchecked_record = search_for_record(find_by_login_method, send(login_field))
-
- if unchecked_record.blank?
- errors.add(login_field, "was not found")
- return false
- end
-
- unless unchecked_record.send(verify_password_method, send("protected_#{password_field}"))
- errors.add(password_field, "is invalid")
- return false
- end
- when :unauthorized_record
- unchecked_record = unauthorized_record
-
- if unchecked_record.blank?
- errors.add_to_base("The record could not be found and did not match the requirements.")
- return false
- end
-
- if unchecked_record.new_record?
- errors.add_to_base("You can not login with a new record.")
- return false
- end
- else
- errors.add_to_base("You must provide some form of credentials before logging in.")
- return false
- end
-
- [:active, :approved, :confirmed].each do |required_status|
- if unchecked_record.respond_to?("#{required_status}?") && !unchecked_record.send("#{required_status}?")
- errors.add_to_base("Your account has not been marked as #{required_status}")
- return false
- end
- end
-
- self.record = unchecked_record
- true
- end
- end
- end
-end
View
72 vendor/plugins/authlogic/lib/authlogic/session/callbacks.rb
@@ -1,72 +0,0 @@
-module Authlogic
- module Session
- # = Callbacks
- #
- # Just like in ActiveRecord you have before_save, before_validation, etc. You have similar callbacks with Authlogic, see all callbacks below.
- module Callbacks
- CALLBACKS = %w(before_create after_create before_destroy after_destroy before_save after_save before_update after_update before_validation after_validation)
-
- def self.included(base) #:nodoc:
- [:destroy, :save, :validate].each do |method|
- base.send :alias_method_chain, method, :callbacks
- end
-
- base.send :include, ActiveSupport::Callbacks
- base.define_callbacks *CALLBACKS
- end
-
- # Run the following callbacks:
- #
- # before_destroy
- # destroy
- # after_destroy # only if destroy is successful
- def destroy_with_callbacks
- run_callbacks(:before_destroy)
- result = destroy_without_callbacks
- run_callbacks(:after_destroy) if result
- result
- end
-
- # Runs the following callbacks:
- #
- # before_save
- # before_create # only if new_session? == true
- # before_update # only if new_session? == false
- # save
- # # the following are only run is save is successful
- # after_save
- # before_update # only if new_session? == false
- # before_create # only if new_session? == true
- def save_with_callbacks
- run_callbacks(:before_save)
- if new_session?
- run_callbacks(:before_create)
- else
- run_callbacks(:before_update)
- end
- result = save_without_callbacks
- if result
- run_callbacks(:after_save)
-
- if new_session?
- run_callbacks(:after_create)
- else
- run_callbacks(:after_update)
- end
- end
- result
- end
-
- # Runs the following callbacks:
- #
- # before_validation
- # validate
- # after_validation # only if errors.empty?
- def validate_with_callbacks
- run_callbacks(:before_validation)
- validate_without_callbacks
- run_callbacks(:after_validation) if errors.empty?
- end
- end
- end
-end
View
241 vendor/plugins/authlogic/lib/authlogic/session/config.rb
@@ -1,241 +0,0 @@
-module Authlogic
- module Session
- module Config # :nodoc:
- def self.included(klass)
- klass.extend(ClassMethods)
- klass.send(:include, InstanceMethods)
- end
-
- # = Config
- #
- # Configuration is simple. The configuration options are just class methods. Just put this in your config/initializers directory
- #
- # UserSession.configure do |config|
- # config.authenticate_with = User
- # # ... more configuration
- # end
- #
- # or you can set your configuration in the session class directly:
- #
- # class UserSession < Authlogic::Session::Base
- # authenticate_with User
- # # ... more configuration
- # end
- #
- # You can also access the values in the same fashion:
- #
- # UserSession.authenticate_with
- #
- # See the methods belows for all configuration options.
- module ClassMethods
- # Lets you change which model to use for authentication.
- #
- # * <tt>Default:</tt> inferred from the class name. UserSession would automatically try User
- # * <tt>Accepts:</tt> an ActiveRecord class
- def authenticate_with(klass)
- @klass_name = klass.name
- @klass = klass
- end
- alias_method :authenticate_with=, :authenticate_with
-
- # Convenience method that lets you easily set configuration, see examples above
- def configure
- yield self
- end
-
- # The name of the cookie or the key in the cookies hash. Be sure and use a unique name. If you have multiple sessions and they use the same cookie it will cause problems.
- # Also, if a id is set it will be inserted into the beginning of the string. Exmaple:
- #
- # session = UserSession.new(:super_high_secret)
- # session.cookie_key => "super_high_secret_user_credentials"
- #
- # * <tt>Default:</tt> "#{klass_name.underscore}_credentials"
- # * <tt>Accepts:</tt> String
- def cookie_key(value = nil)
- if value.nil?
- read_inheritable_attribute(:cookie_key) || cookie_key("#{klass_name.underscore}_credentials")
- else
- write_inheritable_attribute(:cookie_key, value)
- end
- end
- alias_method :cookie_key=, :cookie_key
-
- # The name of the method used to find the record by the login. What's nifty about this is that you can do anything in your method, Authlogic will just pass you the login.
- #
- # Let's say you allow users to login by username or email. Set this to "find_login", or whatever method you want. Then in your model create a class method like:
- #
- # def self.find_login(login)
- # find_by_login(login) || find_by_email(login)
- # end
- #
- # * <tt>Default:</tt> "find_by_#{login_field}"
- # * <tt>Accepts:</tt> Symbol or String
- def find_by_login_method(value = nil)
- if value.nil?
- read_inheritable_attribute(:find_by_login_method) || find_by_login_method("find_by_#{login_field}")
- else
- write_inheritable_attribute(:find_by_login_method, value)
- end
- end
- alias_method :find_by_login_method=, :find_by_login_method
-
- # Calling UserSession.find tries to find the user session by session, then cookie, then basic http auth. This option allows you to change the order or remove any of these.
- #
- # * <tt>Default:</tt> [:session, :cookie, :http_auth]
- # * <tt>Accepts:</tt> Array, and can only use any of the 3 options above
- def find_with(*values)
- if values.blank?
- read_inheritable_attribute(:find_with) || find_with(:session, :cookie, :http_auth)
- else
- values.flatten!
- write_inheritable_attribute(:find_with, values)
- end
- end
- alias_method :find_with=, :find_with
-
- # The name of the method you want Authlogic to create for storing the login / username. Keep in mind this is just for your Authlogic::Session, if you want it can be something completely different
- # than the field in your model. So if you wanted people to login with a field called "login" and then find users by email this is compeltely doable. See the find_by_login_method configuration option for
- # more details.
- #
- # * <tt>Default:</tt> Guesses based on the model columns, tries login, username, and email. If none are present it defaults to login
- # * <tt>Accepts:</tt> Symbol or String
- def login_field(value = nil)
- if value.nil?
- read_inheritable_attribute(:login_field) || login_field((klass.column_names.include?("login") && :login) || (klass.column_names.include?("username") && :username) || (klass.column_names.include?("email") && :email) || :login)
- else
- write_inheritable_attribute(:login_field, value)
- end
- end
- alias_method :login_field=, :login_field
-
- # Works exactly like login_field, but for the password instead.
- #
- # * <tt>Default:</tt> Guesses based on the model columns, tries password and pass. If none are present it defaults to password
- # * <tt>Accepts:</tt> Symbol or String
- def password_field(value = nil)
- if value.nil?
- read_inheritable_attribute(:password_field) || password_field((klass.column_names.include?("password") && :password) || (klass.column_names.include?("pass") && :pass) || :password)
- else
- write_inheritable_attribute(:password_field, value)
- end
- end
- alias_method :password_field=, :password_field
-
- # If sessions should be remembered by default or not.
- #
- # * <tt>Default:</tt> false
- # * <tt>Accepts:</tt> Boolean
- def remember_me(value = nil)
- if value.nil?
- read_inheritable_attribute(:remember_me)
- else
- write_inheritable_attribute(:remember_me, value)
- end
- end
- alias_method :remember_me=, :remember_me
-
- # The length of time until the cookie expires.
- #
- # * <tt>Default:</tt> 3.months
- # * <tt>Accepts:</tt> Integer, length of time in seconds, such as 60 or 3.months
- def remember_me_for(value = :_read)
- if value == :_read
- read_inheritable_attribute(:remember_me_for) || remember_me_for(3.months)
- else
- write_inheritable_attribute(:remember_me_for, value)
- end
- end
- alias_method :remember_me_for=, :remember_me_for
-
- # The name of the field that the remember token is stored. This is for cookies. Let's say you set up your app and want all users to be remembered for 6 months. Then you realize that might be a little too
- # long. Well they already have a cookie set to expire in 6 months. Without a token you would have to reset their password, which obviously isn't feasible. So instead of messing with their password
- # just reset their remember token. Next time they access the site and try to login via a cookie it will be rejected and they will have to relogin.
- #
- # * <tt>Default:</tt> Guesses based on the model columns, tries remember_token, remember_key, cookie_token, and cookie_key. If none are present it defaults to remember_token
- # * <tt>Accepts:</tt> Symbol or String
- def remember_token_field(value = nil)
- if value.nil?
- read_inheritable_attribute(:remember_token_field) ||
- remember_token_field(
- (klass.column_names.include?("remember_token") && :remember_token) ||
- (klass.column_names.include?("remember_key") && :remember_key) ||
- (klass.column_names.include?("cookie_token") && :cookie_token) ||
- (klass.column_names.include?("cookie_key") && :cookie_key) ||
- :remember_token
- )
- else
- write_inheritable_attribute(:remember_token_field, value)
- end
- end
- alias_method :remember_token_field=, :remember_token_field
-
- # Works exactly like cookie_key, but for sessions. See cookie_key for more info.
- #
- # * <tt>Default:</tt> cookie_key
- # * <tt>Accepts:</tt> Symbol or String
- def session_key(value = nil)
- if value.nil?
- read_inheritable_attribute(:session_key) || session_key(cookie_key)
- else
- write_inheritable_attribute(:session_key, value)
- end
- end
- alias_method :session_key=, :session_key
-
- # The name of the method in your model used to verify the password. This should be an instance method. It should also be prepared to accept a raw password and a crytped password.
- #
- # * <tt>Default:</tt> "valid_#{password_field}?"
- # * <tt>Accepts:</tt> Symbol or String
- def verify_password_method(value = nil)
- if value.nil?
- read_inheritable_attribute(:verify_password_method) || verify_password_method("valid_#{password_field}?")
- else
- write_inheritable_attribute(:verify_password_method, value)
- end
- end
- alias_method :verify_password_method=, :verify_password_method
- end
-
- module InstanceMethods # :nodoc:
- def cookie_key
- key_parts = [id, scope[:id], self.class.cookie_key].compact
- key_parts.join("_")
- end
-
- def find_by_login_method
- self.class.find_by_login_method
- end
-
- def find_with
- self.class.find_with
- end
-
- def login_field
- self.class.login_field
- end
-
- def password_field
- self.class.password_field
- end
-
- def remember_me_for
- return unless remember_me?
- self.class.remember_me_for
- end
-
- def remember_token_field
- self.class.remember_token_field
- end
-
- def session_key
- key_parts = [id, scope[:id], self.class.session_key].compact
- key_parts.join("_")
- end
-
- def verify_password_method
- self.class.verify_password_method
- end
- end
- end
- end
-end
View
18 vendor/plugins/authlogic/lib/authlogic/session/errors.rb
@@ -1,18 +0,0 @@
-module Authlogic
- module Session
- class Errors < ::ActiveRecord::Errors # :nodoc:
- end
-
- class NotActivated < ::StandardError # :nodoc:
- def initialize(session)
- super("You must activate the Authlogic::Session::Base.controller with a controller object before creating objects")
- end
- end
-
- class SessionInvalid < ::StandardError # :nodoc:
- def initialize(session)
- super("Authentication failed: #{session.errors.full_messages.to_sentence}")
- end
- end
- end
-end
View
101 vendor/plugins/authlogic/lib/authlogic/session/scopes.rb
@@ -1,101 +0,0 @@
-module Authlogic
- module Session
- # = Scopes
- #
- # Authentication can be scoped, but scoping authentication can get a little tricky. Checkout the section "Scoping" in the readme for more details.
- #
- # What with_scopes focuses on is scoping the query when finding the object and the name of the cookie / session. It works very similar to
- # ActiveRecord::Base#with_scopes. It accepts a hash with any of the following options:
- #
- # * <tt>find_options:</tt> any options you can pass into ActiveRecord::Base.find. This is used when trying to find the record.
- # * <tt>id:</tt> The id of the session, this gets merged with the real id. For information ids see the id method.
- #
- # Here is how you use it:
- #
- # UserSession.with_scope(:find_options => {:conditions => "account_id = 2"}, :id => "account_2") do
- # UserSession.find
- # end
- #
- # Eseentially what the above does is scope the searching of the object with the sql you provided. So instead of:
- #
- # User.find(:first, :conditions => "login = 'ben'")
- #
- # it would be:
- #
- # User.find(:first, :conditions => "login = 'ben' and account_id = 2")
- #
- # You will also notice the :id option. This works just like the id method. It scopes your cookies. So the name of your cookie will be:
- #
- # account_2_user_credentials
- #
- # instead of:
- #
- # user_credentials
- #
- # What is also nifty about scoping with an :id is that it merges your id's. So if you do:
- #
- # UserSession.with_scope(:find_options => {:conditions => "account_id = 2"}, :id => "account_2") do
- # session = UserSession.new
- # session.id = :secure
- # end
- #
- # The name of your cookies will be:
- #
- # secure_account_2_user_credentials
- module Scopes # :nodoc:
- def self.included(klass)
- klass.extend(ClassMethods)
- klass.send(:include, InstanceMethods)
- klass.class_eval do
- attr_writer :scope
- alias_method_chain :initialize, :scopes
- alias_method_chain :search_for_record, :scopes
- end
- end
-
- # = Scopes
- module ClassMethods
- # The current scope set, should be used in the block passed to with_scope.
- def scope
- scopes[Thread.current]
- end
-
- # See the documentation for this class for more information on how to use this method.
- def with_scope(options = {}, &block)
- raise ArgumentError.new("You must provide a block") unless block_given?
- self.scope = options
- result = yield
- self.scope = nil
- result
- end
-
- private
- def scope=(value)
- scopes[Thread.current] = value
- end
-
- def scopes
- @scopes ||= {}
- end
- end
-
- module InstanceMethods
- def initialize_with_scopes(*args) # :nodoc:
- self.scope = self.class.scope
- initialize_without_scopes(*args)
- end
-
- # See the documentation for this class for more information on how to use this method.
- def scope
- @scope ||= {}
- end
-
- def search_for_record_with_scopes(*args) # :nodoc:
- klass.send(:with_scope, :find => (scope[:find_options] || {})) do
- search_for_record_without_scopes(*args)
- end
- end
- end
- end
- end
-end
View
18 vendor/plugins/authlogic/lib/authlogic/sha512_crypto_provider.rb
@@ -1,18 +0,0 @@
-require "digest/sha2"
-
-module Authlogic
- # = Sha512 Crypto Provider
- #
- # The acts_as_authentic method allows you to pass a :crypto_provider option. This allows you to use any type of encryption you like. Just create a class with a class level encrypt and decrypt method.
- # The password will be passed as the single parameter to each of these methods so you can do your magic.
- #
- # If you are encrypting via a hash just don't include a decrypt method, since hashes can't be decrypted. Authlogic will notice this adjust accordingly.
- class Sha512CryptoProvider
- STRETCHES = 20
- def self.encrypt(pass)
- digest = pass
- STRETCHES.times { digest = Digest::SHA512.hexdigest(digest) }
- digest
- end
- end
-end
View
56 vendor/plugins/authlogic/lib/authlogic/version.rb
@@ -1,56 +0,0 @@
-module Authlogic # :nodoc:
- # = Version
- #
- # A class for describing the current version of a library. The version
- # consists of three parts: the +major+ number, the +minor+ number, and the
- # +tiny+ (or +patch+) number.
- class Version
-
- include Comparable
-
- # A convenience method for instantiating a new Version instance with the
- # given +major+, +minor+, and +tiny+ components.
- def self.[](major, minor, tiny)
- new(major, minor, tiny)
- end
-
- attr_reader :major, :minor, :tiny
-
- # Create a new Version object with the given components.
- def initialize(major, minor, tiny)
- @major, @minor, @tiny = major, minor, tiny
- end
-
- # Compare this version to the given +version+ object.
- def <=>(version)
- to_i <=> version.to_i
- end
-
- # Converts this version object to a string, where each of the three
- # version components are joined by the '.' character. E.g., 2.0.0.
- def to_s
- @to_s ||= [@major, @minor, @tiny].join(".")
- end
-
- # Converts this version to a canonical integer that may be compared
- # against other version objects.
- def to_i
- @to_i ||= @major * 1_000_000 + @minor * 1_000 + @tiny
- end
-
- def to_a
- [@major, @minor, @tiny]
- end
-
- MAJOR = 1
- MINOR = 0
- TINY = 0
-
- # The current version as a Version instance
- CURRENT = new(MAJOR, MINOR, TINY)
- # The current version as a String
- STRING = CURRENT.to_s
-
- end
-
-end
View
213 vendor/plugins/authlogic/test/active_record_acts_as_authentic_test.rb
@@ -1,213 +0,0 @@
-require File.dirname(__FILE__) + '/test_helper.rb'
-
-class ActiveRecordActsAsAuthenticTest < ActiveSupport::TestCase
- def test_user_validations
- user = User.new
- assert !user.valid?
- assert user.errors.on(:login)
- assert user.errors.on(:password)
-
- user.login = "a"
- assert !user.valid?
- assert user.errors.on(:login)
- assert user.errors.on(:password)
-
- user.login = "%ben*"
- assert !user.valid?
- assert user.errors.on(:login)
- assert user.errors.on(:password)
-
- user.login = "bjohnson"
- assert !user.valid?
- assert user.errors.on(:login)
- assert user.errors.on(:password)
-
- user.login = "my login"
- assert !user.valid?
- assert !user.errors.on(:login)
- assert user.errors.on(:password)
-
- user.password = "my pass"
- assert !user.valid?
- assert !user.errors.on(:password)
- assert user.errors.on(:confirm_password)
-
- user.confirm_password = "my pizass"
- assert !user.valid?
- assert !user.errors.on(:password)
- assert user.errors.on(:confirm_password)
-
- user.confirm_password = "my pass"
- assert user.valid?
- end
-
- def test_employee_validations
- employee = Employee.new
- employee.password = "pass"
- employee.confirm_password = "pass"
-