ruby on rails - Is hitting the database required for current_user? -
i've been following tutorial sets simple user authentication. following code used determine if user logged in:
def current_user @current_user ||= user.find(session[:user_id]) if session[:user_id] end
if wanted ensure user logged in (and don't require user model), use like:
def is_user_logged_in true if session[:user_id] end
this way wouldn't have hit database if wanted check if user logged in. correct? , if so, there security concerns?
the current_user
helper popularized devise (if didn't know).
in fact, user_signed_in?
method popularized devise:
def user_signed_in? !!current_user end
i looked @ devise time back; built on top of warden middleware. there's tutorial here:
the
devise
gem built on top of warden. warden rack application, means runs separate , standalone module, , (nearly always) executed before chief rails application invoked.
warden
provides cookie handling verifies identity of logged in user via (secure) session string, in id (primary key) of particular user somehow stored , disguised. warden provides hook app can deal users aren’t logged in. these users either have restricted access, or none @ all, except, of course, sign-in/sign-up pages.
warden handles user authentication well. if need ideas, can @ how it.
--
from technical perspective, there's absolutely nothing wrong you're doing.
however, pointed out, problems may encounter systemic; validating authentication need consistent, not once user sets :user_id
session.
thus, following:
user_id
should not kept in session variable. @ least, should encoded sort of salt. (the less people know user data structure better)- i validate authentication somehow. once authenticated, i'd create
authenticated
token in session, compare stored token (kind of oauth).
in respect second suggestion, there interesting thing do. there semi-persistent storage solutions (the popular rails being redis) save db authentication whilst providing ram-type data access...
redis database stored in memory; use store key: value
pairs (json). more importantly, allows create super lightweight authentication system, saving expensive sql.
def user_signed_in? return redis.get(current_user.id) ? true : false end
although crude example, should give idea how caching , external sources give ability streamline queries somewhat.
you'd able see if user has right token in redis, providing array of "logged in" users. no db calls.
Comments
Post a Comment