CreateOrUpdateUser creates or updates a user with the given email, name, and photo URL. If the user doesn't exist, it creates a new user and simultaneously adds them to any orgs and projects they have been invited to.
(ctx context.Context, email, name, photoURL string)
| 129 | // CreateOrUpdateUser creates or updates a user with the given email, name, and photo URL. |
| 130 | // If the user doesn't exist, it creates a new user and simultaneously adds them to any orgs and projects they have been invited to. |
| 131 | func (s *Service) CreateOrUpdateUser(ctx context.Context, email, name, photoURL string) (*database.User, error) { |
| 132 | // Validate email address |
| 133 | _, err := mail.ParseAddress(email) |
| 134 | if err != nil { |
| 135 | return nil, fmt.Errorf("invalid user email address %q", email) |
| 136 | } |
| 137 | |
| 138 | // Update user if exists |
| 139 | user, err := s.DB.FindUserByEmail(ctx, email) |
| 140 | if err == nil { |
| 141 | return s.DB.UpdateUser(ctx, user.ID, &database.UpdateUserOptions{ |
| 142 | DisplayName: name, |
| 143 | PhotoURL: photoURL, |
| 144 | GithubUsername: user.GithubUsername, |
| 145 | GithubToken: user.GithubToken, |
| 146 | GithubTokenExpiresOn: user.GithubTokenExpiresOn, |
| 147 | GithubRefreshToken: user.GithubRefreshToken, |
| 148 | QuotaSingleuserOrgs: user.QuotaSingleuserOrgs, |
| 149 | QuotaTrialOrgs: user.QuotaTrialOrgs, |
| 150 | PreferenceTimeZone: user.PreferenceTimeZone, |
| 151 | }) |
| 152 | } else if !errors.Is(err, database.ErrNotFound) { |
| 153 | return nil, err |
| 154 | } |
| 155 | |
| 156 | // User does not exist. Creating a new user. |
| 157 | |
| 158 | // Get user invites if exists |
| 159 | orgInvites, err := s.DB.FindOrganizationInvitesByEmail(ctx, email) |
| 160 | if err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | projectInvites, err := s.DB.FindProjectInvitesByEmail(ctx, email) |
| 164 | if err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | |
| 168 | ctx, tx, err := s.DB.NewTx(ctx, false) |
| 169 | if err != nil { |
| 170 | return nil, err |
| 171 | } |
| 172 | defer func() { _ = tx.Rollback() }() |
| 173 | |
| 174 | isFirstUser, err := s.DB.CheckUsersEmpty(ctx) |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | |
| 179 | opts := &database.InsertUserOptions{ |
| 180 | Email: email, |
| 181 | DisplayName: name, |
| 182 | PhotoURL: photoURL, |
| 183 | QuotaSingleuserOrgs: deref(s.Biller.DefaultUserQuotas().SingleuserOrgs, -1), |
| 184 | QuotaTrialOrgs: deref(s.Biller.DefaultUserQuotas().TrialOrgs, -1), |
| 185 | Superuser: isFirstUser, |
| 186 | } |
| 187 | |
| 188 | // Create user |
no test coverage detected