Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,22 @@ func RequireSecondFactorPhone() gin.HandlerFunc {
ctx.Next()
}
}

func RequireSecondFactor() gin.HandlerFunc {
return func(ctx *gin.Context) {
userInfo := ginfirebasemw.GetUserInfo(ctx)

// skip validation of service accounts
if userInfo.IsServiceAccount() {
ctx.Next()
return
}

if userInfo.Firebase.SignInSecondFactor == "" {
ctx.AbortWithStatusJSON(response.NewErrResponseForbidden("Please add a second factor authentication"))
return
}

ctx.Next()
}
}
43 changes: 43 additions & 0 deletions middleware/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,46 @@ func TestRequireSecondFactorPhone(t *testing.T) {
})
}
}

func TestRequireSecondFactor(t *testing.T) {
tests := []struct {
name string
header []byte
wantStatus int
}{

{
"no second factor",
userEmailVerified,
http.StatusForbidden,
},
{
"has second factor phone",
userSecondFactorPhone,
http.StatusOK,
},
}

for i := range tests {
test := tests[i]
t.Run(test.name, func(t *testing.T) {
t.Parallel()

req := httptest.NewRequest(http.MethodGet, "/", nil)

// encoding the header value to match what expected by `ginfirebasemw`
req.Header.Set("X-Apigateway-Api-Userinfo", base64.RawURLEncoding.EncodeToString(test.header))

w := httptest.NewRecorder()
router := router.NewRouterWithValidation()
router.Use(ginfirebasemw.Middleware())
router.Use(middleware.RequireSecondFactor())
router.GET("/", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "the end.")
})
router.ServeHTTP(w, req)

require.Equal(t, test.wantStatus, w.Code)
})
}
}