Skip to content

Commit

Permalink
chore: Update cache creation and logging in CreateCache function
Browse files Browse the repository at this point in the history
  • Loading branch information
waveyboym committed Jul 21, 2024
1 parent c484ced commit a3f95f3
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 13 deletions.
5 changes: 4 additions & 1 deletion occupi-backend/configs/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ func ConnectToDatabase(args ...string) *mongo.Client {

// Create cache
func CreateCache() *bigcache.BigCache {
if GetGinRunMode() == "devlocalhost" || GetGinRunMode() == "devdeployed" || GetGinRunMode() == "devlocalhostdocker" {
if GetEnv() == "devlocalhost" || GetEnv() == "devdeployed" || GetEnv() == "devlocalhostdocker" {
logrus.Printf("Cache is disabled in %s mode\n", GetEnv())
return nil
}

Expand All @@ -77,6 +78,8 @@ func CreateCache() *bigcache.BigCache {
logrus.Fatal(err)
}

logrus.Info("Cache created!")

return cache
}

Expand Down
26 changes: 26 additions & 0 deletions occupi-backend/pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -1417,3 +1417,29 @@ func AddImageIDToRoom(ctx *gin.Context, appsession *models.AppSession, roomID, i

return nil
}

func CheckIfUserHasMFAEnabled(ctx *gin.Context, appsession *models.AppSession, email string) (bool, error) {
// check if database is nil
if appsession.DB == nil {
logrus.Error("Database is nil")
return false, errors.New("database is nil")
}

// check if user is in cache
if userData, err := cache.GetUser(appsession, email); err == nil {
return userData.Security.MFA, nil
}

collection := appsession.DB.Database(configs.GetMongoDBName()).Collection("Users")
filter := bson.M{"email": email}
var user models.User
err := collection.FindOne(ctx, filter).Decode(&user)
if err != nil {
return false, err
}

// Add the user to the cache if cache is not nil
cache.SetUser(appsession, user)

return user.Security.MFA, nil
}
6 changes: 3 additions & 3 deletions occupi-backend/pkg/handlers/auth_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ func ResetPassword(ctx *gin.Context, appsession *models.AppSession, role string,
http.StatusBadRequest,
"Password validation failed",
"ValidationErrorCode",
err.Error(),
"Password does not meet requirements",
nil))
return
}
Expand All @@ -437,7 +437,7 @@ func ResetPassword(ctx *gin.Context, appsession *models.AppSession, role string,
}

// Log the user in and Generate a JWT token
token, expi, err := GenerateJWTTokenAndStartSession(ctx, appsession, resetRequest.Email, role)
token, exp, err := GenerateJWTTokenAndStartSession(ctx, appsession, resetRequest.Email, role)
if err != nil {
ctx.JSON(http.StatusInternalServerError, utils.ErrorResponse(
http.StatusInternalServerError,
Expand All @@ -449,7 +449,7 @@ func ResetPassword(ctx *gin.Context, appsession *models.AppSession, role string,
}

// Use AllocateAuthTokens to handle the response
AllocateAuthTokens(ctx, token, expi, cookies)
AllocateAuthTokens(ctx, token, exp, cookies)
}

// handler for logging out a request
Expand Down
19 changes: 13 additions & 6 deletions occupi-backend/pkg/handlers/auth_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func ValidatePasswordEntry(ctx *gin.Context, appsession *models.AppSession, pass
constants.InvalidRequestPayloadCode,
"Password does neet meet requirements",
nil))
return false, nil
return false, errors.New("invalid password")
}

return true, nil
Expand All @@ -138,14 +138,14 @@ func ValidatePasswordEntryAndReturnHash(ctx *gin.Context, appsession *models.App
constants.InvalidRequestPayloadCode,
"Password does neet meet requirements",
nil))
return "", nil
return "", errors.New("invalid password")
}

password, err := utils.Argon2IDHash(password)

if err != nil {
ctx.JSON(http.StatusInternalServerError, utils.InternalServerError())
return "", nil
return "", err
}

return password, nil
Expand All @@ -163,7 +163,7 @@ func ValidatePasswordCorrectness(ctx *gin.Context, appsession *models.AppSession
constants.InvalidRequestPayloadCode,
"Password does neet meet requirements",
nil))
return false, nil
return false, errors.New("invalid password")
}

// fetch hashed password
Expand All @@ -185,7 +185,7 @@ func ValidatePasswordCorrectness(ctx *gin.Context, appsession *models.AppSession
constants.InvalidAuthCode,
"Password is incorrect",
nil))
return false, nil
return false, errors.New("password is incorrect")
}

return true, nil
Expand Down Expand Up @@ -325,7 +325,14 @@ func PreLoginAccountChecks(ctx *gin.Context, appsession *models.AppSession, emai
return false, err
}

if isVerificationDue {
// chec if the user has mfa enabled
mfaEnabled, err := database.CheckIfUserHasMFAEnabled(ctx, appsession, email)

if err != nil {
return false, err
}

if isVerificationDue || mfaEnabled {
_, err := SendOTPEmail(ctx, appsession, email, constants.ReverifyEmail)
if err != nil {
return false, err
Expand Down
6 changes: 3 additions & 3 deletions occupi-backend/pkg/models/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ type SecuritySettingsRequest struct {
Email string `json:"email" binding:"omitempty,email"`
Mfa string `json:"mfa"`
ForceLogout string `json:"forceLogout"`
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
NewPasswordConfirm string `json:"newPasswordConfirm"`
CurrentPassword string `json:"currentPassword" binding:"omitempty,min=8"`
NewPassword string `json:"newPassword" binding:"omitempty,min=8"`
NewPasswordConfirm string `json:"newPasswordConfirm" binding:"omitempty,min=8"`
}

type UserDetailsRequest struct {
Expand Down
33 changes: 33 additions & 0 deletions occupi-backend/tests/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,39 @@ func TestCompareArgon2IDHash(t *testing.T) {
})
}

func TestCompareArgon2IDHashAfterSanitizing(t *testing.T) {
password := "password123$"
wrongPassword := "wrongpassword"

hash, err := utils.Argon2IDHash(utils.SanitizeInput(password))
assert.NoError(t, err)
assert.NotEmpty(t, hash)

t.Run("Correct password sanitized", func(t *testing.T) {
match, err := utils.CompareArgon2IDHash(utils.SanitizeInput(password), hash)
assert.NoError(t, err)
assert.True(t, match)
})

t.Run("Incorrect password sanitized", func(t *testing.T) {
match, err := utils.CompareArgon2IDHash(utils.SanitizeInput(wrongPassword), hash)
assert.NoError(t, err)
assert.False(t, match)
})

t.Run("Empty password sanitized", func(t *testing.T) {
match, err := utils.CompareArgon2IDHash(utils.SanitizeInput(""), hash)
assert.NoError(t, err)
assert.False(t, match)
})

t.Run("Empty hash sanitized", func(t *testing.T) {
match, err := utils.CompareArgon2IDHash(utils.SanitizeInput(password), "")
assert.Error(t, err)
assert.False(t, match)
})
}

func TestSuccessResponse(t *testing.T) {
expected := gin.H{
"status": http.StatusOK,
Expand Down

0 comments on commit a3f95f3

Please sign in to comment.