github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/auth/rate_limiting.go (about) 1 package auth 2 3 import ( 4 "fmt" 5 6 "github.com/cozy/cozy-stack/model/instance" 7 "github.com/cozy/cozy-stack/model/instance/lifecycle" 8 "github.com/cozy/cozy-stack/pkg/config/config" 9 "github.com/cozy/cozy-stack/pkg/limits" 10 ) 11 12 // LoginRateExceeded blocks the instance after too many failed attempts to 13 // login 14 func LoginRateExceeded(i *instance.Instance) error { 15 err := fmt.Errorf("Instance was blocked because of too many login failed attempts") 16 i.Logger().WithNamespace("rate_limiting").Warn(err.Error()) 17 return lifecycle.Block(i, instance.BlockedLoginFailed.Code) 18 } 19 20 // TwoFactorRateExceeded regenerates a new 2FA passcode after too many failed 21 // attempts to login 22 func TwoFactorRateExceeded(i *instance.Instance) error { 23 err := config.GetRateLimiter().CheckRateLimit(i, limits.TwoFactorGenerationType) 24 if limits.IsLimitReachedOrExceeded(err) { 25 return TwoFactorGenerationExceeded(i) 26 } 27 // Reset the key and send a new passcode to the user 28 config.GetRateLimiter().ResetCounter(i, limits.TwoFactorType) 29 _, err = lifecycle.SendTwoFactorPasscode(i) 30 return err 31 } 32 33 // TwoFactorGenerationExceeded checks if there was too many attempts to 34 // regenerate a 2FA code within an hour 35 func TwoFactorGenerationExceeded(i *instance.Instance) error { 36 err := fmt.Errorf("Instance was blocked because of too many 2FA passcode generations") 37 i.Logger().WithNamespace("rate_limiting").Warn(err.Error()) 38 39 return lifecycle.Block(i, instance.BlockedLoginFailed.Code) 40 }