DEV: Improve Guardian devex (#24706)

It's quite confusing for blank? to be overridden
on AnonymousUser and BasicUser to represent
whether the fake user is authenticated or not;
we can achieve the same thing more clearly with
a wrapper GuardianUser class around these
user classes. Also fixes an issue where
`def user` would be returning nil.
This commit is contained in:
Martin Brennan 2023-12-06 10:57:04 +10:00 committed by GitHub
parent 47629db3db
commit 77b6a038ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -11,6 +11,36 @@ require "guardian/tag_guardian"
require "guardian/topic_guardian"
require "guardian/user_guardian"
class GuardianUser
def initialize(user_alike)
@user_alike = user_alike
end
def actual
@user_alike
end
def fake?
if @user_alike.respond_to?(:fake?)
@user_alike.fake?
else
false
end
end
def authenticated?
if @user_alike.respond_to?(:authenticated?)
@user_alike.authenticated?
else
true
end
end
def method_missing(method, *args, &block)
@user_alike.public_send(method, *args, &block)
end
end
# The guardian is responsible for confirming access to various site resources and operations
class Guardian
include BookmarkGuardian
@ -28,6 +58,12 @@ class Guardian
def blank?
true
end
def fake?
true
end
def authenticated?
false
end
def admin?
false
end
@ -84,7 +120,13 @@ class Guardian
# categories or PMs but can read public topics.
class BasicUser
def blank?
false
true
end
def fake?
true
end
def authenticated?
true
end
def admin?
false
@ -139,7 +181,8 @@ class Guardian
attr_reader :request
def initialize(user = nil, request = nil)
@user = user.presence || AnonymousUser.new
@guardian_user = GuardianUser.new(user.presence || AnonymousUser.new)
@user = @guardian_user.actual
@request = request
end
@ -152,7 +195,7 @@ class Guardian
end
def user
@user.presence
@guardian_user.fake? ? nil : @user
end
alias current_user user
@ -161,7 +204,7 @@ class Guardian
end
def authenticated?
@user.present?
@guardian_user.authenticated?
end
def is_admin?