Skip to content

Commit 3515d60

Browse files
Merge pull request #94 from glocurrency/GEN-2622
feat: totp
2 parents e324947 + 5a7819b commit 3515d60

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

middleware/auth.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,22 @@ func RequireSecondFactorPhone() gin.HandlerFunc {
4848
ctx.Next()
4949
}
5050
}
51+
52+
func RequireSecondFactor() gin.HandlerFunc {
53+
return func(ctx *gin.Context) {
54+
userInfo := ginfirebasemw.GetUserInfo(ctx)
55+
56+
// skip validation of service accounts
57+
if userInfo.IsServiceAccount() {
58+
ctx.Next()
59+
return
60+
}
61+
62+
if userInfo.Firebase.SignInSecondFactor == "" {
63+
ctx.AbortWithStatusJSON(response.NewErrResponseForbidden("Please add a second factor authentication"))
64+
return
65+
}
66+
67+
ctx.Next()
68+
}
69+
}

middleware/auth_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,46 @@ func TestRequireSecondFactorPhone(t *testing.T) {
115115
})
116116
}
117117
}
118+
119+
func TestRequireSecondFactor(t *testing.T) {
120+
tests := []struct {
121+
name string
122+
header []byte
123+
wantStatus int
124+
}{
125+
126+
{
127+
"no second factor",
128+
userEmailVerified,
129+
http.StatusForbidden,
130+
},
131+
{
132+
"has second factor phone",
133+
userSecondFactorPhone,
134+
http.StatusOK,
135+
},
136+
}
137+
138+
for i := range tests {
139+
test := tests[i]
140+
t.Run(test.name, func(t *testing.T) {
141+
t.Parallel()
142+
143+
req := httptest.NewRequest(http.MethodGet, "/", nil)
144+
145+
// encoding the header value to match what expected by `ginfirebasemw`
146+
req.Header.Set("X-Apigateway-Api-Userinfo", base64.RawURLEncoding.EncodeToString(test.header))
147+
148+
w := httptest.NewRecorder()
149+
router := router.NewRouterWithValidation()
150+
router.Use(ginfirebasemw.Middleware())
151+
router.Use(middleware.RequireSecondFactor())
152+
router.GET("/", func(ctx *gin.Context) {
153+
ctx.String(http.StatusOK, "the end.")
154+
})
155+
router.ServeHTTP(w, req)
156+
157+
require.Equal(t, test.wantStatus, w.Code)
158+
})
159+
}
160+
}

0 commit comments

Comments
 (0)