Перенести WithUser в httpx
This commit is contained in:
@@ -1,16 +1,18 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const keyUserID = "messenger.user_id"
|
||||
|
||||
// SetUserID records the identified caller for the handlers behind the
|
||||
// identification middleware and for the access log. It lives here rather
|
||||
// than in the auth package because the access log needs it and auth already
|
||||
// depends on this package.
|
||||
// SetUserID records the authenticated caller for the handlers behind the
|
||||
// authentication middleware and for the access log. It lives here rather
|
||||
// than in the auth package because the access log needs it and the business
|
||||
// modules must not depend on auth.
|
||||
func SetUserID(c *gin.Context, id uuid.UUID) {
|
||||
c.Set(keyUserID, id)
|
||||
}
|
||||
@@ -23,3 +25,20 @@ func UserID(c *gin.Context) (uuid.UUID, bool) {
|
||||
id, ok := v.(uuid.UUID)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
// UserHandler is a handler that needs the authenticated caller.
|
||||
type UserHandler func(c *gin.Context, actor uuid.UUID)
|
||||
|
||||
// WithUser adapts a UserHandler to gin. Reaching it without the
|
||||
// authentication middleware in front is a wiring mistake, so it is reported
|
||||
// as an internal error rather than blamed on the client with a 401.
|
||||
func WithUser(h UserHandler) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
actor, ok := UserID(c)
|
||||
if !ok {
|
||||
Error(c, errors.New("route is missing the authentication middleware"))
|
||||
return
|
||||
}
|
||||
h(c, actor)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user