1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-18 13:47:47 +02:00

return an error in case of required MFA so that external handlers can react if necessary

This commit is contained in:
Gani Georgiev 2024-11-21 11:12:25 +02:00
parent 8ab02ce402
commit 7ee6b11e9d
3 changed files with 16 additions and 10 deletions

View File

@ -79,17 +79,17 @@ func recordAuthWithOTP(e *core.RequestEvent) error {
}
}
err = RecordAuthResponse(e.RequestEvent, e.Record, core.MFAMethodOTP, nil)
if err != nil {
return err
}
// try to delete the used otp
err = e.App.Delete(e.OTP)
if err != nil {
e.App.Logger().Error("Failed to delete used OTP", "error", err, "otpId", e.OTP.Id)
}
err = RecordAuthResponse(e.RequestEvent, e.Record, core.MFAMethodOTP, nil)
if err != nil {
return err
}
return nil
})
}

View File

@ -20,6 +20,8 @@ const (
fieldsQueryParam = "fields"
)
var ErrMFA = errors.New("mfa required")
// RecordAuthResponse writes standardized json record auth response
// into the specified request context.
//
@ -70,9 +72,12 @@ func recordAuthResponse(e *core.RequestEvent, authRecord *core.Record, token str
// require additional authentication
if mfaId != "" {
return e.JSON(http.StatusUnauthorized, map[string]string{
// eagerly write the mfa response and return an err so that
// external middlewars are aware that the auth response requires an extra step
e.JSON(http.StatusUnauthorized, map[string]string{
"mfaId": mfaId,
})
return ErrMFA
}
// ---

View File

@ -2,6 +2,7 @@ package apis_test
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@ -584,8 +585,8 @@ func TestRecordAuthResponseMFACheck(t *testing.T) {
user.Collection().MFA.Rule = "1=1"
err = apis.RecordAuthResponse(event, user, "example", nil)
if err != nil {
t.Fatalf("Expected nil, got error: %v", err)
if !errors.Is(err, apis.ErrMFA) {
t.Fatalf("Expected ErrMFA, got: %v", err)
}
body := rec.Body.String()
@ -602,8 +603,8 @@ func TestRecordAuthResponseMFACheck(t *testing.T) {
resetMFAs(user)
err = apis.RecordAuthResponse(event, user, "example", nil)
if err != nil {
t.Fatalf("Expected nil, got error: %v", err)
if !errors.Is(err, apis.ErrMFA) {
t.Fatalf("Expected ErrMFA, got: %v", err)
}
body := rec.Body.String()