AdGuardHome/internal/home/context.go
Stanislav Chzhen 21834ee3c5 Pull request 2414: AGDNS-2743-auth-middleware
Merge in DNS/adguard-home from AGDNS-2743-auth-middleware to master

Squashed commit of the following:

commit 3d0621f1992fd42ecdf3f5b1039d938db065e478
Merge: 320581ba7 57dc791f5
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Fri May 30 16:38:22 2025 +0300

    Merge branch 'master' into AGDNS-2743-auth-middleware

commit 320581ba7693183a39c53dc9f71180ab2a4f4d88
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Thu May 29 21:39:13 2025 +0300

    all: imp code

commit 4de3e7e9baa4459ce0c18d229c809dedeb59a590
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Thu May 29 17:46:51 2025 +0300

    home: imp tests

commit 6556aa48e77bd11254f097a888c51b6c5cd931b9
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Wed May 28 22:53:01 2025 +0300

    all: add tests

commit 338eea6699bd2f3ae654c2f1f65fe44f43f4b1dd
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue May 27 15:53:31 2025 +0300

    home: ctx key web user

commit 0453e5a9717954308331ea1aff2e43257c0f5569
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Thu May 22 14:28:09 2025 +0300

    home: auth mw
2025-05-30 16:49:10 +03:00

57 lines
1.2 KiB
Go

package home
import (
"context"
"fmt"
"github.com/AdguardTeam/AdGuardHome/internal/aghuser"
"github.com/AdguardTeam/golibs/errors"
)
// ctxKey is the type for context keys within this package.
type ctxKey uint8
const (
ctxKeyWebUser ctxKey = iota
)
// type check
var _ fmt.Stringer = ctxKey(0)
// String implements the [fmt.Stringer] interface for ctxKey.
func (k ctxKey) String() (s string) {
switch k {
case ctxKeyWebUser:
return "ctxKeyWebUser"
default:
panic(fmt.Errorf("ctx key: %w: %d", errors.ErrBadEnumValue, k))
}
}
// panicBadType is a helper that panics with a message about the context key and
// the expected type.
func panicBadType(key ctxKey, v any) {
panic(fmt.Errorf("bad type for %s: %T(%[2]v)", key, v))
}
// withWebUser returns a copy of the parent context with the web user added.
func withWebUser(ctx context.Context, u *aghuser.User) (withUser context.Context) {
return context.WithValue(ctx, ctxKeyWebUser, u)
}
// webUserFromContext returns the web user from the context, if any.
func webUserFromContext(ctx context.Context) (u *aghuser.User, ok bool) {
const key = ctxKeyWebUser
v := ctx.Value(key)
if v == nil {
return nil, false
}
u, ok = v.(*aghuser.User)
if !ok {
panicBadType(key, v)
}
return u, true
}