Skip to content

Commit

Permalink
renamed BlockedUser to InvalidLoginAttempt
Browse files Browse the repository at this point in the history
Signed-off-by: Abdul-Az <[email protected]>
  • Loading branch information
iamazzeez committed Apr 11, 2022
1 parent bd0c6d9 commit 4e5c55c
Show file tree
Hide file tree
Showing 10 changed files with 198 additions and 200 deletions.
48 changes: 24 additions & 24 deletions server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,32 +209,32 @@ func (s *Server) discoveryHandler() (http.HandlerFunc, error) {
}), nil
}

func (s *Server) isFailedAttemptDurationExceeded(u storage.BlockedUser) bool {
func (s *Server) isFailedAttemptDurationExceeded(u storage.InvalidLoginAttempt) bool {
if diff := time.Since(u.UpdatedAt); diff.Minutes() > float64(s.blockDuration) {
return true
}
return false
}

func (s *Server) resetFailedAttempt(username string, w http.ResponseWriter, r *http.Request) {
updater := func(u storage.BlockedUser) (storage.BlockedUser, error) {
updater := func(u storage.InvalidLoginAttempt) (storage.InvalidLoginAttempt, error) {
u.InvalidAttemptsCount = 1
u.UpdatedAt = time.Now()
return u, nil
}

if err := s.storage.UpdateBlockedUser(username, updater); err != nil {
if err := s.storage.UpdateInvalidLoginAttempt(username, updater); err != nil {
s.logger.Errorf("Failed to reset invalid counter: %v", err)
s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
}

func (s *Server) isAllowedFailedAttemptExceeded(u storage.BlockedUser) bool {
func (s *Server) isAllowedFailedAttemptExceeded(u storage.InvalidLoginAttempt) bool {
return u.InvalidAttemptsCount >= s.maxAttemptsAllowed
}

func (s *Server) isUserBlocked(u storage.BlockedUser) bool {
func (s *Server) isUserBlocked(u storage.InvalidLoginAttempt) bool {
diff := time.Since(u.UpdatedAt)
if diff.Minutes() <= float64(s.blockDuration) && u.InvalidAttemptsCount >= s.maxAttemptsAllowed {
return true
Expand All @@ -243,13 +243,13 @@ func (s *Server) isUserBlocked(u storage.BlockedUser) bool {
}

func (s *Server) updateInvalidAttemptCount(username string, w http.ResponseWriter, r *http.Request) {
updater := func(u storage.BlockedUser) (storage.BlockedUser, error) {
updater := func(u storage.InvalidLoginAttempt) (storage.InvalidLoginAttempt, error) {
u.InvalidAttemptsCount = u.InvalidAttemptsCount + 1
u.UpdatedAt = time.Now()
return u, nil
}

if err := s.storage.UpdateBlockedUser(username, updater); err != nil {
if err := s.storage.UpdateInvalidLoginAttempt(username, updater); err != nil {
s.logger.Errorf("Failed to increment invalid counter: %v", err)
s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
Expand Down Expand Up @@ -439,17 +439,17 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("login")
password := r.FormValue("password")

//check if username is in blocked_user table
blockedUser, err := s.storage.GetBlockedUser(username)
//check if username is in invalid_login_attempts table
InvalidLoginAttempt, err := s.storage.GetInvalidLoginAttempt(username)
if err != nil {
s.logger.Errorf("Failed to get blocked user: %v", err)
s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Failed to get blocked user: %v", err))
s.logger.Errorf("Failed to get InvalidLoginAttempt: %v", err)
s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Failed to get InvalidLoginAttempt: %v", err))
return
}

if s.isUserBlocked(blockedUser) {
if s.isUserBlocked(InvalidLoginAttempt) {
s.logger.Errorf("User is blocked")
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, blockedUser.InvalidAttemptsCount, s.maxAttemptsAllowed, s.blockDuration); err != nil {
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, InvalidLoginAttempt.InvalidAttemptsCount, s.maxAttemptsAllowed, s.blockDuration); err != nil {
s.logger.Errorf("Server template error: %v", err)
}
return
Expand All @@ -462,16 +462,16 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
return
}
if !ok {
if blockedUser.Username != username {
//create blocked user
err := s.storage.CreateBlockedUser(storage.BlockedUser{
if InvalidLoginAttempt.Username != username {
//create InvalidLoginAttempt
err := s.storage.CreateInvalidLoginAttempt(storage.InvalidLoginAttempt{
Username: username,
InvalidAttemptsCount: 1,
UpdatedAt: time.Now(),
})

if err != nil {
s.logger.Errorf("Failed to create blocked user: %v", err)
s.logger.Errorf("Failed to create InvalidLoginAttempt: %v", err)
s.renderError(r, w, http.StatusInternalServerError, "db error.")
return
}
Expand All @@ -482,25 +482,25 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
return
}

if s.isFailedAttemptDurationExceeded(blockedUser) {
if s.isFailedAttemptDurationExceeded(InvalidLoginAttempt) {
s.resetFailedAttempt(username, w, r)
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, 1, s.maxAttemptsAllowed, s.blockDuration); err != nil {
s.logger.Errorf("Server template error: %v", err)
}
return
}

if s.isAllowedFailedAttemptExceeded(blockedUser) {
s.logger.Errorf("User is blocked: %v", blockedUser.InvalidAttemptsCount)
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, blockedUser.InvalidAttemptsCount, s.maxAttemptsAllowed, s.blockDuration); err != nil {
if s.isAllowedFailedAttemptExceeded(InvalidLoginAttempt) {
s.logger.Errorf("User is blocked: %v", InvalidLoginAttempt.InvalidAttemptsCount)
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, InvalidLoginAttempt.InvalidAttemptsCount, s.maxAttemptsAllowed, s.blockDuration); err != nil {
s.logger.Errorf("Server template error: %v", err)
}
return
}

s.updateInvalidAttemptCount(username, w, r)

if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, blockedUser.InvalidAttemptsCount+1, s.maxAttemptsAllowed, s.blockDuration); err != nil {
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, InvalidLoginAttempt.InvalidAttemptsCount+1, s.maxAttemptsAllowed, s.blockDuration); err != nil {
s.logger.Errorf("Server template error: %v", err)
}
return
Expand All @@ -513,8 +513,8 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
return
}

if err := s.storage.DeleteBlockedUser(username); err != nil && err != storage.ErrNotFound {
s.logger.Errorf("Failed to delete blocked user: %v", err)
if err := s.storage.DeleteInvalidLoginAttempt(username); err != nil && err != storage.ErrNotFound {
s.logger.Errorf("Failed to delete InvalidLoginAttempt: %v", err)
s.renderError(r, w, http.StatusInternalServerError, "db error.")
return
}
Expand Down
40 changes: 20 additions & 20 deletions storage/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ import (
)

const (
clientPrefix = "client/"
authCodePrefix = "auth_code/"
refreshTokenPrefix = "refresh_token/"
authRequestPrefix = "auth_req/"
passwordPrefix = "password/"
blockedUserPrefix = "blocked_user/"
offlineSessionPrefix = "offline_session/"
connectorPrefix = "connector/"
keysName = "openid-connect-keys"
deviceRequestPrefix = "device_req/"
deviceTokenPrefix = "device_token/"
clientPrefix = "client/"
authCodePrefix = "auth_code/"
refreshTokenPrefix = "refresh_token/"
authRequestPrefix = "auth_req/"
passwordPrefix = "password/"
InvalidLoginAttemptPrefix = "invalid_login_attempt/"
offlineSessionPrefix = "offline_session/"
connectorPrefix = "connector/"
keysName = "openid-connect-keys"
deviceRequestPrefix = "device_req/"
deviceTokenPrefix = "device_token/"

// defaultStorageTimeout will be applied to all storage's operations.
defaultStorageTimeout = 5 * time.Second
Expand Down Expand Up @@ -284,10 +284,10 @@ func (c *conn) CreatePassword(p storage.Password) error {
return c.txnCreate(ctx, passwordPrefix+strings.ToLower(p.Email), p)
}

func (c *conn) CreateBlockedUser(u storage.BlockedUser) error {
func (c *conn) CreateInvalidLoginAttempt(u storage.InvalidLoginAttempt) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultStorageTimeout)
defer cancel()
return c.txnCreate(ctx, blockedUserPrefix+strings.ToLower(u.Username), u)
return c.txnCreate(ctx, InvalidLoginAttemptPrefix+strings.ToLower(u.Username), u)
}

func (c *conn) GetPassword(email string) (p storage.Password, err error) {
Expand All @@ -297,10 +297,10 @@ func (c *conn) GetPassword(email string) (p storage.Password, err error) {
return p, err
}

func (c *conn) GetBlockedUser(username string) (u storage.BlockedUser, err error) {
func (c *conn) GetInvalidLoginAttempt(username string) (u storage.InvalidLoginAttempt, err error) {
ctx, cancel := context.WithTimeout(context.Background(), defaultStorageTimeout)
defer cancel()
err = c.getKey(ctx, keyUsername(blockedUserPrefix, username), &u)
err = c.getKey(ctx, keyUsername(InvalidLoginAttemptPrefix, username), &u)
return u, err
}

Expand All @@ -322,11 +322,11 @@ func (c *conn) UpdatePassword(email string, updater func(p storage.Password) (st
})
}

func (c *conn) UpdateBlockedUser(username string, updater func(p storage.BlockedUser) (storage.BlockedUser, error)) error {
func (c *conn) UpdateInvalidLoginAttempt(username string, updater func(p storage.InvalidLoginAttempt) (storage.InvalidLoginAttempt, error)) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultStorageTimeout)
defer cancel()
return c.txnUpdate(ctx, keyEmail(blockedUserPrefix, username), func(currentValue []byte) ([]byte, error) {
var current storage.BlockedUser
return c.txnUpdate(ctx, keyEmail(InvalidLoginAttemptPrefix, username), func(currentValue []byte) ([]byte, error) {
var current storage.InvalidLoginAttempt
if len(currentValue) > 0 {
if err := json.Unmarshal(currentValue, &current); err != nil {
return nil, err
Expand All @@ -346,10 +346,10 @@ func (c *conn) DeletePassword(email string) error {
return c.deleteKey(ctx, keyEmail(passwordPrefix, email))
}

func (c *conn) DeleteBlockedUser(username string) error {
func (c *conn) DeleteInvalidLoginAttempt(username string) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultStorageTimeout)
defer cancel()
return c.deleteKey(ctx, keyEmail(blockedUserPrefix, username))
return c.deleteKey(ctx, keyEmail(InvalidLoginAttemptPrefix, username))
}

func (c *conn) ListPasswords() (passwords []storage.Password, err error) {
Expand Down
84 changes: 42 additions & 42 deletions storage/kubernetes/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,31 @@ import (
)

const (
kindAuthCode = "AuthCode"
kindAuthRequest = "AuthRequest"
kindClient = "OAuth2Client"
kindRefreshToken = "RefreshToken"
kindKeys = "SigningKey"
kindPassword = "Password"
kindBlockedUser = "BlockedUser"
kindOfflineSessions = "OfflineSessions"
kindConnector = "Connector"
kindDeviceRequest = "DeviceRequest"
kindDeviceToken = "DeviceToken"
kindAuthCode = "AuthCode"
kindAuthRequest = "AuthRequest"
kindClient = "OAuth2Client"
kindRefreshToken = "RefreshToken"
kindKeys = "SigningKey"
kindPassword = "Password"
kindInvalidLoginAttempt = "InvalidLoginAttempt"
kindOfflineSessions = "OfflineSessions"
kindConnector = "Connector"
kindDeviceRequest = "DeviceRequest"
kindDeviceToken = "DeviceToken"
)

const (
resourceAuthCode = "authcodes"
resourceAuthRequest = "authrequests"
resourceClient = "oauth2clients"
resourceRefreshToken = "refreshtokens"
resourceKeys = "signingkeies" // Kubernetes attempts to pluralize.
resourcePassword = "passwords"
resourceBlockedUser = "blockedusers"
resourceOfflineSessions = "offlinesessionses" // Again attempts to pluralize.
resourceConnector = "connectors"
resourceDeviceRequest = "devicerequests"
resourceDeviceToken = "devicetokens"
resourceAuthCode = "authcodes"
resourceAuthRequest = "authrequests"
resourceClient = "oauth2clients"
resourceRefreshToken = "refreshtokens"
resourceKeys = "signingkeies" // Kubernetes attempts to pluralize.
resourcePassword = "passwords"
resourceInvalidLoginAttempt = "InvalidLoginAttempt"
resourceOfflineSessions = "offlinesessionses" // Again attempts to pluralize.
resourceConnector = "connectors"
resourceDeviceRequest = "devicerequests"
resourceDeviceToken = "devicetokens"
)

// Config values for the Kubernetes storage type.
Expand Down Expand Up @@ -239,8 +239,8 @@ func (cli *client) CreatePassword(p storage.Password) error {
return cli.post(resourcePassword, cli.fromStoragePassword(p))
}

func (cli *client) CreateBlockedUser(u storage.BlockedUser) error {
return cli.post(resourceBlockedUser, cli.fromStorageBlockedUser(u))
func (cli *client) CreateInvalidLoginAttempt(u storage.InvalidLoginAttempt) error {
return cli.post(resourceInvalidLoginAttempt, cli.fromStorageInvalidLoginAttempt(u))
}

func (cli *client) CreateRefresh(r storage.RefreshToken) error {
Expand Down Expand Up @@ -299,12 +299,12 @@ func (cli *client) GetPassword(email string) (storage.Password, error) {
return toStoragePassword(p), nil
}

func (cli *client) GetBlockedUser(username string) (storage.BlockedUser, error) {
u, err := cli.getBlockedUser(username)
func (cli *client) GetInvalidLoginAttempt(username string) (storage.InvalidLoginAttempt, error) {
u, err := cli.getInvalidLoginAttempt(username)
if err != nil {
return storage.BlockedUser{}, err
return storage.InvalidLoginAttempt{}, err
}
return toStorageBlockedUser(u), nil
return toStorageInvalidLoginAttempt(u), nil
}

func (cli *client) getPassword(email string) (Password, error) {
Expand All @@ -321,15 +321,15 @@ func (cli *client) getPassword(email string) (Password, error) {
return p, nil
}

func (cli *client) getBlockedUser(username string) (BlockedUser, error) {
func (cli *client) getInvalidLoginAttempt(username string) (InvalidLoginAttempt, error) {
username = strings.ToLower(username)
var u BlockedUser
var u InvalidLoginAttempt
name := cli.idToName(username)
if err := cli.get(resourceBlockedUser, name, &u); err != nil {
return BlockedUser{}, err
if err := cli.get(resourceInvalidLoginAttempt, name, &u); err != nil {
return InvalidLoginAttempt{}, err
}
if username != u.Username {
return BlockedUser{}, fmt.Errorf("get blockedUser: username %q mapped to blockedUser with username %q", username, u.Username)
return InvalidLoginAttempt{}, fmt.Errorf("get InvalidLoginAttempt: username %q mapped to InvalidLoginAttempt with username %q", username, u.Username)
}
return u, nil
}
Expand Down Expand Up @@ -453,13 +453,13 @@ func (cli *client) DeletePassword(email string) error {
return cli.delete(resourcePassword, p.ObjectMeta.Name)
}

func (cli *client) DeleteBlockedUser(username string) error {
func (cli *client) DeleteInvalidLoginAttempt(username string) error {
// Check for hash collision.
u, err := cli.getBlockedUser(username)
u, err := cli.getInvalidLoginAttempt(username)
if err != nil {
return err
}
return cli.delete(resourceBlockedUser, u.ObjectMeta.Name)
return cli.delete(resourceInvalidLoginAttempt, u.ObjectMeta.Name)
}

func (cli *client) DeleteOfflineSessions(userID string, connID string) error {
Expand Down Expand Up @@ -527,22 +527,22 @@ func (cli *client) UpdatePassword(email string, updater func(old storage.Passwor
return cli.put(resourcePassword, p.ObjectMeta.Name, newPassword)
}

func (cli *client) UpdateBlockedUser(username string, updater func(old storage.BlockedUser) (storage.BlockedUser, error)) error {
u, err := cli.getBlockedUser(username)
func (cli *client) UpdateInvalidLoginAttempt(username string, updater func(old storage.InvalidLoginAttempt) (storage.InvalidLoginAttempt, error)) error {
u, err := cli.getInvalidLoginAttempt(username)
if err != nil {
return err
}

updated, err := updater(toStorageBlockedUser(u))
updated, err := updater(toStorageInvalidLoginAttempt(u))
if err != nil {
return err
}
updated.InvalidAttemptsCount = u.InvalidAttemptsCount
updated.UpdatedAt = u.UpdatedAt

newBlockedUser := cli.fromStorageBlockedUser(updated)
newBlockedUser.ObjectMeta = u.ObjectMeta
return cli.put(resourceBlockedUser, u.ObjectMeta.Name, newBlockedUser)
newInvalidLoginAttempt := cli.fromStorageInvalidLoginAttempt(updated)
newInvalidLoginAttempt.ObjectMeta = u.ObjectMeta
return cli.put(resourceInvalidLoginAttempt, u.ObjectMeta.Name, newInvalidLoginAttempt)
}

func (cli *client) UpdateOfflineSessions(userID string, connID string, updater func(old storage.OfflineSessions) (storage.OfflineSessions, error)) error {
Expand Down
Loading

0 comments on commit 4e5c55c

Please sign in to comment.