Devise token auth another user login - ruby-on-rails

I am developing an application through Rails.
I need the ability to login to another user with admin account in devise token auth gem
When user log in, authHeaders are stored in the browser cookie.
Determine user by authHeaders value.
ex)
{ %22access-token%22:%22"access-token value"%22%2C
%22token-type%22:%22Bearer%22%2C
%22client%22:%22"client value"%22%2C
%22expiry%22:%"expiry value"%22%2C
%22uid%22:%22"uid value"%22}
in my controller
returns a new token value when admin clicks user id
def login_as
user = User.find(params[:user_id])
user_new_token_data = user.create_new_auth_token
## return new access-token, token-type, client, expiry, uid in browser cookies format same value
end
I want to change the return value to a browser cookie value and log in as another user, but I do not know how to put it in the cookie.
I would appreciate your help. Thank you

Related

Authenticate active admin user in grape api endpoint

So here are the components of my application
admin panel is on myapp.com/admin built with active admin. then I have a dashboard for users at dashboard.myapp.com built with AngularJs and then I have api built with grape at myapp.com/api.
I have a feature on my admin panel where an admin can log in on the dashboard as another user. we call this capture_session. basically the users session is captured by admin and we drop a cookie admin_capture whose value is the id of the admin_user.
now here is what I want to achieve. in one of my grape api endpoints I need validate that the session is captured and that the admin user who has captured the session is also logged in on the admin panel.
now figuring out whether the session is captured or not is easy as I already have a cookie for that. but how can I verify that the admin user is logged in?
as active admin methods and helpers cannot be called in grape api endpoint.
can I achieve this with cookies or sessions? any help will be highly appreciated
Thanks
So here is how I solved this..
I set another cookie admin_session with the encrypted session and then returned the same cookie as header from the dashboard.
In the grape endpoint I decrypted the session and got the admin user's id and initial part of the encrypted password. and used this information to verify admin.
here is the code.
admin_id = ADMIN_ID_HEADER
admin_session = ADMIN_SESSION_HEADER
admin_user = AdminUser.find_by_id(admin_id)
return unless admin_id.present? && admin_session.present? && admin_user.present?
salt = Rails.application.config.action_dispatch.encrypted_cookie_salt
signed_salt = Rails.application.config.action_dispatch.encrypted_signed_cookie_salt
key_generator = ActiveSupport::KeyGenerator.new(ENV['SECRET_KEY_BASE'], :iterations => 1000)
secret = key_generator.generate_key(salt)
signed_secret = key_generator.generate_key(signed_salt)
encryptor = ActiveSupport::MessageEncryptor.new(secret, signed_secret, :serializer => ActiveSupport::MessageEncryptor::NullSerializer)
session_data = JSON.parse(encryptor.decrypt_and_verify(CGI::unescape(admin_session))) rescue {}

Devise login custom endpoint, current_user session id

I have a mobile application that needs to login to a legacy Rails 3.2 app.
I have an endpoint that the mobile app makes a POST request to passing the username and password.
I want to verify the password and sign in the user and then need to save the now signed user's session id.
I have tried the following:
user = User.find_by_username(params[:username])
if user.valid_password?(params[:password])
sign_in(:user, user)
session_id = request.session_options[:id]
p "session id: #{session_id}"
current_user.logins.create({ session_id: session_id })
end
When I check my redis store that session id being stored is different from the session_id I print out. I read somewhere that this is because rails creates a session id for the request and then once you sign in you get a new session id to prevent fake requests. How can I get the signed in user's session_id?

Secure Handling of Auth Tokens with Rails

I'm working on a new rails api project, and I'm trying to get to the best usability/security balance.
The user will establish a session by posting username/password to api/v1/sessions. For a valid user, it will create an authentication token, which is it's own activerecord model, associated by the polymorphic relationship authenticatable, giving me the flexibility to have multiple user models if I need to.
class AuthenticationToken < ActiveRecord::Base
before_create :digest_token
def self.from_authenticatable(authenticatable)
self.create(authenticatable: authenticatable, token: generate_token)
end
end
The undigested token (SecureRandom.hex) gets rendered back to the client via JSON to authenticate future requests. The token gets salted and digested for storage in the database using BCrypt and a configured work factor.
The client will provide the raw auth token and an identity (can be username or password) to load the user record. Authentication will be handled by authenticate_with_http_token
def authenticate_token
authenticate_with_http_token do |token, options|
user = User.identified_by(options["identity"])
user.authentication_tokens.any? do |auth_token|
#current_user = user if auth_token.secure_compare(token)
end
end
end
Auth tokens are compared via a constant time alogrithm lifted from devise.
If current user is not successfully set, I render 401 unauthorized.
I feel like this is reasonably secure, and the only thing I really want to do is add some more fields to the auth token to track where it was last used (user agent) to allow the user to revoke some of the auth tokens if they like.
Are there any major holes with this approach? Anything else I should consider?

Rails3 User Changed Password, how do I change the current session password?

I have the need to let the user change their password. I'd like to switch the password in the session to reflect this new password, without logging them out.
def set_auth username, password
# test username and password here?
auth_object = AuthCookie.new
auth_object.set_username username
auth_object.set_password password
session[:user_login] = auth_object
end
I use something like the above, but it doesn't seem to work in changing the current session's password to the new one the use just entered.
What am I doing wrong?
Don't save your whole auth object in the session, the most important thing is you should not save password info in the session. Rails default session storage is cookie based, just base64 encode string. So if you save user password info in the session, there is security problem.
Just put the user identify in the session, for example, the user_id. session[:user_id] = user_id

In Ruby on Rails Restful Authentication, why does current_user check the HTTP username and password?

In Restful Authentication, lib/authenticated_system.rb,
why does current_user do a login_from_basic_auth, which does a authenticate_with_http_basic, which is to check the HTTP user provided login name and password?
I thought the login form is in /session/new (or /login), and then it POST to /session, which will go to the sessions controller, create action, and there, it
verifies the login name and password provided by the user.
This is line 8 of lib/authenticated_system.rb
def current_<%= file_name %>
#current_user ||= (login_from_session
|| login_from_basic_auth
|| login_from_cookie) unless #current_user == false
end
So the question is, if the login name and password was previously verified, then why checking it in current_user?
This function indicates that there are three ways to authenticate in your system:
Using a POST request from /session/new or /login.
Using BASIC HTTP authentication (a popup or URL provided username and password).
Using a remember me cookie so that sessions can persist even when session cookies are destroyed or the browser is restarted.
Even though your basic login happens with a POST request from /session/new or /login, the only thing that POST request actually does is set the session user id (probably session[:user_id]). Once that session[:user_id] has been set, you no longer need to login to perform a request, because you are authenticated. From this point forward the actual authentication happens by checking the session[:user_id] to see if someone has already logged in.
Here is a more detailed authentication lifecycle (for login):
User visits /login.
User enters password and username and submits form.
Password is checked, if authenticated the session[:user_id] is set.
User visits another page.
To check if the user is authenticated, current_user is called.
login_from_session is called and the user corresponding to session[:user_id] is returned.
The user is considered authenticated.
Here is a more detailed authentication lifecycle (for HTTP BASIC authentication):
A user visits http://username:password#www.example.com.
To check if the user is authenticated, current_user is called.
login_from_session is called, but session[:user_id] is nil, so nil is returned.
login_from_basic_auth is called, and username:password is present, so the corresponding user is returned.
The user is considered authenticated.
Here is a more detailed authentication lifecycle (remember me cookie):
A user has previously logged in and chosen the 'remember me' option.
A user closes their browser and then re-opens it and visits your site.
login_from_session is called, but session[:user_id] is nil, so nil is returned.
login_from_basic_auth is called, but username and password are missing, so nil is returned.
login_from_cookie is called and a cookie is found and used to return a user.
The user is considered authenticated.

Resources