sessions_helper.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. module SessionsHelper
  2. # Logs in the given user
  3. def log_in(user)
  4. session[:user_id] = user.id
  5. end
  6. # Remembers a user in a persistent session.
  7. def remember(user)
  8. user.remember
  9. cookies.permanent.signed[:user_id] = user.id
  10. cookies.permanent[:remember_token] = user.remember_token
  11. end
  12. # Returns true if the given user is the current user.
  13. def current_user?(user)
  14. user == current_user
  15. end
  16. # Returns the current logged-in user (if any).
  17. def current_user
  18. if (user_id = session[:user_id])
  19. @current_user ||= User.find_by(id: user_id)
  20. elsif (user_id = cookies.signed[:user_id])
  21. user = User.find_by(id: user_id)
  22. if user && user.authenticated?(:remember, cookies[:remember_token])
  23. log_in user
  24. @current_user = user
  25. end
  26. end
  27. end
  28. # Returns true if the user is logged in, false otherwise.
  29. def logged_in?
  30. !current_user.nil?
  31. end
  32. # Forgets a persistent session.
  33. def forget(user)
  34. user.forget
  35. cookies.delete(:user_id)
  36. cookies.delete(:remember_token)
  37. end
  38. # Logs out the current user.
  39. def log_out
  40. forget current_user
  41. session.delete(:user_id)
  42. @current_user = nil
  43. end
  44. # Redirects to stored location (or to the default).
  45. def redirect_back_or(default)
  46. redirect_to(session[:forwarding_url] || default)
  47. session.delete(:forwarding_url)
  48. end
  49. # Stores the URL trying to be accessed.
  50. def store_location
  51. session[:forwarding_url] = request.original_url if request.get?
  52. end
  53. end