working commit

This commit is contained in:
2026-02-14 18:45:11 +02:00
parent 8d46c6a677
commit 53ed35dc08
16 changed files with 144 additions and 120 deletions
+126
View File
@@ -0,0 +1,126 @@
package handler
import (
"context"
"fmt"
"regexp"
"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 {
rctx.SetBool(authTag, true)
rctx.SetString(userTag, accountID)
hand.logg.Debugf("Authorization for accountID [%s]", rctx.Strings[userTag])
}
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
}
}
success, id, err := hand.ValidatePassword(rctx.Ctx, username, password)
if err != nil {
return false, accountID, err
}
if !success {
err = fmt.Errorf("Incorrect username or password")
return false, accountID, err
}
accountID = id
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
}
func (hand *Handler) CheckRight(ctx context.Context, accountID, right, subject string) (bool, error) {
var err error
var res bool
hand.logg.Debugf("Cop check your right %s: %s %s", accountID, right, subject)
// =[]=
// /------\
// .---[-] [#] \--,
// >| [ ] [ ] |
// '--0-------0----'
// Bad news for you, baby.... #
// TODO: defer logger
defer hand.logg.Debugf("Checking right %s for %s: %v", right, accountID, res)
exists, grant, err := hand.mdb.GetGrantByAccoundIDRight(ctx, accountID, right)
if err != nil {
return res, err
}
if !exists {
return res, err
}
switch right {
case descr.RightReadFiles, descr.RightWriteFiles:
grant.Pattern = ".*"
re, err := regexp.Compile(grant.Pattern)
if err != nil {
return res, err
}
if !re.MatchString(subject) {
return res, err
}
default:
// NOP
}
res = true
return res, err
}