module SessionsHelper
  # @return The current user who is logged in
  def current_user
    @current_user ||= User.find_by(uid: session[:user_id])
  end

  # Logs a user in by setting their session id
  # @param user_id String A user ID to display to the user
  def log_in(user_id)
    session[:user_id] = user_id
  end

  # @return Boolean Whether a user is currently logged in
  def logged_in?
    !current_user.nil?
  end

  # Logs a user out by removing their session and setting the current user to nil
  def log_out
    session.delete(:user_id) if logged_in?
    @current_user = nil
  end

  # Redirects a user back to where they originated from, or a default url
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  # Stores the location of where a user accessed the page from
  def store_location
    session[:forwarding_url] = request.url if request.get?
  end
end
