package handler import ( "context" "fmt" "mstore/app/descr" "mstore/app/router" "mstore/pkg/auxhttp" "mstore/pkg/auxpwd" ) const ( authTag = "authpass" userTag = "accountID" ) func (hand *Handler) AuthMiddleware(next router.Handler) router.Handler { var handlerFunc router.HandlerFunc handlerFunc = func(rctx *router.Context) { hand.logg.Debugf("Call authorization middleware") success, accountID, err := hand.CheckAccess(rctx) if success && err == nil { rctx.SetBool(authTag, true) rctx.SetString(userTag, accountID) } if err != nil { hand.logg.Errorf("Authorization middleware error: %v", err) } next.ServeHTTP(rctx) } return handlerFunc } func (hand *Handler) CheckAccess(rctx *router.Context) (bool, string, error) { var err error var success bool var username string var password string var accountID string accountID = descr.AnonymousID authHeader := rctx.GetHeader("Authorization") if authHeader != "" { hand.logg.Debugf("Authorization header is %s", authHeader) username, password, err = auxhttp.ParseBasicAuth(authHeader) if err != nil { return success, accountID, err } hand.logg.Debugf("Authorization username is %s:%s", username, password) } success = true // TODO: change to actual call return success, accountID, err } func (hand *Handler) ValidatePassword(ctx context.Context, username, password string) (bool, string, error) { var err error var accountID string valid := false accountExists, accountDescr, err := hand.mdb.GetAccountByUsername(ctx, username) if !accountExists { err := fmt.Errorf("Account not exists") return valid, accountID, err } if !auxpwd.PasswordMatch([]byte(password), accountDescr.Passhash) { err := fmt.Errorf("Login data mismatch") return valid, accountID, err } valid = true accountID = accountDescr.ID return valid, accountID, err }