Skip to content

Commit d2aac2d

Browse files
Merge pull request #748 from 0mar/refactor/strip-domain-switch
[Google] Add switch to strip domain from username
2 parents bb1d2c5 + 81fd6be commit d2aac2d

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

oauthenticator/google.py

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from jupyterhub.auth import LocalAuthenticator
88
from tornado.auth import GoogleOAuth2Mixin
99
from tornado.web import HTTPError
10-
from traitlets import Dict, List, Set, Unicode, default, validate
10+
from traitlets import Bool, Dict, List, Set, Unicode, default, validate
1111

1212
from .oauth2 import OAuthenticator
1313

@@ -105,6 +105,32 @@ def _userdata_url_default(self):
105105
""",
106106
)
107107

108+
strip_domain = Bool(
109+
config=True,
110+
help="""
111+
Strip the username to exclude the `@domain` part.
112+
This happens by default when there is only one hosted domain specified
113+
114+
.. warning::
115+
116+
If domains are stripped from usernames and multiple `hosted_domains` are specified,
117+
there is a chance of clashing usernames.
118+
""",
119+
)
120+
121+
@default('strip_domain')
122+
def _strip_if_single_domain(self):
123+
return len(self.hosted_domain) <= 1
124+
125+
@validate('strip_domain')
126+
def _check_multiple_hosted_domain(self, strip_domain):
127+
if len(self.hosted_domain) > 1 and strip_domain:
128+
self.log.warning(
129+
"User names are stripped of `@domain`, but multiple domains are specified."
130+
" This can lead to clashing usernames"
131+
)
132+
return strip_domain.value
133+
108134
hosted_domain = List(
109135
Unicode(),
110136
config=True,
@@ -179,21 +205,13 @@ def user_info_to_username(self, user_info):
179205
"""
180206
username = super().user_info_to_username(user_info)
181207
user_email = user_info["email"]
182-
user_domain = user_info["domain"] = user_email.split("@")[1].lower()
208+
user_info["domain"] = user_email.split("@")[1].lower()
183209

184210
# NOTE: This is not an authorization check, it just about username
185211
# derivation. Decoupling hosted_domain from this is considered in
186212
# https://github.com/jupyterhub/oauthenticator/issues/733.
187-
#
188-
# NOTE: This code is written with without knowing for sure if the user
189-
# email's domain could be different from the domain in hd, so we
190-
# assume it could be even though it seems like it can't be. If a
191-
# Google organization/workspace manages users in a "primary
192-
# domain" and a "secondary domain", users with respective email
193-
# domain have their hd field set respectively.
194-
#
195-
if len(self.hosted_domain) == 1 and user_domain == self.hosted_domain[0]:
196-
# strip the domain in this situation
213+
214+
if self.strip_domain and user_info["domain"] in self.hosted_domain:
197215
username = username.split("@")[0]
198216

199217
return username

0 commit comments

Comments
 (0)