Apply go fix ./... analysers (Go 1.26) across backend and examples:
- interface{} → any (type alias, no behaviour change)
- for i := 0; i < N; i++ → for range N / for i := range N
- slices.Contains / slices.ContainsFunc replacing manual loops
- strings.SplitSeq replacing strings.Split in range (avoids allocation)
- strings.CutPrefix replacing HasPrefix+TrimPrefix
- min() replacing manual if/else
- fmt.Appendf replacing []byte(fmt.Sprintf(...))
- strings.Builder replacing string += concatenation
- wg.Go(func(){}) replacing wg.Add(1)/go/wg.Done() pattern
- removed redundant ii := i loop variable copies (unnecessary since Go 1.22)
omitempty on struct-typed JSON fields: go fix removed omitempty from
struct-typed fields (time.Time, PostInfo, UserDetailEntry) because
encoding/json's omitempty never applied to struct types — it was always
a no-op. Kept as bare tags (no omitzero replacement) to preserve the
existing serialisation behaviour.
69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package rest
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/go-pkgz/auth/v2/token"
|
|
|
|
"github.com/umputun/remark42/backend/app/store"
|
|
)
|
|
|
|
// MustGetUserInfo fails if can't extract user data from the request.
|
|
// should be called from authed controllers only
|
|
func MustGetUserInfo(r *http.Request) store.User {
|
|
user, err := GetUserInfo(r)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return user
|
|
}
|
|
|
|
// GetUserInfo returns user from request context
|
|
func GetUserInfo(r *http.Request) (user store.User, err error) {
|
|
u, err := token.GetUserInfo(r)
|
|
if err != nil {
|
|
return store.User{}, fmt.Errorf("can't extract user info from the token: %w", err)
|
|
}
|
|
|
|
return store.User{
|
|
Name: u.Name,
|
|
ID: u.ID,
|
|
IP: u.IP,
|
|
Picture: u.Picture,
|
|
Admin: u.IsAdmin(),
|
|
Verified: u.BoolAttr("verified"),
|
|
Blocked: u.BoolAttr("blocked"),
|
|
SiteID: u.Audience,
|
|
PaidSub: u.IsPaidSub(),
|
|
}, nil
|
|
}
|
|
|
|
// GetUserOrEmpty attempts to get user info from request and returns empty object if failed
|
|
func GetUserOrEmpty(r *http.Request) store.User {
|
|
user, err := GetUserInfo(r)
|
|
if err != nil {
|
|
return store.User{}
|
|
}
|
|
return user
|
|
}
|
|
|
|
// SetUserInfo sets user into request context
|
|
func SetUserInfo(r *http.Request, user store.User) *http.Request {
|
|
u := token.User{
|
|
ID: user.ID,
|
|
Name: user.Name,
|
|
Picture: user.Picture,
|
|
IP: user.IP,
|
|
Audience: user.SiteID,
|
|
Attributes: map[string]any{
|
|
"blocked": user.Blocked,
|
|
"verified": user.Verified,
|
|
},
|
|
}
|
|
u.SetAdmin(user.Admin)
|
|
u.SetPaidSub(user.PaidSub)
|
|
|
|
return token.SetUserInfo(r, u)
|
|
}
|