Documentation ¶
Overview ¶
Package twofactor provides authentication strategy, to authenticate HTTP requests based on one time password(otp).
Example ¶
package main import ( "context" "fmt" "net/http" "github.com/shaj13/go-guardian/v2/auth" "github.com/shaj13/go-guardian/v2/auth/strategies/basic" "github.com/shaj13/go-guardian/v2/auth/strategies/twofactor" "github.com/shaj13/go-guardian/v2/otp" ) type OTPManager struct{} func (OTPManager) Enabled(_ auth.Info) bool { return true } func (OTPManager) Load(_ auth.Info) (twofactor.Verifier, error) { // user otp configuration must be loaded from persistent storage key := otp.NewKey(otp.HOTP, "LABEL", "GXNRHI2MFRFWXQGJHWZJFOSYI6E7MEVA") ver := otp.New(key) return ver, nil } func (OTPManager) Store(_ auth.Info, o twofactor.Verifier) error { // persist user otp after verification fmt.Println("Failures: ", o.(*otp.Verifier).Failures) return nil } func main() { strategy := twofactor.TwoFactor{ Parser: twofactor.XHeaderParser("X-Example-OTP"), Manager: OTPManager{}, Primary: basic.New( func(ctx context.Context, r *http.Request, userName, password string) (auth.Info, error) { return auth.NewDefaultUser("example", "1", nil, nil), nil }, ), } r, _ := http.NewRequest("GET", "/", nil) r.SetBasicAuth("example", "example") r.Header.Set("X-Example-OTP", "345515") info, err := strategy.Authenticate(r.Context(), r) fmt.Println(info.GetUserName(), err) }
Output: Failures: 0 example <nil>
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidOTP = errors.New("strategies/twofactor: Invalid one time password")
ErrInvalidOTP is returned by twofactor strategy, When the user-supplied an invalid one time password and verification process failed.
var ErrMissingOTP = errors.New("strategies/twofactor: One-time password missing or empty")
ErrMissingOTP is returned by Parser, When one-time password missing or empty in HTTP request.
Functions ¶
This section is empty.
Types ¶
type Manager ¶
type Manager interface { // Enabled check if two factor for user enabled. Enabled(user auth.Info) bool // Load return user OTP Verifier or error. Load(user auth.Info) (Verifier, error) // Store user OTP Verifier. Store(user auth.Info, v Verifier) error }
Manager load and store user OTP Verifier.
type Parser ¶
Parser parse and extract one-time password from incoming HTTP request.
func CookieParser ¶
CookieParser return a one-time password parser, where otp extracted form HTTP Cookie.
func JSONBodyParser ¶
JSONBodyParser return a one-time password parser, where otp extracted form request body.
func QueryParser ¶
QueryParser return a one-time password parser, where otp extracted form HTTP query string.
func XHeaderParser ¶
XHeaderParser return a one-time password parser, where otp extracted form "X-" header.