|
| 1 | +module Authenticate |
| 2 | + extend ActiveSupport::Concern |
| 3 | + |
| 4 | + included do |
| 5 | + before_action :authenticate |
| 6 | + before_action :need_to_login, unless: :logged_in? |
| 7 | + |
| 8 | + helper_method :logged_in? |
| 9 | + helper_method :current_user |
| 10 | + end |
| 11 | + |
| 12 | + class_methods do |
| 13 | + def skip_authentication(**options) |
| 14 | + skip_before_action :authenticate, options |
| 15 | + skip_before_action :need_to_login, options |
| 16 | + end |
| 17 | + |
| 18 | + def allow_unauthenticated(**options) |
| 19 | + skip_before_action :need_to_login, options |
| 20 | + end |
| 21 | + end |
| 22 | + |
| 23 | + protected |
| 24 | + |
| 25 | + def log_in(app_session, remember_me: false) |
| 26 | + if remember_me |
| 27 | + cookies.encrypted.permanent[:app_session] = { |
| 28 | + value: app_session.to_h |
| 29 | + } |
| 30 | + else |
| 31 | + cookies.signed[:app_session] = { |
| 32 | + value: app_session.to_h, |
| 33 | + expires: 1.day |
| 34 | + } |
| 35 | + end |
| 36 | + end |
| 37 | + |
| 38 | + def logout |
| 39 | + Current&.app_session&.destroy |
| 40 | + end |
| 41 | + |
| 42 | + def logged_in? |
| 43 | + Current.user.present? |
| 44 | + end |
| 45 | + |
| 46 | + def current_user |
| 47 | + Current.user |
| 48 | + end |
| 49 | + |
| 50 | + private |
| 51 | + |
| 52 | + def need_to_login |
| 53 | + flash[:notice] = t('login_required') |
| 54 | + render 'sessions/new', status: :unauthorized |
| 55 | + end |
| 56 | + |
| 57 | + def authenticate |
| 58 | + cookie = cookies.encrypted[:app_session]&.with_indifferent_access |
| 59 | + cookie = cookies.signed[:app_session]&.with_indifferent_access if cookie.nil? |
| 60 | + |
| 61 | + return nil if cookie.nil? |
| 62 | + |
| 63 | + user = User.find(cookie[:user_id]) |
| 64 | + app_session = user&.authenticate_session_token(cookie[:app_session], cookie[:token]) |
| 65 | + |
| 66 | + Current.user = app_session&.user |
| 67 | + Current.app_session = app_session |
| 68 | + rescue NoMatchingPatternError, ActiveRecord::RecordNotFound |
| 69 | + Current.user = nil |
| 70 | + Current.app_session = nil |
| 71 | + end |
| 72 | +end |
0 commit comments