检查点:保留账号分组隔离实现,继续权限复审
This commit is contained in:
1 parent
4084bc0682
commit
8ad62d8509
23 files changed
+811
-81
No files matched your search
@@ -0,0 +1,132 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
func requireAccountScope(ctx *context.Context, w http.ResponseWriter, targetID int) bool {
|
||||
if ctx == nil || !accountgroup.CanAccess(db.Instance, ctx.UserID, ctx.EffectiveRole(), targetID) {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "无权查看或管理该账号")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func GetAccountGroups(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if ctx == nil {
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return
|
||||
}
|
||||
groups, err := accountgroup.VisibleGroups(db.Instance, ctx.UserID, ctx.EffectiveRole())
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
response.NewSuccessResponse(map[string]any{"groups": groups, "can_manage": ctx.EffectiveRole() == access.RoleSuperAdmin}).FPrint(w)
|
||||
}
|
||||
|
||||
func requireAccountGroupManagement(ctx *context.Context, w http.ResponseWriter) bool {
|
||||
if err := authorizeCapability(ctx, access.CapabilityAccountGroupManage, "", false); err != nil {
|
||||
writeUserAuthorizationError(w, err, "无权管理账号分组")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func SaveAccountGroup(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !requireAccountGroupManagement(ctx, w) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if decodeUserRequest(w, req, &input) != nil || input.ID < 0 {
|
||||
writeAccountGroupError(w, accountgroup.ErrInvalid)
|
||||
return
|
||||
}
|
||||
name, err := accountgroup.NormalizeName(input.Name)
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
if db.Instance == nil {
|
||||
writeSecurityError(w, response.ServerError, "数据库不可用")
|
||||
return
|
||||
}
|
||||
item := models.AccountGroup{ID: input.ID, Name: name}
|
||||
if item.ID == 0 {
|
||||
_, err = db.Instance.Insert(&item)
|
||||
} else {
|
||||
var found bool
|
||||
found, err = db.Instance.ID(item.ID).Exist(&models.AccountGroup{})
|
||||
if err == nil && !found {
|
||||
err = accountgroup.ErrInvalid
|
||||
}
|
||||
if err == nil {
|
||||
_, err = db.Instance.ID(item.ID).Cols("name").Update(&item)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(item).FPrint(w)
|
||||
}
|
||||
|
||||
func SetAccountGroupMembership(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !requireAccountGroupManagement(ctx, w) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
UserID int `json:"user_id"`
|
||||
GroupIDs []int `json:"group_ids"`
|
||||
Version int `json:"version"`
|
||||
}
|
||||
if decodeUserRequest(w, req, &input) != nil || input.UserID <= 0 || input.Version < 1 || input.GroupIDs == nil {
|
||||
writeAccountGroupError(w, accountgroup.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if db.Instance == nil {
|
||||
writeSecurityError(w, response.ServerError, "数据库不可用")
|
||||
return
|
||||
}
|
||||
var user models.User
|
||||
found, err := db.Instance.ID(input.UserID).Get(&user)
|
||||
if err != nil || !found {
|
||||
writeAccountGroupError(w, accountgroup.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if input.Version != user.SecurityVersion {
|
||||
writeAccountGroupError(w, accountgroup.ErrConflict)
|
||||
return
|
||||
}
|
||||
if err := accountgroup.SetMembership(db.Instance, user, input.GroupIDs); err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
InvalidateSecurityRuntimeUser(user.ID, user.Account)
|
||||
response.NewSuccessResponse(map[string]any{"user_id": user.ID}).FPrint(w)
|
||||
}
|
||||
|
||||
func writeAccountGroupError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, accountgroup.ErrDenied):
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "无权查看或管理该分组")
|
||||
case errors.Is(err, accountgroup.ErrInvalid):
|
||||
writeSecurityError(w, response.ParamsError, "分组参数无效:名称为 1–32 个字符,普通用户只能属于一个分组")
|
||||
case errors.Is(err, accountgroup.ErrConflict):
|
||||
writeSecurityError(w, response.ParamsError, "账号状态已变化,请刷新列表后重试")
|
||||
default:
|
||||
writeSecurityError(w, response.ServerError, "分组操作失败,请检查是否重名并刷新后重试")
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/services/logstore"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
@@ -29,7 +30,10 @@ func runtimeLogActors(requestContext context.Context, ctx *appcontext.Context) (
|
||||
return nil, logstore.ErrUnavailable
|
||||
}
|
||||
var users []models.User
|
||||
if err := db.Instance.Context(requestContext).Cols("id").Where(models.OrdinaryUserPredicate).Find(&users); err != nil {
|
||||
query := db.Instance.Context(requestContext).Cols("id").Where(models.OrdinaryUserPredicate)
|
||||
defer query.Close()
|
||||
accountgroup.ApplyScope(query, ctx.UserID, ctx.EffectiveRole())
|
||||
if err := query.Find(&users); err != nil {
|
||||
return nil, logstore.ErrUnavailable
|
||||
}
|
||||
for _, user := range users {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/services/logstore"
|
||||
"git.pcux.cn/xuans/Smail/services/notification"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
@@ -19,14 +20,17 @@ import (
|
||||
)
|
||||
|
||||
type notificationRequest struct {
|
||||
UserID int `json:"user_id"`
|
||||
Version int `json:"version"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
MinuteLimit int `json:"minute_limit"`
|
||||
DayLimit int `json:"day_limit"`
|
||||
UserID int `json:"user_id"`
|
||||
Version int `json:"version"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
MinuteLimit int `json:"minute_limit"`
|
||||
DayLimit int `json:"day_limit"`
|
||||
}
|
||||
|
||||
func loadNotificationUser(ctx *context.Context, w http.ResponseWriter, userID int, write bool) (*models.User, bool) {
|
||||
if !requireAccountScope(ctx, w, userID) {
|
||||
return nil, false
|
||||
}
|
||||
if ctx == nil || ctx.UserID <= 0 {
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return nil, false
|
||||
@@ -76,7 +80,9 @@ func GetNotificationStatus(ctx *context.Context, w http.ResponseWriter, req *htt
|
||||
}
|
||||
}
|
||||
user, ok := loadNotificationUser(ctx, w, userID, false)
|
||||
if !ok { return }
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := notification.Load(db.Instance, user.ID)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ServerError, "读取系统通知授权失败")
|
||||
@@ -84,20 +90,24 @@ func GetNotificationStatus(ctx *context.Context, w http.ResponseWriter, req *htt
|
||||
}
|
||||
minuteUsed, dayUsed := 0, 0
|
||||
now := time.Now().UTC()
|
||||
if item.MinuteKey == now.Format("2006-01-02T15:04") { minuteUsed = item.MinuteCount }
|
||||
if item.DayKey == now.Format("2006-01-02") { dayUsed = item.DayCount }
|
||||
if item.MinuteKey == now.Format("2006-01-02T15:04") {
|
||||
minuteUsed = item.MinuteCount
|
||||
}
|
||||
if item.DayKey == now.Format("2006-01-02") {
|
||||
dayUsed = item.DayCount
|
||||
}
|
||||
domain := config.CurrentMailDomains().Primary
|
||||
ports := config.CurrentMailPorts()
|
||||
response.NewSuccessResponse(map[string]any{
|
||||
"user_id": user.ID, "account": user.Account, "enabled": item.Enabled == 1,
|
||||
"configured": notification.Configured(item, *user), "version": item.CodeVersion,
|
||||
"account_available": user.Disabled == 0 && user.MustChangePassword == 0,
|
||||
"can_manage": access.CanManageNotification(ctx.EffectiveRole(), user.EffectiveRole(), ctx.UserID == user.ID),
|
||||
"minute_limit": item.MinuteLimit, "day_limit": item.DayLimit,
|
||||
"can_manage": access.CanManageNotification(ctx.EffectiveRole(), user.EffectiveRole(), ctx.UserID == user.ID),
|
||||
"minute_limit": item.MinuteLimit, "day_limit": item.DayLimit,
|
||||
"minute_used": minuteUsed, "day_used": dayUsed,
|
||||
"host": "smtp." + domain, "tls_port": ports.SMTPTLS, "starttls_port": ports.SMTPSTARTTLS,
|
||||
"username": notification.UsernamePrefix + user.Account + "@" + domain,
|
||||
"sender": validation.NotificationAddress(domain), "sender_name": "系统通知",
|
||||
"sender": validation.NotificationAddress(domain), "sender_name": "系统通知",
|
||||
"max_recipients": notification.MaxRecipients, "max_message_bytes": notification.MaxMessageBytes,
|
||||
}).FPrint(w)
|
||||
}
|
||||
@@ -113,21 +123,26 @@ func ListNotificationAccounts(ctx *context.Context, w http.ResponseWriter, req *
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(req.URL.Query().Get("page"))
|
||||
if page < 1 || page > 100000 { page = 1 }
|
||||
if page < 1 || page > 100000 {
|
||||
page = 1
|
||||
}
|
||||
query := db.Instance.Table(&models.User{})
|
||||
defer query.Close()
|
||||
accountgroup.ApplyScope(query, ctx.UserID, ctx.EffectiveRole())
|
||||
if ctx.EffectiveRole() == access.RoleAdmin {
|
||||
query.Where("(" + models.OrdinaryUserPredicate + ") OR id = ?", ctx.UserID)
|
||||
query.And("("+models.OrdinaryUserPredicate+") OR id = ?", ctx.UserID)
|
||||
}
|
||||
var users []models.User
|
||||
total, err := query.Asc("id").Limit(20, (page - 1) * 20).FindAndCount(&users)
|
||||
total, err := query.Asc("id").Limit(20, (page-1)*20).FindAndCount(&users)
|
||||
if err != nil {
|
||||
writeSecurityError(w, response.ServerError, "读取账号列表失败")
|
||||
return
|
||||
}
|
||||
items := make([]map[string]any, 0, len(users))
|
||||
userIDs := make([]int, 0, len(users))
|
||||
for _, user := range users { userIDs = append(userIDs, user.ID) }
|
||||
for _, user := range users {
|
||||
userIDs = append(userIDs, user.ID)
|
||||
}
|
||||
grants := make(map[int]models.NotificationGrant)
|
||||
if len(userIDs) > 0 {
|
||||
var rows []models.NotificationGrant
|
||||
@@ -135,7 +150,9 @@ func ListNotificationAccounts(ctx *context.Context, w http.ResponseWriter, req *
|
||||
writeSecurityError(w, response.ServerError, "读取账号通知状态失败")
|
||||
return
|
||||
}
|
||||
for _, item := range rows { grants[item.UserID] = item }
|
||||
for _, item := range rows {
|
||||
grants[item.UserID] = item
|
||||
}
|
||||
}
|
||||
for _, user := range users {
|
||||
item := grants[user.ID]
|
||||
@@ -152,10 +169,15 @@ func SetNotificationAuthorization(ctx *context.Context, w http.ResponseWriter, r
|
||||
return
|
||||
}
|
||||
user, ok := loadNotificationUser(ctx, w, input.UserID, true)
|
||||
if !ok { return }
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
err := notification.SetAuthorization(db.Instance, *user, input.Version, *input.Enabled, input.MinuteLimit, input.DayLimit)
|
||||
recordNotificationManagement(ctx, user.ID, "设置系统通知授权", err, map[string]any{"enabled": *input.Enabled, "minute_limit": input.MinuteLimit, "day_limit": input.DayLimit})
|
||||
if err != nil { writeNotificationError(w, err); return }
|
||||
if err != nil {
|
||||
writeNotificationError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"user_id": user.ID, "enabled": *input.Enabled}).FPrint(w)
|
||||
}
|
||||
|
||||
@@ -166,17 +188,24 @@ func RotateNotificationCredential(ctx *context.Context, w http.ResponseWriter, r
|
||||
return
|
||||
}
|
||||
user, ok := loadNotificationUser(ctx, w, input.UserID, true)
|
||||
if !ok { return }
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
code, err := notification.Rotate(db.Instance, *user, input.Version)
|
||||
recordNotificationManagement(ctx, user.ID, "重置系统通知凭据", err, nil)
|
||||
if err != nil { writeNotificationError(w, err); return }
|
||||
if err != nil {
|
||||
writeNotificationError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
response.NewSuccessResponse(map[string]any{"code": code, "user_id": user.ID}).FPrint(w)
|
||||
}
|
||||
|
||||
func recordNotificationManagement(ctx *context.Context, userID int, action string, err error, changes map[string]any) {
|
||||
result := "success"
|
||||
if err != nil { result = "failure" }
|
||||
if err != nil {
|
||||
result = "failure"
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]any{"target_user_id": userID, "changes": changes})
|
||||
logstore.Record(ctx, logstore.Entry{Kind: "operation", ActorID: strconv.Itoa(ctx.UserID), ActorRole: string(ctx.EffectiveRole()), Action: action,
|
||||
Section: "系统通知发信", Result: result, CreatedAt: time.Now(), Payload: payload})
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/accountgroup"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
"git.pcux.cn/xuans/Smail/session"
|
||||
"git.pcux.cn/xuans/Smail/utils/array"
|
||||
@@ -107,11 +108,14 @@ func CreateUser(ctx *context.Context, w http.ResponseWriter, req *http.Request)
|
||||
}
|
||||
|
||||
type userListRequest struct {
|
||||
CurrentPage int `json:"current_page"`
|
||||
PageSize int `json:"page_size"`
|
||||
GroupID *int `json:"group_id"`
|
||||
CurrentPage int `json:"current_page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type userListItem struct {
|
||||
GroupIDs []int `json:"GroupIDs,omitempty"`
|
||||
MembershipVersion int `json:"MembershipVersion,omitempty"`
|
||||
ID int `json:"ID"`
|
||||
Account string `json:"Account"`
|
||||
Name string `json:"Name"`
|
||||
@@ -176,8 +180,24 @@ func UserList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
var users []models.User
|
||||
query := db.Instance.Table(&models.User{})
|
||||
defer query.Close()
|
||||
if ctx.EffectiveRole() == access.RoleAdmin {
|
||||
query.Where(models.OrdinaryUserPredicate)
|
||||
accountgroup.ApplyScope(query, ctx.UserID, ctx.EffectiveRole())
|
||||
if reqData.GroupID != nil {
|
||||
groups, err := accountgroup.VisibleGroups(db.Instance, ctx.UserID, ctx.EffectiveRole())
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
allowed := false
|
||||
for _, group := range groups {
|
||||
if group.ID == *reqData.GroupID {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
writeAccountGroupError(w, accountgroup.ErrDenied)
|
||||
return
|
||||
}
|
||||
accountgroup.ApplyGroup(query, *reqData.GroupID)
|
||||
}
|
||||
totalNum, err := query.Asc("id").Limit(reqData.PageSize, offset).FindAndCount(&users)
|
||||
if err != nil {
|
||||
@@ -192,8 +212,21 @@ func UserList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
items := make([]userListItem, 0, len(users))
|
||||
memberships := map[int][]int{}
|
||||
if ctx.EffectiveRole() == access.RoleSuperAdmin {
|
||||
ids := make([]int, 0, len(users))
|
||||
for _, user := range users {
|
||||
ids = append(ids, user.ID)
|
||||
}
|
||||
memberships, err = accountgroup.Memberships(db.Instance, ids)
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, user := range users {
|
||||
items = append(items, userListItem{
|
||||
GroupIDs: memberships[user.ID],
|
||||
ID: user.ID,
|
||||
Account: user.Account,
|
||||
Name: user.Name,
|
||||
@@ -205,6 +238,9 @@ func UserList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
ExternalEmailEnabled: user.ExternalEmailEnabled == 1,
|
||||
ExternalEmailConfigured: externalEmailConfigured[user.ID],
|
||||
})
|
||||
if ctx.EffectiveRole() == access.RoleSuperAdmin {
|
||||
items[len(items)-1].MembershipVersion = user.SecurityVersion
|
||||
}
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{
|
||||
"current_page": reqData.CurrentPage,
|
||||
@@ -284,6 +320,9 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
targetRole := user.EffectiveRole()
|
||||
if !requireAccountScope(ctx, w, user.ID) {
|
||||
return
|
||||
}
|
||||
if err := authorizeCapability(ctx, access.CapabilityUserManage, targetRole, false); err != nil {
|
||||
response.NewErrorResponse(response.NoAccessPrivileges, "无权管理该用户", "").FPrint(w)
|
||||
return
|
||||
@@ -388,7 +427,9 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if reqData.Password != "" || user.Disabled != originalDisabled || user.EffectiveRole() != originalRole {
|
||||
updateColumns = append(updateColumns, "session_version", "security_version")
|
||||
}
|
||||
if num, err := tx.ID(user.ID).Where("session_version = ? AND security_version = ?", originalSessionVersion, originalSecurityVersion).Cols(updateColumns...).Update(&user); err != nil {
|
||||
update := tx.ID(user.ID).Where("session_version = ? AND security_version = ?", originalSessionVersion, originalSecurityVersion).Cols(updateColumns...)
|
||||
accountgroup.ApplyScope(update, ctx.UserID, ctx.EffectiveRole())
|
||||
if num, err := update.Update(&user); err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("update user failed")
|
||||
response.NewErrorResponse(response.ServerError, "更新用户失败", "").FPrint(w)
|
||||
return
|
||||
@@ -403,6 +444,17 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if user.EffectiveRole() != access.RoleAdmin {
|
||||
count, err := tx.Where("user_id = ?", user.ID).Count(&models.AccountGroupMember{})
|
||||
if err != nil {
|
||||
writeAccountGroupError(w, err)
|
||||
return
|
||||
}
|
||||
if count > 1 {
|
||||
writeSecurityError(w, response.ParamsError, "请先将账号调整为一个分组,再更改为普通用户")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("commit user update failed")
|
||||
response.NewErrorResponse(response.ServerError, "更新用户失败", "").FPrint(w)
|
||||
|
||||
@@ -27,6 +27,9 @@ type managedUserSecurityRequest struct {
|
||||
}
|
||||
|
||||
func loadManagedSecurityUser(ctx *context.Context, w http.ResponseWriter, userID int) (*models.User, bool) {
|
||||
if !requireAccountScope(ctx, w, userID) {
|
||||
return nil, false
|
||||
}
|
||||
if ctx == nil || ctx.UserID <= 0 {
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return nil, false
|
||||
|
||||
Reference in new issue
Block a user