Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add clerk_organization & clerk_organization_id helpers #22

Merged
merged 1 commit into from
Nov 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion lib/clerk/authenticatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ def clerk_user_id
request.env["clerk"].user_id
end

# Makes a request to the Clerk API to fetch the data of the authenticated
# session's organization. If caching is configured (see
# Config.middleware_cache_store), subsequent calls will return the cached
# object.
def clerk_organization
request.env["clerk"].org
end

def clerk_organization_id
request.env["clerk"].org_id
end

def clerk_user_signed_in?
!!clerk_verified_session_claims
end
Expand All @@ -69,7 +81,8 @@ def clerk_user_profile_url
helper_method :clerk_session, :clerk_reverify_session!,
:clerk_verified_session_claims, :clerk_verified_session_token,
:clerk_user, :clerk_user_id, :clerk_user_signed_in?, :clerk_sign_in_url,
:clerk_sign_up_url, :clerk_user_profile_url
:clerk_sign_up_url, :clerk_user_profile_url,
:clerk_organization, :clerk_organization_id
end
end
end
20 changes: 19 additions & 1 deletion lib/clerk/rack_middleware_v2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ def user_id
@session_claims["sub"]
end

def org
return nil if org_id.nil?

@org ||= fetch_org(org_id)
end

def org_id
return nil if user_id.nil?

@session_claims["org_id"]
end

private

def fetch_user(user_id)
Expand All @@ -44,6 +56,12 @@ def fetch_user(user_id)
end
end

def fetch_org(org_id)
cached_fetch("clerk_org:#{org_id}") do
sdk.organizations.find(org_id)
end
end

def cached_fetch(key, &block)
if store = Clerk.configuration.middleware_cache_store
store.fetch(key, expires_in: CACHE_TTL, &block)
Expand Down Expand Up @@ -105,7 +123,7 @@ def call(env)
rescue JWT::DecodeError
return signed_out(env) # malformed JSON authorization header
end

token = verify_token(header_token)
return signed_in(env, token, header_token) if token

Expand Down