feat: middleware for request body parsing, validation and authentication;
feat: helper function for getting request info from gin context
This commit is contained in:
@@ -43,13 +43,21 @@ func UserInfoFromContext(c *gin.Context) (*UserInfo, bool) {
|
||||
var ok bool
|
||||
|
||||
username, ok = c.Get("username") ; if !ok {
|
||||
return nil, true
|
||||
return &UserInfo{Username: "", Role: enums.GuestRole}, true
|
||||
}
|
||||
|
||||
role, ok = c.Get("role"); if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if username == nil {
|
||||
return &UserInfo{Username: "", Role: enums.GuestRole}, true
|
||||
}
|
||||
|
||||
if role == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &UserInfo{Username: username.(string), Role: role.(enums.Role)}, true
|
||||
}
|
||||
|
||||
@@ -67,9 +75,13 @@ func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if userInfo.Role < role {
|
||||
c.Status(http.StatusForbidden)
|
||||
}
|
||||
|
||||
var body T
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, err)
|
||||
c.String(http.StatusBadRequest, err.Error())
|
||||
|
||||
// TODO: implement automatic validation here
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user