code
stringlengths
22
3.95M
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
472
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
func (a *API) adminSSOProvidersList(w http.ResponseWriter, r *http.Request) error { ctx := r.Context() db := a.db.WithContext(ctx) providers, err := models.FindAllSAMLProviders(db) if err != nil { return err } for i := range providers { // remove metadata XML so that the returned JSON is not ginormous providers[i].SAMLProvider.MetadataXML = "" } return sendJSON(w, http.StatusOK, map[string]interface{}{ "items": providers, }) }
adminSSOProvidersList lists all SAML SSO Identity Providers in the system. Does not deal with pagination at this time.
adminSSOProvidersList
go
supabase/auth
internal/api/ssoadmin.go
https://github.com/supabase/auth/blob/master/internal/api/ssoadmin.go
MIT
func (a *API) adminSSOProvidersCreate(w http.ResponseWriter, r *http.Request) error { ctx := r.Context() db := a.db.WithContext(ctx) params := &CreateSSOProviderParams{} if err := retrieveRequestParams(r, params); err != nil { return err } if err := params.validate(false /* <- forUpdate */); err != nil { return err } rawMetadata, metadata, err := params.metadata(ctx) if err != nil { return err } existingProvider, err := models.FindSAMLProviderByEntityID(db, metadata.EntityID) if err != nil && !models.IsNotFoundError(err) { return err } if existingProvider != nil { return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeSAMLIdPAlreadyExists, "SAML Identity Provider with this EntityID (%s) already exists", metadata.EntityID) } provider := &models.SSOProvider{ // TODO handle Name, Description, Attribute Mapping SAMLProvider: models.SAMLProvider{ EntityID: metadata.EntityID, MetadataXML: string(rawMetadata), }, } if params.MetadataURL != "" { provider.SAMLProvider.MetadataURL = &params.MetadataURL } if params.NameIDFormat != "" { provider.SAMLProvider.NameIDFormat = &params.NameIDFormat } provider.SAMLProvider.AttributeMapping = params.AttributeMapping for _, domain := range params.Domains { existingProvider, err := models.FindSSOProviderByDomain(db, domain) if err != nil && !models.IsNotFoundError(err) { return err } if existingProvider != nil { return apierrors.NewBadRequestError(apierrors.ErrorCodeSSODomainAlreadyExists, "SSO Domain '%s' is already assigned to an SSO identity provider (%s)", domain, existingProvider.ID.String()) } provider.SSODomains = append(provider.SSODomains, models.SSODomain{ Domain: domain, }) } if err := db.Transaction(func(tx *storage.Connection) error { if terr := tx.Eager().Create(provider); terr != nil { return terr } return tx.Eager().Load(provider) }); err != nil { return err } return sendJSON(w, http.StatusCreated, provider) }
adminSSOProvidersCreate creates a new SAML Identity Provider in the system.
adminSSOProvidersCreate
go
supabase/auth
internal/api/ssoadmin.go
https://github.com/supabase/auth/blob/master/internal/api/ssoadmin.go
MIT
func (a *API) adminSSOProvidersGet(w http.ResponseWriter, r *http.Request) error { provider := getSSOProvider(r.Context()) return sendJSON(w, http.StatusOK, provider) }
adminSSOProvidersGet returns an existing SAML Identity Provider in the system.
adminSSOProvidersGet
go
supabase/auth
internal/api/ssoadmin.go
https://github.com/supabase/auth/blob/master/internal/api/ssoadmin.go
MIT
func (a *API) adminSSOProvidersUpdate(w http.ResponseWriter, r *http.Request) error { ctx := r.Context() db := a.db.WithContext(ctx) params := &CreateSSOProviderParams{} if err := retrieveRequestParams(r, params); err != nil { return err } if err := params.validate(true /* <- forUpdate */); err != nil { return err } modified := false updateSAMLProvider := false provider := getSSOProvider(ctx) if params.MetadataXML != "" || params.MetadataURL != "" { // metadata is being updated rawMetadata, metadata, err := params.metadata(ctx) if err != nil { return err } if provider.SAMLProvider.EntityID != metadata.EntityID { return apierrors.NewBadRequestError(apierrors.ErrorCodeSAMLEntityIDMismatch, "SAML Metadata can be updated only if the EntityID matches for the provider; expected '%s' but got '%s'", provider.SAMLProvider.EntityID, metadata.EntityID) } if params.MetadataURL != "" { provider.SAMLProvider.MetadataURL = &params.MetadataURL } provider.SAMLProvider.MetadataXML = string(rawMetadata) updateSAMLProvider = true modified = true } // domains are being "updated" only when params.Domains is not nil, if // it was nil (but not `[]`) then the caller is expecting not to modify // the domains updateDomains := params.Domains != nil var createDomains, deleteDomains []models.SSODomain keepDomains := make(map[string]bool) for _, domain := range params.Domains { existingProvider, err := models.FindSSOProviderByDomain(db, domain) if err != nil && !models.IsNotFoundError(err) { return err } if existingProvider != nil { if existingProvider.ID == provider.ID { keepDomains[domain] = true } else { return apierrors.NewBadRequestError(apierrors.ErrorCodeSSODomainAlreadyExists, "SSO domain '%s' already assigned to another provider (%s)", domain, existingProvider.ID.String()) } } else { modified = true createDomains = append(createDomains, models.SSODomain{ Domain: domain, SSOProviderID: provider.ID, }) } } if updateDomains { for i, domain := range provider.SSODomains { if !keepDomains[domain.Domain] { modified = true deleteDomains = append(deleteDomains, provider.SSODomains[i]) } } } updateAttributeMapping := false if params.AttributeMapping.Keys != nil { updateAttributeMapping = !provider.SAMLProvider.AttributeMapping.Equal(&params.AttributeMapping) if updateAttributeMapping { modified = true provider.SAMLProvider.AttributeMapping = params.AttributeMapping } } nameIDFormat := "" if provider.SAMLProvider.NameIDFormat != nil { nameIDFormat = *provider.SAMLProvider.NameIDFormat } if params.NameIDFormat != nameIDFormat { modified = true if params.NameIDFormat == "" { provider.SAMLProvider.NameIDFormat = nil } else { provider.SAMLProvider.NameIDFormat = &params.NameIDFormat } } if modified { if err := db.Transaction(func(tx *storage.Connection) error { if terr := tx.Eager().Update(provider); terr != nil { return terr } if updateDomains { if terr := tx.Destroy(deleteDomains); terr != nil { return terr } if terr := tx.Eager().Create(createDomains); terr != nil { return terr } } if updateAttributeMapping || updateSAMLProvider { if terr := tx.Eager().Update(&provider.SAMLProvider); terr != nil { return terr } } return tx.Eager().Load(provider) }); err != nil { return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeConflict, "Updating SSO provider failed, likely due to a conflict. Try again?").WithInternalError(err) } } return sendJSON(w, http.StatusOK, provider) }
adminSSOProvidersUpdate updates a provider with the provided diff values.
adminSSOProvidersUpdate
go
supabase/auth
internal/api/ssoadmin.go
https://github.com/supabase/auth/blob/master/internal/api/ssoadmin.go
MIT
func (r *AccessTokenResponse) AsRedirectURL(redirectURL string, extraParams url.Values) string { extraParams.Set("access_token", r.Token) extraParams.Set("token_type", r.TokenType) extraParams.Set("expires_in", strconv.Itoa(r.ExpiresIn)) extraParams.Set("expires_at", strconv.FormatInt(r.ExpiresAt, 10)) extraParams.Set("refresh_token", r.RefreshToken) return redirectURL + "#" + extraParams.Encode() }
AsRedirectURL encodes the AccessTokenResponse as a redirect URL that includes the access token response data in a URL fragment.
AsRedirectURL
go
supabase/auth
internal/api/token.go
https://github.com/supabase/auth/blob/master/internal/api/token.go
MIT
func (a *API) Token(w http.ResponseWriter, r *http.Request) error { ctx := r.Context() grantType := r.FormValue("grant_type") handler := a.ResourceOwnerPasswordGrant limiter := a.limiterOpts.Token switch grantType { case "password": // set above case "refresh_token": handler = a.RefreshTokenGrant case "id_token": handler = a.IdTokenGrant case "pkce": handler = a.PKCE case "web3": handler = a.Web3Grant limiter = a.limiterOpts.Web3 default: return apierrors.NewBadRequestError(apierrors.ErrorCodeInvalidCredentials, "unsupported_grant_type") } if err := a.performRateLimiting(limiter, r); err != nil { return err } return handler(ctx, w, r) }
Token is the endpoint for OAuth access token requests
Token
go
supabase/auth
internal/api/token.go
https://github.com/supabase/auth/blob/master/internal/api/token.go
MIT
func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error { db := a.db.WithContext(ctx) params := &PasswordGrantParams{} if err := retrieveRequestParams(r, params); err != nil { return err } aud := a.requestAud(ctx, r) config := a.config if params.Email != "" && params.Phone != "" { return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Only an email address or phone number should be provided on login.") } var user *models.User var grantParams models.GrantParams var provider string var err error grantParams.FillGrantParams(r) if params.Email != "" { provider = "email" if !config.External.Email.Enabled { return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeEmailProviderDisabled, "Email logins are disabled") } user, err = models.FindUserByEmailAndAudience(db, params.Email, aud) } else if params.Phone != "" { provider = "phone" if !config.External.Phone.Enabled { return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodePhoneProviderDisabled, "Phone logins are disabled") } params.Phone = formatPhoneNumber(params.Phone) user, err = models.FindUserByPhoneAndAudience(db, params.Phone, aud) } else { return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "missing email or phone") } if err != nil { if models.IsNotFoundError(err) { return apierrors.NewBadRequestError(apierrors.ErrorCodeInvalidCredentials, InvalidLoginMessage) } return apierrors.NewInternalServerError("Database error querying schema").WithInternalError(err) } if !user.HasPassword() { return apierrors.NewBadRequestError(apierrors.ErrorCodeInvalidCredentials, InvalidLoginMessage) } if user.IsBanned() { return apierrors.NewBadRequestError(apierrors.ErrorCodeUserBanned, "User is banned") } isValidPassword, shouldReEncrypt, err := user.Authenticate(ctx, db, params.Password, config.Security.DBEncryption.DecryptionKeys, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID) if err != nil { return err } var weakPasswordError *WeakPasswordError if isValidPassword { if err := a.checkPasswordStrength(ctx, params.Password); err != nil { if wpe, ok := err.(*WeakPasswordError); ok { weakPasswordError = wpe } else { observability.GetLogEntry(r).Entry.WithError(err).Warn("Password strength check on sign-in failed") } } if shouldReEncrypt { if err := user.SetPassword(ctx, params.Password, true, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey); err != nil { return err } // directly change this in the database without // calling user.UpdatePassword() because this // is not a password change, just encryption // change in the database if err := db.UpdateOnly(user, "encrypted_password"); err != nil { return err } } } if config.Hook.PasswordVerificationAttempt.Enabled { input := v0hooks.PasswordVerificationAttemptInput{ UserID: user.ID, Valid: isValidPassword, } output := v0hooks.PasswordVerificationAttemptOutput{} if err := a.hooksMgr.InvokeHook(nil, r, &input, &output); err != nil { return err } if output.Decision == v0hooks.HookRejection { if output.Message == "" { output.Message = v0hooks.DefaultPasswordHookRejectionMessage } if output.ShouldLogoutUser { if err := models.Logout(a.db, user.ID); err != nil { return err } } return apierrors.NewBadRequestError(apierrors.ErrorCodeInvalidCredentials, output.Message) } } if !isValidPassword { return apierrors.NewBadRequestError(apierrors.ErrorCodeInvalidCredentials, InvalidLoginMessage) } if params.Email != "" && !user.IsConfirmed() { return apierrors.NewBadRequestError(apierrors.ErrorCodeEmailNotConfirmed, "Email not confirmed") } else if params.Phone != "" && !user.IsPhoneConfirmed() { return apierrors.NewBadRequestError(apierrors.ErrorCodePhoneNotConfirmed, "Phone not confirmed") } var token *AccessTokenResponse err = db.Transaction(func(tx *storage.Connection) error { var terr error if terr = models.NewAuditLogEntry(r, tx, user, models.LoginAction, "", map[string]interface{}{ "provider": provider, }); terr != nil { return terr } token, terr = a.issueRefreshToken(r, tx, user, models.PasswordGrant, grantParams) if terr != nil { return terr } return nil }) if err != nil { return err } token.WeakPassword = weakPasswordError metering.RecordLogin("password", user.ID) return sendJSON(w, http.StatusOK, token) }
ResourceOwnerPasswordGrant implements the password grant type flow
ResourceOwnerPasswordGrant
go
supabase/auth
internal/api/token.go
https://github.com/supabase/auth/blob/master/internal/api/token.go
MIT
func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error { log := observability.GetLogEntry(r).Entry db := a.db.WithContext(ctx) config := a.config params := &IdTokenGrantParams{} if err := retrieveRequestParams(r, params); err != nil { return err } if params.IdToken == "" { return apierrors.NewOAuthError("invalid request", "id_token required") } if params.Provider == "" && (params.ClientID == "" || params.Issuer == "") { return apierrors.NewOAuthError("invalid request", "provider or client_id and issuer required") } oidcProvider, skipNonceCheck, providerType, acceptableClientIDs, err := params.getProvider(ctx, config, r) if err != nil { return err } var oidcConfig *oidc.Config if providerType == "apple" { oidcConfig = &oidc.Config{ SkipClientIDCheck: true, SkipIssuerCheck: true, } } idToken, userData, err := provider.ParseIDToken(ctx, oidcProvider, oidcConfig, params.IdToken, provider.ParseIDTokenOptions{ SkipAccessTokenCheck: params.AccessToken == "", AccessToken: params.AccessToken, }) if err != nil { return apierrors.NewOAuthError("invalid request", "Bad ID token").WithInternalError(err) } userData.Metadata.EmailVerified = false for _, email := range userData.Emails { if email.Primary { userData.Metadata.Email = email.Email userData.Metadata.EmailVerified = email.Verified break } else { userData.Metadata.Email = email.Email userData.Metadata.EmailVerified = email.Verified } } if idToken.Subject == "" { return apierrors.NewOAuthError("invalid request", "Missing sub claim in id_token") } correctAudience := false for _, clientID := range acceptableClientIDs { if clientID == "" { continue } for _, aud := range idToken.Audience { if aud == clientID { correctAudience = true break } } if correctAudience { break } } if !correctAudience { return apierrors.NewOAuthError("invalid request", fmt.Sprintf("Unacceptable audience in id_token: %v", idToken.Audience)) } if !skipNonceCheck { tokenHasNonce := idToken.Nonce != "" paramsHasNonce := params.Nonce != "" if tokenHasNonce != paramsHasNonce { return apierrors.NewOAuthError("invalid request", "Passed nonce and nonce in id_token should either both exist or not.") } else if tokenHasNonce && paramsHasNonce { // verify nonce to mitigate replay attacks hash := fmt.Sprintf("%x", sha256.Sum256([]byte(params.Nonce))) if hash != idToken.Nonce { return apierrors.NewOAuthError("invalid nonce", "Nonces mismatch") } } } if params.AccessToken == "" { if idToken.AccessTokenHash != "" { log.Warn("ID token has a at_hash claim, but no access_token parameter was provided. In future versions, access_token will be mandatory as it's security best practice.") } } else { if idToken.AccessTokenHash == "" { log.Info("ID token does not have a at_hash claim, access_token parameter is unused.") } } var token *AccessTokenResponse var grantParams models.GrantParams grantParams.FillGrantParams(r) if err := a.triggerBeforeUserCreatedExternal(r, db, userData, providerType); err != nil { return err } if err := db.Transaction(func(tx *storage.Connection) error { var user *models.User var terr error user, terr = a.createAccountFromExternalIdentity(tx, r, userData, providerType) if terr != nil { return terr } token, terr = a.issueRefreshToken(r, tx, user, models.OAuth, grantParams) if terr != nil { return terr } return nil }); err != nil { switch err.(type) { case *storage.CommitWithError: return err case *HTTPError: return err default: return apierrors.NewOAuthError("server_error", "Internal Server Error").WithInternalError(err) } } return sendJSON(w, http.StatusOK, token) }
IdTokenGrant implements the id_token grant type flow
IdTokenGrant
go
supabase/auth
internal/api/token_oidc.go
https://github.com/supabase/auth/blob/master/internal/api/token_oidc.go
MIT
func (a *API) RefreshTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error { db := a.db.WithContext(ctx) config := a.config params := &RefreshTokenGrantParams{} if err := retrieveRequestParams(r, params); err != nil { return err } if params.RefreshToken == "" { return apierrors.NewOAuthError("invalid_request", "refresh_token required") } // A 5 second retry loop is used to make sure that refresh token // requests do not waste database connections waiting for each other. // Instead of waiting at the database level, they're waiting at the API // level instead and retry to refresh the locked row every 10-30 // milliseconds. retryStart := a.Now() retry := true for retry && time.Since(retryStart).Seconds() < retryLoopDuration { retry = false user, token, session, err := models.FindUserWithRefreshToken(db, params.RefreshToken, false) if err != nil { if models.IsNotFoundError(err) { return apierrors.NewBadRequestError(apierrors.ErrorCodeRefreshTokenNotFound, "Invalid Refresh Token: Refresh Token Not Found") } return apierrors.NewInternalServerError(err.Error()) } if user.IsBanned() { return apierrors.NewBadRequestError(apierrors.ErrorCodeUserBanned, "Invalid Refresh Token: User Banned") } if session == nil { // a refresh token won't have a session if it's created prior to the sessions table introduced if err := db.Destroy(token); err != nil { return apierrors.NewInternalServerError("Error deleting refresh token with missing session").WithInternalError(err) } return apierrors.NewBadRequestError(apierrors.ErrorCodeSessionNotFound, "Invalid Refresh Token: No Valid Session Found") } sessionValidityConfig := models.SessionValidityConfig{ Timebox: config.Sessions.Timebox, InactivityTimeout: config.Sessions.InactivityTimeout, AllowLowAAL: config.Sessions.AllowLowAAL, } result := session.CheckValidity(sessionValidityConfig, retryStart, &token.UpdatedAt, user.HighestPossibleAAL()) switch result { case models.SessionValid: // do nothing case models.SessionTimedOut: return apierrors.NewBadRequestError(apierrors.ErrorCodeSessionExpired, "Invalid Refresh Token: Session Expired (Inactivity)") case models.SessionLowAAL: return apierrors.NewBadRequestError(apierrors.ErrorCodeSessionExpired, "Invalid Refresh Token: Session Expired (Low AAL: User Needs MFA Verification)") default: return apierrors.NewBadRequestError(apierrors.ErrorCodeSessionExpired, "Invalid Refresh Token: Session Expired") } // Basic checks above passed, now we need to serialize access // to the session in a transaction so that there's no // concurrent modification. In the event that the refresh // token's row or session is locked, the transaction is closed // and the whole process will be retried a bit later so that // the connection pool does not get exhausted. var tokenString string var expiresAt int64 var newTokenResponse *AccessTokenResponse err = db.Transaction(func(tx *storage.Connection) error { user, token, session, terr := models.FindUserWithRefreshToken(tx, params.RefreshToken, true /* forUpdate */) if terr != nil { if models.IsNotFoundError(terr) { // because forUpdate was set, and the // previous check outside the // transaction found a refresh token // and session, but now we're getting a // IsNotFoundError, this means that the // refresh token row and session are // probably locked so we need to retry // in a few milliseconds. retry = true return terr } return apierrors.NewInternalServerError(terr.Error()) } if a.config.Sessions.SinglePerUser { sessions, terr := models.FindAllSessionsForUser(tx, user.ID, true /* forUpdate */) if models.IsNotFoundError(terr) { // because forUpdate was set, and the // previous check outside the // transaction found a user and // session, but now we're getting a // IsNotFoundError, this means that the // user is locked and we need to retry // in a few milliseconds retry = true return terr } else if terr != nil { return apierrors.NewInternalServerError(terr.Error()) } sessionTag := session.DetermineTag(config.Sessions.Tags) // go through all sessions of the user and // check if the current session is the user's // most recently refreshed valid session for _, s := range sessions { if s.ID == session.ID { // current session, skip it continue } if s.CheckValidity(sessionValidityConfig, retryStart, nil, user.HighestPossibleAAL()) != models.SessionValid { // session is not valid so it // can't be regarded as active // on the user continue } if s.DetermineTag(config.Sessions.Tags) != sessionTag { // if tags are specified, // ignore sessions with a // mismatching tag continue } // since token is not the refresh token // of s, we can't use it's UpdatedAt // time to compare! if s.LastRefreshedAt(nil).After(session.LastRefreshedAt(&token.UpdatedAt)) { // session is not the most // recently active one return apierrors.NewBadRequestError(apierrors.ErrorCodeSessionExpired, "Invalid Refresh Token: Session Expired (Revoked by Newer Login)") } } // this session is the user's active session } // refresh token row and session are locked at this // point, cannot be concurrently refreshed var issuedToken *models.RefreshToken if token.Revoked { activeRefreshToken, terr := session.FindCurrentlyActiveRefreshToken(tx) if terr != nil && !models.IsNotFoundError(terr) { return apierrors.NewInternalServerError(terr.Error()) } if activeRefreshToken != nil && activeRefreshToken.Parent.String() == token.Token { // Token was revoked, but it's the // parent of the currently active one. // This indicates that the client was // not able to store the result when it // refreshed token. This case is // allowed, provided we return back the // active refresh token instead of // creating a new one. issuedToken = activeRefreshToken } else { // For a revoked refresh token to be reused, it // has to fall within the reuse interval. reuseUntil := token.UpdatedAt.Add( time.Second * time.Duration(config.Security.RefreshTokenReuseInterval)) if a.Now().After(reuseUntil) { // not OK to reuse this token if config.Security.RefreshTokenRotationEnabled { // Revoke all tokens in token family if err := models.RevokeTokenFamily(tx, token); err != nil { return apierrors.NewInternalServerError(err.Error()) } } return storage.NewCommitWithError(apierrors.NewBadRequestError(apierrors.ErrorCodeRefreshTokenAlreadyUsed, "Invalid Refresh Token: Already Used").WithInternalMessage("Possible abuse attempt: %v", token.ID)) } } } if terr = models.NewAuditLogEntry(r, tx, user, models.TokenRefreshedAction, "", nil); terr != nil { return terr } if issuedToken == nil { newToken, terr := models.GrantRefreshTokenSwap(r, tx, user, token) if terr != nil { return terr } issuedToken = newToken } tokenString, expiresAt, terr = a.generateAccessToken(r, tx, user, issuedToken.SessionId, models.TokenRefresh) if terr != nil { httpErr, ok := terr.(*HTTPError) if ok { return httpErr } return apierrors.NewInternalServerError("error generating jwt token").WithInternalError(terr) } refreshedAt := a.Now() session.RefreshedAt = &refreshedAt userAgent := r.Header.Get("User-Agent") if userAgent != "" { session.UserAgent = &userAgent } else { session.UserAgent = nil } ipAddress := utilities.GetIPAddress(r) if ipAddress != "" { session.IP = &ipAddress } else { session.IP = nil } if terr := session.UpdateOnlyRefreshInfo(tx); terr != nil { return apierrors.NewInternalServerError("failed to update session information").WithInternalError(terr) } newTokenResponse = &AccessTokenResponse{ Token: tokenString, TokenType: "bearer", ExpiresIn: config.JWT.Exp, ExpiresAt: expiresAt, RefreshToken: issuedToken.Token, User: user, } return nil }) if err != nil { if retry && models.IsNotFoundError(err) { // refresh token and session row were likely locked, so // we need to wait a moment before retrying the whole // process anew time.Sleep(time.Duration(10+mathRand.Intn(20)) * time.Millisecond) // #nosec continue } else { return err } } metering.RecordLogin("token", user.ID) return sendJSON(w, http.StatusOK, newTokenResponse) } return apierrors.NewConflictError("Too many concurrent token refresh requests on the same session or refresh token") }
RefreshTokenGrant implements the refresh_token grant type flow
RefreshTokenGrant
go
supabase/auth
internal/api/token_refresh.go
https://github.com/supabase/auth/blob/master/internal/api/token_refresh.go
MIT
func (a *API) Verify(w http.ResponseWriter, r *http.Request) error { params := &VerifyParams{} switch r.Method { case http.MethodGet: params.Token = r.FormValue("token") params.Type = r.FormValue("type") params.RedirectTo = utilities.GetReferrer(r, a.config) if err := params.Validate(r, a); err != nil { return err } return a.verifyGet(w, r, params) case http.MethodPost: if err := retrieveRequestParams(r, params); err != nil { return err } if err := params.Validate(r, a); err != nil { return err } return a.verifyPost(w, r, params) default: // this should have been handled by Chi panic("Only GET and POST methods allowed") } }
Verify exchanges a confirmation or recovery token to a refresh token
Verify
go
supabase/auth
internal/api/verify.go
https://github.com/supabase/auth/blob/master/internal/api/verify.go
MIT
func (a *API) verifyUserAndToken(conn *storage.Connection, params *VerifyParams, aud string) (*models.User, error) { config := a.config var user *models.User var err error tokenHash := params.TokenHash switch params.Type { case phoneChangeVerification: user, err = models.FindUserByPhoneChangeAndAudience(conn, params.Phone, aud) case smsVerification: user, err = models.FindUserByPhoneAndAudience(conn, params.Phone, aud) case mail.EmailChangeVerification: // Since the email change could be trigger via the implicit or PKCE flow, // the query used has to also check if the token saved in the db contains the pkce_ prefix user, err = models.FindUserForEmailChange(conn, params.Email, tokenHash, aud, config.Mailer.SecureEmailChangeEnabled) default: user, err = models.FindUserByEmailAndAudience(conn, params.Email, aud) } if err != nil { if models.IsNotFoundError(err) { return nil, apierrors.NewForbiddenError(apierrors.ErrorCodeOTPExpired, "Token has expired or is invalid").WithInternalError(err) } return nil, apierrors.NewInternalServerError("Database error finding user").WithInternalError(err) } if user.IsBanned() { return nil, apierrors.NewForbiddenError(apierrors.ErrorCodeUserBanned, "User is banned") } var isValid bool smsProvider, _ := sms_provider.GetSmsProvider(*config) switch params.Type { case mail.EmailOTPVerification: // if the type is emailOTPVerification, we'll check both the confirmation_token and recovery_token columns if isOtpValid(tokenHash, user.ConfirmationToken, user.ConfirmationSentAt, config.Mailer.OtpExp) { isValid = true params.Type = mail.SignupVerification } else if isOtpValid(tokenHash, user.RecoveryToken, user.RecoverySentAt, config.Mailer.OtpExp) { isValid = true params.Type = mail.MagicLinkVerification } else { isValid = false } case mail.SignupVerification, mail.InviteVerification: isValid = isOtpValid(tokenHash, user.ConfirmationToken, user.ConfirmationSentAt, config.Mailer.OtpExp) case mail.RecoveryVerification, mail.MagicLinkVerification: isValid = isOtpValid(tokenHash, user.RecoveryToken, user.RecoverySentAt, config.Mailer.OtpExp) case mail.EmailChangeVerification: isValid = isOtpValid(tokenHash, user.EmailChangeTokenCurrent, user.EmailChangeSentAt, config.Mailer.OtpExp) || isOtpValid(tokenHash, user.EmailChangeTokenNew, user.EmailChangeSentAt, config.Mailer.OtpExp) case phoneChangeVerification, smsVerification: if testOTP, ok := config.Sms.GetTestOTP(params.Phone, time.Now()); ok { if params.Token == testOTP { return user, nil } } phone := params.Phone sentAt := user.ConfirmationSentAt expectedToken := user.ConfirmationToken if params.Type == phoneChangeVerification { phone = user.PhoneChange sentAt = user.PhoneChangeSentAt expectedToken = user.PhoneChangeToken } if !config.Hook.SendSMS.Enabled && config.Sms.IsTwilioVerifyProvider() { if err := smsProvider.(*sms_provider.TwilioVerifyProvider).VerifyOTP(phone, params.Token); err != nil { return nil, apierrors.NewForbiddenError(apierrors.ErrorCodeOTPExpired, "Token has expired or is invalid").WithInternalError(err) } return user, nil } isValid = isOtpValid(tokenHash, expectedToken, sentAt, config.Sms.OtpExp) } if !isValid { return nil, apierrors.NewForbiddenError(apierrors.ErrorCodeOTPExpired, "Token has expired or is invalid").WithInternalMessage("token has expired or is invalid") } return user, nil }
verifyUserAndToken verifies the token associated to the user based on the verify type
verifyUserAndToken
go
supabase/auth
internal/api/verify.go
https://github.com/supabase/auth/blob/master/internal/api/verify.go
MIT
func isOtpValid(actual, expected string, sentAt *time.Time, otpExp uint) bool { if expected == "" || sentAt == nil { return false } return !isOtpExpired(sentAt, otpExp) && ((actual == expected) || ("pkce_"+actual == expected)) }
isOtpValid checks the actual otp sent against the expected otp and ensures that it's within the valid window
isOtpValid
go
supabase/auth
internal/api/verify.go
https://github.com/supabase/auth/blob/master/internal/api/verify.go
MIT
func isPhoneOtpVerification(params *VerifyParams) bool { return params.Phone != "" && params.Email == "" }
isPhoneOtpVerification checks if the verification came from a phone otp
isPhoneOtpVerification
go
supabase/auth
internal/api/verify.go
https://github.com/supabase/auth/blob/master/internal/api/verify.go
MIT
func isEmailOtpVerification(params *VerifyParams) bool { return params.Phone == "" && params.Email != "" }
isEmailOtpVerification checks if the verification came from an email otp
isEmailOtpVerification
go
supabase/auth
internal/api/verify.go
https://github.com/supabase/auth/blob/master/internal/api/verify.go
MIT
func (e *OAuthError) WithInternalError(err error) *OAuthError { e.InternalError = err return e }
WithInternalError adds internal error information to the error
WithInternalError
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (e *OAuthError) WithInternalMessage(fmtString string, args ...any) *OAuthError { e.InternalMessage = fmt.Sprintf(fmtString, args...) return e }
WithInternalMessage adds internal message information to the error
WithInternalMessage
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (e *OAuthError) Cause() error { if e.InternalError != nil { return e.InternalError } return e }
Cause returns the root cause error
Cause
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (e *HTTPError) Cause() error { if e.InternalError != nil { return e.InternalError } return e }
Cause returns the root cause error
Cause
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (e *HTTPError) WithInternalError(err error) *HTTPError { e.InternalError = err return e }
WithInternalError adds internal error information to the error
WithInternalError
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (e *HTTPError) WithInternalMessage(fmtString string, args ...any) *HTTPError { e.InternalMessage = fmt.Sprintf(fmtString, args...) return e }
WithInternalMessage adds internal message information to the error
WithInternalMessage
go
supabase/auth
internal/api/apierrors/apierrors.go
https://github.com/supabase/auth/blob/master/internal/api/apierrors/apierrors.go
MIT
func (b *IsPrivateEmail) UnmarshalJSON(data []byte) error { var boolVal bool if err := json.Unmarshal(data, &boolVal); err == nil { *b = IsPrivateEmail(boolVal) return nil } // ignore the error and try to unmarshal as a string var strVal string if err := json.Unmarshal(data, &strVal); err != nil { return err } var err error boolVal, err = strconv.ParseBool(strVal) if err != nil { return err } *b = IsPrivateEmail(boolVal) return nil }
Apple returns an is_private_email field that could be a string or boolean value so we need to implement a custom unmarshaler https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple
UnmarshalJSON
go
supabase/auth
internal/api/provider/apple.go
https://github.com/supabase/auth/blob/master/internal/api/provider/apple.go
MIT
func (p AppleProvider) GetOAuthToken(code string) (*oauth2.Token, error) { opts := []oauth2.AuthCodeOption{ oauth2.SetAuthURLParam("client_id", p.ClientID), oauth2.SetAuthURLParam("secret", p.ClientSecret), } return p.Exchange(context.Background(), code, opts...) }
GetOAuthToken returns the apple provider access token
GetOAuthToken
go
supabase/auth
internal/api/provider/apple.go
https://github.com/supabase/auth/blob/master/internal/api/provider/apple.go
MIT
func (p AppleProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) { idToken := tok.Extra("id_token") if tok.AccessToken == "" || idToken == nil { // Apple returns user data only the first time return &UserProvidedData{}, nil } _, data, err := ParseIDToken(ctx, p.oidc, &oidc.Config{ ClientID: p.ClientID, SkipIssuerCheck: true, }, idToken.(string), ParseIDTokenOptions{ AccessToken: tok.AccessToken, }) if err != nil { return nil, err } return data, nil }
GetUserData returns the user data fetched from the apple provider
GetUserData
go
supabase/auth
internal/api/provider/apple.go
https://github.com/supabase/auth/blob/master/internal/api/provider/apple.go
MIT
func (p AppleProvider) ParseUser(data string, userData *UserProvidedData) error { u := &appleUser{} err := json.Unmarshal([]byte(data), u) if err != nil { return err } userData.Metadata.Name = strings.TrimSpace(u.Name.FirstName + " " + u.Name.LastName) userData.Metadata.FullName = strings.TrimSpace(u.Name.FirstName + " " + u.Name.LastName) return nil }
ParseUser parses the apple user's info
ParseUser
go
supabase/auth
internal/api/provider/apple.go
https://github.com/supabase/auth/blob/master/internal/api/provider/apple.go
MIT
func (e *HTTPError) Cause() error { if e.InternalError != nil { return e.InternalError } return e }
Cause returns the root cause error
Cause
go
supabase/auth
internal/api/provider/errors.go
https://github.com/supabase/auth/blob/master/internal/api/provider/errors.go
MIT
func (e *HTTPError) WithInternalError(err error) *HTTPError { e.InternalError = err return e }
WithInternalError adds internal error information to the error
WithInternalError
go
supabase/auth
internal/api/provider/errors.go
https://github.com/supabase/auth/blob/master/internal/api/provider/errors.go
MIT
func (e *HTTPError) WithInternalMessage(fmtString string, args ...interface{}) *HTTPError { e.InternalMessage = fmt.Sprintf(fmtString, args...) return e }
WithInternalMessage adds internal message information to the error
WithInternalMessage
go
supabase/auth
internal/api/provider/errors.go
https://github.com/supabase/auth/blob/master/internal/api/provider/errors.go
MIT
func ResetGoogleProvider() { internalIssuerGoogle = IssuerGoogle internalUserInfoEndpointGoogle = UserInfoEndpointGoogle }
ResetGoogleProvider should only be used in tests!
ResetGoogleProvider
go
supabase/auth
internal/api/provider/google.go
https://github.com/supabase/auth/blob/master/internal/api/provider/google.go
MIT
func OverrideGoogleProvider(issuer, userInfo string) { internalIssuerGoogle = issuer internalUserInfoEndpointGoogle = userInfo }
OverrideGoogleProvider should only be used in tests!
OverrideGoogleProvider
go
supabase/auth
internal/api/provider/google.go
https://github.com/supabase/auth/blob/master/internal/api/provider/google.go
MIT
func NewLinkedinOIDCProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { if err := ext.ValidateOAuth(); err != nil { return nil, err } apiPath := chooseHost(ext.URL, defaultLinkedinOIDCAPIBase) oauthScopes := []string{ "openid", "email", "profile", } if scopes != "" { oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) } oidcProvider, err := oidc.NewProvider(context.Background(), IssuerLinkedin) if err != nil { return nil, err } return &linkedinOIDCProvider{ oidc: oidcProvider, Config: &oauth2.Config{ ClientID: ext.ClientID[0], ClientSecret: ext.Secret, Endpoint: oauth2.Endpoint{ AuthURL: apiPath + "/oauth/v2/authorization", TokenURL: apiPath + "/oauth/v2/accessToken", }, Scopes: oauthScopes, RedirectURL: ext.RedirectURI, }, APIPath: apiPath, }, nil }
NewLinkedinOIDCProvider creates a Linkedin account provider via OIDC.
NewLinkedinOIDCProvider
go
supabase/auth
internal/api/provider/linkedin_oidc.go
https://github.com/supabase/auth/blob/master/internal/api/provider/linkedin_oidc.go
MIT
func NewSlackProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { if err := ext.ValidateOAuth(); err != nil { return nil, err } apiPath := chooseHost(ext.URL, defaultSlackApiBase) + "/api" authPath := chooseHost(ext.URL, defaultSlackApiBase) + "/oauth" oauthScopes := []string{ "profile", "email", "openid", } if scopes != "" { oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) } return &slackProvider{ Config: &oauth2.Config{ ClientID: ext.ClientID[0], ClientSecret: ext.Secret, Endpoint: oauth2.Endpoint{ AuthURL: authPath + "/authorize", TokenURL: apiPath + "/oauth.access", }, Scopes: oauthScopes, RedirectURL: ext.RedirectURI, }, APIPath: apiPath, }, nil }
NewSlackProvider creates a Slack account provider with Legacy Slack OAuth.
NewSlackProvider
go
supabase/auth
internal/api/provider/slack.go
https://github.com/supabase/auth/blob/master/internal/api/provider/slack.go
MIT
func NewSlackOIDCProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { if err := ext.ValidateOAuth(); err != nil { return nil, err } apiPath := chooseHost(ext.URL, defaultSlackOIDCApiBase) + "/api" authPath := chooseHost(ext.URL, defaultSlackOIDCApiBase) + "/openid" // these are required scopes for slack's OIDC flow // see https://api.slack.com/authentication/sign-in-with-slack#implementation oauthScopes := []string{ "profile", "email", "openid", } if scopes != "" { oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) } return &slackOIDCProvider{ Config: &oauth2.Config{ ClientID: ext.ClientID[0], ClientSecret: ext.Secret, Endpoint: oauth2.Endpoint{ AuthURL: authPath + "/connect/authorize", TokenURL: apiPath + "/openid.connect.token", }, Scopes: oauthScopes, RedirectURL: ext.RedirectURI, }, APIPath: apiPath, }, nil }
NewSlackOIDCProvider creates a Slack account provider with Sign in with Slack.
NewSlackOIDCProvider
go
supabase/auth
internal/api/provider/slack_oidc.go
https://github.com/supabase/auth/blob/master/internal/api/provider/slack_oidc.go
MIT
func (t TwitterProvider) GetOAuthToken(_ string) (*oauth2.Token, error) { return &oauth2.Token{}, nil }
GetOAuthToken is a stub method for OAuthProvider interface, unused in OAuth1.0 protocol
GetOAuthToken
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func (t TwitterProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) { return &UserProvidedData{}, nil }
GetUserData is a stub method for OAuthProvider interface, unused in OAuth1.0 protocol
GetUserData
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func (t TwitterProvider) FetchUserData(ctx context.Context, tok *oauth.AccessToken) (*UserProvidedData, error) { var u twitterUser resp, err := t.Consumer.Get( t.UserInfoURL, map[string]string{"include_entities": "false", "skip_status": "true", "include_email": "true"}, tok, ) if err != nil { return nil, err } defer utilities.SafeClose(resp.Body) if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { return &UserProvidedData{}, fmt.Errorf("a %v error occurred with retrieving user from twitter", resp.StatusCode) } bits, err := io.ReadAll(resp.Body) if err != nil { return nil, err } _ = json.NewDecoder(bytes.NewReader(bits)).Decode(&u) data := &UserProvidedData{} if u.Email != "" { data.Emails = []Email{{ Email: u.Email, Verified: true, Primary: true, }} } data.Metadata = &Claims{ Issuer: t.UserInfoURL, Subject: u.ID, Name: u.Name, Picture: u.AvatarURL, PreferredUsername: u.UserName, // To be deprecated UserNameKey: u.UserName, FullName: u.Name, AvatarURL: u.AvatarURL, ProviderId: u.ID, } return data, nil }
FetchUserData retrieves the user's data from the twitter provider
FetchUserData
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func (t *TwitterProvider) AuthCodeURL(state string, args ...oauth2.AuthCodeOption) string { // we do nothing with the state here as the state is passed in the requestURL step requestToken, url, err := t.Consumer.GetRequestTokenAndUrl(t.CallbackURL + "?state=" + state) if err != nil { return "" } t.RequestToken = requestToken t.AuthURL = url return t.AuthURL }
AuthCodeURL fetches the request token from the twitter provider
AuthCodeURL
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func (t TwitterProvider) Marshal() string { b, _ := json.Marshal(t.RequestToken) return string(b) }
Marshal encodes the twitter request token
Marshal
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func (t TwitterProvider) Unmarshal(data string) (*oauth.RequestToken, error) { requestToken := &oauth.RequestToken{} err := json.NewDecoder(strings.NewReader(data)).Decode(requestToken) return requestToken, err }
Unmarshal decodes the twitter request token
Unmarshal
go
supabase/auth
internal/api/provider/twitter.go
https://github.com/supabase/auth/blob/master/internal/api/provider/twitter.go
MIT
func NewVercelMarketplaceProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { if err := ext.ValidateOAuth(); err != nil { return nil, err } apiPath := chooseHost(ext.URL, defaultVercelMarketplaceAPIBase) oauthScopes := []string{} if scopes != "" { oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) } oidcProvider, err := oidc.NewProvider(context.Background(), IssuerVercelMarketplace) if err != nil { return nil, err } return &vercelMarketplaceProvider{ oidc: oidcProvider, Config: &oauth2.Config{ ClientID: ext.ClientID[0], ClientSecret: ext.Secret, Endpoint: oauth2.Endpoint{ AuthURL: apiPath + "/oauth/v2/authorization", TokenURL: apiPath + "/oauth/v2/accessToken", }, Scopes: oauthScopes, RedirectURL: ext.RedirectURI, }, APIPath: apiPath, }, nil }
NewVercelMarketplaceProvider creates a VercelMarketplace account provider via OIDC.
NewVercelMarketplaceProvider
go
supabase/auth
internal/api/provider/vercel_marketplace.go
https://github.com/supabase/auth/blob/master/internal/api/provider/vercel_marketplace.go
MIT
func NewMessagebirdProvider(config conf.MessagebirdProviderConfiguration) (SmsProvider, error) { if err := config.Validate(); err != nil { return nil, err } apiPath := defaultMessagebirdApiBase + "/messages" return &MessagebirdProvider{ Config: &config, APIPath: apiPath, }, nil }
Creates a SmsProvider with the Messagebird Config
NewMessagebirdProvider
go
supabase/auth
internal/api/sms_provider/messagebird.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/messagebird.go
MIT
func (t *MessagebirdProvider) SendSms(phone string, message string) (string, error) { body := url.Values{ "originator": {t.Config.Originator}, "body": {message}, "recipients": {phone}, "type": {"sms"}, "datacoding": {"unicode"}, } client := &http.Client{Timeout: defaultTimeout} r, err := http.NewRequest("POST", t.APIPath, strings.NewReader(body.Encode())) if err != nil { return "", err } r.Header.Add("Content-Type", "application/x-www-form-urlencoded") r.Header.Add("Authorization", "AccessKey "+t.Config.AccessKey) res, err := client.Do(r) if err != nil { return "", err } if res.StatusCode == http.StatusBadRequest || res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusUnprocessableEntity { resp := &MessagebirdErrResponse{} if err := json.NewDecoder(res.Body).Decode(resp); err != nil { return "", err } return "", resp } defer utilities.SafeClose(res.Body) // validate sms status resp := &MessagebirdResponse{} derr := json.NewDecoder(res.Body).Decode(resp) if derr != nil { return "", derr } if resp.Recipients.TotalSentCount == 0 { return "", fmt.Errorf("messagebird error: total sent count is 0") } return resp.ID, nil }
Send an SMS containing the OTP with Messagebird's API
SendSms
go
supabase/auth
internal/api/sms_provider/messagebird.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/messagebird.go
MIT
func NewTextlocalProvider(config conf.TextlocalProviderConfiguration) (SmsProvider, error) { if err := config.Validate(); err != nil { return nil, err } apiPath := defaultTextLocalApiBase + "/send" return &TextlocalProvider{ Config: &config, APIPath: apiPath, }, nil }
Creates a SmsProvider with the Textlocal Config
NewTextlocalProvider
go
supabase/auth
internal/api/sms_provider/textlocal.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/textlocal.go
MIT
func (t *TextlocalProvider) SendSms(phone string, message string) (string, error) { body := url.Values{ "sender": {t.Config.Sender}, "apikey": {t.Config.ApiKey}, "message": {message}, "numbers": {phone}, } client := &http.Client{Timeout: defaultTimeout} r, err := http.NewRequest("POST", t.APIPath, strings.NewReader(body.Encode())) if err != nil { return "", err } r.Header.Add("Content-Type", "application/x-www-form-urlencoded") res, err := client.Do(r) if err != nil { return "", err } defer utilities.SafeClose(res.Body) resp := &TextlocalResponse{} derr := json.NewDecoder(res.Body).Decode(resp) if derr != nil { return "", derr } messageID := "" if resp.Status != "success" { if len(resp.Messages) > 0 { messageID = resp.Messages[0].MessageID } if len(resp.Errors) > 0 && resp.Errors[0].Code == textLocalTemplateErrorCode { return messageID, fmt.Errorf("textlocal error: %v (code: %v) template message: %s", resp.Errors[0].Message, resp.Errors[0].Code, message) } return messageID, fmt.Errorf("textlocal error: %v (code: %v) message %s", resp.Errors[0].Message, resp.Errors[0].Code, messageID) } return messageID, nil }
Send an SMS containing the OTP with Textlocal's API
SendSms
go
supabase/auth
internal/api/sms_provider/textlocal.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/textlocal.go
MIT
func formatPhoneNumber(phone string) string { return strings.ReplaceAll(strings.TrimPrefix(phone, "+"), " ", "") }
formatPhoneNumber removes "+" and whitespaces in a phone number
formatPhoneNumber
go
supabase/auth
internal/api/sms_provider/twilio.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/twilio.go
MIT
func NewTwilioProvider(config conf.TwilioProviderConfiguration) (SmsProvider, error) { if err := config.Validate(); err != nil { return nil, err } apiPath := defaultTwilioApiBase + "/" + apiVersion + "/" + "Accounts" + "/" + config.AccountSid + "/Messages.json" return &TwilioProvider{ Config: &config, APIPath: apiPath, }, nil }
Creates a SmsProvider with the Twilio Config
NewTwilioProvider
go
supabase/auth
internal/api/sms_provider/twilio.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/twilio.go
MIT
func (t *TwilioProvider) SendSms(phone, message, channel, otp string) (string, error) { sender := t.Config.MessageServiceSid receiver := "+" + phone body := url.Values{ "To": {receiver}, // twilio api requires "+" extension to be included "Channel": {channel}, "From": {sender}, "Body": {message}, } if channel == WhatsappProvider { receiver = channel + ":" + receiver if isPhoneNumber.MatchString(formatPhoneNumber(sender)) { sender = channel + ":" + sender } // Programmable Messaging (WhatsApp) takes in different set of inputs body = url.Values{ "To": {receiver}, // twilio api requires "+" extension to be included "Channel": {channel}, "From": {sender}, } // For backward compatibility with old API. if t.Config.ContentSid != "" { // Used to substitute OTP. See https://www.twilio.com/docs/content/whatsappauthentication for more details contentVariables := fmt.Sprintf(`{"1": "%s"}`, otp) body.Set("ContentSid", t.Config.ContentSid) body.Set("ContentVariables", contentVariables) } else { body.Set("Body", message) } } client := &http.Client{Timeout: defaultTimeout} r, err := http.NewRequest("POST", t.APIPath, strings.NewReader(body.Encode())) if err != nil { return "", err } r.Header.Add("Content-Type", "application/x-www-form-urlencoded") r.SetBasicAuth(t.Config.AccountSid, t.Config.AuthToken) res, err := client.Do(r) if err != nil { return "", err } defer utilities.SafeClose(res.Body) if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { resp := &twilioErrResponse{} if err := json.NewDecoder(res.Body).Decode(resp); err != nil { return "", err } return "", resp } // validate sms status resp := &SmsStatus{} derr := json.NewDecoder(res.Body).Decode(resp) if derr != nil { return "", derr } if resp.Status == "failed" || resp.Status == "undelivered" { return resp.MessageSID, fmt.Errorf("twilio error: %v %v for message %s", resp.ErrorMessage, resp.ErrorCode, resp.MessageSID) } return resp.MessageSID, nil }
Send an SMS containing the OTP with Twilio's API
SendSms
go
supabase/auth
internal/api/sms_provider/twilio.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/twilio.go
MIT
func NewTwilioVerifyProvider(config conf.TwilioVerifyProviderConfiguration) (SmsProvider, error) { if err := config.Validate(); err != nil { return nil, err } apiPath := verifyServiceApiBase + config.MessageServiceSid + "/Verifications" return &TwilioVerifyProvider{ Config: &config, APIPath: apiPath, }, nil }
Creates a SmsProvider with the Twilio Config
NewTwilioVerifyProvider
go
supabase/auth
internal/api/sms_provider/twilio_verify.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/twilio_verify.go
MIT
func (t *TwilioVerifyProvider) SendSms(phone, message, channel string) (string, error) { // Unlike Programmable Messaging, Verify does not require a prefix for channel receiver := "+" + phone body := url.Values{ "To": {receiver}, "Channel": {channel}, } client := &http.Client{Timeout: defaultTimeout} r, err := http.NewRequest("POST", t.APIPath, strings.NewReader(body.Encode())) if err != nil { return "", err } r.Header.Add("Content-Type", "application/x-www-form-urlencoded") r.SetBasicAuth(t.Config.AccountSid, t.Config.AuthToken) res, err := client.Do(r) if err != nil { return "", err } defer utilities.SafeClose(res.Body) if !(res.StatusCode == http.StatusOK || res.StatusCode == http.StatusCreated) { resp := &twilioErrResponse{} if err := json.NewDecoder(res.Body).Decode(resp); err != nil { return "", err } return "", resp } resp := &VerificationResponse{} derr := json.NewDecoder(res.Body).Decode(resp) if derr != nil { return "", derr } return resp.VerificationSID, nil }
Send an SMS containing the OTP with Twilio's API
SendSms
go
supabase/auth
internal/api/sms_provider/twilio_verify.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/twilio_verify.go
MIT
func NewVonageProvider(config conf.VonageProviderConfiguration) (SmsProvider, error) { if err := config.Validate(); err != nil { return nil, err } apiPath := defaultVonageApiBase + "/sms/json" return &VonageProvider{ Config: &config, APIPath: apiPath, }, nil }
Creates a SmsProvider with the Vonage Config
NewVonageProvider
go
supabase/auth
internal/api/sms_provider/vonage.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/vonage.go
MIT
func (t *VonageProvider) SendSms(phone string, message string) (string, error) { body := url.Values{ "from": {t.Config.From}, "to": {phone}, "text": {message}, "api_key": {t.Config.ApiKey}, "api_secret": {t.Config.ApiSecret}, } isMessageContainUnicode := !utf8string.NewString(message).IsASCII() if isMessageContainUnicode { body.Set("type", "unicode") } client := &http.Client{Timeout: defaultTimeout} r, err := http.NewRequest("POST", t.APIPath, strings.NewReader(body.Encode())) if err != nil { return "", err } r.Header.Add("Content-Type", "application/x-www-form-urlencoded") res, err := client.Do(r) if err != nil { return "", err } defer utilities.SafeClose(res.Body) resp := &VonageResponse{} derr := json.NewDecoder(res.Body).Decode(resp) if derr != nil { return "", derr } if len(resp.Messages) <= 0 { return "", errors.New("vonage error: Internal Error") } // A status of zero indicates success; a non-zero value means something went wrong. if resp.Messages[0].Status != "0" { return resp.Messages[0].MessageID, fmt.Errorf("vonage error: %v (status: %v) for message %s", resp.Messages[0].ErrorText, resp.Messages[0].Status, resp.Messages[0].MessageID) } return resp.Messages[0].MessageID, nil }
Send an SMS containing the OTP with Vonage's API
SendSms
go
supabase/auth
internal/api/sms_provider/vonage.go
https://github.com/supabase/auth/blob/master/internal/api/sms_provider/vonage.go
MIT
func LoadFile(filename string) error { var err error if filename != "" { err = godotenv.Overload(filename) } else { err = godotenv.Load() // handle if .env file does not exist, this is OK if os.IsNotExist(err) { return nil } } return err }
LoadFile calls godotenv.Load() when the given filename is empty ignoring any errors loading, otherwise it calls godotenv.Overload(filename). godotenv.Load: preserves env, ".env" path is optional godotenv.Overload: overrides env, "filename" path must exist
LoadFile
go
supabase/auth
internal/conf/configuration.go
https://github.com/supabase/auth/blob/master/internal/conf/configuration.go
MIT
func LoadDirectory(configDir string) error { if configDir == "" { return nil } // Returns entries sorted by filename ents, err := os.ReadDir(configDir) if err != nil { // We mimic the behavior of LoadGlobal here, if an explicit path is // provided we return an error. return err } var paths []string for _, ent := range ents { if ent.IsDir() { continue // ignore directories } // We only read files ending in .env name := ent.Name() if !strings.HasSuffix(name, ".env") { continue } // ent.Name() does not include the watch dir. paths = append(paths, filepath.Join(configDir, name)) } // If at least one path was found we load the configuration files in the // directory. We don't call override without config files because it will // override the env vars previously set with a ".env", if one exists. return loadDirectoryPaths(paths...) }
LoadDirectory does nothing when configDir is empty, otherwise it will attempt to load a list of configuration files located in configDir by using ReadDir to obtain a sorted list of files containing a .env suffix. When the list is empty it will do nothing, otherwise it passes the file list to godotenv.Overload to pull them into the current environment.
LoadDirectory
go
supabase/auth
internal/conf/configuration.go
https://github.com/supabase/auth/blob/master/internal/conf/configuration.go
MIT
func LoadGlobalFromEnv() (*GlobalConfiguration, error) { config := new(GlobalConfiguration) if err := loadGlobal(config); err != nil { return nil, err } return config, nil }
LoadGlobalFromEnv will return a new *GlobalConfiguration value from the currently configured environment.
LoadGlobalFromEnv
go
supabase/auth
internal/conf/configuration.go
https://github.com/supabase/auth/blob/master/internal/conf/configuration.go
MIT
func (r *Rate) Decode(value string) error { if f, err := strconv.ParseFloat(value, 64); err == nil { r.typ = IntervalRateType r.Events = f r.OverTime = defaultOverTime return nil } parts := strings.Split(value, "/") if len(parts) != 2 { return fmt.Errorf("rate: value does not match rate syntax %q", value) } // 52 because the uint needs to fit in a float64 e, err := strconv.ParseUint(parts[0], 10, 52) if err != nil { return fmt.Errorf("rate: events part of rate value %q failed to parse as uint64: %w", value, err) } d, err := time.ParseDuration(parts[1]) if err != nil { return fmt.Errorf("rate: over-time part of rate value %q failed to parse as duration: %w", value, err) } r.typ = BurstRateType r.Events = float64(e) r.OverTime = d return nil }
Decode is used by envconfig to parse the env-config string to a Rate value.
Decode
go
supabase/auth
internal/conf/rate.go
https://github.com/supabase/auth/blob/master/internal/conf/rate.go
MIT
func (c *SAMLConfiguration) PopulateFields(externalURL string) error { // errors are intentionally ignored since they should have been handled // within #Validate() bytes, err := base64.StdEncoding.DecodeString(c.PrivateKey) if err != nil { return fmt.Errorf("saml: PopulateFields: invalid base64: %w", err) } privateKey, err := x509.ParsePKCS1PrivateKey(bytes) if err != nil { return fmt.Errorf("saml: PopulateFields: invalid private key: %w", err) } c.RSAPrivateKey = privateKey c.RSAPublicKey = privateKey.Public().(*rsa.PublicKey) parsedURL, err := url.ParseRequestURI(externalURL) if err != nil { return fmt.Errorf("saml: unable to parse external URL for SAML, check API_EXTERNAL_URL: %w", err) } host := "" host, _, err = net.SplitHostPort(parsedURL.Host) if err != nil { host = parsedURL.Host } // SAML does not care much about the contents of the certificate, it // only uses it as a vessel for the public key; therefore we set these // fixed values. // Please avoid modifying or adding new values to this template as they // will change the exposed SAML certificate, requiring users of // GoTrue to re-establish a connection between their Identity Provider // and their running GoTrue instances. certTemplate := &x509.Certificate{ SerialNumber: big.NewInt(0), IsCA: false, DNSNames: []string{ "_samlsp." + host, }, KeyUsage: x509.KeyUsageDigitalSignature, NotBefore: time.UnixMilli(0).UTC(), NotAfter: time.UnixMilli(0).UTC().AddDate(200, 0, 0), Subject: pkix.Name{ CommonName: "SAML 2.0 Certificate for " + host, }, } if c.AllowEncryptedAssertions { certTemplate.KeyUsage = certTemplate.KeyUsage | x509.KeyUsageDataEncipherment } return c.createCertificate(certTemplate) }
PopulateFields fills the configuration details based off the provided parameters.
PopulateFields
go
supabase/auth
internal/conf/saml.go
https://github.com/supabase/auth/blob/master/internal/conf/saml.go
MIT
func secureRandomInt(max int) int { randomInt := must(rand.Int(rand.Reader, big.NewInt(int64(max)))) return int(randomInt.Int64()) }
Generated a random secure integer from [0, max[
secureRandomInt
go
supabase/auth
internal/crypto/crypto.go
https://github.com/supabase/auth/blob/master/internal/crypto/crypto.go
MIT
func (es *EncryptedString) ShouldReEncrypt(encryptionKeyID string) bool { return es.KeyID != encryptionKeyID }
ShouldReEncrypt tells you if the value encrypted needs to be encrypted again with a newer key.
ShouldReEncrypt
go
supabase/auth
internal/crypto/crypto.go
https://github.com/supabase/auth/blob/master/internal/crypto/crypto.go
MIT
func SecureAlphanumeric(length int) string { if length < 8 { length = 8 } // Calculate bytes needed for desired length // base32 encoding: 5 bytes -> 8 chars numBytes := (length*5 + 7) / 8 b := make([]byte, numBytes) must(io.ReadFull(rand.Reader, b)) // Use standard library's base32 without padding return strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b))[:length] }
SecureAlphanumeric generates a secure random alphanumeric string using standard library
SecureAlphanumeric
go
supabase/auth
internal/crypto/crypto.go
https://github.com/supabase/auth/blob/master/internal/crypto/crypto.go
MIT
func ParseFirebaseScryptHash(hash string) (*FirebaseScryptHashInput, error) { submatch := fbscryptHashRegexp.FindStringSubmatchIndex(hash) if submatch == nil { return nil, errors.New("crypto: incorrect scrypt hash format") } v := string(fbscryptHashRegexp.ExpandString(nil, "$v", hash, submatch)) n := string(fbscryptHashRegexp.ExpandString(nil, "$n", hash, submatch)) r := string(fbscryptHashRegexp.ExpandString(nil, "$r", hash, submatch)) p := string(fbscryptHashRegexp.ExpandString(nil, "$p", hash, submatch)) ss := string(fbscryptHashRegexp.ExpandString(nil, "$ss", hash, submatch)) sk := string(fbscryptHashRegexp.ExpandString(nil, "$sk", hash, submatch)) saltB64 := string(fbscryptHashRegexp.ExpandString(nil, "$salt", hash, submatch)) hashB64 := string(fbscryptHashRegexp.ExpandString(nil, "$hash", hash, submatch)) if v != "1" { return nil, fmt.Errorf("crypto: Firebase scrypt hash uses unsupported version %q only version 1 is supported", v) } memoryPower, err := strconv.ParseUint(n, 10, 32) if err != nil { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid n parameter %q %w", n, err) } if memoryPower == 0 { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid n=0") } rounds, err := strconv.ParseUint(r, 10, 64) if err != nil { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid r parameter %q: %w", r, err) } if rounds == 0 { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid r=0") } threads, err := strconv.ParseUint(p, 10, 8) if err != nil { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid p parameter %q %w", p, err) } if threads == 0 { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid p=0") } rawHash, err := base64.StdEncoding.DecodeString(hashB64) if err != nil { return nil, fmt.Errorf("crypto: Firebase scrypt hash has invalid base64 in the hash section %w", err) } salt, err := base64.StdEncoding.DecodeString(saltB64) if err != nil { return nil, fmt.Errorf("crypto: Firebase scrypt salt has invalid base64 in the hash section %w", err) } var saltSeparator, signerKey []byte if signerKey, err = base64.StdEncoding.DecodeString(sk); err != nil { return nil, err } if saltSeparator, err = base64.StdEncoding.DecodeString(ss); err != nil { return nil, err } input := &FirebaseScryptHashInput{ v: v, memory: uint64(1) << memoryPower, rounds: rounds, threads: threads, salt: salt, rawHash: rawHash, saltSeparator: saltSeparator, signerKey: signerKey, } return input, nil }
See: https://github.com/firebase/scrypt for implementation
ParseFirebaseScryptHash
go
supabase/auth
internal/crypto/password.go
https://github.com/supabase/auth/blob/master/internal/crypto/password.go
MIT
func CompareHashAndPassword(ctx context.Context, hash, password string) error { if strings.HasPrefix(hash, Argon2Prefix) { return compareHashAndPasswordArgon2(ctx, hash, password) } else if strings.HasPrefix(hash, FirebaseScryptPrefix) { return compareHashAndPasswordFirebaseScrypt(ctx, hash, password) } // assume bcrypt hashCost, err := bcrypt.Cost([]byte(hash)) if err != nil { return err } attributes := []attribute.KeyValue{ attribute.String("alg", "bcrypt"), attribute.Int("bcrypt_cost", hashCost), } compareHashAndPasswordSubmittedCounter.Add(ctx, 1, metric.WithAttributes(attributes...)) defer func() { attributes = append(attributes, attribute.Bool( "match", !errors.Is(err, bcrypt.ErrMismatchedHashAndPassword), )) compareHashAndPasswordCompletedCounter.Add(ctx, 1, metric.WithAttributes(attributes...)) }() err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err }
CompareHashAndPassword compares the hash and password, returns nil if equal otherwise an error. Context can be used to cancel the hashing if the algorithm supports it.
CompareHashAndPassword
go
supabase/auth
internal/crypto/password.go
https://github.com/supabase/auth/blob/master/internal/crypto/password.go
MIT
func GenerateFromPassword(ctx context.Context, password string) (string, error) { hashCost := bcrypt.DefaultCost switch PasswordHashCost { case QuickHashCost: hashCost = bcrypt.MinCost } attributes := []attribute.KeyValue{ attribute.String("alg", "bcrypt"), attribute.Int("bcrypt_cost", hashCost), } generateFromPasswordSubmittedCounter.Add(ctx, 1, metric.WithAttributes(attributes...)) defer generateFromPasswordCompletedCounter.Add(ctx, 1, metric.WithAttributes(attributes...)) hash := must(bcrypt.GenerateFromPassword([]byte(password), hashCost)) return string(hash), nil }
GenerateFromPassword generates a password hash from a password, using PasswordHashCost. Context can be used to cancel the hashing if the algorithm supports it.
GenerateFromPassword
go
supabase/auth
internal/crypto/password.go
https://github.com/supabase/auth/blob/master/internal/crypto/password.go
MIT
func GetProjectRoot() string { return projectRoot }
GetProjectRoot returns the path to the root of the project. This may be used to locate files without needing the relative path from a given test.
GetProjectRoot
go
supabase/auth
internal/e2e/e2e.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2e.go
MIT
func GetConfigPath() string { return configPath }
GetConfigPath returns the path for the "/hack/test.env" config file.
GetConfigPath
go
supabase/auth
internal/e2e/e2e.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2e.go
MIT
func Config() (*conf.GlobalConfiguration, error) { globalCfg, err := conf.LoadGlobal(GetConfigPath()) if err != nil { return nil, err } return globalCfg, nil }
Config calls conf.LoadGlobal using GetConfigPath().
Config
go
supabase/auth
internal/e2e/e2e.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2e.go
MIT
func Conn(globalCfg *conf.GlobalConfiguration) (*storage.Connection, error) { conn, err := test.SetupDBConnection(globalCfg) if err != nil { return nil, err } return conn, nil }
Conn returns a connection for the given config.
Conn
go
supabase/auth
internal/e2e/e2e.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2e.go
MIT
func Must[T any](res T, err error) T { if err != nil { panic(err) } return res }
Must may be used by Config and Conn, i.e.: cfg := e2e.Must(e2e.Config()) conn := e2e.Must(e2e.Conn(cfg))
Must
go
supabase/auth
internal/e2e/e2e.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2e.go
MIT
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
RoundTrip implements http.RoundTripper by calling itself.
RoundTrip
go
supabase/auth
internal/e2e/e2eapi/e2eapi_test.go
https://github.com/supabase/auth/blob/master/internal/e2e/e2eapi/e2eapi_test.go
MIT
func (e *Error) As(target any) bool { switch T := target.(type) { case **Error: v := (*T) if v == nil { return false } v.HTTPCode = e.HTTPCode v.Message = e.Message return true case *Error: T.HTTPCode = e.HTTPCode T.Message = e.Message return true case **apierrors.HTTPError: v := (*T) if v == nil { return false } v.HTTPStatus = e.HTTPCode v.Message = e.Message return true case *apierrors.HTTPError: T.HTTPStatus = e.HTTPCode T.Message = e.Message return true default: return false } }
As implements the errors.As interface to allow unwrapping as either an Error or apierrors.HTTPError, depending on the needs of the caller.
As
go
supabase/auth
internal/hooks/hookserrors/hookserrors.go
https://github.com/supabase/auth/blob/master/internal/hooks/hookserrors/hookserrors.go
MIT
func Check(b []byte) error { e, ok := fromBytes(b) if !ok { return nil } return check(e) }
Check will attempt to extract a hook Error from a byte slice and return a non-nil error, otherwise Check returns nil if no error was found.
Check
go
supabase/auth
internal/hooks/hookserrors/hookserrors.go
https://github.com/supabase/auth/blob/master/internal/hooks/hookserrors/hookserrors.go
MIT
func (o *Manager) invokeHook( conn *storage.Connection, r *http.Request, input, output any, ) error { switch input.(type) { default: return apierrors.NewInternalServerError( "Unknown hook type %T.", input) case *SendSMSInput: if _, ok := output.(*SendSMSOutput); !ok { return apierrors.NewInternalServerError( "output should be *hooks.SendSMSOutput") } return o.dispatch( r.Context(), &o.config.Hook.SendSMS, conn, input, output) case *SendEmailInput: if _, ok := output.(*SendEmailOutput); !ok { return apierrors.NewInternalServerError( "output should be *hooks.SendEmailOutput") } return o.dispatch( r.Context(), &o.config.Hook.SendEmail, conn, input, output) case *MFAVerificationAttemptInput: if _, ok := output.(*MFAVerificationAttemptOutput); !ok { return apierrors.NewInternalServerError( "output should be *hooks.MFAVerificationAttemptOutput") } return o.dispatch( r.Context(), &o.config.Hook.MFAVerificationAttempt, conn, input, output) case *PasswordVerificationAttemptInput: if _, ok := output.(*PasswordVerificationAttemptOutput); !ok { return apierrors.NewInternalServerError( "output should be *hooks.PasswordVerificationAttemptOutput") } return o.dispatch( r.Context(), &o.config.Hook.PasswordVerificationAttempt, conn, input, output) case *CustomAccessTokenInput: _, ok := output.(*CustomAccessTokenOutput) if !ok { return apierrors.NewInternalServerError( "output should be *hooks.CustomAccessTokenOutput") } return o.dispatch( r.Context(), &o.config.Hook.CustomAccessToken, conn, input, output) case *BeforeUserCreatedInput: if _, ok := output.(*BeforeUserCreatedOutput); !ok { return apierrors.NewInternalServerError( "output should be *hooks.BeforeUserCreatedOutput") } return o.dispatch( r.Context(), &o.config.Hook.BeforeUserCreated, conn, input, output) case *AfterUserCreatedInput: _, ok := output.(*AfterUserCreatedOutput) if !ok { return apierrors.NewInternalServerError( "output should be *hooks.AfterUserCreatedOutput") } return o.dispatch( r.Context(), &o.config.Hook.AfterUserCreated, conn, input, output) } }
invokeHook invokes the hook code. conn can be nil, in which case a new transaction is opened. If calling invokeHook within a transaction, always pass the current transaction, as pool-exhaustion deadlocks are very easy to trigger.
invokeHook
go
supabase/auth
internal/hooks/v0hooks/manager.go
https://github.com/supabase/auth/blob/master/internal/hooks/v0hooks/manager.go
MIT
func (m *MailmeMailer) Mail( ctx context.Context, to, subjectTemplate, templateURL, defaultTemplate string, templateData map[string]interface{}, headers map[string][]string, typ string, ) error { if m.FuncMap == nil { m.FuncMap = map[string]interface{}{} } if m.cache == nil { m.cache = &TemplateCache{ templates: map[string]*MailTemplate{}, funcMap: m.FuncMap, logger: m.Logger, } } if m.EmailValidator != nil { if err := m.EmailValidator.Validate(ctx, to); err != nil { return err } } tmp, err := template.New("Subject").Funcs(template.FuncMap(m.FuncMap)).Parse(subjectTemplate) if err != nil { return err } subject := &bytes.Buffer{} err = tmp.Execute(subject, templateData) if err != nil { return err } body, err := m.MailBody(templateURL, defaultTemplate, templateData) if err != nil { return err } mail := gomail.NewMessage() mail.SetHeader("From", m.From) mail.SetHeader("To", to) mail.SetHeader("Subject", subject.String()) for k, v := range headers { if v != nil { mail.SetHeader(k, v...) } } mail.SetBody("text/html", body) dial := gomail.NewDialer(m.Host, m.Port, m.User, m.Pass) if m.LocalName != "" { dial.LocalName = m.LocalName } if m.MailLogging { defer func() { fields := logrus.Fields{ "event": "mail.send", "mail_type": typ, "mail_from": m.From, "mail_to": to, } m.Logger.WithFields(fields).Info("mail.send") }() } if err := dial.DialAndSend(mail); err != nil { return err } return nil }
Mail sends a templated mail. It will try to load the template from a URL, and otherwise fall back to the default
Mail
go
supabase/auth
internal/mailer/mailme.go
https://github.com/supabase/auth/blob/master/internal/mailer/mailme.go
MIT
func (m *TemplateMailer) InviteMail(r *http.Request, user *models.User, otp, referrerURL string, externalURL *url.URL) error { path, err := getPath(m.Config.Mailer.URLPaths.Invite, &EmailParams{ Token: user.ConfirmationToken, Type: "invite", RedirectTo: referrerURL, }) if err != nil { return err } data := map[string]interface{}{ "SiteURL": m.Config.SiteURL, "ConfirmationURL": externalURL.ResolveReference(path).String(), "Email": user.Email, "Token": otp, "TokenHash": user.ConfirmationToken, "Data": user.UserMetaData, "RedirectTo": referrerURL, } return m.Mailer.Mail( r.Context(), user.GetEmail(), withDefault(m.Config.Mailer.Subjects.Invite, "You have been invited"), m.Config.Mailer.Templates.Invite, defaultInviteMail, data, m.Headers("invite"), "invite", ) }
InviteMail sends a invite mail to a new user
InviteMail
go
supabase/auth
internal/mailer/template.go
https://github.com/supabase/auth/blob/master/internal/mailer/template.go
MIT
func (m *TemplateMailer) ConfirmationMail(r *http.Request, user *models.User, otp, referrerURL string, externalURL *url.URL) error { path, err := getPath(m.Config.Mailer.URLPaths.Confirmation, &EmailParams{ Token: user.ConfirmationToken, Type: "signup", RedirectTo: referrerURL, }) if err != nil { return err } data := map[string]interface{}{ "SiteURL": m.Config.SiteURL, "ConfirmationURL": externalURL.ResolveReference(path).String(), "Email": user.Email, "Token": otp, "TokenHash": user.ConfirmationToken, "Data": user.UserMetaData, "RedirectTo": referrerURL, } return m.Mailer.Mail( r.Context(), user.GetEmail(), withDefault(m.Config.Mailer.Subjects.Confirmation, "Confirm Your Email"), m.Config.Mailer.Templates.Confirmation, defaultConfirmationMail, data, m.Headers("confirm"), "confirm", ) }
ConfirmationMail sends a signup confirmation mail to a new user
ConfirmationMail
go
supabase/auth
internal/mailer/template.go
https://github.com/supabase/auth/blob/master/internal/mailer/template.go
MIT
func (m *TemplateMailer) ReauthenticateMail(r *http.Request, user *models.User, otp string) error { data := map[string]interface{}{ "SiteURL": m.Config.SiteURL, "Email": user.Email, "Token": otp, "Data": user.UserMetaData, } return m.Mailer.Mail( r.Context(), user.GetEmail(), withDefault(m.Config.Mailer.Subjects.Reauthentication, "Confirm reauthentication"), m.Config.Mailer.Templates.Reauthentication, defaultReauthenticateMail, data, m.Headers("reauthenticate"), "reauthenticate", ) }
ReauthenticateMail sends a reauthentication mail to an authenticated user
ReauthenticateMail
go
supabase/auth
internal/mailer/template.go
https://github.com/supabase/auth/blob/master/internal/mailer/template.go
MIT
func (m *TemplateMailer) EmailChangeMail(r *http.Request, user *models.User, otpNew, otpCurrent, referrerURL string, externalURL *url.URL) error { type Email struct { Address string Otp string TokenHash string Subject string Template string } emails := []Email{ { Address: user.EmailChange, Otp: otpNew, TokenHash: user.EmailChangeTokenNew, Subject: withDefault(m.Config.Mailer.Subjects.EmailChange, "Confirm Email Change"), Template: m.Config.Mailer.Templates.EmailChange, }, } currentEmail := user.GetEmail() if m.Config.Mailer.SecureEmailChangeEnabled && currentEmail != "" { emails = append(emails, Email{ Address: currentEmail, Otp: otpCurrent, TokenHash: user.EmailChangeTokenCurrent, Subject: withDefault(m.Config.Mailer.Subjects.Confirmation, "Confirm Email Address"), Template: m.Config.Mailer.Templates.EmailChange, }) } ctx, cancel := context.WithCancel(r.Context()) defer cancel() errors := make(chan error, len(emails)) for _, email := range emails { path, err := getPath( m.Config.Mailer.URLPaths.EmailChange, &EmailParams{ Token: email.TokenHash, Type: "email_change", RedirectTo: referrerURL, }, ) if err != nil { return err } go func(address, token, tokenHash, template string) { data := map[string]interface{}{ "SiteURL": m.Config.SiteURL, "ConfirmationURL": externalURL.ResolveReference(path).String(), "Email": user.GetEmail(), "NewEmail": user.EmailChange, "Token": token, "TokenHash": tokenHash, "SendingTo": address, "Data": user.UserMetaData, "RedirectTo": referrerURL, } errors <- m.Mailer.Mail( ctx, address, withDefault(m.Config.Mailer.Subjects.EmailChange, "Confirm Email Change"), template, defaultEmailChangeMail, data, m.Headers("email_change"), "email_change", ) }(email.Address, email.Otp, email.TokenHash, email.Template) } for i := 0; i < len(emails); i++ { e := <-errors if e != nil { return e } } return nil }
EmailChangeMail sends an email change confirmation mail to a user
EmailChangeMail
go
supabase/auth
internal/mailer/template.go
https://github.com/supabase/auth/blob/master/internal/mailer/template.go
MIT
func (m TemplateMailer) GetEmailActionLink(user *models.User, actionType, referrerURL string, externalURL *url.URL) (string, error) { var err error var path *url.URL switch actionType { case "magiclink": path, err = getPath(m.Config.Mailer.URLPaths.Recovery, &EmailParams{ Token: user.RecoveryToken, Type: "magiclink", RedirectTo: referrerURL, }) case "recovery": path, err = getPath(m.Config.Mailer.URLPaths.Recovery, &EmailParams{ Token: user.RecoveryToken, Type: "recovery", RedirectTo: referrerURL, }) case "invite": path, err = getPath(m.Config.Mailer.URLPaths.Invite, &EmailParams{ Token: user.ConfirmationToken, Type: "invite", RedirectTo: referrerURL, }) case "signup": path, err = getPath(m.Config.Mailer.URLPaths.Confirmation, &EmailParams{ Token: user.ConfirmationToken, Type: "signup", RedirectTo: referrerURL, }) case "email_change_current": path, err = getPath(m.Config.Mailer.URLPaths.EmailChange, &EmailParams{ Token: user.EmailChangeTokenCurrent, Type: "email_change", RedirectTo: referrerURL, }) case "email_change_new": path, err = getPath(m.Config.Mailer.URLPaths.EmailChange, &EmailParams{ Token: user.EmailChangeTokenNew, Type: "email_change", RedirectTo: referrerURL, }) default: return "", fmt.Errorf("invalid email action link type: %s", actionType) } if err != nil { return "", err } return externalURL.ResolveReference(path).String(), nil }
GetEmailActionLink returns a magiclink, recovery or invite link based on the actionType passed.
GetEmailActionLink
go
supabase/auth
internal/mailer/template.go
https://github.com/supabase/auth/blob/master/internal/mailer/template.go
MIT
func (ev *EmailValidator) Validate(ctx context.Context, email string) error { if !ev.isExtendedEnabled() && !ev.isServiceEnabled() { return nil } // One of the two validation methods are enabled, set a timeout. ctx, cancel := context.WithTimeout(ctx, validateEmailTimeout) defer cancel() // Easier control flow here to always use errgroup, it has very little // overhad in comparison to the network calls it makes. The reason // we run both checks concurrently is to tighten the timeout without // potentially missing a call to the validation service due to a // dns timeout or something more nefarious like a honeypot dns entry. g := new(errgroup.Group) // Validate the static rules first to prevent round trips on bad emails // and to parse the host ahead of time. if ev.isExtendedEnabled() { // First validate static checks such as format, known invalid hosts // and any other network free checks. Running this check before we // call the service will help reduce the number of calls with known // invalid emails. host, err := ev.validateStatic(email) if err != nil { return err } // Start the goroutine to validate the host. g.Go(func() error { return ev.validateHost(ctx, host) }) } // If the service check is enabled we start a goroutine to run // that check as well. if ev.isServiceEnabled() { g.Go(func() error { return ev.validateService(ctx, email) }) } return g.Wait() }
Validate performs validation on the given email. When extended is true, returns a nil error in all cases but the following: - `email` cannot be parsed by mail.ParseAddress - `email` has a domain with no DNS configured When serviceURL AND serviceKey are non-empty strings it uses the remote service to determine if the email is valid.
Validate
go
supabase/auth
internal/mailer/validate.go
https://github.com/supabase/auth/blob/master/internal/mailer/validate.go
MIT
func (ev *EmailValidator) validateStatic(email string) (string, error) { if !ev.isExtendedEnabled() { return "", nil } ea, err := mail.ParseAddress(email) if err != nil { return "", ErrInvalidEmailFormat } i := strings.LastIndex(ea.Address, "@") if i == -1 { return "", ErrInvalidEmailFormat } // few static lookups that are typed constantly and known to be invalid. if invalidEmailMap[email] { return "", ErrInvalidEmailAddress } host := email[i+1:] if invalidHostMap[host] { return "", ErrInvalidEmailDNS } for i := range invalidHostSuffixes { if strings.HasSuffix(host, invalidHostSuffixes[i]) { return "", ErrInvalidEmailDNS } } name := email[:i] if err := ev.validateProviders(name, host); err != nil { return "", err } return host, nil }
validateStatic will validate the format and do the static checks before returning the host portion of the email.
validateStatic
go
supabase/auth
internal/mailer/validate.go
https://github.com/supabase/auth/blob/master/internal/mailer/validate.go
MIT
func (c *Cleanup) Clean(db *storage.Connection) (int, error) { ctx, span := observability.Tracer("gotrue").Start(db.Context(), "database-cleanup") defer span.End() affectedRows := 0 defer span.SetAttributes(attribute.Int64("gotrue.cleanup.affected_rows", int64(affectedRows))) if err := db.WithContext(ctx).Transaction(func(tx *storage.Connection) error { nextIndex := atomic.AddUint32(&c.cleanupNext, 1) % uint32(len(c.cleanupStatements)) // #nosec G115 statement := c.cleanupStatements[nextIndex] count, terr := tx.RawQuery(statement).ExecWithCount() if terr != nil { return terr } affectedRows += count return nil }); err != nil { return affectedRows, err } c.cleanupAffectedRows.Add(int64(affectedRows)) return affectedRows, nil }
Cleanup removes stale entities in the database. You can call it on each request or as a periodic background job. It does quick lockless updates or deletes, has an execution timeout and acquire timeout so that cleanups do not affect performance of other database jobs. Note that calling this does not clean up the whole database, but does a small piecemeal clean up each time when called.
Clean
go
supabase/auth
internal/models/cleanup.go
https://github.com/supabase/auth/blob/master/internal/models/cleanup.go
MIT
func TruncateAll(conn *storage.Connection) error { return conn.Transaction(func(tx *storage.Connection) error { tables := []string{ (&pop.Model{Value: User{}}).TableName(), (&pop.Model{Value: Identity{}}).TableName(), (&pop.Model{Value: RefreshToken{}}).TableName(), (&pop.Model{Value: AuditLogEntry{}}).TableName(), (&pop.Model{Value: Session{}}).TableName(), (&pop.Model{Value: Factor{}}).TableName(), (&pop.Model{Value: Challenge{}}).TableName(), (&pop.Model{Value: AMRClaim{}}).TableName(), (&pop.Model{Value: SSOProvider{}}).TableName(), (&pop.Model{Value: SSODomain{}}).TableName(), (&pop.Model{Value: SAMLProvider{}}).TableName(), (&pop.Model{Value: SAMLRelayState{}}).TableName(), (&pop.Model{Value: FlowState{}}).TableName(), (&pop.Model{Value: OneTimeToken{}}).TableName(), } for _, tableName := range tables { if err := tx.RawQuery("DELETE FROM " + tableName + " CASCADE").Exec(); err != nil { return err } } return nil }) }
TruncateAll deletes all data from the database, as managed by GoTrue. Not intended for use outside of tests.
TruncateAll
go
supabase/auth
internal/models/connection.go
https://github.com/supabase/auth/blob/master/internal/models/connection.go
MIT
func IsNotFoundError(err error) bool { switch err.(type) { case UserNotFoundError, *UserNotFoundError: return true case SessionNotFoundError, *SessionNotFoundError: return true case ConfirmationTokenNotFoundError, *ConfirmationTokenNotFoundError: return true case ConfirmationOrRecoveryTokenNotFoundError, *ConfirmationOrRecoveryTokenNotFoundError: return true case RefreshTokenNotFoundError, *RefreshTokenNotFoundError: return true case IdentityNotFoundError, *IdentityNotFoundError: return true case ChallengeNotFoundError, *ChallengeNotFoundError: return true case FactorNotFoundError, *FactorNotFoundError: return true case SSOProviderNotFoundError, *SSOProviderNotFoundError: return true case SAMLRelayStateNotFoundError, *SAMLRelayStateNotFoundError: return true case FlowStateNotFoundError, *FlowStateNotFoundError: return true case OneTimeTokenNotFoundError, *OneTimeTokenNotFoundError: return true } return false }
IsNotFoundError returns whether an error represents a "not found" error.
IsNotFoundError
go
supabase/auth
internal/models/errors.go
https://github.com/supabase/auth/blob/master/internal/models/errors.go
MIT
func (i *Identity) GetEmail() string { return string(i.Email) }
GetEmail returns the user's email as a string
GetEmail
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func NewIdentity(user *User, provider string, identityData map[string]interface{}) (*Identity, error) { providerId, ok := identityData["sub"] if !ok { return nil, errors.New("error missing provider id") } now := time.Now() identity := &Identity{ ProviderID: providerId.(string), UserID: user.ID, IdentityData: identityData, Provider: provider, LastSignInAt: &now, } if email, ok := identityData["email"]; ok { identity.Email = storage.NullString(email.(string)) } return identity, nil }
NewIdentity returns an identity associated to the user's id.
NewIdentity
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func FindIdentityByIdAndProvider(tx *storage.Connection, providerId, provider string) (*Identity, error) { identity := &Identity{} if err := tx.Q().Where("provider_id = ? AND provider = ?", providerId, provider).First(identity); err != nil { if errors.Cause(err) == sql.ErrNoRows { return nil, IdentityNotFoundError{} } return nil, errors.Wrap(err, "error finding identity") } return identity, nil }
FindIdentityById searches for an identity with the matching id and provider given.
FindIdentityByIdAndProvider
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func FindIdentitiesByUserID(tx *storage.Connection, userID uuid.UUID) ([]*Identity, error) { identities := []*Identity{} if err := tx.Q().Where("user_id = ?", userID).All(&identities); err != nil { if errors.Cause(err) == sql.ErrNoRows { return identities, nil } return nil, errors.Wrap(err, "error finding identities") } return identities, nil }
FindIdentitiesByUserID returns all identities associated to a user ID.
FindIdentitiesByUserID
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func FindProvidersByUser(tx *storage.Connection, user *User) ([]string, error) { identities := []Identity{} providerExists := map[string]bool{} providers := make([]string, 0) if err := tx.Q().Select("provider").Where("user_id = ?", user.ID).All(&identities); err != nil { if errors.Cause(err) == sql.ErrNoRows { return providers, nil } return nil, errors.Wrap(err, "error finding providers") } for _, identity := range identities { if _, ok := providerExists[identity.Provider]; !ok { providers = append(providers, identity.Provider) providerExists[identity.Provider] = true } } return providers, nil }
FindProvidersByUser returns all providers associated to a user
FindProvidersByUser
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func (i *Identity) UpdateIdentityData(tx *storage.Connection, updates map[string]interface{}) error { if i.IdentityData == nil { i.IdentityData = updates } else { for key, value := range updates { if value != nil { i.IdentityData[key] = value } else { delete(i.IdentityData, key) } } } // pop doesn't support updates on tables with composite primary keys so we use a raw query here. return tx.RawQuery( "update "+(&pop.Model{Value: Identity{}}).TableName()+" set identity_data = ? where id = ?", i.IdentityData, i.ID, ).Exec() }
UpdateIdentityData sets all identity_data from a map of updates, ensuring that it doesn't override attributes that are not in the provided map.
UpdateIdentityData
go
supabase/auth
internal/models/identity.go
https://github.com/supabase/auth/blob/master/internal/models/identity.go
MIT
func GetAccountLinkingDomain(provider string) string { if strings.HasPrefix(provider, "sso:") { // when the provider ID is a SSO provider, then the linking // domain is the provider itself i.e. there can only be one // user + identity per identity provider return provider } // otherwise, the linking domain is the default linking domain that // links all accounts return "default" }
GetAccountLinkingDomain returns a string that describes the account linking domain. An account linking domain describes a set of Identity entities that _should_ generally fall under the same User entity. It's just a runtime string, and is not typically persisted in the database. This value can vary across time.
GetAccountLinkingDomain
go
supabase/auth
internal/models/linking.go
https://github.com/supabase/auth/blob/master/internal/models/linking.go
MIT
func DetermineAccountLinking(tx *storage.Connection, config *conf.GlobalConfiguration, emails []provider.Email, aud, providerName, sub string) (AccountLinkingResult, error) { var verifiedEmails []string var candidateEmail provider.Email for _, email := range emails { if email.Verified || config.Mailer.Autoconfirm { verifiedEmails = append(verifiedEmails, strings.ToLower(email.Email)) } if email.Primary { candidateEmail = email candidateEmail.Email = strings.ToLower(email.Email) } } if identity, terr := FindIdentityByIdAndProvider(tx, sub, providerName); terr == nil { // account exists var user *User if user, terr = FindUserByID(tx, identity.UserID); terr != nil { return AccountLinkingResult{}, terr } // we overwrite the email with the existing user's email since the user // could have an empty email candidateEmail.Email = user.GetEmail() return AccountLinkingResult{ Decision: AccountExists, User: user, Identities: []*Identity{identity}, LinkingDomain: GetAccountLinkingDomain(providerName), CandidateEmail: candidateEmail, }, nil } else if !IsNotFoundError(terr) { return AccountLinkingResult{}, terr } // the identity does not exist, so we need to check if we should create a new account // or link to an existing one // this is the linking domain for the new identity candidateLinkingDomain := GetAccountLinkingDomain(providerName) if len(verifiedEmails) == 0 { // if there are no verified emails, we always decide to create a new account user, terr := IsDuplicatedEmail(tx, candidateEmail.Email, aud, nil) if terr != nil { return AccountLinkingResult{}, terr } if user != nil { candidateEmail.Email = "" } return AccountLinkingResult{ Decision: CreateAccount, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil } var similarIdentities []*Identity var similarUsers []*User // look for similar identities and users based on email if terr := tx.Q().Eager().Where("email = any (?)", verifiedEmails).All(&similarIdentities); terr != nil { return AccountLinkingResult{}, terr } if !strings.HasPrefix(providerName, "sso:") { // there can be multiple user accounts with the same email when is_sso_user is true // so we just do not consider those similar user accounts if terr := tx.Q().Eager().Where("email = any (?) and is_sso_user = false", verifiedEmails).All(&similarUsers); terr != nil { return AccountLinkingResult{}, terr } } // Need to check if the new identity should be assigned to an // existing user or to create a new user, according to the automatic // linking rules var linkingIdentities []*Identity // now let's see if there are any existing and similar identities in // the same linking domain for _, identity := range similarIdentities { if GetAccountLinkingDomain(identity.Provider) == candidateLinkingDomain { linkingIdentities = append(linkingIdentities, identity) } } if len(linkingIdentities) == 0 { if len(similarUsers) == 1 { // no similarIdentities but a user with the same email exists // so we link this new identity to the user // TODO: Backfill the missing identity for the user return AccountLinkingResult{ Decision: LinkAccount, User: similarUsers[0], Identities: linkingIdentities, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil } else if len(similarUsers) > 1 { // this shouldn't happen since there is a partial unique index on (email and is_sso_user = false) return AccountLinkingResult{ Decision: MultipleAccounts, Identities: linkingIdentities, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil } else { // there are no identities in the linking domain, we have to // create a new identity and new user return AccountLinkingResult{ Decision: CreateAccount, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil } } // there is at least one identity in the linking domain let's do a // sanity check to see if all of the identities in the domain share the // same user ID linkingUserId := linkingIdentities[0].UserID for _, identity := range linkingIdentities { if identity.UserID != linkingUserId { // ok this linking domain has more than one user account // caller should decide what to do return AccountLinkingResult{ Decision: MultipleAccounts, Identities: linkingIdentities, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil } } // there's only one user ID in this linking domain, we can go on and // create a new identity and link it to the existing account var user *User var terr error if user, terr = FindUserByID(tx, linkingUserId); terr != nil { return AccountLinkingResult{}, terr } return AccountLinkingResult{ Decision: LinkAccount, User: user, Identities: linkingIdentities, LinkingDomain: candidateLinkingDomain, CandidateEmail: candidateEmail, }, nil }
DetermineAccountLinking uses the provided data and database state to compute a decision on whether: - A new User should be created (CreateAccount) - A new Identity should be created (LinkAccount) with a UserID pointing to an existing user account - Nothing should be done (AccountExists) - It's not possible to decide due to data inconsistency (MultipleAccounts) and the caller should decide Errors signal failure in processing only, like database access errors.
DetermineAccountLinking
go
supabase/auth
internal/models/linking.go
https://github.com/supabase/auth/blob/master/internal/models/linking.go
MIT
func FindUserByConfirmationOrRecoveryToken(tx *storage.Connection, token string) (*User, error) { ott, err := FindOneTimeToken(tx, token, ConfirmationToken, RecoveryToken) if err != nil { return nil, err } return FindUserByID(tx, ott.UserID) }
FindUserByConfirmationToken finds users with the matching confirmation token.
FindUserByConfirmationOrRecoveryToken
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserByConfirmationToken(tx *storage.Connection, token string) (*User, error) { ott, err := FindOneTimeToken(tx, token, ConfirmationToken) if err != nil { return nil, err } return FindUserByID(tx, ott.UserID) }
FindUserByConfirmationToken finds users with the matching confirmation token.
FindUserByConfirmationToken
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserByRecoveryToken(tx *storage.Connection, token string) (*User, error) { ott, err := FindOneTimeToken(tx, token, RecoveryToken) if err != nil { return nil, err } return FindUserByID(tx, ott.UserID) }
FindUserByRecoveryToken finds a user with the matching recovery token.
FindUserByRecoveryToken
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserByEmailChangeToken(tx *storage.Connection, token string) (*User, error) { ott, err := FindOneTimeToken(tx, token, EmailChangeTokenCurrent, EmailChangeTokenNew) if err != nil { return nil, err } return FindUserByID(tx, ott.UserID) }
FindUserByEmailChangeToken finds a user with the matching email change token.
FindUserByEmailChangeToken
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserByEmailChangeCurrentAndAudience(tx *storage.Connection, email, token, aud string) (*User, error) { ott, err := FindOneTimeToken(tx, token, EmailChangeTokenCurrent) if err != nil && !IsNotFoundError(err) { return nil, err } if ott == nil { ott, err = FindOneTimeToken(tx, "pkce_"+token, EmailChangeTokenCurrent) if err != nil { return nil, err } } if ott == nil { return nil, err } user, err := FindUserByID(tx, ott.UserID) if err != nil { return nil, err } if user.Aud != aud && strings.EqualFold(user.GetEmail(), email) { return nil, UserNotFoundError{} } return user, nil }
FindUserByEmailChangeCurrentAndAudience finds a user with the matching email change and audience.
FindUserByEmailChangeCurrentAndAudience
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserByEmailChangeNewAndAudience(tx *storage.Connection, email, token, aud string) (*User, error) { ott, err := FindOneTimeToken(tx, token, EmailChangeTokenNew) if err != nil && !IsNotFoundError(err) { return nil, err } if ott == nil { ott, err = FindOneTimeToken(tx, "pkce_"+token, EmailChangeTokenNew) if err != nil && !IsNotFoundError(err) { return nil, err } } if ott == nil { return nil, err } user, err := FindUserByID(tx, ott.UserID) if err != nil { return nil, err } if user.Aud != aud && strings.EqualFold(user.EmailChange, email) { return nil, UserNotFoundError{} } return user, nil }
FindUserByEmailChangeNewAndAudience finds a user with the matching email change and audience.
FindUserByEmailChangeNewAndAudience
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func FindUserForEmailChange(tx *storage.Connection, email, token, aud string, secureEmailChangeEnabled bool) (*User, error) { if secureEmailChangeEnabled { if user, err := FindUserByEmailChangeCurrentAndAudience(tx, email, token, aud); err == nil { return user, err } else if !IsNotFoundError(err) { return nil, err } } return FindUserByEmailChangeNewAndAudience(tx, email, token, aud) }
FindUserForEmailChange finds a user requesting for an email change
FindUserForEmailChange
go
supabase/auth
internal/models/one_time_token.go
https://github.com/supabase/auth/blob/master/internal/models/one_time_token.go
MIT
func GrantAuthenticatedUser(tx *storage.Connection, user *User, params GrantParams) (*RefreshToken, error) { return createRefreshToken(tx, user, nil, &params) }
GrantAuthenticatedUser creates a refresh token for the provided user.
GrantAuthenticatedUser
go
supabase/auth
internal/models/refresh_token.go
https://github.com/supabase/auth/blob/master/internal/models/refresh_token.go
MIT
func GrantRefreshTokenSwap(r *http.Request, tx *storage.Connection, user *User, token *RefreshToken) (*RefreshToken, error) { var newToken *RefreshToken err := tx.Transaction(func(rtx *storage.Connection) error { var terr error if terr = NewAuditLogEntry(r, tx, user, TokenRevokedAction, "", nil); terr != nil { return errors.Wrap(terr, "error creating audit log entry") } token.Revoked = true if terr = tx.UpdateOnly(token, "revoked"); terr != nil { return terr } newToken, terr = createRefreshToken(rtx, user, token, &GrantParams{}) return terr }) return newToken, err }
GrantRefreshTokenSwap swaps a refresh token for a new one, revoking the provided token.
GrantRefreshTokenSwap
go
supabase/auth
internal/models/refresh_token.go
https://github.com/supabase/auth/blob/master/internal/models/refresh_token.go
MIT
func RevokeTokenFamily(tx *storage.Connection, token *RefreshToken) error { var err error tablename := (&pop.Model{Value: RefreshToken{}}).TableName() if token.SessionId != nil { err = tx.RawQuery(`update `+tablename+` set revoked = true, updated_at = now() where session_id = ? and revoked = false;`, token.SessionId).Exec() } else { err = tx.RawQuery(` with recursive token_family as ( select id, user_id, token, revoked, parent from `+tablename+` where parent = ? union select r.id, r.user_id, r.token, r.revoked, r.parent from `+tablename+` r inner join token_family t on t.token = r.parent ) update `+tablename+` r set revoked = true from token_family where token_family.id = r.id;`, token.Token).Exec() } if err != nil { if errors.Cause(err) == sql.ErrNoRows || errors.Is(err, sql.ErrNoRows) { return nil } return err } return nil }
RevokeTokenFamily revokes all refresh tokens that descended from the provided token.
RevokeTokenFamily
go
supabase/auth
internal/models/refresh_token.go
https://github.com/supabase/auth/blob/master/internal/models/refresh_token.go
MIT
func CompareAAL(a, b AuthenticatorAssuranceLevel) int { return strings.Compare(a.String(), b.String()) }
CompareAAL returns 0 if both AAL levels are equal, > 0 if A is a higher level than B or < 0 if A is a lower level than B.
CompareAAL
go
supabase/auth
internal/models/sessions.go
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
MIT