Skip to content

Commit 05d1dc2

Browse files
committed
4102: Ensured dynamic role assignment is used in oauth
1 parent c2d8924 commit 05d1dc2

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

backend/open_webui/models/roles.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,16 @@ def delete_by_id(self, role_id: str) -> bool:
103103
except Exception:
104104
return False
105105

106+
def add_role_if_role_do_not_exists(self, role_name: str) -> Optional[RoleModel]:
107+
# Check if role already exists
108+
existing_role = self.get_role_by_name(role_name)
109+
if existing_role:
110+
return existing_role
111+
112+
# Role is allowed and doesn't exist, so create it
113+
try:
114+
return self.insert_new_role(name=role_name)
115+
except Exception as e:
116+
return None
117+
106118
Roles = RolesTable()

backend/open_webui/utils/oauth.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
from open_webui.models.auths import Auths
1717
from open_webui.models.users import Users
18+
from open_webui.models.roles import Roles
1819
from open_webui.models.groups import Groups, GroupModel, GroupUpdateForm
1920
from open_webui.config import (
2021
DEFAULT_USER_ROLE,
@@ -79,6 +80,17 @@ def __init__(self, app):
7980
def get_client(self, provider_name):
8081
return self.oauth.create_client(provider_name)
8182

83+
def find_first_role_match(self, oauth_roles, allowed_roles):
84+
# Convert to sets for more efficient lookup if lists are large
85+
oauth_roles_set = set(oauth_roles)
86+
allowed_roles_set = set(allowed_roles)
87+
88+
# Find the intersection of the two sets
89+
matching_roles = oauth_roles_set.intersection(allowed_roles_set)
90+
91+
# Return the first matching role if any matches found
92+
return next(iter(matching_roles), None)
93+
8294
def get_user_role(self, user, user_data):
8395
if user and Users.get_num_users() == 1:
8496
# If the user is the only user, assign the role "admin" - actually repairs role for single user on login
@@ -117,8 +129,15 @@ def get_user_role(self, user, user_data):
117129
for allowed_role in oauth_allowed_roles:
118130
# If the user has any of the allowed roles, assign the role "user"
119131
if allowed_role in oauth_roles:
120-
log.debug("Assigned user the user role")
121-
role = "user"
132+
first_match = self.find_first_role_match(oauth_roles, oauth_allowed_roles)
133+
if first_match:
134+
Roles.add_role_if_role_do_not_exists(first_match)
135+
role = first_match
136+
else:
137+
# Fallback to role user.
138+
role = "user"
139+
140+
log.debug(f"Assigned user the {role} role")
122141
break
123142
for admin_role in oauth_admin_roles:
124143
# If the user has any of the admin roles, assign the role "admin"

0 commit comments

Comments
 (0)