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 FindSessionByID(tx *storage.Connection, id uuid.UUID, forUpdate bool) (*Session, error) {
session := &Session{}
if forUpdate {
// pop does not provide us with a way to execute FOR UPDATE
// queries which lock the rows affected by the query from
// being accessed by any other transaction that also uses FOR
// UPDATE
if err := tx.RawQuery(fmt.Sprintf("SELECT * FROM %q WHERE id = ? LIMIT 1 FOR UPDATE SKIP LOCKED;", session.TableName()), id).First(session); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, SessionNotFoundError{}
}
return nil, err
}
}
// once the rows are locked (if forUpdate was true), we can query again using pop
if err := tx.Eager().Q().Where("id = ?", id).First(session); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, SessionNotFoundError{}
}
return nil, errors.Wrap(err, "error finding session")
}
return session, nil
}
|
FindSessionByID looks up a Session by the provided id. If forUpdate is set
to true, then the SELECT statement used by the query has the form SELECT ...
FOR UPDATE SKIP LOCKED. This means that a FOR UPDATE lock will only be
acquired if there's no other lock. In case there is a lock, a
IsNotFound(err) error will be retured.
|
FindSessionByID
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func FindAllSessionsForUser(tx *storage.Connection, userId uuid.UUID, forUpdate bool) ([]*Session, error) {
if forUpdate {
user := &User{}
if err := tx.RawQuery(fmt.Sprintf("SELECT id FROM %q WHERE id = ? LIMIT 1 FOR UPDATE SKIP LOCKED;", user.TableName()), userId).First(user); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, UserNotFoundError{}
}
return nil, err
}
}
var sessions []*Session
if err := tx.Where("user_id = ?", userId).All(&sessions); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return sessions, nil
}
|
FindAllSessionsForUser finds all of the sessions for a user. If forUpdate is
set, it will first lock on the user row which can be used to prevent issues
with concurrency. If the lock is acquired, it will return a
UserNotFoundError and the operation should be retried. If there are no
sessions for the user, a nil result is returned without an error.
|
FindAllSessionsForUser
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func Logout(tx *storage.Connection, userId uuid.UUID) error {
return tx.RawQuery("DELETE FROM "+(&pop.Model{Value: Session{}}).TableName()+" WHERE user_id = ?", userId).Exec()
}
|
Logout deletes all sessions for a user.
|
Logout
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func LogoutSession(tx *storage.Connection, sessionId uuid.UUID) error {
return tx.RawQuery("DELETE FROM "+(&pop.Model{Value: Session{}}).TableName()+" WHERE id = ?", sessionId).Exec()
}
|
LogoutSession deletes the current session for a user
|
LogoutSession
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func LogoutAllExceptMe(tx *storage.Connection, sessionId uuid.UUID, userID uuid.UUID) error {
return tx.RawQuery("DELETE FROM "+(&pop.Model{Value: Session{}}).TableName()+" WHERE id != ? AND user_id = ?", sessionId, userID).Exec()
}
|
LogoutAllExceptMe deletes all sessions for a user except the current one
|
LogoutAllExceptMe
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func (s *Session) FindCurrentlyActiveRefreshToken(tx *storage.Connection) (*RefreshToken, error) {
var activeRefreshToken RefreshToken
if err := tx.Q().Where("session_id = ? and revoked is false", s.ID).Order("id desc").First(&activeRefreshToken); err != nil {
if errors.Cause(err) == sql.ErrNoRows || errors.Is(err, sql.ErrNoRows) {
return nil, RefreshTokenNotFoundError{}
}
return nil, err
}
return &activeRefreshToken, nil
}
|
FindCurrentlyActiveRefreshToken returns the currently active refresh
token in the session. This is the last created (ordered by the serial
primary key) non-revoked refresh token for the session.
|
FindCurrentlyActiveRefreshToken
|
go
|
supabase/auth
|
internal/models/sessions.go
|
https://github.com/supabase/auth/blob/master/internal/models/sessions.go
|
MIT
|
func NewUser(phone, email, password, aud string, userData map[string]interface{}) (*User, error) {
passwordHash := ""
if password != "" {
pw, err := crypto.GenerateFromPassword(context.Background(), password)
if err != nil {
return nil, err
}
passwordHash = pw
}
if userData == nil {
userData = make(map[string]interface{})
}
id := uuid.Must(uuid.NewV4())
user := &User{
ID: id,
Aud: aud,
Email: storage.NullString(strings.ToLower(email)),
Phone: storage.NullString(phone),
UserMetaData: userData,
EncryptedPassword: &passwordHash,
}
return user, nil
}
|
NewUser initializes a new user from an email, password and user data.
|
NewUser
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (User) TableName() string {
tableName := "users"
return tableName
}
|
TableName overrides the table name used by pop
|
TableName
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) BeforeSave(tx *pop.Connection) error {
if u.EmailConfirmedAt != nil && u.EmailConfirmedAt.IsZero() {
u.EmailConfirmedAt = nil
}
if u.PhoneConfirmedAt != nil && u.PhoneConfirmedAt.IsZero() {
u.PhoneConfirmedAt = nil
}
if u.InvitedAt != nil && u.InvitedAt.IsZero() {
u.InvitedAt = nil
}
if u.ConfirmationSentAt != nil && u.ConfirmationSentAt.IsZero() {
u.ConfirmationSentAt = nil
}
if u.RecoverySentAt != nil && u.RecoverySentAt.IsZero() {
u.RecoverySentAt = nil
}
if u.EmailChangeSentAt != nil && u.EmailChangeSentAt.IsZero() {
u.EmailChangeSentAt = nil
}
if u.PhoneChangeSentAt != nil && u.PhoneChangeSentAt.IsZero() {
u.PhoneChangeSentAt = nil
}
if u.ReauthenticationSentAt != nil && u.ReauthenticationSentAt.IsZero() {
u.ReauthenticationSentAt = nil
}
if u.LastSignInAt != nil && u.LastSignInAt.IsZero() {
u.LastSignInAt = nil
}
if u.BannedUntil != nil && u.BannedUntil.IsZero() {
u.BannedUntil = nil
}
return nil
}
|
BeforeSave is invoked before the user is saved to the database
|
BeforeSave
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) IsConfirmed() bool {
return u.EmailConfirmedAt != nil
}
|
IsConfirmed checks if a user has already been
registered and confirmed.
|
IsConfirmed
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) HasBeenInvited() bool {
return u.InvitedAt != nil
}
|
HasBeenInvited checks if user has been invited
|
HasBeenInvited
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) IsPhoneConfirmed() bool {
return u.PhoneConfirmedAt != nil
}
|
IsPhoneConfirmed checks if a user's phone has already been
registered and confirmed.
|
IsPhoneConfirmed
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) SetRole(tx *storage.Connection, roleName string) error {
u.Role = strings.TrimSpace(roleName)
return tx.UpdateOnly(u, "role")
}
|
SetRole sets the users Role to roleName
|
SetRole
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) HasRole(roleName string) bool {
return u.Role == roleName
}
|
HasRole returns true when the users role is set to roleName
|
HasRole
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) GetEmail() string {
return string(u.Email)
}
|
GetEmail returns the user's email as a string
|
GetEmail
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) GetPhone() string {
return string(u.Phone)
}
|
GetPhone returns the user's phone number as a string
|
GetPhone
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdateUserMetaData(tx *storage.Connection, updates map[string]interface{}) error {
if u.UserMetaData == nil {
u.UserMetaData = updates
} else {
for key, value := range updates {
if value != nil {
u.UserMetaData[key] = value
} else {
delete(u.UserMetaData, key)
}
}
}
return tx.UpdateOnly(u, "raw_user_meta_data")
}
|
UpdateUserMetaData sets all user data from a map of updates,
ensuring that it doesn't override attributes that are not
in the provided map.
|
UpdateUserMetaData
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdateAppMetaData(tx *storage.Connection, updates map[string]interface{}) error {
if u.AppMetaData == nil {
u.AppMetaData = updates
} else {
for key, value := range updates {
if value != nil {
u.AppMetaData[key] = value
} else {
delete(u.AppMetaData, key)
}
}
}
return tx.UpdateOnly(u, "raw_app_meta_data")
}
|
UpdateAppMetaData updates all app data from a map of updates
|
UpdateAppMetaData
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdateAppMetaDataProviders(tx *storage.Connection) error {
providers, terr := FindProvidersByUser(tx, u)
if terr != nil {
return terr
}
payload := map[string]interface{}{
"providers": providers,
}
if len(providers) > 0 {
payload["provider"] = providers[0]
}
return u.UpdateAppMetaData(tx, payload)
}
|
UpdateAppMetaDataProviders updates the provider field in AppMetaData column
|
UpdateAppMetaDataProviders
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdateUserEmailFromIdentities(tx *storage.Connection) error {
identities, terr := FindIdentitiesByUserID(tx, u.ID)
if terr != nil {
return terr
}
for _, i := range identities {
if u.GetEmail() == i.GetEmail() {
// there's an existing identity that uses the same email
// so the user's email can be kept
return nil
}
}
var primaryIdentity *Identity
for _, i := range identities {
if _, terr := FindUserByEmailAndAudience(tx, i.GetEmail(), u.Aud); terr != nil {
if IsNotFoundError(terr) {
// the identity's email is not used by another user
// so we can set it as the primary identity
primaryIdentity = i
break
}
return terr
}
}
if primaryIdentity == nil {
return UserEmailUniqueConflictError{}
}
// default to the first identity's email
if terr := u.SetEmail(tx, primaryIdentity.GetEmail()); terr != nil {
return terr
}
if primaryIdentity.GetEmail() == "" {
u.EmailConfirmedAt = nil
if terr := tx.UpdateOnly(u, "email_confirmed_at"); terr != nil {
return terr
}
}
return nil
}
|
UpdateUserEmail updates the user's email to one of the identity's email
if the current email used doesn't match any of the identities email
|
UpdateUserEmailFromIdentities
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdatePassword(tx *storage.Connection, sessionID *uuid.UUID) error {
// These need to be reset because password change may mean the user no longer trusts the actions performed by the previous password.
u.ConfirmationToken = ""
u.ConfirmationSentAt = nil
u.RecoveryToken = ""
u.RecoverySentAt = nil
u.EmailChangeTokenCurrent = ""
u.EmailChangeTokenNew = ""
u.EmailChangeSentAt = nil
u.PhoneChangeToken = ""
u.PhoneChangeSentAt = nil
u.ReauthenticationToken = ""
u.ReauthenticationSentAt = nil
if err := tx.UpdateOnly(u, "encrypted_password", "confirmation_token", "confirmation_sent_at", "recovery_token", "recovery_sent_at", "email_change_token_current", "email_change_token_new", "email_change_sent_at", "phone_change_token", "phone_change_sent_at", "reauthentication_token", "reauthentication_sent_at"); err != nil {
return err
}
if err := ClearAllOneTimeTokensForUser(tx, u.ID); err != nil {
return err
}
if sessionID == nil {
// log out user from all sessions to ensure reauthentication after password change
return Logout(tx, u.ID)
} else {
// log out user from all other sessions to ensure reauthentication after password change
return LogoutAllExceptMe(tx, *sessionID, u.ID)
}
}
|
UpdatePassword updates the user's password. Use SetPassword outside of a transaction first!
|
UpdatePassword
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) Confirm(tx *storage.Connection) error {
u.ConfirmationToken = ""
now := time.Now()
u.EmailConfirmedAt = &now
if err := tx.UpdateOnly(u, "confirmation_token", "email_confirmed_at"); err != nil {
return err
}
if err := u.UpdateUserMetaData(tx, map[string]interface{}{
"email_verified": true,
}); err != nil {
return err
}
if err := ClearAllOneTimeTokensForUser(tx, u.ID); err != nil {
return err
}
return nil
}
|
Confirm resets the confimation token and sets the confirm timestamp
|
Confirm
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) ConfirmPhone(tx *storage.Connection) error {
u.ConfirmationToken = ""
now := time.Now()
u.PhoneConfirmedAt = &now
if err := tx.UpdateOnly(u, "confirmation_token", "phone_confirmed_at"); err != nil {
return err
}
return ClearAllOneTimeTokensForUser(tx, u.ID)
}
|
ConfirmPhone resets the confimation token and sets the confirm timestamp
|
ConfirmPhone
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) UpdateLastSignInAt(tx *storage.Connection) error {
return tx.UpdateOnly(u, "last_sign_in_at")
}
|
UpdateLastSignInAt update field last_sign_in_at for user according to specified field
|
UpdateLastSignInAt
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) ConfirmEmailChange(tx *storage.Connection, status int) error {
email := u.EmailChange
u.Email = storage.NullString(email)
u.EmailChange = ""
u.EmailChangeTokenCurrent = ""
u.EmailChangeTokenNew = ""
u.EmailChangeConfirmStatus = status
if err := tx.UpdateOnly(
u,
"email",
"email_change",
"email_change_token_current",
"email_change_token_new",
"email_change_confirm_status",
); err != nil {
return err
}
if err := ClearAllOneTimeTokensForUser(tx, u.ID); err != nil {
return err
}
if !u.IsConfirmed() {
if err := u.Confirm(tx); err != nil {
return err
}
}
identity, err := FindIdentityByIdAndProvider(tx, u.ID.String(), "email")
if err != nil {
if IsNotFoundError(err) {
// no email identity, not an error
return nil
}
return err
}
if _, ok := identity.IdentityData["email"]; ok {
identity.IdentityData["email"] = email
if err := tx.UpdateOnly(identity, "identity_data"); err != nil {
return err
}
}
return nil
}
|
ConfirmEmailChange confirm the change of email for a user
|
ConfirmEmailChange
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) ConfirmPhoneChange(tx *storage.Connection) error {
now := time.Now()
phone := u.PhoneChange
u.Phone = storage.NullString(phone)
u.PhoneChange = ""
u.PhoneChangeToken = ""
u.PhoneConfirmedAt = &now
if err := tx.UpdateOnly(
u,
"phone",
"phone_change",
"phone_change_token",
"phone_confirmed_at",
); err != nil {
return err
}
if err := ClearAllOneTimeTokensForUser(tx, u.ID); err != nil {
return err
}
identity, err := FindIdentityByIdAndProvider(tx, u.ID.String(), "phone")
if err != nil {
if IsNotFoundError(err) {
// no phone identity, not an error
return nil
}
return err
}
if _, ok := identity.IdentityData["phone"]; ok {
identity.IdentityData["phone"] = phone
}
if err := tx.UpdateOnly(identity, "identity_data"); err != nil {
return err
}
return nil
}
|
ConfirmPhoneChange confirms the change of phone for a user
|
ConfirmPhoneChange
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) HighestPossibleAAL() AuthenticatorAssuranceLevel {
for _, factor := range u.Factors {
if factor.Status == FactorStateVerified.String() {
return AAL2
}
}
return AAL1
}
|
HighestPossibleAAL returns the AAL level that this user can obtain. Derived
from the number of verified MFA factors associated with the user object.
|
HighestPossibleAAL
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func CountOtherUsers(tx *storage.Connection, id uuid.UUID) (int, error) {
userCount, err := tx.Q().Where("instance_id = ? and id != ?", uuid.Nil, id).Count(&User{})
return userCount, errors.Wrap(err, "error finding registered users")
}
|
CountOtherUsers counts how many other users exist besides the one provided
|
CountOtherUsers
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUserByEmailAndAudience(tx *storage.Connection, email, aud string) (*User, error) {
return findUser(tx, "instance_id = ? and LOWER(email) = ? and aud = ? and is_sso_user = false", uuid.Nil, strings.ToLower(email), aud)
}
|
FindUserByEmailAndAudience finds a user with the matching email and audience.
|
FindUserByEmailAndAudience
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUserByPhoneAndAudience(tx *storage.Connection, phone, aud string) (*User, error) {
return findUser(tx, "instance_id = ? and phone = ? and aud = ? and is_sso_user = false", uuid.Nil, phone, aud)
}
|
FindUserByPhoneAndAudience finds a user with the matching email and audience.
|
FindUserByPhoneAndAudience
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUserByID(tx *storage.Connection, id uuid.UUID) (*User, error) {
return findUser(tx, "instance_id = ? and id = ?", uuid.Nil, id)
}
|
FindUserByID finds a user matching the provided ID.
|
FindUserByID
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUserWithRefreshToken(tx *storage.Connection, token string, forUpdate bool) (*User, *RefreshToken, *Session, error) {
refreshToken := &RefreshToken{}
if forUpdate {
// pop does not provide us with a way to execute FOR UPDATE
// queries which lock the rows affected by the query from
// being accessed by any other transaction that also uses FOR
// UPDATE
if err := tx.RawQuery(fmt.Sprintf("SELECT * FROM %q WHERE token = ? LIMIT 1 FOR UPDATE SKIP LOCKED;", refreshToken.TableName()), token).First(refreshToken); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, nil, nil, RefreshTokenNotFoundError{}
}
return nil, nil, nil, errors.Wrap(err, "error finding refresh token for update")
}
}
// once the rows are locked (if forUpdate was true), we can query again using pop
if err := tx.Where("token = ?", token).First(refreshToken); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, nil, nil, RefreshTokenNotFoundError{}
}
return nil, nil, nil, errors.Wrap(err, "error finding refresh token")
}
user, err := FindUserByID(tx, refreshToken.UserID)
if err != nil {
return nil, nil, nil, err
}
var session *Session
if refreshToken.SessionId != nil {
sessionId := *refreshToken.SessionId
if sessionId != uuid.Nil {
session, err = FindSessionByID(tx, sessionId, forUpdate)
if err != nil {
if forUpdate {
return nil, nil, nil, err
}
if !IsNotFoundError(err) {
return nil, nil, nil, errors.Wrap(err, "error finding session from refresh token")
}
// otherwise, there's no session for this refresh token
}
}
}
return user, refreshToken, session, nil
}
|
FindUserWithRefreshToken finds a user from the provided refresh token. If
forUpdate is set to true, then the SELECT statement used by the query has
the form SELECT ... FOR UPDATE SKIP LOCKED. This means that a FOR UPDATE
lock will only be acquired if there's no other lock. In case there is a
lock, a IsNotFound(err) error will be returned.
|
FindUserWithRefreshToken
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUsersInAudience(tx *storage.Connection, aud string, pageParams *Pagination, sortParams *SortParams, filter string) ([]*User, error) {
users := []*User{}
q := tx.Q().Where("instance_id = ? and aud = ?", uuid.Nil, aud)
if filter != "" {
lf := "%" + filter + "%"
// we must specify the collation in order to get case insensitive search for the JSON column
q = q.Where("(email LIKE ? OR raw_user_meta_data->>'full_name' ILIKE ?)", lf, lf)
}
if sortParams != nil && len(sortParams.Fields) > 0 {
for _, field := range sortParams.Fields {
q = q.Order(field.Name + " " + string(field.Dir))
}
}
var err error
if pageParams != nil {
err = q.Paginate(int(pageParams.Page), int(pageParams.PerPage)).All(&users) // #nosec G115
pageParams.Count = uint64(q.Paginator.TotalEntriesSize) // #nosec G115
} else {
err = q.All(&users)
}
return users, err
}
|
FindUsersInAudience finds users with the matching audience.
|
FindUsersInAudience
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func IsDuplicatedEmail(tx *storage.Connection, email, aud string, currentUser *User) (*User, error) {
var identities []Identity
if err := tx.Eager().Q().Where("email = ?", strings.ToLower(email)).All(&identities); err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "unable to find identity by email for duplicates")
}
userIDs := make(map[string]uuid.UUID)
for _, identity := range identities {
if _, ok := userIDs[identity.UserID.String()]; !ok {
if !identity.IsForSSOProvider() {
userIDs[identity.UserID.String()] = identity.UserID
}
}
}
var currentUserId uuid.UUID
if currentUser != nil {
currentUserId = currentUser.ID
}
for _, userID := range userIDs {
if userID != currentUserId {
user, err := FindUserByID(tx, userID)
if err != nil {
return nil, errors.Wrap(err, "unable to find user from email identity for duplicates")
}
if user.Aud == aud {
return user, nil
}
}
}
// out of an abundance of caution, if nothing was found via the
// identities table we also do a final check on the users table
user, err := FindUserByEmailAndAudience(tx, email, aud)
if err != nil && !IsNotFoundError(err) {
return nil, errors.Wrap(err, "unable to find user email address for duplicates")
}
return user, nil
}
|
IsDuplicatedEmail returns whether a user exists with a matching email and audience.
If a currentUser is provided, we will need to filter out any identities that belong to the current user.
|
IsDuplicatedEmail
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func IsDuplicatedPhone(tx *storage.Connection, phone, aud string) (bool, error) {
_, err := FindUserByPhoneAndAudience(tx, phone, aud)
if err != nil {
if IsNotFoundError(err) {
return false, nil
}
return false, err
}
return true, nil
}
|
IsDuplicatedPhone checks if the phone number already exists in the users table
|
IsDuplicatedPhone
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) IsBanned() bool {
if u.BannedUntil == nil {
return false
}
return time.Now().Before(*u.BannedUntil)
}
|
IsBanned checks if a user is banned or not
|
IsBanned
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) RemoveUnconfirmedIdentities(tx *storage.Connection, identity *Identity) error {
if identity.Provider != "email" && identity.Provider != "phone" {
// user is unconfirmed so the password should be reset
u.EncryptedPassword = nil
if terr := tx.UpdateOnly(u, "encrypted_password"); terr != nil {
return terr
}
}
// user is unconfirmed so existing user_metadata should be overwritten
// to use the current identity metadata
u.UserMetaData = identity.IdentityData
if terr := u.UpdateUserMetaData(tx, u.UserMetaData); terr != nil {
return terr
}
// finally, remove all identities except the current identity being authenticated
for i := range u.Identities {
if u.Identities[i].ID != identity.ID {
if terr := tx.Destroy(&u.Identities[i]); terr != nil {
return terr
}
}
}
// user is unconfirmed so none of the providers associated to it are verified yet
// only the current provider should be kept
if terr := u.UpdateAppMetaDataProviders(tx); terr != nil {
return terr
}
return nil
}
|
RemoveUnconfirmedIdentities removes potentially malicious unconfirmed identities from a user (if any)
|
RemoveUnconfirmedIdentities
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) SoftDeleteUser(tx *storage.Connection) error {
u.Email = storage.NullString(obfuscateEmail(u, u.GetEmail()))
u.Phone = storage.NullString(obfuscatePhone(u, u.GetPhone()))
u.EmailChange = obfuscateEmail(u, u.EmailChange)
u.PhoneChange = obfuscatePhone(u, u.PhoneChange)
u.EncryptedPassword = nil
u.ConfirmationToken = ""
u.RecoveryToken = ""
u.EmailChangeTokenCurrent = ""
u.EmailChangeTokenNew = ""
u.PhoneChangeToken = ""
// set deleted_at time
now := time.Now()
u.DeletedAt = &now
if err := tx.UpdateOnly(
u,
"email",
"phone",
"encrypted_password",
"email_change",
"phone_change",
"confirmation_token",
"recovery_token",
"email_change_token_current",
"email_change_token_new",
"phone_change_token",
"deleted_at",
); err != nil {
return err
}
if err := ClearAllOneTimeTokensForUser(tx, u.ID); err != nil {
return err
}
// set raw_user_meta_data to {}
userMetaDataUpdates := map[string]interface{}{}
for k := range u.UserMetaData {
userMetaDataUpdates[k] = nil
}
if err := u.UpdateUserMetaData(tx, userMetaDataUpdates); err != nil {
return err
}
// set raw_app_meta_data to {}
appMetaDataUpdates := map[string]interface{}{}
for k := range u.AppMetaData {
appMetaDataUpdates[k] = nil
}
if err := u.UpdateAppMetaData(tx, appMetaDataUpdates); err != nil {
return err
}
if err := Logout(tx, u.ID); err != nil {
return err
}
return nil
}
|
SoftDeleteUser performs a soft deletion on the user by obfuscating and clearing certain fields
|
SoftDeleteUser
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func (u *User) SoftDeleteUserIdentities(tx *storage.Connection) error {
identities, err := FindIdentitiesByUserID(tx, u.ID)
if err != nil {
return err
}
// set identity_data to {}
for _, identity := range identities {
identityDataUpdates := map[string]interface{}{}
for k := range identity.IdentityData {
identityDataUpdates[k] = nil
}
if err := identity.UpdateIdentityData(tx, identityDataUpdates); err != nil {
return err
}
// updating the identity.ID has to happen last since the primary key is on (provider, id)
// we use RawQuery here instead of UpdateOnly because UpdateOnly relies on the primary key of Identity
if err := tx.RawQuery(
"update "+
(&pop.Model{Value: Identity{}}).TableName()+
" set provider_id = ? where id = ?",
obfuscateIdentityProviderId(identity),
identity.ID,
).Exec(); err != nil {
return err
}
}
return nil
}
|
SoftDeleteUserIdentities performs a soft deletion on all identities associated to a user
|
SoftDeleteUserIdentities
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func FindUserByPhoneChangeAndAudience(tx *storage.Connection, phone, aud string) (*User, error) {
return findUser(tx, "instance_id = ? and phone_change = ? and aud = ? and is_sso_user = false", uuid.Nil, phone, aud)
}
|
FindUserByPhoneChangeAndAudience finds a user with the matching phone change and audience.
|
FindUserByPhoneChangeAndAudience
|
go
|
supabase/auth
|
internal/models/user.go
|
https://github.com/supabase/auth/blob/master/internal/models/user.go
|
MIT
|
func WaitForCleanup(ctx context.Context) {
utilities.WaitForCleanup(ctx, &cleanupWaitGroup)
}
|
WaitForCleanup waits until all observability long-running goroutines shut
down cleanly or until the provided context signals done.
|
WaitForCleanup
|
go
|
supabase/auth
|
internal/observability/cleanup.go
|
https://github.com/supabase/auth/blob/master/internal/observability/cleanup.go
|
MIT
|
func traceChiRoutesSafely(r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
logrus.WithField("error", rec).Error("unable to trace chi routes, traces may be off")
span := trace.SpanFromContext(r.Context())
span.SetAttributes(semconv.HTTPRouteKey.String(r.URL.Path))
}
}()
routeContext := chi.RouteContext(r.Context())
span := trace.SpanFromContext(r.Context())
span.SetAttributes(semconv.HTTPRouteKey.String(routeContext.RoutePattern()))
}
|
traceChiRoutesSafely attempts to extract the Chi RouteContext. If the
request does not have a RouteContext it will recover from the panic and
attempt to figure out the route from the URL's path.
|
traceChiRoutesSafely
|
go
|
supabase/auth
|
internal/observability/request-tracing.go
|
https://github.com/supabase/auth/blob/master/internal/observability/request-tracing.go
|
MIT
|
func traceChiRouteURLParamsSafely(r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
logrus.WithField("error", rec).Error("unable to trace route with route params, traces may be off")
}
}()
routeContext := chi.RouteContext(r.Context())
span := trace.SpanFromContext(r.Context())
var attributes []attribute.KeyValue
for i := 0; i < len(routeContext.URLParams.Keys); i += 1 {
key := routeContext.URLParams.Keys[i]
value := routeContext.URLParams.Values[i]
attributes = append(attributes, attribute.String("http.route.param."+key, value))
}
if len(attributes) > 0 {
span.SetAttributes(attributes...)
}
}
|
traceChiRouteURLParamsSafely attempts to extract the Chi RouteContext
URLParams values for the route and assign them to the tracing span. If the
request does not have a RouteContext it will recover from the panic and not
set any params.
|
traceChiRouteURLParamsSafely
|
go
|
supabase/auth
|
internal/observability/request-tracing.go
|
https://github.com/supabase/auth/blob/master/internal/observability/request-tracing.go
|
MIT
|
func countStatusCodesSafely(w *interceptingResponseWriter, r *http.Request, counter metric.Int64Counter) {
if counter == nil {
return
}
defer func() {
if rec := recover(); rec != nil {
logrus.WithField("error", rec).Error("unable to count status codes safely, metrics may be off")
counter.Add(
r.Context(),
1,
metric.WithAttributes(
attribute.Bool("noroute", true),
attribute.Int("code", w.statusCode)),
)
}
}()
ctx := r.Context()
routeContext := chi.RouteContext(ctx)
routePattern := semconv.HTTPRouteKey.String(routeContext.RoutePattern())
counter.Add(
ctx,
1,
metric.WithAttributes(attribute.Int("code", w.statusCode), routePattern),
)
}
|
countStatusCodesSafely counts the number of HTTP status codes per route that
occurred while GoTrue was running. If it is not able to identify the route
via chi.RouteContext(ctx).RoutePattern() it counts with a noroute attribute.
|
countStatusCodesSafely
|
go
|
supabase/auth
|
internal/observability/request-tracing.go
|
https://github.com/supabase/auth/blob/master/internal/observability/request-tracing.go
|
MIT
|
func RequestTracing() func(http.Handler) http.Handler {
meter := otel.Meter("gotrue")
statusCodes, err := meter.Int64Counter(
"http_status_codes",
metric.WithDescription("Number of returned HTTP status codes"),
)
if err != nil {
logrus.WithError(err).Error("unable to get gotrue.http_status_codes counter metric")
}
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
writer := interceptingResponseWriter{
writer: w,
}
defer traceChiRoutesSafely(r)
defer traceChiRouteURLParamsSafely(r)
defer countStatusCodesSafely(&writer, r, statusCodes)
originalUserAgent := r.Header.Get("X-Gotrue-Original-User-Agent")
if originalUserAgent != "" {
r.Header.Set("User-Agent", originalUserAgent)
}
next.ServeHTTP(&writer, r)
if originalUserAgent != "" {
r.Header.Set("X-Gotrue-Original-User-Agent", originalUserAgent)
r.Header.Set("User-Agent", "stripped")
}
}
otelHandler := otelhttp.NewHandler(http.HandlerFunc(fn), "api")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// there is a vulnerability with otelhttp where
// User-Agent strings are kept in RAM indefinitely and
// can be used as an easy way to resource exhaustion;
// so this code strips the User-Agent header before
// it's passed to be traced by otelhttp, and then is
// returned back to the middleware
// https://github.com/supabase/gotrue/security/dependabot/11
userAgent := r.UserAgent()
if userAgent != "" {
r.Header.Set("X-Gotrue-Original-User-Agent", userAgent)
r.Header.Set("User-Agent", "stripped")
}
otelHandler.ServeHTTP(w, r)
})
}
}
|
RequestTracing returns an HTTP handler that traces all HTTP requests coming
in. Supports Chi routers, so this should be one of the first middlewares on
the router.
|
RequestTracing
|
go
|
supabase/auth
|
internal/observability/request-tracing.go
|
https://github.com/supabase/auth/blob/master/internal/observability/request-tracing.go
|
MIT
|
func ConfigureTracing(ctx context.Context, tc *conf.TracingConfig) error {
if ctx == nil {
panic("context must not be nil")
}
var err error
tracingOnce.Do(func() {
if tc.Enabled {
if tc.Exporter == conf.OpenTelemetryTracing {
if err = enableOpenTelemetryTracing(ctx, tc); err != nil {
logrus.WithError(err).Error("unable to start OTLP trace exporter")
}
}
}
})
return err
}
|
ConfigureTracing sets up global tracing configuration for OpenTracing /
OpenTelemetry. The context should be the global context. Cancelling this
context will cancel tracing collection.
|
ConfigureTracing
|
go
|
supabase/auth
|
internal/observability/tracing.go
|
https://github.com/supabase/auth/blob/master/internal/observability/tracing.go
|
MIT
|
func NewAtomicHandler(h http.Handler) *AtomicHandler {
ah := new(AtomicHandler)
ah.Store(h)
return ah
}
|
NewAtomicHandler creates a new AtomicHandler ready for use.
|
NewAtomicHandler
|
go
|
supabase/auth
|
internal/reloader/handler.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/handler.go
|
MIT
|
func (ah *AtomicHandler) load() http.Handler {
return ah.val.Load().(*atomicHandlerValue).Handler
}
|
load will return the underlying http.Handler used to serve requests.
|
load
|
go
|
supabase/auth
|
internal/reloader/handler.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/handler.go
|
MIT
|
func (ah *AtomicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ah.load().ServeHTTP(w, r)
}
|
ServeHTTP implements the standard libraries http.Handler interface by
atomically passing the request along to the most recently stored handler.
|
ServeHTTP
|
go
|
supabase/auth
|
internal/reloader/handler.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/handler.go
|
MIT
|
func (rl *Reloader) reload() (*conf.GlobalConfiguration, error) {
return rl.reloadFn(rl.watchDir)
}
|
reload attempts to create a new *conf.GlobalConfiguration after loading the
currently configured watchDir.
|
reload
|
go
|
supabase/auth
|
internal/reloader/reloader.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/reloader.go
|
MIT
|
func (rl *Reloader) reloadCheckAt(at, lastUpdate time.Time) bool {
if lastUpdate.IsZero() {
return false // no pending updates
}
if at.Sub(lastUpdate) < rl.reloadIval {
return false // waiting for reload interval
}
// Update is pending.
return true
}
|
reloadCheckAt checks if reloadConfig should be called, returns true if config
should be reloaded or false otherwise.
|
reloadCheckAt
|
go
|
supabase/auth
|
internal/reloader/reloader.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/reloader.go
|
MIT
|
func defaultAddDirFn(ctx context.Context, wr watcher, dir string, dur time.Duration) error {
if err := wr.Add(dir); err != nil {
tr := time.NewTicker(dur)
defer tr.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-tr.C:
return err
}
}
return nil
}
|
defaultAddDirFn adds a dir to a watcher with a common error and sleep
duration if the directory doesn't exist.
|
defaultAddDirFn
|
go
|
supabase/auth
|
internal/reloader/reloader.go
|
https://github.com/supabase/auth/blob/master/internal/reloader/reloader.go
|
MIT
|
func Dial(config *conf.GlobalConfiguration) (*Connection, error) {
if config.DB.Driver == "" && config.DB.URL != "" {
u, err := url.Parse(config.DB.URL)
if err != nil {
return nil, errors.Wrap(err, "parsing db connection url")
}
config.DB.Driver = u.Scheme
}
driver := ""
if config.DB.Driver != "postgres" {
logrus.Warn("DEPRECATION NOTICE: only PostgreSQL is supported by Supabase's GoTrue, will be removed soon")
} else {
// pop v5 uses pgx as the default PostgreSQL driver
driver = "pgx"
}
if driver != "" && (config.Tracing.Enabled || config.Metrics.Enabled) {
instrumentedDriver, err := otelsql.Register(driver)
if err != nil {
logrus.WithError(err).Errorf("unable to instrument sql driver %q for use with OpenTelemetry", driver)
} else {
logrus.Debugf("using %s as an instrumented driver for OpenTelemetry", instrumentedDriver)
// sqlx needs to be informed that the new instrumented
// driver has the same semantics as the
// non-instrumented driver
sqlx.BindDriver(instrumentedDriver, sqlx.BindType(driver))
driver = instrumentedDriver
}
}
options := make(map[string]string)
if config.DB.HealthCheckPeriod != time.Duration(0) {
options["pool_health_check_period"] = config.DB.HealthCheckPeriod.String()
}
if config.DB.ConnMaxIdleTime != time.Duration(0) {
options["pool_max_conn_idle_time"] = config.DB.ConnMaxIdleTime.String()
}
db, err := pop.NewConnection(&pop.ConnectionDetails{
Dialect: config.DB.Driver,
Driver: driver,
URL: config.DB.URL,
Pool: config.DB.MaxPoolSize,
IdlePool: config.DB.MaxIdlePoolSize,
ConnMaxLifetime: config.DB.ConnMaxLifetime,
ConnMaxIdleTime: config.DB.ConnMaxIdleTime,
Options: options,
})
if err != nil {
return nil, errors.Wrap(err, "opening database connection")
}
if err := db.Open(); err != nil {
return nil, errors.Wrap(err, "checking database connection")
}
if config.Metrics.Enabled {
registerOpenTelemetryDatabaseStats(db)
}
return &Connection{db}, nil
}
|
Dial will connect to that storage engine
|
Dial
|
go
|
supabase/auth
|
internal/storage/dial.go
|
https://github.com/supabase/auth/blob/master/internal/storage/dial.go
|
MIT
|
func (c *Connection) WithContext(ctx context.Context) *Connection {
return &Connection{c.Connection.WithContext(ctx)}
}
|
WithContext returns a new connection with an updated context. This is
typically used for tracing as the context contains trace span information.
|
WithContext
|
go
|
supabase/auth
|
internal/storage/dial.go
|
https://github.com/supabase/auth/blob/master/internal/storage/dial.go
|
MIT
|
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey, id)
}
|
WithRequestID adds the provided request ID to the context.
|
WithRequestID
|
go
|
supabase/auth
|
internal/utilities/context.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/context.go
|
MIT
|
func GetRequestID(ctx context.Context) string {
obj := ctx.Value(requestIDKey)
if obj == nil {
return ""
}
return obj.(string)
}
|
GetRequestID reads the request ID from the context.
|
GetRequestID
|
go
|
supabase/auth
|
internal/utilities/context.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/context.go
|
MIT
|
func WaitForCleanup(ctx context.Context, wg *sync.WaitGroup) {
cleanupDone := make(chan struct{})
go func() {
defer close(cleanupDone)
wg.Wait()
}()
select {
case <-ctx.Done():
return
case <-cleanupDone:
return
}
}
|
WaitForCleanup waits until all long-running goroutines shut
down cleanly or until the provided context signals done.
|
WaitForCleanup
|
go
|
supabase/auth
|
internal/utilities/context.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/context.go
|
MIT
|
func NewPostgresError(err error) *PostgresError {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && isPubliclyAccessiblePostgresError(pgErr.Code) {
return &PostgresError{
Code: pgErr.Code,
HttpStatusCode: getHttpStatusCodeFromPostgresErrorCode(pgErr.Code),
Message: pgErr.Message,
Detail: pgErr.Detail,
Hint: pgErr.Hint,
}
}
return nil
}
|
NewPostgresError returns a new PostgresError if the error was from a publicly
accessible Postgres error.
|
NewPostgresError
|
go
|
supabase/auth
|
internal/utilities/postgres.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/postgres.go
|
MIT
|
func isPubliclyAccessiblePostgresError(code string) bool {
if len(code) != 5 {
return false
}
// default response
return getHttpStatusCodeFromPostgresErrorCode(code) != 0
}
|
isPubliclyAccessiblePostgresError checks if the Postgres error should be
made accessible.
|
isPubliclyAccessiblePostgresError
|
go
|
supabase/auth
|
internal/utilities/postgres.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/postgres.go
|
MIT
|
func getHttpStatusCodeFromPostgresErrorCode(code string) int {
if code == pgerrcode.RaiseException ||
code == pgerrcode.IntegrityConstraintViolation ||
code == pgerrcode.RestrictViolation ||
code == pgerrcode.NotNullViolation ||
code == pgerrcode.ForeignKeyViolation ||
code == pgerrcode.UniqueViolation ||
code == pgerrcode.CheckViolation ||
code == pgerrcode.ExclusionViolation {
return 500
}
// Use custom HTTP status code if Postgres error was triggered with `PTXXX`
// code. This is consistent with PostgREST's behaviour as well.
if strings.HasPrefix(code, "PT") {
if httpStatusCode, err := strconv.ParseInt(code[2:], 10, 0); err == nil {
return int(httpStatusCode)
}
}
return 0
}
|
getHttpStatusCodeFromPostgresErrorCode maps a Postgres error code to a HTTP
status code. Returns 0 if the code doesn't map to a given postgres error code.
|
getHttpStatusCodeFromPostgresErrorCode
|
go
|
supabase/auth
|
internal/utilities/postgres.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/postgres.go
|
MIT
|
func GetIPAddress(r *http.Request) string {
if r.Header != nil {
xForwardedFor := r.Header.Get("X-Forwarded-For")
if xForwardedFor != "" {
ips := strings.Split(xForwardedFor, ",")
for i := range ips {
ips[i] = strings.TrimSpace(ips[i])
}
for _, ip := range ips {
if ip != "" {
parsed := net.ParseIP(ip)
if parsed == nil {
continue
}
return parsed.String()
}
}
}
}
ipPort := r.RemoteAddr
ip, _, err := net.SplitHostPort(ipPort)
if err != nil {
return ipPort
}
return ip
}
|
GetIPAddress returns the real IP address of the HTTP request. It parses the
X-Forwarded-For header.
|
GetIPAddress
|
go
|
supabase/auth
|
internal/utilities/request.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/request.go
|
MIT
|
func GetBodyBytes(req *http.Request) ([]byte, error) {
if req.Body == nil || req.Body == http.NoBody {
return nil, nil
}
originalBody := req.Body
defer SafeClose(originalBody)
buf, err := io.ReadAll(originalBody)
if err != nil {
return nil, err
}
req.Body = io.NopCloser(bytes.NewReader(buf))
return buf, nil
}
|
GetBodyBytes reads the whole request body properly into a byte array.
|
GetBodyBytes
|
go
|
supabase/auth
|
internal/utilities/request.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/request.go
|
MIT
|
func getRedirectTo(r *http.Request) (reqref string) {
reqref = r.Header.Get("redirect_to")
if reqref != "" {
return
}
if err := r.ParseForm(); err == nil {
reqref = r.Form.Get("redirect_to")
}
return
}
|
getRedirectTo tries extract redirect url from header or from query params
|
getRedirectTo
|
go
|
supabase/auth
|
internal/utilities/request.go
|
https://github.com/supabase/auth/blob/master/internal/utilities/request.go
|
MIT
|
func (g *GCloud) DeleteNode(name string) (err error) {
_, err = g.Service.Instances.Delete(g.ProjectID, g.Zone, name).Context(context.Background()).Do()
return
}
|
DeleteNode delete a GCloud instance from a given node name
|
DeleteNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
gcloud.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/gcloud.go
|
MIT
|
func (c *kubernetesClient) GetProjectIdAndZoneFromNode(ctx context.Context, nodeName string) (projectID string, zone string, err error) {
node, err := c.GetNode(ctx, nodeName)
if err != nil {
return
}
s := strings.Split(node.Spec.ProviderID, "/")
projectID = s[2]
zone = s[3]
return
}
|
GetProjectIdAndZoneFromNode returns project id and zone from given node name
by getting informations from node spec provider id
|
GetProjectIdAndZoneFromNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) GetPreemptibleNodes(ctx context.Context, filters map[string]string) (nodes *v1.NodeList, err error) {
labelSelector := labels.Set{
"cloud.google.com/gke-preemptible": "true",
}
for key, value := range filters {
labelSelector[key] = value
}
nodes, err = c.kubeClientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{
LabelSelector: labelSelector.String(),
})
if err != nil {
return
}
return
}
|
GetPreemptibleNodes return a list of preemptible node
|
GetPreemptibleNodes
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) GetNode(ctx context.Context, nodeName string) (node *v1.Node, err error) {
node, err = c.kubeClientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return
}
return
}
|
GetNode return the node object from given name
|
GetNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) SetNodeAnnotation(ctx context.Context, nodeName string, key string, value string) (err error) {
newNode, err := c.GetNode(ctx, nodeName)
if err != nil {
err = fmt.Errorf("Error getting node information before setting annotation:\n%v", err)
return
}
newNode.ObjectMeta.Annotations[key] = value
_, err = c.kubeClientset.CoreV1().Nodes().Update(ctx, newNode, metav1.UpdateOptions{})
if err != nil {
return
}
return
}
|
SetNodeAnnotation add an annotation (key/value) to a node from a given node name
As the nodes are constantly being updated, the k8s client doesn't support patch feature yet and
to reduce the chance to hit a failure 409 we fetch the node before update
|
SetNodeAnnotation
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) SetUnschedulableState(ctx context.Context, nodeName string, unschedulable bool) (err error) {
node, err := c.GetNode(ctx, nodeName)
if err != nil {
err = fmt.Errorf("Error getting node information before setting unschedulable state:\n%v", err)
return
}
node.Spec.Unschedulable = unschedulable
_, err = c.kubeClientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err != nil {
return
}
return
}
|
SetUnschedulableState set the unschedulable state of a given node name
|
SetUnschedulableState
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func filterOutPodByOwnerReferenceKind(podList []v1.Pod, kind string) (output []v1.Pod) {
for _, pod := range podList {
for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
if ownerReference.Kind != kind {
output = append(output, pod)
}
}
}
return
}
|
filterOutPodByOwnerReferenceKind filter out a list of pods by its owner references kind
|
filterOutPodByOwnerReferenceKind
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func filterOutPodByNode(podList []v1.Pod, nodeName string) (output []v1.Pod) {
for _, pod := range podList {
if pod.Spec.NodeName == nodeName {
output = append(output, pod)
}
}
return
}
|
filterOutPodByNode filters out a list of pods by its node
|
filterOutPodByNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) DrainNode(ctx context.Context, nodeName string, drainTimeout int) (err error) {
// Select all pods sitting on the node except the one from kube-system
fieldSelector := fmt.Sprintf("spec.nodeName=%v,metadata.namespace!=kube-system", nodeName)
podList, err := c.kubeClientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fieldSelector,
})
if err != nil {
return
}
// Filter out DaemonSet from the list of pods
filteredPodList := filterOutPodByOwnerReferenceKind(podList.Items, "DaemonSet")
log.Info().
Str("host", nodeName).
Msgf("%d pod(s) found", len(filteredPodList))
stopEvicting := make(chan bool)
stopPolling := make(chan bool)
errCh := make(chan error)
defer func() {
if len(errCh) > 0 {
err = <-errCh
}
}()
go func() {
if err := c.evictPods(ctx, filteredPodList, stopEvicting); err != nil {
errCh <- err
}
}()
doneDraining := make(chan bool)
// Wait until all pods are deleted
go func() {
for {
sleepTime := ApplyJitter(10)
sleepDuration := time.Duration(sleepTime) * time.Second
pendingPodList, err := c.kubeClientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fieldSelector,
})
if err != nil {
log.Error().
Err(err).
Str("host", nodeName).
Msgf("Error getting list of pods, sleeping %ds", sleepTime)
time.Sleep(sleepDuration)
continue
}
// Filter out DaemonSet from the list of pods
filteredPendingPodList := filterOutPodByOwnerReferenceKind(pendingPodList.Items, "DaemonSet")
podsPending := len(filteredPendingPodList)
if podsPending == 0 {
doneDraining <- true
return
}
log.Info().
Str("host", nodeName).
Msgf("%d pod(s) pending deletion, sleeping %ds", podsPending, sleepTime)
select {
case <-stopPolling:
return
default:
time.Sleep(sleepDuration)
}
}
}()
select {
case <-doneDraining:
break
case <-time.After(time.Duration(drainTimeout) * time.Second):
log.Warn().
Str("host", nodeName).
Msg("Draining node timeout reached")
close(stopPolling)
close(stopEvicting)
return
case <-ctx.Done():
close(stopPolling)
close(stopEvicting)
return
}
log.Info().
Str("host", nodeName).
Msg("Done draining node")
return
}
|
DrainNode delete every pods from a given node and wait that all pods are removed before it succeed
it also make sure we don't select DaemonSet because they are not subject to unschedulable state
|
DrainNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (c *kubernetesClient) DrainKubeDNSFromNode(ctx context.Context, nodeName string, drainTimeout int) (err error) {
// Select all pods sitting on the node except the one from kube-system
labelSelector := labels.Set{
"k8s-app": "kube-dns",
}
podList, err := c.kubeClientset.CoreV1().Pods("kube-system").List(ctx, metav1.ListOptions{
LabelSelector: labelSelector.String(),
})
if err != nil {
return
}
// Filter out pods running on other nodes
filteredPodList := filterOutPodByNode(podList.Items, nodeName)
log.Info().
Str("host", nodeName).
Msgf("%d kube-dns pod(s) found", len(filteredPodList))
stopEvicting := make(chan bool)
stopPolling := make(chan bool)
errCh := make(chan error)
defer func() {
if len(errCh) > 0 {
err = <-errCh
}
}()
go func() {
if err := c.evictPods(ctx, filteredPodList, stopEvicting); err != nil {
errCh <- err
}
}()
doneDraining := make(chan bool)
// Wait until all pods are deleted
go func() {
for {
sleepTime := ApplyJitter(10)
sleepDuration := time.Duration(sleepTime) * time.Second
podList, err := c.kubeClientset.CoreV1().Pods("kube-system").List(ctx, metav1.ListOptions{
LabelSelector: labelSelector.String(),
})
if err != nil {
log.Error().
Err(err).
Str("host", nodeName).
Msgf("Error getting list of kube-dns pods, sleeping %ds", sleepTime)
time.Sleep(sleepDuration)
continue
}
// Filter out DaemonSet from the list of pods
filteredPendingPodList := filterOutPodByNode(podList.Items, nodeName)
podsPending := len(filteredPendingPodList)
if podsPending == 0 {
doneDraining <- true
return
}
log.Info().
Str("host", nodeName).
Msgf("%d pod(s) pending deletion, sleeping %ds", podsPending, sleepTime)
select {
case <-stopPolling:
return
default:
time.Sleep(sleepDuration)
}
}
}()
select {
case <-doneDraining:
break
case <-time.After(time.Duration(drainTimeout) * time.Second):
log.Warn().
Str("host", nodeName).
Msg("Draining kube-dns node timeout reached")
close(stopPolling)
close(stopEvicting)
return
case <-ctx.Done():
close(stopPolling)
close(stopEvicting)
return
}
log.Info().
Str("host", nodeName).
Msg("Done draining kube-dns from node")
return
}
|
DrainKubeDNSFromNode deletes any kube-dns pods running on the node
|
DrainKubeDNSFromNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client.go
|
MIT
|
func (m *MockKubernetesClient) EXPECT() *MockKubernetesClientMockRecorder {
return m.recorder
}
|
EXPECT returns an object that allows the caller to indicate expected use
|
EXPECT
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) DrainNode(ctx, nodeName, drainTimeout interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DrainNode", reflect.TypeOf((*MockKubernetesClient)(nil).DrainNode), ctx, nodeName, drainTimeout)
}
|
DrainNode indicates an expected call of DrainNode
|
DrainNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) DrainKubeDNSFromNode(ctx, nodeName, drainTimeout interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DrainKubeDNSFromNode", reflect.TypeOf((*MockKubernetesClient)(nil).DrainKubeDNSFromNode), ctx, nodeName, drainTimeout)
}
|
DrainKubeDNSFromNode indicates an expected call of DrainKubeDNSFromNode
|
DrainKubeDNSFromNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) GetNode(ctx, nodeName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNode", reflect.TypeOf((*MockKubernetesClient)(nil).GetNode), ctx, nodeName)
}
|
GetNode indicates an expected call of GetNode
|
GetNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) DeleteNode(ctx, nodeName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteNode", reflect.TypeOf((*MockKubernetesClient)(nil).DeleteNode), ctx, nodeName)
}
|
DeleteNode indicates an expected call of DeleteNode
|
DeleteNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) GetPreemptibleNodes(ctx, filters interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPreemptibleNodes", reflect.TypeOf((*MockKubernetesClient)(nil).GetPreemptibleNodes), ctx, filters)
}
|
GetPreemptibleNodes indicates an expected call of GetPreemptibleNodes
|
GetPreemptibleNodes
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) GetProjectIdAndZoneFromNode(ctx, nodeName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProjectIdAndZoneFromNode", reflect.TypeOf((*MockKubernetesClient)(nil).GetProjectIdAndZoneFromNode), ctx, nodeName)
}
|
GetProjectIdAndZoneFromNode indicates an expected call of GetProjectIdAndZoneFromNode
|
GetProjectIdAndZoneFromNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) SetNodeAnnotation(ctx, nodeName, key, value interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetNodeAnnotation", reflect.TypeOf((*MockKubernetesClient)(nil).SetNodeAnnotation), ctx, nodeName, key, value)
}
|
SetNodeAnnotation indicates an expected call of SetNodeAnnotation
|
SetNodeAnnotation
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func (mr *MockKubernetesClientMockRecorder) SetUnschedulableState(ctx, nodeName, unschedulable interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUnschedulableState", reflect.TypeOf((*MockKubernetesClient)(nil).SetUnschedulableState), ctx, nodeName, unschedulable)
}
|
SetUnschedulableState indicates an expected call of SetUnschedulableState
|
SetUnschedulableState
|
go
|
estafette/estafette-gke-preemptible-killer
|
kubernetes_client_mock.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/kubernetes_client_mock.go
|
MIT
|
func getCurrentNodeState(node v1.Node) (state GKEPreemptibleKillerState) {
var ok bool
state.ExpiryDatetime, ok = node.ObjectMeta.Annotations[annotationGKEPreemptibleKillerState]
if !ok {
state.ExpiryDatetime = ""
}
return
}
|
getCurrentNodeState return the state of the node by reading its metadata annotations
|
getCurrentNodeState
|
go
|
estafette/estafette-gke-preemptible-killer
|
main.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/main.go
|
MIT
|
func getDesiredNodeState(now time.Time, ctx context.Context, kubernetesClient KubernetesClient, node v1.Node) (state GKEPreemptibleKillerState, err error) {
twelveHours := 12 * time.Hour
twentyFourHours := 24 * time.Hour
drainTimeoutTime := time.Duration(*drainTimeout) * time.Second
creationTime := node.ObjectMeta.CreationTimestamp.Time
nodeDeletedBy := creationTime.Add(twentyFourHours)
expectedRemainingLife := time.Duration(math.Max(float64(nodeDeletedBy.Sub(now)), 0))
kickOffDeletionBy := time.Duration(math.Max(float64(expectedRemainingLife-drainTimeoutTime), 0))
var randomOffset time.Duration
if kickOffDeletionBy > 0 {
randomOffset = time.Duration(randomEstafette.Intn(int(kickOffDeletionBy)))
}
if expectedRemainingLife > twelveHours && randomOffset < twelveHours {
randomOffset += twelveHours
}
expiryDateTime := whitelistInstance.getExpiryDate(now, randomOffset)
state.ExpiryDatetime = expiryDateTime.Format(time.RFC3339)
log.Info().
Str("host", node.ObjectMeta.Name).
Msgf("Annotation not found, adding %s to %s", annotationGKEPreemptibleKillerState, state.ExpiryDatetime)
err = kubernetesClient.SetNodeAnnotation(ctx, node.ObjectMeta.Name, annotationGKEPreemptibleKillerState, state.ExpiryDatetime)
if err != nil {
log.Warn().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error updating node metadata")
nodeTotals.With(prometheus.Labels{"status": "failed"}).Inc()
return
}
nodeTotals.With(prometheus.Labels{"status": "annotated"}).Inc()
return
}
|
getDesiredNodeState define the state of the node, update node annotations if not present
|
getDesiredNodeState
|
go
|
estafette/estafette-gke-preemptible-killer
|
main.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/main.go
|
MIT
|
func processNode(ctx context.Context, kubernetesClient KubernetesClient, node v1.Node) (err error) {
// get current node state
state := getCurrentNodeState(node)
// set node state if doesn't already have annotations
if state.ExpiryDatetime == "" {
state, _ = getDesiredNodeState(time.Now(), ctx, kubernetesClient, node)
}
// compute time difference
now := time.Now().UTC()
expiryDatetime, err := time.Parse(time.RFC3339, state.ExpiryDatetime)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msgf("Error parsing expiry datetime with value '%s'", state.ExpiryDatetime)
return
}
timeDiff := expiryDatetime.Sub(now).Minutes()
// check if we need to delete the node or not
if timeDiff < 0 {
log.Info().
Str("host", node.ObjectMeta.Name).
Msgf("Node expired %.0f minute(s) ago, deleting...", timeDiff)
// set node unschedulable
err = kubernetesClient.SetUnschedulableState(ctx, node.ObjectMeta.Name, true)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error setting node to unschedulable state")
return
}
var projectID string
var zone string
projectID, zone, err = kubernetesClient.GetProjectIdAndZoneFromNode(ctx, node.ObjectMeta.Name)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error getting project id and zone from node")
return
}
var gcloud GCloudClient
gcloud, err = NewGCloudClient(projectID, zone)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error creating GCloud client")
return
}
// drain kubernetes node
err = kubernetesClient.DrainNode(ctx, node.ObjectMeta.Name, *drainTimeout)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error draining kubernetes node")
return
}
// drain kube-dns from kubernetes node
err = kubernetesClient.DrainKubeDNSFromNode(ctx, node.ObjectMeta.Name, *drainTimeout)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error draining kube-dns from kubernetes node")
return
}
// delete node from kubernetes cluster
err = kubernetesClient.DeleteNode(ctx, node.ObjectMeta.Name)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error deleting node")
return
}
// delete gcloud instance
err = gcloud.DeleteNode(node.ObjectMeta.Name)
if err != nil {
log.Error().
Err(err).
Str("host", node.ObjectMeta.Name).
Msg("Error deleting GCloud instance")
return
}
nodeTotals.With(prometheus.Labels{"status": "killed"}).Inc()
log.Info().
Str("host", node.ObjectMeta.Name).
Msg("Node deleted")
return
}
nodeTotals.With(prometheus.Labels{"status": "skipped"}).Inc()
log.Info().
Str("host", node.ObjectMeta.Name).
Msgf("%.0f minute(s) to go before kill, keeping node", timeDiff)
return
}
|
processNode returns the time to delete a node after n minutes
|
processNode
|
go
|
estafette/estafette-gke-preemptible-killer
|
main.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/main.go
|
MIT
|
func (w *WhitelistInstance) initialize() {
w.whitelistHours = timespanset.Empty()
w.whitelistSecondCount = 0
}
|
initializeWhitelistHours initializes data structures by taking command line arguments into account.
|
initialize
|
go
|
estafette/estafette-gke-preemptible-killer
|
whitelist.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/whitelist.go
|
MIT
|
func (w *WhitelistInstance) getExpiryDate(t time.Time, timeToBeAdded time.Duration) (expiryDatetime time.Time) {
truncatedCreationTime := t.Truncate(24 * time.Hour)
projectedCreation := whitelistStart.Add(t.Sub(truncatedCreationTime))
first := true
for timeToBeAdded > 0 {
// For all whitelisted intervals...
w.whitelistHours.IntervalsBetween(whitelistStart, whitelistEnd, func(start, end time.Time) bool {
// For the first iteration only...
if first {
// If the current interval ends before the creation...
if end.Before(projectedCreation) {
// Skip for now.
return true
}
// If creation is in the middle of the current interval...
if start.Before(projectedCreation) {
// Start with creation.
start = projectedCreation
}
}
// If expiry time has been reached...
intervalDuration := end.Sub(start)
if timeToBeAdded <= intervalDuration {
// This is it, project it back to real time.
expiryDatetime = truncatedCreationTime.Add(start.Add(timeToBeAdded).Sub(whitelistStart))
// But if expiryDatetime is before creation...
fmt.Println("before creation? " + expiryDatetime.String() + " " + t.String())
if expiryDatetime.Before(t) {
// Simply add 24h.
expiryDatetime = expiryDatetime.Add(24 * time.Hour)
}
}
// Consume this interval.
timeToBeAdded -= intervalDuration
// Do we want another interval?
return timeToBeAdded > 0
})
first = false
}
return expiryDatetime
}
|
getExpiryDate calculates the expiry date of a node.
|
getExpiryDate
|
go
|
estafette/estafette-gke-preemptible-killer
|
whitelist.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/whitelist.go
|
MIT
|
func (w *WhitelistInstance) processHours(input string, direction string) {
// Time not specified, continue with no restrictions.
if len(input) == 0 {
return
}
// Split in intervals.
input = strings.Replace(input, " ", "", -1)
intervals := strings.Split(input, ",")
for _, timeInterval := range intervals {
times := strings.Split(timeInterval, "-")
// Check format.
if len(times) != 2 {
panic(fmt.Sprintf("processHours(): interval '%v' should be of the form `09:00 - 11:00[, 21:00 - 23:00[, ...]]`", timeInterval))
}
// Start time
start, err := time.Parse(time.RFC3339, whitelistStartPrefix+times[0]+whitelistTimePostfix)
if err != nil {
panic(fmt.Sprintf("processHours(): %v cannot be parsed: %v", times[0], err))
}
// End time
end, err := time.Parse(time.RFC3339, whitelistStartPrefix+times[1]+whitelistTimePostfix)
if err != nil {
panic(fmt.Sprintf("processHours(): %v cannot be parsed: %v", times[1], err))
}
// If end is before start it means it contains midnight, so split in two.
if end.Before(start) {
w.mergeTimespans(whitelistStart, end, direction)
end = whitelistEnd
}
// Merge timespans.
w.mergeTimespans(start, end, direction)
}
}
|
processHours parses time stamps and passes them to mergeTimespans(), direction can be "+" or "-".
|
processHours
|
go
|
estafette/estafette-gke-preemptible-killer
|
whitelist.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/whitelist.go
|
MIT
|
func (w *WhitelistInstance) updateWhitelistSecondCount(start, end time.Time) bool {
if end.Before(start) {
panic(fmt.Sprintf("updateWhitelistSecondCount(): go-intervals timespanset is acting up providing reverse intervals: %v - %v", start, end))
}
w.whitelistSecondCount += int(end.Sub(start).Seconds())
return true
}
|
updateWhitelistSecondCount adds the difference between two times to an accumulator.
|
updateWhitelistSecondCount
|
go
|
estafette/estafette-gke-preemptible-killer
|
whitelist.go
|
https://github.com/estafette/estafette-gke-preemptible-killer/blob/master/whitelist.go
|
MIT
|
func main() {
app := cli.NewApp()
app.Name = "ginadmin"
app.Version = VERSION
app.Usage = "A lightweight, flexible, elegant and full-featured RBAC scaffolding based on GIN + GORM 2.0 + Casbin 2.0 + Wire DI."
app.Commands = []*cli.Command{
cmd.StartCmd(),
cmd.StopCmd(),
cmd.VersionCmd(VERSION),
}
err := app.Run(os.Args)
if err != nil {
panic(err)
}
}
|
@title ginadmin
@version v10.1.0
@description A lightweight, flexible, elegant and full-featured RBAC scaffolding based on GIN + GORM 2.0 + Casbin 2.0 + Wire DI.
@securityDefinitions.apikey ApiKeyAuth
@in header
@name Authorization
@schemes http https
@basePath /
|
main
|
go
|
LyricTian/gin-admin
|
main.go
|
https://github.com/LyricTian/gin-admin/blob/master/main.go
|
Apache-2.0
|
func StartCmd() *cli.Command {
return &cli.Command{
Name: "start",
Usage: "Start server",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "workdir",
Aliases: []string{"d"},
Usage: "Working directory",
DefaultText: "configs",
Value: "configs",
},
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Runtime configuration files or directory (relative to workdir, multiple separated by commas)",
DefaultText: "dev",
Value: "dev",
},
&cli.StringFlag{
Name: "static",
Aliases: []string{"s"},
Usage: "Static files directory",
},
&cli.BoolFlag{
Name: "daemon",
Usage: "Run as a daemon",
},
},
Action: func(c *cli.Context) error {
workDir := c.String("workdir")
staticDir := c.String("static")
configs := c.String("config")
if c.Bool("daemon") {
bin, err := filepath.Abs(os.Args[0])
if err != nil {
fmt.Printf("failed to get absolute path for command: %s \n", err.Error())
return err
}
args := []string{"start"}
args = append(args, "-d", workDir)
args = append(args, "-c", configs)
args = append(args, "-s", staticDir)
fmt.Printf("execute command: %s %s \n", bin, strings.Join(args, " "))
command := exec.Command(bin, args...)
// Redirect stdout and stderr to log file
stdLogFile := fmt.Sprintf("%s.log", c.App.Name)
file, err := os.OpenFile(stdLogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("failed to open log file: %s \n", err.Error())
return err
}
defer file.Close()
command.Stdout = file
command.Stderr = file
err = command.Start()
if err != nil {
fmt.Printf("failed to start daemon thread: %s \n", err.Error())
return err
}
// Don't wait for the command to finish
// The main process will exit, allowing the daemon to run independently
fmt.Printf("Service %s daemon thread started successfully\n", config.C.General.AppName)
pid := command.Process.Pid
_ = os.WriteFile(fmt.Sprintf("%s.lock", c.App.Name), []byte(fmt.Sprintf("%d", pid)), 0666)
fmt.Printf("service %s daemon thread started with pid %d \n", config.C.General.AppName, pid)
os.Exit(0)
}
err := bootstrap.Run(context.Background(), bootstrap.RunConfig{
WorkDir: workDir,
Configs: configs,
StaticDir: staticDir,
})
if err != nil {
panic(err)
}
return nil
},
}
}
|
The function defines a CLI command to start a server with various flags and options, including the
ability to run as a daemon.
|
StartCmd
|
go
|
LyricTian/gin-admin
|
cmd/start.go
|
https://github.com/LyricTian/gin-admin/blob/master/cmd/start.go
|
Apache-2.0
|
func StopCmd() *cli.Command {
return &cli.Command{
Name: "stop",
Usage: "stop server",
Action: func(c *cli.Context) error {
appName := c.App.Name
lockFile := fmt.Sprintf("%s.lock", appName)
pid, err := os.ReadFile(lockFile)
if err != nil {
return err
}
command := exec.Command("kill", string(pid))
err = command.Start()
if err != nil {
return err
}
err = os.Remove(lockFile)
if err != nil {
return fmt.Errorf("can't remove %s.lock. %s", appName, err.Error())
}
fmt.Printf("service %s stopped \n", appName)
return nil
},
}
}
|
The function defines a CLI command to stop a server by reading a lock file, killing the process with
the corresponding PID, and removing the lock file.
|
StopCmd
|
go
|
LyricTian/gin-admin
|
cmd/stop.go
|
https://github.com/LyricTian/gin-admin/blob/master/cmd/stop.go
|
Apache-2.0
|
func VersionCmd(v string) *cli.Command {
return &cli.Command{
Name: "version",
Usage: "Show version",
Action: func(_ *cli.Context) error {
fmt.Println(v)
return nil
},
}
}
|
This function creates a CLI command that prints the version number.
|
VersionCmd
|
go
|
LyricTian/gin-admin
|
cmd/version.go
|
https://github.com/LyricTian/gin-admin/blob/master/cmd/version.go
|
Apache-2.0
|
func Run(ctx context.Context, runCfg RunConfig) error {
defer func() {
if err := zap.L().Sync(); err != nil {
fmt.Printf("failed to sync zap logger: %s \n", err.Error())
}
}()
// Load configuration.
workDir := runCfg.WorkDir
staticDir := runCfg.StaticDir
config.MustLoad(workDir, strings.Split(runCfg.Configs, ",")...)
config.C.General.WorkDir = workDir
config.C.Middleware.Static.Dir = staticDir
config.C.Print()
config.C.PreLoad()
// Initialize logger.
cleanLoggerFn, err := logging.InitWithConfig(ctx, &config.C.Logger, initLoggerHook)
if err != nil {
return err
}
ctx = logging.NewTag(ctx, logging.TagKeyMain)
logging.Context(ctx).Info("starting service ...",
zap.String("version", config.C.General.Version),
zap.Int("pid", os.Getpid()),
zap.String("workdir", workDir),
zap.String("config", runCfg.Configs),
zap.String("static", staticDir),
)
// Start pprof server.
if addr := config.C.General.PprofAddr; addr != "" {
logging.Context(ctx).Info("pprof server is listening on " + addr)
go func() {
err := http.ListenAndServe(addr, nil)
if err != nil {
logging.Context(ctx).Error("failed to listen pprof server", zap.Error(err))
}
}()
}
// Build injector.
injector, cleanInjectorFn, err := wirex.BuildInjector(ctx)
if err != nil {
return err
}
if err := injector.M.Init(ctx); err != nil {
return err
}
// Initialize global prometheus metrics.
prom.Init()
return util.Run(ctx, func(ctx context.Context) (func(), error) {
cleanHTTPServerFn, err := startHTTPServer(ctx, injector)
if err != nil {
return cleanInjectorFn, err
}
return func() {
if err := injector.M.Release(ctx); err != nil {
logging.Context(ctx).Error("failed to release injector", zap.Error(err))
}
if cleanHTTPServerFn != nil {
cleanHTTPServerFn()
}
if cleanInjectorFn != nil {
cleanInjectorFn()
}
if cleanLoggerFn != nil {
cleanLoggerFn()
}
}, nil
})
}
|
The Run function initializes and starts a service with configuration and logging, and handles
cleanup upon exit.
|
Run
|
go
|
LyricTian/gin-admin
|
internal/bootstrap/bootstrap.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/bootstrap/bootstrap.go
|
Apache-2.0
|
func Load(dir string, names ...string) error {
// Set default values
if err := defaults.Set(C); err != nil {
return err
}
supportExts := []string{".json", ".toml"}
parseFile := func(name string) error {
ext := filepath.Ext(name)
if ext == "" || !strings.Contains(strings.Join(supportExts, ","), ext) {
return nil
}
buf, err := os.ReadFile(name)
if err != nil {
return errors.Wrapf(err, "failed to read config file %s", name)
}
switch ext {
case ".json":
err = json.Unmarshal(buf, C)
case ".toml":
err = toml.Unmarshal(buf, C)
}
return errors.Wrapf(err, "failed to unmarshal config %s", name)
}
for _, name := range names {
fullname := filepath.Join(dir, name)
info, err := os.Stat(fullname)
if err != nil {
return errors.Wrapf(err, "failed to get config file %s", name)
}
if info.IsDir() {
err := filepath.WalkDir(fullname, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
} else if d.IsDir() {
return nil
}
return parseFile(path)
})
if err != nil {
return errors.Wrapf(err, "failed to walk config dir %s", name)
}
continue
}
if err := parseFile(fullname); err != nil {
return err
}
}
return nil
}
|
Loads configuration files in various formats from a directory and parses them into
a struct.
|
Load
|
go
|
LyricTian/gin-admin
|
internal/config/parse.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/config/parse.go
|
Apache-2.0
|
func (a *Logger) Query(c *gin.Context) {
ctx := c.Request.Context()
var params schema.LoggerQueryParam
if err := util.ParseQuery(c, ¶ms); err != nil {
util.ResError(c, err)
return
}
result, err := a.LoggerBIZ.Query(ctx, params)
if err != nil {
util.ResError(c, err)
return
}
util.ResPage(c, result.Data, result.PageResult)
}
|
@Tags LoggerAPI
@Security ApiKeyAuth
@Summary Query logger list
@Param current query int true "pagination index" default(1)
@Param pageSize query int true "pagination size" default(10)
@Param level query string false "log level"
@Param traceID query string false "trace ID"
@Param userName query string false "user name"
@Param tag query string false "log tag"
@Param message query string false "log message"
@Param startTime query string false "start time"
@Param endTime query string false "end time"
@Success 200 {object} util.ResponseResult{data=[]schema.Logger}
@Failure 401 {object} util.ResponseResult
@Failure 500 {object} util.ResponseResult
@Router /api/v1/loggers [get]
|
Query
|
go
|
LyricTian/gin-admin
|
internal/mods/rbac/api/logger.api.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/mods/rbac/api/logger.api.go
|
Apache-2.0
|
func (a *Login) GetCaptcha(c *gin.Context) {
ctx := c.Request.Context()
data, err := a.LoginBIZ.GetCaptcha(ctx)
if err != nil {
util.ResError(c, err)
return
}
util.ResSuccess(c, data)
}
|
@Tags LoginAPI
@Summary Get captcha ID
@Success 200 {object} util.ResponseResult{data=schema.Captcha}
@Router /api/v1/captcha/id [get]
|
GetCaptcha
|
go
|
LyricTian/gin-admin
|
internal/mods/rbac/api/login.api.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/mods/rbac/api/login.api.go
|
Apache-2.0
|
func (a *Login) ResponseCaptcha(c *gin.Context) {
ctx := c.Request.Context()
err := a.LoginBIZ.ResponseCaptcha(ctx, c.Writer, c.Query("id"), c.Query("reload") == "1")
if err != nil {
util.ResError(c, err)
}
}
|
@Tags LoginAPI
@Summary Response captcha image
@Param id query string true "Captcha ID"
@Param reload query number false "Reload captcha image (reload=1)"
@Produce image/png
@Success 200 "Captcha image"
@Failure 404 {object} util.ResponseResult
@Router /api/v1/captcha/image [get]
|
ResponseCaptcha
|
go
|
LyricTian/gin-admin
|
internal/mods/rbac/api/login.api.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/mods/rbac/api/login.api.go
|
Apache-2.0
|
func (a *Login) Login(c *gin.Context) {
ctx := c.Request.Context()
item := new(schema.LoginForm)
if err := util.ParseJSON(c, item); err != nil {
util.ResError(c, err)
return
}
data, err := a.LoginBIZ.Login(ctx, item.Trim())
if err != nil {
util.ResError(c, err)
return
}
util.ResSuccess(c, data)
}
|
@Tags LoginAPI
@Summary Login system with username and password
@Param body body schema.LoginForm true "Request body"
@Success 200 {object} util.ResponseResult{data=schema.LoginToken}
@Failure 400 {object} util.ResponseResult
@Failure 500 {object} util.ResponseResult
@Router /api/v1/login [post]
|
Login
|
go
|
LyricTian/gin-admin
|
internal/mods/rbac/api/login.api.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/mods/rbac/api/login.api.go
|
Apache-2.0
|
func (a *Login) Logout(c *gin.Context) {
ctx := c.Request.Context()
err := a.LoginBIZ.Logout(ctx)
if err != nil {
util.ResError(c, err)
return
}
util.ResOK(c)
}
|
@Tags LoginAPI
@Security ApiKeyAuth
@Summary Logout system
@Success 200 {object} util.ResponseResult
@Failure 500 {object} util.ResponseResult
@Router /api/v1/current/logout [post]
|
Logout
|
go
|
LyricTian/gin-admin
|
internal/mods/rbac/api/login.api.go
|
https://github.com/LyricTian/gin-admin/blob/master/internal/mods/rbac/api/login.api.go
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.