From abe92678937e8257577d95b276a8934cd8733cc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20B=C3=B6hm?= Date: Sun, 25 Aug 2024 01:20:55 +0200 Subject: [PATCH] Modified authentication with user_signed_in? and current_user --- app/controllers/application_controller.rb | 20 ++++++++++-- app/controllers/home_controller.rb | 1 + app/views/home/index.html.erb | 40 ++++++++++------------- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 27fa7bd..b1ec843 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,10 +3,24 @@ class ApplicationController < ActionController::Base before_action :authenticate private + def current_user + Current.user || authenticate_user_from_session + end + helper_method :current_user + + def authenticate_user_from_session + session_record = Session.find_by_id(cookies.signed[:session_token]) + Current.session = session_record + Current.user + end + + def user_signed_in? + current_user.present? + end + helper_method :user_signed_in? + def authenticate - if session_record = Session.find_by_id(cookies.signed[:session_token]) - Current.session = session_record - else + unless user_signed_in? redirect_to sign_in_path end end diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 95f2992..ce7e2f6 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -1,4 +1,5 @@ class HomeController < ApplicationController + skip_before_action :authenticate def index end end diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb index 677883d..c9edeaa 100644 --- a/app/views/home/index.html.erb +++ b/app/views/home/index.html.erb @@ -1,23 +1,19 @@

<%= notice %>

- -

Signed as <%= Current.user.email %>

- -

Login and verification

- -
- <%= link_to "Change password", edit_password_path %> -
- -
- <%= link_to "Change email address", edit_identity_email_path %> -
- -

Access history

- -
- <%= link_to "Devices & Sessions", sessions_path %> -
- -
- -<%= button_to "Log out", Current.session, method: :delete %> +<% if user_signed_in? %> +

Signed as <%= current_user.email %>

+

Login and verification

+
+ <%= link_to "Change password", edit_password_path %> +
+
+ <%= link_to "Change email address", edit_identity_email_path %> +
+

Access history

+
+ <%= link_to "Devices & Sessions", sessions_path %> +
+
+ <%= button_to "Log out", Current.session, method: :delete %> +<% else %> + <%= link_to "Log in", sign_in_path %> +<% end %>