I have a very simple rails app that I rolled my own authentication for, based on the rails tutorial book by Michael Hartl (http://www.railstutorial.org/book/modeling_users). The app is a content management system for an equally simple iOS app. I am aware that devise is very popular, but I really do not think it is necessary for this project. I want to be able to link my iOS app to my rails app, but everywhere I look the only advice I can find is how to do it with devise. All I want to do is have the user be presented with a login screen so they can establish a session and then I can handle all of the permission logic on the rails end of things. Here are a few things to give you an idea of my current authentication scheme:
My session controller:
class SessionsController < ApplicationController
def new
end
##
#Use the email in the nested hash to find the right user
#Check to make sure that the user authenticates with the given password
##
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or root_url
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
current_user.update_attribute(:remember_token,User.digest(User.new_remember_token))
cookies.delete(:remember_token)
self.current_user = nil
session.delete(:return_to) #not sure if this should really be here or if better way to fix bug
redirect_and_alert(root_url, "User Successfully Logged Out!",:success)
end
end
Sessions helper:
module SessionsHelper
##
#set the remember token for the user
#make the cookie reflect that token
#update the users remember token column
#set the user being passed in as the current user
##
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.digest(remember_token))
self.current_user = user
end
#set the current user
def current_user=(user)
#current_user = user
end
#Helper current user method
def current_user
remember_token = User.digest(cookies[:remember_token])
#current_user ||= User.find_by(remember_token: remember_token)
end
#Is the requesting user the current user
def current_user?(user)
user == current_user
end
#Is the user signed in?
def signed_in?
!current_user.nil?
end
#Store user request info for friendly forwarding
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
#Store user request info for friendly forwarding
def store_location
session[:return_to] = request.url if request.get?
end
#Authorization
def signed_in_user
store_location
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def super_user
redirect_and_alert(root_url,
"You are not allowed to do that. Contact the admin for this account.",
:error) unless (current_user.role.id == 1)
end
def super_user_or_admin
redirect_and_alert(root_url,
"You are not allowed to do that. Contact the admin for this account.",
:error) unless (current_user.role.id == 1 || current_user.role.id == 2)
end
def is_super_user
current_user.role.id == 1
end
def is_admin
current_user.role.id == 2
end
def is_regular_user
current_user.role.id == 3
end
end
You could go for a token-based system rather than a session-based system.
Create an attribute called authentication token for every user. This token can be generated and assigned during sign-up. The token itself can be generated using simple techniques such as SecureRandom.hex(n), where n is the length of the random hex number generated.
After sign-in/sign-up from the app, send the authentication token in the response from the server. You can then have the iOS app send the token along with every subsequent request to the server.
Have the server check the token every time a controller is hit with a request. This can be achieved using the before_filter. So a sample controller could look like this:
before_filter :authenticate_user
def authenticate_user
# assuming the parameter sent from the app is called auth_token
auth_token = params[:auth_token]
user = User.find_by_authentication_token(auth_token)
if user.nil?
# what to do if user does not exist
else
# what to do if user exists
end
end
Typically for mobile applications tokens are used instead of sessions. The token is essentially just a string that your Rails app will give each mobile device to verify it has access.
Step 1 is to have your mobile app authenticate against the Rails app (this can be through a custom email/password login or through a 3rd party like Facebook).
Have your Rails app send a token to the mobile application
Store this token in UserDefaults on iOS (help link: http://www.learnswiftonline.com/objective-c-to-swift-guides/nsuserdefaults-swift/)
Whenever your app makes a request (or websocket connection, etc.) to the Rails app, send the token (usually as a header).
Whenever the iOS app opens, check for the token in UserDefaults. If it is there, then you skip having the user authenticate again.
If you want to get really fancy, the Rails app should only accept a token once and issue new-tokens on each request. So your iOS app would send a token on each request and then grab a new one with each response. This is a more secure practice so someone does not grab a token and mess with your Rails app.
This diagram covers the high-level process (it uses FB login for initial authentication, but you can plug yours/an alternate system in instead): http://www.eggie5.com/57-ios-rails-oauth-flow.
Related
I'm trying to find a way to display logged in active users on my web app. I'm not using any gem for authentication like Devise. I have a list of users and wanted to show an icon or some type of indicator next to a users name if they are currently on the site.
I'm not sure how to go about this. Possibly I could add a column called currently_logged_in to my User model and could set the value to true when the session is created and then to false when the user session is destroyed?
class SessionsController < ApplicationController
def new
end
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id #session id created off of the
redirect_to(session[:intended_url] || user)
session[:intended_url] = nil #removes url from the sessions
else
flash.now[:error] = "Invalid email/password combination"
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to root_url
end
end
User model
# tries to find an existing user in the database so that they can be authenticated.
def self.authenticate(email, password)
user = User.find_by(email: email) # returns user or nil value
user && user.authenticate(password) # if user exists validate that password is correct
end
It depends what you mean by "currently on the site".
Adding a currently_logged_in column like you described works IF you want to mark users that are currently logged in. However most users don't log out when leaving a website these days so that probably won't do what you want.
A better solution would be to add a last_active_at column which you can update with the current time whenever a user performs some action. Then determine a threshold that makes sense for your website, let's say 15 minutes, and only mark users in your list that have a last_active_at value less than 15 minutes in the past.
Assuming the definition of "active user" for your website involves hitting authenticated endpoints it would be as simple as changing your authenticate method to:
def self.authenticate(email, password)
user = User.find_by(email: email) # returns user or nil value
if user && user.authenticate(password)
user.update!(last_active_at: Time.now)
true
else
false
end
end
Firstly You need to find current user on site.
You may b call current_user method which is in application helper and you should display all current user in wherever you want.
For Example,
module ApplicationHelper
def current_user
#current_user ||= session[:user_id] && User.find_by_id(session[:user_id])
end
end
And you call this method in Session controller as #current_user.
After logging into the application and then closing the browser completely, I re-open the browser expecting to be logged-out. However I am still logged in?
I am in section 8.2.3 Changing the layout links and apart from the above, the application looks and runs as expected. Also the code is as it is from the tutorial. I think these are the relevant files:
app/helpers/sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
end
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end
Ordinarily, the session is cleared when you close your browser, so you should be logged out automatically in this case. Some browsers remember your session anyway, though, as discussed in this footnote, and that could be what's going on here.
After logging into the application and then closing the browser completely, I re-open the browser expecting to be logged-out. However I am still logged in?
Because you are still logged in your application. Your browser remember login data by a cookie used to trace the session.
To log out you can use the logout link explained in the tutorial or you can clean your browser cache.
because you have a cookies, that the way you have like in every page sessions, that's the way are created. They are stored. If you want to deleted, just go to config, delete cookies
According to Mhartl's answer, you will experience the user not being logged out once you close the browser if you are using Chrome (I don't know why exactly) but when you open your application via firefox, user will be logged out automatically (again not sure how) as stated in Chapter 8 .
Navigating within the app and re-directs are all fine, its just when the browser refreshes the user has to log back in. I only want the session to expire when the browser closes and not on refresh..
My session_store.rb
Rails.application.config.session_store :cookie_store, key:
'_workspace_session'
My sessions controller new and create actions:
def new
end
def create
merchant = Merchant.find_by(email: params[:email])
if merchant && merchant.authenticate(params[:password])
session[:merchant_id] = merchant.id
log_in(merchant)
flash[:success] = "You were logged in successfully"
redirect_to merchant_path(merchant.id)
else
flash.now[:danger] = "Snap! either your email or password is
incorrect. Try again"
render 'new'
end
end
It's probably because you don't have a sessions helper that adds a cookie of the logged in merchant's credentials and checks them every time you reload the page:
First, add your sessions_helper.rb to your main controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
Here is your sessions helper:
module SessionsHelper
# Returns the user corresponding to the remember token cookie.
def current_merchant
if (merchant_id = session[:merchant_id])
#current_merchant ||= Merchant.find_by(id: merchant_id)
elsif (merchant_id = cookies.signed[:merchant_id])
merchant= Merchant.find_by(id: merchant_id)
if merchant && merchant.authenticated?(cookies[:remember_token])
log_in merchant
#current_user = merchant
end
end
end
#logs the merchant in.I don't know what your log_in method does there in the question, if it does the same, you are doing it two times.
def log_in(merchant)
session[:merchant_id] = merchant.id
end
end
Adapted from RailsTutorial <- I'd recommend you read this. A lot of great stuff in there.
I'm new to rails and are have a pretty basic understanding of the Devise Gem. Besides the CRUD and views I'm not clear on what it provides that could help me for a AngularJs app talking to a Rails Json Api.
At the moment I'm hand rolling things ie. for security I have I exchange a HTTP Header token between client (js) and server. I'm also using the Railscast #250 for user authentication - but as I don't see how to apply the SessionController for a remote client.
Are there any strategies I could employ for authentication and managing session via a remote json API?
Thanks!
I personally wouldn't use devise for something like this because there's only a small part of it you'd be using anyways
Dont
You pretty much just don't use a session. All you need to do is pass in basic authentication each time, and in the application controller you determine if its valid, if not just send them back an auth error.
Example request: http://username:password#example.com/api/endpoint
class ApplicationController
before_filter :check_auth!
private
def check_auth!
username, password = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
user = User.find_by(username: username)
if user && user.encrypted_password == SomeEncryptFunction(params[:password])
#current_user = user
else
raise "error"
end
end
end
But if you want to...
Then what you can do is update a DateTime field on the user when they first auth (which starts their session), then on subsequent calls they can just pass a token you give them that you you check for each time they sign in. You also check that only a certain amount of time has passed since they first authed, otherwise their session is invalid.
class SessionsController < ApplicationController
skip_before_filter :check_auth!
before_filter :login!
private
# Note: I don't remember the actual devise method for validating username + password
def login!
user = User.find_by(username: params[:username])
if user && user.valid_password(params[:password])
current_user = user
current_user.update_attributes(
authenticated_at: DateTime.now,
authentication_token: Devise.friendly_token
)
else
raise "error"
end
end
end
class ApplicationController
before_filter :check_auth!
private
def check_auth!
if valid_token(params[:token])
current_user = User.find_by(authentication_token: params[:token])
else
raise "error"
end
end
# Returns true if token belongs to a user and is recent enough
def valid_token(token)
user = User.find_by(authentication_token: params[:token])
user && user.authenticated_at < DateTime.now - 1.day
end
end
In Michael Hart's book this code is used to implement authentication:
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt] #permanent
# -alternatively-
# cookies.signed[:remember_token]={
# :value => [user.id, user.salt],
# expires => some_time.from_now
# }
current_user = user
end
def current_user=(user)
#current_user = user
end
def current_user
return #current_user ||= user_from_remember_token
end
private
def user_from_remember_token
#passes array of length two as a parameter -- first slot contains ID,
#second contains SALT for encryption
User.authenticate_with_salt(*remember_token)
end
def remember_token
#ensures return of a double array in the event that
#cookies.signed[:remember_token] is nil.
cookies.signed[:remember_token] || [nil,nil]
end
end
It does it's job very well, I can either log in for an infinite amount of time, or for a limited period of time as I wish.
But it has a downside, cookies are stored on the client and they dont go away even if the browser is closed
Now I was wondering, since rails sessions get destroyed after a browser is closed, how would I combine them and the cookies presented here to implement authentication with the following characteristics:
-- if a user logs in,
the data should be stored in a session
so that after a user closes his browser they get logged of
-- if a user logs in, with a 'remember me' checkbox selected
their data should be stored in a cookie with a long expiration date
What would be a take on this that remains secure and simple?
I googled on the web and found nothing recent enough (Rails 3) that
could guide me in the right direction.
I was thinking of creating 2 separate modules for sessions and cookies and fire their respective sign_in methods in the controller whether a remember_me param was present or not, but that would seem a lot of duplication.
PS I am not looking into any authentication gems to provide this functionality, id prefer to implement it on my own.
Thanks