MCPcopy Create free account
hub / github.com/PatchMon/PatchMon / createOidcUser

Method createOidcUser

server-source-code/internal/handler/oidc.go:836–888  ·  view source on GitHub ↗
(ctx context.Context, info *oidc.UserInfo)

Source from the content-addressed store, hash-verified

834var usernameSanitize = regexp.MustCompile(`[^a-zA-Z0-9._-]`)
835
836func (h *OidcHandler) createOidcUser(ctx context.Context, info *oidc.UserInfo) *models.User {
837 baseUsername := usernameSanitize.ReplaceAllString(strings.Split(info.Email, "@")[0], "")
838 if len(baseUsername) > 32 {
839 baseUsername = baseUsername[:32]
840 }
841 username := baseUsername
842 counter := 1
843 for {
844 _, err := h.users.GetByUsername(ctx, username)
845 if err != nil && errors.Is(err, pgx.ErrNoRows) {
846 break
847 }
848 username = baseUsername + fmt.Sprintf("%d", counter)
849 counter++
850 if counter > 1000 {
851 username = baseUsername + uuid.New().String()[:8]
852 break
853 }
854 }
855 role := h.mapGroupsToRole(info.Groups)
856 if h.log != nil && len(info.Groups) == 0 && h.oidcSyncRoles() {
857 h.log.Warn("oidc no groups in token for new user", "email", info.Email, "hint", "Create a Scope Mapping in Authentik to add 'groups' claim")
858 }
859 // If no admin/superadmin exists yet, promote the first auto-created user to superadmin.
860 adminCount, _ := h.users.CountAdmins(ctx)
861 if adminCount == 0 {
862 role = "superadmin"
863 if h.log != nil {
864 h.log.Info("oidc first user promoted to superadmin", "email", info.Email)
865 }
866 }
867 issuerHost := extractHost(h.oidcIssuerURL())
868 u := &models.User{
869 ID: uuid.New().String(),
870 Username: username,
871 Email: strings.ToLower(info.Email),
872 Role: role,
873 IsActive: true,
874 FirstName: strPtr(info.GivenName),
875 LastName: strPtr(info.FamilyName),
876 OidcSub: &info.Sub,
877 OidcProvider: &issuerHost,
878 AvatarURL: strPtr(info.Picture),
879 }
880 if err := h.users.CreateOidcUser(ctx, u, info.Sub, issuerHost, strPtr(info.Picture)); err != nil {
881 if h.log != nil {
882 h.log.Error("oidc create user failed", "error", err, "email", info.Email)
883 }
884 return nil
885 }
886 AutoSubscribeIfHosted(h.cfg != nil && h.cfg.AdminMode, h.users, h.log, u)
887 return u
888}

Callers 1

CallbackMethod · 0.95

Calls 10

mapGroupsToRoleMethod · 0.95
oidcSyncRolesMethod · 0.95
oidcIssuerURLMethod · 0.95
extractHostFunction · 0.85
AutoSubscribeIfHostedFunction · 0.85
GetByUsernameMethod · 0.80
ErrorMethod · 0.80
strPtrFunction · 0.70
CountAdminsMethod · 0.65
CreateOidcUserMethod · 0.65

Tested by

no test coverage detected