38 lines
957 B
Go
38 lines
957 B
Go
package access
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/user"
|
|
"RenewCMS/internal/infrastructure/useCases"
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
type currentUserContextKey struct{}
|
|
|
|
type currentUserHolder struct {
|
|
loaded bool
|
|
userID uint32
|
|
account user.User
|
|
err error
|
|
}
|
|
|
|
func WithCurrentUser(r *http.Request) *http.Request {
|
|
if _, present := r.Context().Value(currentUserContextKey{}).(*currentUserHolder); present {
|
|
return r
|
|
}
|
|
return r.WithContext(context.WithValue(r.Context(), currentUserContextKey{}, ¤tUserHolder{}))
|
|
}
|
|
|
|
func LoadUser(getUser *useCases.GetUserUseCase, r *http.Request, userID uint32) (user.User, error) {
|
|
holder, present := r.Context().Value(currentUserContextKey{}).(*currentUserHolder)
|
|
if !present {
|
|
return getUser.GetUser(userID)
|
|
}
|
|
if !holder.loaded || holder.userID != userID {
|
|
holder.account, holder.err = getUser.GetUser(userID)
|
|
holder.userID = userID
|
|
holder.loaded = true
|
|
}
|
|
return holder.account, holder.err
|
|
}
|