I'm having a problem using an authlogic single access token to access a page when logout on timeout is set to true and a timeout is set.
user.rb:
acts_as_authentic do |c|
c.logged_in_timeout = 15.minutes
end
user_session.rb:
logout_on_timeout true
controller:
def single_access_allowed?
["download_xml"].include?(action_name)
end
If I try to access a page/method using the token it redirects straight away to my login page. The logout on timeout works when its turned on.
If i remove the timeout code and just have acts_as_authentic in the user.rb, the single access token works.
I want to be able to use the single access token so another application can open an xml file from my ruby on rails website.
Any ideas on what I might have done wrong and where to look to fix it and make it work?
Using authlogic 3.0.3 and rails 3.0.7.
This reply from jgdreyes last Sept 27 at https://github.com/binarylogic/authlogic/issues/64 worked for me:
I went ahead and extended Authlogic's stale? method so that it does
not see requests as stale? if accessing via single_access?. This keeps
logic for logout_on_timeout intact.
class UserSession < Authlogic::Session::Base logout_on_timeout true
def stale?
return false if single_access?
super
end
end
Related
We are using Doorkeeper gem to authenticate our users through an API. Everything is working fine since we've implemented it few years ago, we are using the password grant flow as in the example:
resource_owner_from_credentials do |_routes|
user = User.active.find_for_database_authentication(email: params[:username])
if user&.valid_password?(params[:password])
sign_in(user, force: true)
user
end
end
Doorkeeper is coupled with Devise, which enable reconfirmable strategy. As you can see in the code above, we are only allowing active users (a.k.a users with a confirmed email) to connect:
User.active.find_.....
Problem
Our specifications changed and now we want to return a different error on login (against /oauth/token) depending if the user has confirmed its email or not.
Right now, if login fails, Doorkeeper is returning the following JSON:
{
"error": "invalid_grant",
"error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}
Ideally, we want to be able to return a custom description if and only if the current email trying to login is unconfirmed
We've checked the documentation on Doorkeeper but it does not seems to have an easy way (if any at all) to do this. The fact that resource_owner_from_credentials method is located in the config adds too much magic and not enough flexibility.
Any ideas ?
Ok so after digging a little bit, we found an easy way to work around this issue by overriding Doorkeeper::TokensController.
# frozen_string_literal: true
class TokensController < Doorkeeper::TokensController
before_action :check_if_account_is_pending, only: :create
private
def check_if_account_is_pending
user = User.find_by(email: params['username'])
render json: unconfirmed_account_error if user && !user.confirmed?
end
def unconfirmed_account_error
{ error: 'invalid', error_description: 'You must validate your email address before login' }
end
end
We also needed to make sure the routes were pointing to the custom controller:
use_doorkeeper do
controllers tokens: 'tokens'
end
Hope it can helps someone in the future
I have a ruby on rails application deployed to torquebox. I need some way to secure the websockets in my application. I am using the stomp websockets , is there a way to authenticate users while they make a websocket connection? I could use the username and password parameters but they are currently ignored. Is there any other way to authenticate this connection? Thanks!
You can authenticate a message to a Stomplet by using the session and a stored token. For this to work, you have to setup Rails to use the Torquebox session store. This can be done with an initializer, such as config/initializers/torquebox_init.rb:
AppName::Application.config.session_store :torquebox_store
Now the Stomplet will have access to the session. Here is an example Stomplet that uses the session param :authentication_token to match the User's authentication_token in the database. The auth token is checked for subscribing, sending a message, and unsubscribing:
require 'torquebox-stomp'
class StompletDemo
def initialize()
super
#subscribers = []
end
def configure(stomplet_config)
end
def on_message(stomp_message, session)
token = session[:authentication_token]
if is_authenticated?( token )
#subscribers.each do |subscriber|
subscriber.send( stomp_message )
end
end
end
def on_subscribe(subscriber)
session = subscriber.session
if is_authenticated?(session[:authentication_token])
#subscribers << subscriber
end
end
def on_unsubscribe(subscriber)
session = subscriber.session
if is_authenticated?(session[:authentication_token])
#subscribers.delete( subscriber )
end
end
def is_authenticated?(token)
User.where( authentication_token: token ).exists?
end
end
Now all you have to do is make sure that when the user authenticates, the session[:authentication_token] is set. Mostly like this will be set in a controller:
# user has successfully authenticates
session[:authentication_token] = #user.authentication_token
For other people having this issue, this is how I solved it.
https://gist.github.com/j-mcnally/6207839
Basically the token system didnt scale for me, especially since I use devise.
If you want to host your websocket in say a chrome extension its easier to just pass username/password directly to stomp and have it manage its own virtual subscriber sessions in the stomplet. This also allow you to do some fun things as far as who you are pushing to.
I have a simple demo app set up to be able to access Salesforce.com from a Ruby on Rails app. My code is extremely simple:
def sign_in_salesforce
client = OAuth2::Client.new(ENV['SALESFORCE_CONSUMER_KEY'], ENV['SALESFORCE_CONSUMER_SECRET'], :site => 'https://login.salesforce.com/', :authorize_url => 'services/oauth2/authorize', :token_url => 'services/oauth2/token')
auth_url = client.auth_code.authorize_url(:redirect_uri => 'https://99.44.242.76:3000/users/oauth_callback')
redirect_to auth_url
end
I then have a method to take care of the callback.
def oauth_callback
db_client = Databasedotcom::Client.new
db_client.authenticate(:token => params[:code])
puts db_client.inspect
end
The error in the console is:
ArgumentError (ArgumentError):
app/controllers/users_controller.rb:60:in `oauth_callback'
The line that is causing the error is:
db_client.authenticate(:token => params[:code])
like the token that I am getting is invalid or something.
It worked fine until I changed my Salesforce password (which they required me to do). What am I missing? Thanks for the help.
If the response you receive is that your refresh token is no longer valid then you need to restart the OAuth process from scratch to obtain a new refresh token; you can then use to get new session tokens in subsequent uses of the app as you have been up until now.
Essentially, start the process as you would for the very first time the app is launched.
I need to write a log when somebody failes to log in to my app (to track bruteforce attempts). Also I decided to log successful authentications.
So I created a SessionsController < Devise::SessionsController and tried to override the sessions#create method like that: https://gist.github.com/3884693
The first part works perfectly, but when the auth failes rails throws some kind of an exception and never reaches the if statement. So I don't know what to do.
This answer to a previous SO question - Devise: Registering log in attempts has the answer.
The create action in the devise controller calls warden.authenticate!, which attempts to authenticate the user with the supplied params. If authentication fails then authenticate! will call the devise failure app, which then runs the SessionsController#new action. Note, any filters you have for the create action will not run if authentication fails.
So the solution is to add a filter after the new action which checks the contents of env["warden.options"] and takes the appropriate action.
I tried out the suggestion, and was able to log both the successful & failed login attempts. Here is the relevant controller code:
class SessionsController < Devise::SessionsController
after_filter :log_failed_login, :only => :new
def create
super
::Rails.logger.info "\n***\nSuccessful login with email_id : #{request.filtered_parameters["user"]}\n***\n"
end
private
def log_failed_login
::Rails.logger.info "\n***\nFailed login with email_id : #{request.filtered_parameters["user"]}\n***\n" if failed_login?
end
def failed_login?
(options = env["warden.options"]) && options[:action] == "unauthenticated"
end
end
The log has the following entries:
For a successful login
Started POST "/users/sign_in"
...
...
***
Successful login with email_id : {"email"=>...
***
...
...
Completed 302 Found
For a failed login
Started POST "/users/sign_in"
...
...
Completed 401 Unauthorized
Processing by SessionsController#new as HTML
...
...
***
Failed login with email_id : {"email"=>...
***
...
...
Completed 302 Found
Prakash's answer is helpful, but it's not ideal to rely on SessionsController#new to be run as a side effect. I believe this is cleaner:
class LogAuthenticationFailure < Devise::FailureApp
def respond
if request.env.dig('warden.options', :action) == 'unauthenticated'
Rails.logger.info('...')
end
super
end
end
...
Devise.setup do |config|
config.warden do |manager|
manager.failure_app = LogAuthenticationFailure
end
Check out Graeme's answer if you'd prefer to hook into Warden's callbacks (Devise is implemented using Warden).
I had the same question but was unable to resolve it using the "warden.options" since, in my case, these were being cleared before redirecting to the sessions#new action. After looking into a few alternatives that I judged to be too brittle (because they involved extending some Devise classes and aliasing existing methods), I wound up using some callbacks provided by Warden. It works better for me because the callback is invoked inside the current request-response cycle and the parameters are all preserved in the env object.
These callbacks are named and appear to be designed to solve this and related problems. And they are documented!
Warden supports the following callbacks as of warden-1.2.3:
after_set_user
after_authentication (useful for logging successful sign ins)
after_fetch (alias for after_set_user)
before_failure (useful for logging failed sign ins - example below)
after_failed_fetch
before_logout
on_request
Each callback is set directly on the Warden::Manager class (may be inside config/initializers/devise.rb). To track a failed authentication attempt I added this:
Warden::Manager.before_failure do |env, opts|
email = env["action_dispatch.request.request_parameters"][:user] &&
env["action_dispatch.request.request_parameters"][:user][:email]
# unfortunately, the User object has been lost by the time
# we get here; so we take a db hit because I care to see
# if the email matched a user account in our system
user_exists = User.where(email: email).exists?
if opts[:message] == :unconfirmed
# this is a special case for me because I'm using :confirmable
# the login was correct, but the user hasn't confirmed their
# email address yet
::Rails.logger.info "*** Login Failure: unconfirmed account access: #{email}"
elsif opts[:action] == "unauthenticated"
# "unauthenticated" indicates a login failure
if !user_exists
# bad email:
# no user found by this email address
::Rails.logger.info "*** Login Failure: bad email address given: #{email}"
else
# the user exists in the db, must have been a bad password
::Rails.logger.info "*** Login Failure: email-password mismatch: #{email}"
end
end
end
I expect that you could use the before_logout callback to track logout actions as well, but I haven't tested it. There appear to be prepend_ variants of the callbacks as well.
For logout logging, you need to catch the destroy event, so add the following to the Session controller (from the above answer):
before_filter :log_logout, :only => :destroy #add this at the top with the other filters
def log_logout
::Rails.logger.info "*** Logging out : #{current_user.email} ***\n"
end
I've found another way to do this, if you want, for example, display a custom message if login fails.
In my job, if login fails we check the activity status (custom logic) and display a message, no matter if the login was correct or not.
After debug a little bit and read warden docs I know this now: Warden executes a throw(:warden, opts), so, according to ruby docs, a throw must be captured inside a catch block.
def create
flash.clear
login_result = catch(:warden) { super }
return unless login_failed?(login_result)
email = params[:user][:email]
flash[:alert] = # here I call my service that calculates the message
redirect_to new_user_session_path
end
def login_failed?(login_result)
login_result.is_a?(Hash) && login_result.key?(:scope) && login_result.key?(:recall)
end
throw docs:
https://ruby-doc.org/core-2.6.3/Kernel.html#method-i-throw
catch docs:
https://ruby-doc.org/core-2.6.3/Kernel.html#method-i-catch
Building on Prakash Murty's answer, I think the approach in this answer (https://stackoverflow.com/a/34816998/891359) is a cleaner way to log a succesfull login attempt. Instead of calling super, Devise offers a way to pass a block that is yielded before the view is rendered.
So instead of doing this:
class SessionsController < Devise::SessionsController
def create
super
::Rails.logger.info "\n***\nSuccessful login with email_id : #{request.filtered_parameters["user"]}\n***\n"
end
end
It is cleaner to do:
class SessionsController < Devise::SessionsController
def create
super do |user|
::Rails.logger.info "\n***\nSuccessful login with email_id : #{user.email}\n***\n"
end
end
end
I'm doing some design/debugging in IRB and need to login a user and then be able to use current_user in my efforts.
From Brian Deterling's answer to another question, I have been able to successfully login and access a page response with this sequence:
>> ApplicationController.allow_forgery_protection = false
>> app.post('/sign_in', {"user"=>{"login"=>"some-login-id", "password"=>"some-password"}})
>> app.get '/some_other_path_that_only_works_if_logged_in'
>> pp app.response.body
NOTE: If you get a 200 response you are not logged in. You need a 302 redirect to indicate a successful login. See Tim Santeford's answer.
I've been able to get session info:
1.9.3-p125 :009 > app.session
=> {"_csrf_token"=>"1yAn0jI4VWzUH84PNTH0lVhjpY98e9echQGS4=", "session_id"=>"89984667d30d0fec71f2a5cbb9017e24"}
I've tried everything I can think of to try to get to current_user via app and app.session, but no luck. How can I get current_user?
current_user is a property of the controller so after app.post('/sign_in', ... you can call app.controller.current_user in your rails console to get the User object
It might be possible that you are not really logging in. One thing to keep in mind is that Devise I build on top of Warden which is rack middleware.
I tried your app.post method of logging in on an app I'm working on that uses Devise. After posting to the login page and getting a 302 redirect the app.session showed the warden user id.
>> app.session
{
"_csrf_token"=>"dT0/BqgLb84bnE+f1g...",
"warden.user.user.key"=>["User", [42843], "$2a$10$1OU.1BixIba..."],
"session_id"=>"0dd49c05ff4e6362c207c6eb877f86cd"
}
I was able to fetch the user like this:
>> current_user = User.find(app.session["warden.user.user.key"][1][0])
When I logged out and then tried logging in with a bad password I get a 200 and then the app.session is missing the warden user info and only contained the csrf token and session id like your example.
BTW: Once logged in app.controller.current_user was nil even when the warden user id was in the session.