Git Product home page Git Product logo

sorcery's Introduction

sorcery's People

Contributors

9mm avatar arnvald avatar banyan avatar brianp avatar ckruse avatar gyardley avatar itakeshi avatar joshbuker avatar juike avatar kbighorse avatar kirs avatar kuboon avatar m4tm4t avatar mbillard avatar mchaisse avatar mlainez avatar noamb avatar palkan avatar pirj avatar rafaelsachetto avatar rubenmoya avatar rubiety avatar stepantubanov avatar supremebeing7 avatar toshimaru avatar tyrauber avatar ubermajestix avatar weimeng avatar wendy0402 avatar willywg avatar

Stargazers

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

Watchers

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

sorcery's Issues

remember_me sets always permament cookie

Hi,

I found out that regardless of the params[:remember_me] value (0 or 1) it always sets a permament cookie.

I wonder if following test would pass:

it "should not remember_me! when not asked to" do
  post :test_login, :username => 'gizmo', :password => 'secret', :remember => "0"
  cookies["remember_me_token"].should be_nil
end

Thanks,
Marek

Undefined method 'gmtime' for DateTime

I get the following error when checking remember me:

undefined method `gmtime' for Mon, 26 Dec 2011 22:58:58 -0500:DateTime

It appears to be related to the content of the cookie. The Time class has a gmtime method, but not DateTime. I am running Rails 3.0.9 and mongoid 2.0.2.

Here is the full stack trace, although it isn't very helpful:

rack (1.2.3) lib/rack/utils.rb:184:in set_cookie_header!' actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:205:inblock in write'
actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:205:in each' actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:205:inwrite'
actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:305:in call' actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:46:inblock in call'
activesupport (3.0.9) lib/active_support/callbacks.rb:416:in _run_call_callbacks' actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:44:incall'
rack (1.2.3) lib/rack/sendfile.rb:107:in call' rack (1.2.3) lib/rack/static.rb:33:incall'
sass (3.1.2) lib/sass/plugin/rack.rb:54:in call' actionpack (3.0.9) lib/action_dispatch/middleware/remote_ip.rb:48:incall'
actionpack (3.0.9) lib/action_dispatch/middleware/show_exceptions.rb:47:in call' railties (3.0.9) lib/rails/rack/logger.rb:13:incall'
rack (1.2.3) lib/rack/runtime.rb:17:in call' activesupport (3.0.9) lib/active_support/cache/strategy/local_cache.rb:72:incall'
rack (1.2.3) lib/rack/lock.rb:11:in block in call' <internal:prelude>:10:insynchronize'
rack (1.2.3) lib/rack/lock.rb:11:in call' actionpack (3.0.9) lib/action_dispatch/middleware/static.rb:30:incall'
hoptoad_notifier (2.4.11) lib/hoptoad_notifier/user_informer.rb:12:in call' railties (3.0.9) lib/rails/application.rb:168:incall'
railties (3.0.9) lib/rails/application.rb:77:in method_missing' railties (3.0.9) lib/rails/rack/debugger.rb:21:incall'
railties (3.0.9) lib/rails/rack/log_tailer.rb:14:in call' rack (1.2.3) lib/rack/content_length.rb:13:incall'
rack (1.2.3) lib/rack/chunked.rb:15:in call' thin (1.2.11) lib/thin/connection.rb:84:inblock in pre_process'
thin (1.2.11) lib/thin/connection.rb:82:in catch' thin (1.2.11) lib/thin/connection.rb:82:inpre_process'
thin (1.2.11) lib/thin/connection.rb:57:in process' thin (1.2.11) lib/thin/connection.rb:42:inreceive_data'
eventmachine (0.12.10) lib/eventmachine.rb:256:in run_machine' eventmachine (0.12.10) lib/eventmachine.rb:256:inrun'
thin (1.2.11) lib/thin/backends/base.rb:61:in start' thin (1.2.11) lib/thin/server.rb:159:instart'
rack (1.2.3) lib/rack/handler/thin.rb:14:in run' rack (1.2.3) lib/rack/server.rb:217:instart'
railties (3.0.9) lib/rails/commands/server.rb:65:in start' railties (3.0.9) lib/rails/commands.rb:30:inblock in <top (required)>'
railties (3.0.9) lib/rails/commands.rb:27:in tap' railties (3.0.9) lib/rails/commands.rb:27:in<top (required)>'
script/rails:6:in require' script/rails:6:in

'

facebook permissions?

I was reading over the wiki and was just wondering where exactly do you specify the permissions facebook will ask for?

Re-authenticating a logged-in User?

I apologize if this is the wrong place for this. I have asked on SO, but haven't gotten a reply, perhaps Sorcery is just too new right now.

I have a simple user model with an edit page. Currently you can change your email and your password (with a password confirmation) but I don't currently require you to type your old password again before changing any of that information.

I have a before filter that requires you to be logged in as well as a before filter to ensure you can only edit your own profile. However, in the case of public or shared computers, I would like to re-authenticate a user by making them type their password before they can change any critical account info and I'm having a hard time finding anything in Sorcery that would allow me to do this. Thanks!

undefined method `web_server' for #<OAuth2::Client:0xd2176d0>

It seems when authenticating to Facebook this error occurs. The error is happening at this line in the oauth2.rb file.

        def get_access_token(args)
          client = ::OAuth2::Client.new(@key, @secret, :site => @site)
         client.web_server.get_access_token(args[:code], :redirect_uri => @callback_url)
        end

I checked with version 0.5.0 of the OAuth2::Client and there doesn't appear to be a method 'web_server' present. This is strange, because if I check with the documentation for OAuth2::Client it does say there is web_server method. Can you please investigate?

Account Verification in Background?

Hey, I was just wondering whether it's possible to allow the sending of the account verification email to be run by a background worker like Delayed Job or Resque? I typically do something like this in my UsersController:

def create
  if @user.save
    Resque.enqueue(UserRegistration, @user.id)
    redirect_to ...
  end
end

Is there a way to push the email sending in to a job processor? I noticed it immediately gets invoked by @user.save.

Thanks! I like the approach of this gem.

undefined method `auto_login' for nil:NilClass (NoMethodError)

When running tests in Cucumber, I am getting the above error for auto_login

The code used was....

salt = "asdasdastr4325234324sdfds"

user = User.create(
email: "[email protected]",
salt: salt,
crypted_password: Sorcery::CryptoProviders::BCrypt.encrypt("secret", salt),
activation_state: "active"
)
user.save

@user = User.first(conditions: { email: "[email protected]" } )

login_user

....

The helper is being loaded through RSpec but the rest of the code is not found.

Configuration doesn't run while testing

When running tests, the block that sets the configuration for sorcery doesn't get run (I added puts "something" to make sure), so, while testing, sorcery uses username instead of email, because this line doesn't every run:

user.username_attribute_name = :email

Looks like a bug, is it?

login method returns nil while setting the session correctly

I have a before_filter in my application_controller.rb :

before_filter :something, :if => :logged_in?

Then, when calling "login" method, login sets sessions correctly, but returns nil

if @user = login(params[:email], params[:password], params[:remember]) # returns nil but sets the session values
return redirect_back_or_to(:users, :notice => 'Login successfull.')
else
flash.now[:alert] = "Login failed."
render :new
end

Same problem with :
before_filter :something, :if => :current_user
or if current_user or logged_in? are called in a before_filter

Is it a bug ? Or do I miss something ?

Edit : Damn. This is the same issue as #36. Sorry for duplicating > .< Please delete my issue.

Cannot use login_user helper in cucumber

I have a cucumber step that uses the login_user test helper. I included to Cucumber:

include Sorcery::TestHelpers::Rails

My code calls it like this:

u = User.make(:username => user)
login_user(u)

When Cucumber reaches this helper, it gives me this error:
undefined method 'login_user' for nil:NilClass (NoMethodError)

I found out that it's failing on this line in lib/sorcery/test_helpers/rails.rb:

def login_user(user = nil)
  user ||= @user
  @controller.send(:login_user,user)  # FAILS here
  @controller.send(:after_login!,user,[user.send(user.sorcery_config.username_attribute_name),'secret'])
end

Looks like @controller is nil. Am I missing some steps required for Cucumber?

make Facebook user_info_mapping tolerant to missing fields

I have the following mapping:

config.facebook.user_info_mapping = { email: 'email', fb_location_name: 'location/name' }

If user didn't fill "Current city" field on Facebook, it is not in user_hash object.

throws an error on user creation:

# (NoMethodError) "undefined method `[]' for nil:NilClass"
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:74:in `block (2 levels) in create_from'
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:74:in `each'
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:74:in `inject'
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:74:in `block in create_from'
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:73:in `each'
sorcery-0.5.21/lib/sorcery/controller/submodules/external.rb:73:in `create_from'

Should we silently skip missing fields instead?


If user filled "Current City" than user_hash looks like:

{:user_info=>{"id"=>"1181734206", "name"=>"Nikita Fedyashev", "first_name"=>"Fedyashev", "last_name"=>"Nikita", "link"=>"http://www.facebook.com/profile.php?id=1181734206", "birthday"=>"05/23/1988", "location"=>{"id"=>"114980905185578", "name"=>"Bishkek, Kyrgyzstan"}, "gender"=>"male", "email"=>"[email protected]", "timezone"=>6, "locale"=>"en_US", "languages"=>[{"id"=>"109489299069349", "name"=>"Ukrainian"}, {"id"=>"106059522759137", "name"=>"English"}], "verified"=>true, "updated_time"=>"2011-07-08T06:06:17+0000"}, :uid=>"1181734206"}

if he did not:

{:user_info=>{"id"=>"1181734206", "name"=>"Nikita Fedyashev", "first_name"=>"Fedyashev", "last_name"=>"Nikita", "link"=>"http://www.facebook.com/profile.php?id=1181734206", "birthday"=>"05/23/1988", "gender"=>"male", "email"=>"[email protected]", "timezone"=>6, "locale"=>"en_US", "languages"=>[{"id"=>"109489299069349", "name"=>"Ukrainian"}, {"id"=>"106059522759137", "name"=>"English"}], "verified"=>true, "updated_time"=>"2011-07-08T06:06:17+0000"}, :uid=>"1181734206"}

User Model Generator

Right now to set up sorcery, one must run these commands.

rake sorcery:bootstrap
rails g sorcery_migration core remember_me
rails g model user --skip-migration

In addition to this it's also necessary to add authorizes_with_sorcery! to the User model and add the remember_me module to the config. It would be nice if those 5 steps could be broken down into this.

rails g sorcery:user remember_me

This would generate the initializer and model class, add the authorizes_with_sorcery! to that class, and adds remember_me to the config. You can use options to customize behavior like supplying a different class name:

rails g sorcery:user remember_me --model Account

Then the class can be reflected in the config and the migration.

There can still be a single migration generator for those that want to add functionality to an existing user model.

rails g sorcery:migration password_reset

What do you think? BTW, great job on the gem!

require_no_user before filter

Hi all,

I've been trying to come up with a decent before filter to prevent the creation of new users/sessions for someone already logged in.

I've tried some variants on this

def require_no_user
  if current_user
    redirect_to root_path, :alert => "You must be signed out for that action."
  end
end

using both current_user and logged_in?

The problem I'm having is that calling these methods interferes with the controller later calling the login method. The sessions get set properly, but it returns nil instead of a user, so my actions break.

Transition from another encryption algorithm

I'd like to migrate my users table from SHA1 to BCrypt (like AuthLogic's transition_from_restful_authentication), so I'm guessing the best way would be to set user.custom_encryption_provider = :custom and build my own CryptoProvider, but how would I tell Sorcery to use it?

Maybe this should this be a submodule instead, since both of those algorithms are already built in, and there's more to do than just hashing stuff.

why is username a required field ?

The sorcery core migration added username as a field that cannot be null.

t.string :username,         :null => false

Why this is strange is that the authenticate method, mixed in to the user model, searches the users table for email addresses, not usernames.

Can I drop the username field ? what would the repercussions of doing that be ? would this affect oauth or any other the other modules ?

Luke

User is invalid after save because of password_confirmation

After saving a new user, that user is invalid. This happens even if you call user.reload.

The reason: clear_virtual_password clears the password field but not the password_confirmation field. (Assuming using Rails and have validates_confirmation_of :password).

user = User.new :username => "Homer", :password => "abcd", :password_confirmation => "abcd"
user.valid?
=> true
user.save
=> true
user.valid?
false
user.errors.full_messages
=> ["Password doesn't match confirmation"]
user.password
=> nil
user.password_confirmation
=> "abcd"

Note: by code inspection I think the same problem would happen on a password reset (Sorcery::Model::Submodules::ResetPassword::InstanceMethods#change_password!)

Cannot include the :user_activation submodule

If I add :user_activation to the
Rails.application.config.sorcery.submodules = [:remember_me, :reset_password, :user_activation]
array

I get:
~/.rvm/gems/ruby-1.9.2-p290/gems/sorcery-0.6.1/lib/sorcery/controller.rb:8:in `include': wrong argument type Class (expected Module) (TypeError)

whenever I start the rails app (via rails c or rake)

When I look in the gem's submodules folder I do not see a module called UserActivation. I see it in the gem as a model, but I cannot see how the controller.rb is going to load it.

What could be going wrong? Thanks.

Undefined methods

Accidentally posted this in the example app issue tracker so just moving over here :P

Original post:
When creating a new user the password seems to just be stored as plaintext. I got the feeling that sorcery wasn't processing it for some reason. I checked over the example app and saw authenticates_with_sorcery! in the user class, but I just get an undefined method error when adding it to my class. I also have config.user_class = User in my initializer. Any ideas?

Update:
Also- running current_user results in false, but trying auto_login results in another undefined method error.

Issue with session_timeout submodule on rails 3.1

Is anyone else having issue when trying to run rails g sorcery_migration session_timeout

I get:
Could not find "session_timeout.rb" in any of your source paths. Your current source paths are:
/Users/xavier/.rvm/gems/ruby-1.9.2-p290@mypt/gems/sorcery-0.6.1/lib/generators/sorcery_migration/templates

Doesn't update login status correctly

Thanks for your great plugin - found out about it through the latest Railcast! While following along with the example, I noticed that my login status never updates correctly after logging in and rendering a template w/o redirecting.

current_user runs before processing the login, so it sets @current_user to false. After matching the credentials successfully, the session is reset and updated in Sorcery::Controller::login, but when it tries to run current_user again, it can't because @current_user is already false and it refuses to run. It's not until you go to another page that @current_user is set correctly. Is it possible to set @current_user to nil in Sorcery::Controller::after_login!, or somewhere before current_user is run again?

def login(*credentials)
  user = user_class.authenticate(*credentials)
  if user
    return_to_url = session[:return_to_url]
    reset_session # protect from session fixation attacks
    session[:return_to_url] = return_to_url
    login_user(user)
    after_login!(user, credentials)
    @current_user = nil # can we add something like this here or elsewhere where it makes sense?
    current_user # currently, this will return nil on successful login because @current_user is already false and not nil
  else
    after_failed_login!(credentials)
    nil
  end
end

Doesn't seem to work with modular-style Sinatra apps

When I make this change in sorcery-example-app-sinatra:

-require 'sinatra'
-enable :sessions
+require 'sinatra/base'
+#enable :sessions

and run ruby myapp.rb I get this error:

/usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:55:in `<module:InstanceMethods>': undefined method `helpers' for Sorcery::Controller::Adapters::Sinatra::InstanceMethods:Module (NoMethodError)
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:41:in `<module:Sinatra>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:6:in `<module:Adapters>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:3:in `<module:Controller>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:2:in `<module:Sorcery>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/controller/adapters/sinatra.rb:1:in `<top (required)>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery/sinatra.rb:2:in `<top (required)>'
from <internal:lib/rubygems/custom_require>:29:in `require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `block in require'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:596:in `new_constants_in'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:225:in `load_dependency'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery.rb:79:in `<module:Sorcery>'
from /usr/lib64/ruby/gems/1.9/gems/sorcery-0.5.1/lib/sorcery.rb:1:in `<top (required)>'
from <internal:lib/rubygems/custom_require>:33:in `require'
from <internal:lib/rubygems/custom_require>:33:in `rescue in require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `block in require'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:596:in `new_constants_in'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:225:in `load_dependency'
from /usr/lib64/ruby/gems/1.9/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require'
from myapp.rb:34:in `<main>'

(I get this same error in my working modular Sinatra app, I'm demonstrating it this way because it's probably easier for you to duplicate.)

[sqlite3] Vulnerable to CSRF requests

Rails 3.0.x changed the CSRF policy due to a security bug. The new policy requires you to override handle_unverified_request to clean up anything associated to the signed in user in the current request. Basically, you need to:

  1. Clean up any cookie (like remember_me)
  2. Clean up any cache instance variable related to the user
  3. Clean up session (already done by rails)

You can take a look at what Devise is doing as an example:

https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb#L224

find_by_token clobbering User#token

token is a very common term with many possible meanings in a User model. (In my case, I use it for lots of my models as a unique string identifier, but I'm sure there are lots of other uses... one-time security tokens, etc.)

This becomes a problem as lib/sorcery/model/temporary_token.rb clobbers the method find_by_token, so I can no longer use the expected database query. As this is used only three times (additionally lib/sorcery/model/adapters/active_record.rb and lib/sorcery/model/adapters/mongoid.rb), would you consider accepting a small patch to change the method name?

I am not sure what would be most appropriate, but maybe avoid using the find_by_ prefix used by ActiveRecord or use a better namespaced name, eg. find_by_sorcery_token?

User() expected, got User()

While performing a simple action such as:

@post.user = current_user

I now receive a User() expected, got User() ActiveRecord::AssociationTypeMismatch error.
The issue only occurs in Development. I've replicated the bug in two different apps in development. Cannot reproduce the error in testing. It occurs on both ruby 1.8.7 and 1.9.2 under Rails 3.0.7 & 3.0.9 and Sorcery v0.5.30.

If I change the development env file to set cache_classes = true the issue no longer occurs which maybe why it does not occur in testing. I spent a handful or hours looking for an obvious re-definition or reload of the Config.user_class or User constant but couldn't find anything.

If I put a debugger in the current_user action and run the following I get different results which I believe should be the same:

(rdb:6) current_user.class
User(id: integer, email: string, crypted_password: string, salt: string, created_at: datetime, updated_at: datetime, remember_me_token: string, remember_me_token_expires_at: datetime, reset_password_token: string, reset_password_token_expires_at: datetime, reset_password_email_sent_at: datetime)
(rdb:6) current_user.class.object_id
2172300540
(rdb:6) User.object_id
2173891120

ActiveRecord::AssociationTypeMismatch
User(#2173891120) expected, got User(#2172300540)

Cheers

current_user suffers from bipolar disorder

Came across this weird issue:

module ApplicationHelper
  def current_user_is?(user)
    return false if current_user.nil?
    fail 'current_user IS nil!' if current_user.nil?  # Debugging => Raises Exception!
    current_user.username == user.username   # Or some other logic....
  end
end

but this works:

  def current_user_is?(user)
    return false if current_user.nil? or current_user.nil?  # Note the extra call
    fail 'current_user is nil' if current_user.nil?  # No error
    current_user.username == user.username
  end

which made me think...

  def current_user_is?(user)
    fail current_user.to_s                                  # => false
    return false if current_user.nil?
    fail 'current_user is nil' if current_user.nil?
    current_user.username == user.username
  end

Now, I could just make the sanity check general for falseness (false || nil). But this brings up two questions:

  1. Should current_user ever be false? (I'm thinking this is a bug)
  2. Why is current_user first false, then nil. (I'm thinking this points at a more serious bug... or something that aught to be documented)

Thoughts?

SHA1 created users cannot authenticate

I'm running directly against sorcery master to use the multi-identifier login (e.g. email or login) feature. In setting things up I noticed that there is a problem if you create a user from the command line, exit, go back in and try to authenticate that user via User.authenticate.

Steps to reproduce:

  1. Create a base rails app, add sorcery, generate standard user model.
  2. rails c
  3. User.create(:email => '[email protected]', :password => 'password')
  4. User.authenticate('[email protected]', 'password') => User model returned
  5. Exit console
  6. rails c
  7. User.authenticate('[email protected]', 'password') => nil

I was able to track down the issue to a problem with the salt_join_token. The SHA1 provider attempts to default the join_token to '--' if it's not set. Unfortunately in one case it is nil (during authenticate) but during create (encrypt) it gets set to an empty string which overrides the ||= default in the provider.

When creating a user (which calls Sorcery::Model#encrypt) the code does:

@sorcery_config.encryption_provider.join_token = @sorcery_config.salt_join_token if @sorcery_config.encryption_provider.respond_to?(:join_token) && @sorcery_config.salt_join_token

which sets the join token to whatever's in the config. The config (in the same file) defaults to an emtpy string for that key instead of nil so join token is ''. The code for authenticate however does NOT appear to set the join_token so the the defaulting in the provider uses '--' as the join token and winds up with a different digest than when it was originally encrypted.

I "fixed" the problem for now by setting the salt_join_token default to nil in Sorcery::Model line 210 instead of "". All the other values were already being defaulted to nil. This change makes it so SHA1 uses '--' both during initial encryption and during authentication.

I'm guessing that Sorcery::Model#authenticate actually needs to pass the join_token (and stretches?) value down to the encryption provider like Sorcery::Model#encrypt does currently which would probably make my "fix" unnecessary. My "fix" would still be required though for SHA1 to override the default value to be '--' instead of nil/'' though.

I tried to fork/fix but was unable to get the test suite to run.

Rails 3.1.0 requires bcrypt 3.0

Pretty much sums it up:

Bundler could not find compatible versions for gem "bcrypt-ruby":
  In Gemfile:
    rails (= 3.1.0) depends on
      bcrypt-ruby (~> 3.0.0)

    sorcery (~> 0.6.0) depends on
      bcrypt-ruby (2.1.4)

Fix OpenSSL Error when use Oauth2

When I use Facebook for external login I have this problem:

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed):
app/controllers/oauths_controller.rb:13:in `callback'

I fix that change this on lib/sorcery/controller/submodules/external/protocols/oauth2.rb

           def authorize_url(*args)
              #client = ::OAuth2::Client.new(@key, @secret, :site => @site)
              client = ::OAuth2::Client.new(@key, @secret, :site => @site, :ssl => { :ca_file => '/etc/pki/tls/certs/ca-bundle.crt' })
              client.web_server.authorize_url(:redirect_uri => @callback_url, :scope => @scope)
            end

            def get_access_token(args)
              #client = ::OAuth2::Client.new(@key, @secret, :site => @site)
              client = ::OAuth2::Client.new(@key, @secret, :site => @site, :ssl => { :ca_file => '/etc/pki/tls/certs/ca-bundle.crt' })
              client.web_server.get_access_token(args[:code], :redirect_uri => @callback_url)
            end

But obviously this not optimal for other developer.

Can you add this on configure initializer?

Token authentication

Hi Noam. Great work on the Sorcery gem. Is token authentication something that would find it's way into Sorcery on day?

logout with external

Hey,

Env: Rails 3.1 & Mongoid

I'm using the :external submodule from sorcery and I'm also using subdomain with Rails 3.1

[OK] When I'm loggin and on the root_url (without subdomain) I can logout.
[FAIL] When I'm loggin and on the root_url (WITH subdomain) I can't logout. I'm going through my user_session#destroy but I don't understand why the reset_session does not delete the session[:user_id]

Cheers,

D.

[sqlite3] User Activation: load_from_activation_token fails to find user with correct token

Using rails 3.1, sorcery 0.6.1 and sqlite3 1.3.4.

When running User.load_from_activation_token(params[:id]), say from within an activate method on my user model, the call always returns nil even if the passed parameter is a valid activation token. Indeed breaking out the sqlite console and running SELECT * FROM users WHERE activation_token = 'A VALID TOKEN' returns no records.

However, running SELECT * FROM users WHERE trim(activation_token) = 'A VALID TOKEN' returns the correct result. This indicates that the method populating the column is adding some rubbish to the end of the token which doesn't get passed to the user's activation link or even output to the sqlite console. I can't work out exactly what is going wrong but I assume it occurs when the token is created.

A quick and very dirty fix is to override the class method load_from_token with a SQL call including the trim function. This can be added to your user model.

def self.load_from_token(token, token_attr_name, token_expiration_date_attr)
  return nil if token.blank?
  user = User.find_by_sql("SELECT * from users WHERE trim(#{token_attr_name}) = '#{token}'").first
  if !user.blank? && !user.send(token_expiration_date_attr).nil?
    return Time.now.utc < user.send(token_expiration_date_attr) ? user : nil
  end
  user
end

You can see some group troubleshooting for this bug, specifically on the SQL side of things, here: http://stackoverflow.com/questions/7382093/cant-select-existing-record-via-one-column-name

1.8.7 support

I'm using sorcery in a Rails 3 app that I'm running under REE.

Your current syntax in your Mongoid support breaks 1.8.7

If you switch it over to :type => String, it works just fine.

Feel free to close this issue if you don't want to address it :)

Remember me tokens should probably be digested

Sorcery is currently storing the remember_me_token straight in the cookie. You probably want to digest it first. Imagine someone uses the email as remember_me_token. If you digest it, it is a completely valid approach, but currently it would simple set cookies[:remember_me] = email which would be very easy to forge.

You can digest it using cookies.secure[:remember_me].

Sessions Controller - destroy method

Hello NoamB,

I really like the idea of your plugin and trying to implement in my current application. I followed Ryan Bates screencast and your online wiki, but I keep receiving this error when using the remember_me function.

undefined method `forget_me!' for nil:NilClass in my sessions controller, listed below is the code:

class SessionsController < ApplicationController
def new
end

def create
user = login(params[:email], params[:password], params[:remember_me])
if user
redirect_back_or_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Email or password was invalid"
render :new
end
end

def destroy
logout
redirect_to root_url, :notice => "Logged out!"
end

end

Any help is appreciated!! Thanks!

validate user model (regular and external)

So i've searched through previous tickets and found out that in order to create multiple auth levels i should implement STI. However how should i solve having one level of authentication but 2 different ways of creating the user model - I have a standard User model with all the necessary validations (password, confirmations, etc..) and in par with that i wish to have an option to create an account via the External module. (where password and email can be nil)

Naturally some conditions for validations, so i dug in the code and docs and found the external? method which hovewer does not solve a thing because it simply asks for crypted_password and for new_instance of User model returns true. I thought about asking for the authentications relation as well but in create_from the user is created first and the authentication relation is built after a binged create, so no luck there

So then i thought about STI but that did not help either, create_from(external) does not take my ExternalUser into account, it simply goes for User.

So far im stuck with no validations then.

Great gem btw, i canned Devise for the purpose of having control over everything. This however i cannot solve without a fork

Session timeout submodule can cause login() to return nil

I am using the :session_timeout submodule. If I let my browser sit on my login page longer than session_timeout and then attempt to log in, the call to login(params[:email], params[:password]) returns nil even though the email and password are correct.

I'm not sure exactly what's going on, but it appears that somehow validate_session() is reseting the session immediately after (or maybe before) it's created by login().

Although it seems like an unusual scenario (sitting on the login screen for that long), I have a use case where it's happened many times. It took a while to figured out what what going on though :)

Thanks for any help.

Login User Model

When a user signs up, it would be nice to log him in automatically. Is there a way to login a given user record instead of using the password credentials? I don't think login(user) will work but that seems like a good interface. I noticed there was a login_user method but not sure if that's safe to use.

Running test suite

Hi Noam,

How do you install 'all' the dependencies to run your tests? There's like 9 Gemfile's in total (I did it by hand, took a long time too...)? I recall setting up a gemset based on the Gemfile in the gem's root path and the tests died once it started to test rails3_modular (bison missing for mongodb).

Would be handy if we could also update the Rakefile to allow running the tests for a particular app, for example rake sorcery_tests:rails3 or rake sorcery_tests:rails3_modular

[sqlite3] activation_token column with rails 3.1

It seems, for me anyway, when I run sorcery with rails 3.1 there is a conflict of some sort with the activation_token column.

The problem seems to be any method that eventuates in sql trying to select where :activation_token = "token code". User.load_from_activation_token obviously doesn't work, nor does User.select(:activation_token => "token code") or User.select_by_activation_token("token code"). All return nil.

At one stage I tried changing the :activation_token column name as a solution. This worked, BUT when a new user was created using the new column name the problem arose again. Changing the name of the column seems to make the user respond to the token column for existing users in the database but still not work for any new users created.

To make sure it wasn't a conflict with any other gems, I've cloned the sample app which uses rails 3.0.9 and switched it to sqlite3 like I'm using and it works fine.

I've also started a fresh rails 3.1 project with the only additional gem other than the defaults being sorcery. I've created a .rvmrc for a clean gemset and got sorcery working with :user_activation, :remember_me, :reset_password modules. When I create a user here the problem surfaces again which shows that it's most likely a rails 3.1 issue.

As an additional note it seems that any modification to the column will make the :activation_token work again. If I update the activation_token by changing just one character, everything starts working again. I've also compared User.first.activation_token === "valid token" and they compare true so it's not saving with any additional characters by the look of it. User.first.length always = 40 when first created too.

I'd be very interested to hear if anyone else has this problem.

Missing info from the External tutorial

Hi, first of all thanks for this awesome work!
I was following the tutorial on the wiki about using external login systems, and I've found that probably you forgot to say that it is necessary to update the initializer file by using this line:

user.authentications_class = Authentication

In the initializer I got generated, that line was commented out and the value was setting to nil. I think you should update your good tutorial to include this information, as first-time users can be dazzled by exception thrown. May I also suggest in your code to add a simple fallback and to use a "default" name for the class (like model "Authentication")?

Thank you!
Fabio.

brute_force_protection submodule mass-assign protected attributes error

After enabled :brute_force_protection submodule, the failed_logins_count does increase for every failed login attempt. However, the lock_expires_at never assigned and always null. Also the failed_logins_count haven't reset to 0 for subsequent successful login.

Then I examined the log and found quite a few errors like 'WARNING: Can't mass-assign protected attributes: xxxx' for both lock_expires_at and failed_logins_count.

So, I add attr_accessible :lock_expires_at, :failed_logins_count to the user model and it works as expected. Can the submodule handle the access of these two fields automatically?

Activity Logging module - track login/logout but not last_activity

I like to track when users login and logout but I don't want to make an extra write to the DB on every page view.

Suggestion: add a config option to not add the register_last_activity_time_to_db before_filter. Either that or check for a "#{last_activity_at_attribute_name}=" method and don't add the before_filter if it doesn't exist (i.e. if the migration didn't add the column).

logged_in? in view

It doesn't look like logged_in? is available in the view layer. I can access current_user there though.

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.