info.go

 1package session
 2
 3import (
 4	"context"
 5	"fmt"
 6)
 7
 8type infoKey struct{}
 9
10var ctxKey infoKey = infoKey{}
11
12// ErrNoSessionInfo returned when the session cannot be extracted from the context
13var ErrNoSessionInfo error = fmt.Errorf("no session info found")
14
15// UserType records the basic category of user associated with the session
16type UserType int
17
18const (
19	// User is anonymous
20	Anonymous UserType = iota
21	// User has either an email or handle
22	Registered
23	// Matches the bot list
24	Bot
25)
26
27// Info returns the user associated with the session
28type Info[T ~int64] struct {
29	ID   T
30	Type UserType
31}
32
33func NewInfo[T ~int64](id T, type_ UserType) Info[T] {
34	return Info[T]{ID: id, Type: type_}
35}
36
37// ToContext includes the session info in the request context
38func ToContext[T ~int64](ctx context.Context, i Info[T]) context.Context {
39	return context.WithValue(ctx, ctxKey, i)
40}
41
42// FromContext extracts the info from the request context. If the session info
43// is not found or the wrong type, it returns ErrNoSessionInfo
44func FromContext[T ~int64](ctx context.Context) (Info[T], error) {
45	i, ok := ctx.Value(ctxKey).(Info[T])
46	if !ok {
47		return Info[T]{}, ErrNoSessionInfo
48	}
49	return i, nil
50}