mirror of
https://github.com/go-gitea/gitea.git
synced 2026-11-19 15:14:40 +09:00
enhance: allow admins to force user activity visibility (#40002)
Adds `[service] FORCE_USER_ACTIVITY_VISIBILITY` so admins can force the activity of all users to be `public` or `private`, e.g. for company instances that require public activity. - When the value changes, the next start overwrites the "Hide Activity" setting of all users. New users get the forced value too. - The "Hide Activity" checkbox is disabled with an explanatory tooltip while forced, and `PATCH /api/v1/user/settings` rejects a conflicting `hide_activity` with 422. | Before | After | | --- | --- | | <img width="122" height="17" alt="before" src="https://github.com/user-attachments/assets/d138acec-5d40-4a0a-881c-0097e5197a8f" /> | <img width="258" height="46" alt="after" src="https://github.com/user-attachments/assets/7e8f7d1b-3303-4473-8d3b-aa35ef8fb20d" /> | Fixes: https://github.com/go-gitea/gitea/issues/37961 Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: bircni <bircni@icloud.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
17 files changed
+115
-22
No files matched your search
@@ -912,6 +912,9 @@ LEVEL = Info
|
||||
;; Each new user will get the value of this setting copied into their profile
|
||||
;DEFAULT_KEEP_EMAIL_PRIVATE = false
|
||||
;;
|
||||
;; Force all users' activity to "public" or "private", overwriting their "Hide Activity" setting
|
||||
;FORCE_USER_ACTIVITY_VISIBILITY =
|
||||
;;
|
||||
;; Default value for AllowCreateOrganization
|
||||
;; Every new user will have rights set to create organizations depending on this setting
|
||||
;DEFAULT_ALLOW_CREATE_ORGANIZATION = true
|
||||
|
||||
@@ -722,6 +722,7 @@ func createUser(ctx context.Context, u *User, meta *Meta, createdByAdmin bool, o
|
||||
|
||||
// set system defaults
|
||||
u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
|
||||
u.KeepActivityPrivate = setting.Service.ForceUserActivityVisibility == "private"
|
||||
u.Visibility = setting.Service.DefaultUserVisibilityMode
|
||||
u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
|
||||
u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
|
||||
@@ -1021,6 +1022,13 @@ func UpdateUserColsNoAutoTime(ctx context.Context, u *User, cols ...string) erro
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateAllUsersKeepActivityPrivate sets the activity visibility of all users, organizations excluded
|
||||
func UpdateAllUsersKeepActivityPrivate(ctx context.Context, keepActivityPrivate bool) error {
|
||||
_, err := db.GetEngine(ctx).Where(builder.Neq{"keep_activity_private": keepActivityPrivate, "type": UserTypeOrganization}).
|
||||
Cols("keep_activity_private").NoAutoTime().Update(&User{KeepActivityPrivate: keepActivityPrivate})
|
||||
return err
|
||||
}
|
||||
|
||||
// GetInactiveUsers gets all inactive users
|
||||
func GetInactiveUsers(ctx context.Context, olderThan time.Duration) ([]*User, error) {
|
||||
cond := builder.And(
|
||||
|
||||
@@ -65,6 +65,7 @@ var Service = struct {
|
||||
McaptchaSitekey string
|
||||
McaptchaURL string
|
||||
DefaultKeepEmailPrivate bool
|
||||
ForceUserActivityVisibility string
|
||||
DefaultAllowCreateOrganization bool
|
||||
DefaultUserIsRestricted bool
|
||||
EnableTimetracking bool
|
||||
@@ -193,6 +194,7 @@ func loadServiceFrom(rootCfg ConfigProvider) {
|
||||
Service.McaptchaSecret = sec.Key("MCAPTCHA_SECRET").MustString("")
|
||||
Service.McaptchaSitekey = sec.Key("MCAPTCHA_SITEKEY").MustString("")
|
||||
Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
|
||||
Service.ForceUserActivityVisibility = sec.Key("FORCE_USER_ACTIVITY_VISIBILITY").In("", []string{"public", "private"})
|
||||
Service.DefaultAllowCreateOrganization = sec.Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").MustBool(true)
|
||||
Service.DefaultUserIsRestricted = sec.Key("DEFAULT_USER_IS_RESTRICTED").MustBool(false)
|
||||
Service.EnableTimetracking = sec.Key("ENABLE_TIMETRACKING").MustBool(true)
|
||||
|
||||
@@ -11,15 +11,14 @@ type StateStore interface {
|
||||
Set(ctx context.Context, item StateItem) error
|
||||
}
|
||||
|
||||
// StateItem provides the name for a state item. the name will be used to generate filenames, etc
|
||||
// StateItem provides the name for a state item that is used to the generate key for persistence
|
||||
type StateItem interface {
|
||||
Name() string
|
||||
StateName() string
|
||||
}
|
||||
|
||||
// AppState contains the state items for the app
|
||||
var AppState StateStore
|
||||
|
||||
// Init initialize AppState interface
|
||||
// Init initialize AppState interface to use database to store app state items
|
||||
func Init() error {
|
||||
AppState = &DBStore{}
|
||||
return nil
|
||||
|
||||
@@ -20,7 +20,7 @@ type testItem1 struct {
|
||||
Val2 int
|
||||
}
|
||||
|
||||
func (*testItem1) Name() string {
|
||||
func (*testItem1) StateName() string {
|
||||
return "test-item1"
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ type testItem2 struct {
|
||||
K string
|
||||
}
|
||||
|
||||
func (*testItem2) Name() string {
|
||||
func (*testItem2) StateName() string {
|
||||
return "test-item2"
|
||||
}
|
||||
|
||||
|
||||
+14
-8
@@ -5,32 +5,38 @@ package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gitea.dev/models/system"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// DBStore can be used to store app state items in local filesystem
|
||||
type DBStore struct{}
|
||||
|
||||
// Get reads the state item
|
||||
func (f *DBStore) Get(ctx context.Context, item StateItem) error {
|
||||
content, err := system.GetAppStateContent(ctx, item.Name())
|
||||
content, err := system.GetAppStateContent(ctx, item.StateName())
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to get app state item %s: %w", item.StateName(), err)
|
||||
}
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(util.UnsafeStringToBytes(content), item)
|
||||
err = json.Unmarshal(util.UnsafeStringToBytes(content), item)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to unmarshal app state item %s: %w", item.StateName(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set saves the state item
|
||||
func (f *DBStore) Set(ctx context.Context, item StateItem) error {
|
||||
b, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to marshal app state item %s: %w", item.StateName(), err)
|
||||
}
|
||||
return system.SaveAppStateContent(ctx, item.Name(), util.UnsafeBytesToString(b))
|
||||
err = system.SaveAppStateContent(ctx, item.StateName(), util.UnsafeBytesToString(b))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to save app state item %s: %w", item.StateName(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -3,13 +3,19 @@
|
||||
|
||||
package system
|
||||
|
||||
// RuntimeState contains app state for runtime, and we can save remote version for update checker here in future
|
||||
type RuntimeState struct {
|
||||
LastAppPath string `json:"last_app_path"`
|
||||
LastCustomConf string `json:"last_custom_conf"`
|
||||
}
|
||||
|
||||
// Name returns the item name
|
||||
func (a RuntimeState) Name() string {
|
||||
func (RuntimeState) StateName() string {
|
||||
return "runtime-state"
|
||||
}
|
||||
|
||||
type LastConfig struct {
|
||||
ForceUserActivityVisibility string `json:"force_user_activity_visibility"`
|
||||
}
|
||||
|
||||
func (LastConfig) StateName() string {
|
||||
return "last-config"
|
||||
}
|
||||
@@ -21,8 +21,7 @@ type CheckerState struct {
|
||||
LatestVersion string
|
||||
}
|
||||
|
||||
// Name returns the name of the state item for update checker
|
||||
func (r *CheckerState) Name() string {
|
||||
func (CheckerState) StateName() string {
|
||||
return "update-checker"
|
||||
}
|
||||
|
||||
|
||||
@@ -686,6 +686,7 @@
|
||||
"settings.privacy": "Privacy",
|
||||
"settings.keep_activity_private": "Hide Activity from profile page",
|
||||
"settings.keep_activity_private_popup": "Makes the activity visible only for you and the admins",
|
||||
"settings.keep_activity_private_disabled": "You are not allowed to change your activity visibility. Please contact your site administrator for more details.",
|
||||
"settings.lookup_avatar_by_mail": "Look Up Avatar by Email Address",
|
||||
"settings.enable_custom_avatar": "Use Custom Avatar",
|
||||
"settings.choose_new_avatar": "Choose new avatar",
|
||||
|
||||
@@ -42,6 +42,8 @@ func UpdateUserSettings(ctx *context.APIContext) {
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/UserSettings"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
form := web.GetForm[*api.UserSettingsOptions](ctx)
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ import (
|
||||
"gitea.dev/services/repository/archiver"
|
||||
"gitea.dev/services/task"
|
||||
"gitea.dev/services/uinotification"
|
||||
user_service "gitea.dev/services/user"
|
||||
"gitea.dev/services/webhook"
|
||||
websocket_service "gitea.dev/services/websocket"
|
||||
)
|
||||
@@ -158,6 +159,7 @@ func InitWebInstalled(ctx context.Context) {
|
||||
mustInitCtx(ctx, mailer_incoming.Init)
|
||||
|
||||
mustInitCtx(ctx, syncAppConfForGit)
|
||||
mustInitCtx(ctx, user_service.SyncForcedActivityVisibility)
|
||||
|
||||
mustInit(ssh.Init)
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ func Profile(ctx *context.Context) {
|
||||
ctx.Data["PageIsSettingsProfile"] = true
|
||||
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
|
||||
ctx.Data["DisableGravatar"] = setting.Config().Picture.DisableGravatar.Value(ctx)
|
||||
ctx.Data["ForceUserActivityVisibility"] = setting.Service.ForceUserActivityVisibility
|
||||
|
||||
ctx.HTML(http.StatusOK, tplSettingsProfile)
|
||||
}
|
||||
@@ -91,7 +92,7 @@ func ProfilePost(ctx *context.Context) {
|
||||
Website: optional.Some(form.Website),
|
||||
Location: optional.Some(form.Location),
|
||||
Visibility: optional.Some(form.Visibility),
|
||||
KeepActivityPrivate: optional.Some(form.KeepActivityPrivate),
|
||||
KeepActivityPrivate: util.Iif(setting.Service.ForceUserActivityVisibility == "", optional.Some(form.KeepActivityPrivate), nil),
|
||||
}); err != nil {
|
||||
ctx.JSONErrorAuto(err)
|
||||
return
|
||||
|
||||
@@ -11,9 +11,11 @@ import (
|
||||
auth_model "gitea.dev/models/auth"
|
||||
user_model "gitea.dev/models/user"
|
||||
password_module "gitea.dev/modules/auth/password"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/optional"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/system"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
)
|
||||
@@ -161,6 +163,9 @@ func UpdateUser(ctx context.Context, u *user_model.User, opts *UpdateOptions) er
|
||||
cols = append(cols, "visibility")
|
||||
}
|
||||
if opts.KeepActivityPrivate.Has() {
|
||||
if forced := setting.Service.ForceUserActivityVisibility; forced != "" && opts.KeepActivityPrivate.Value() != (forced == "private") {
|
||||
return util.ErrorWrap(util.ErrUnprocessableContent, "activity visibility is forced to %s", forced)
|
||||
}
|
||||
u.KeepActivityPrivate = opts.KeepActivityPrivate.Value()
|
||||
|
||||
cols = append(cols, "keep_activity_private")
|
||||
@@ -307,3 +312,23 @@ func CheckConvertUserType(u *user_model.User) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SyncForcedActivityVisibility applies FORCE_USER_ACTIVITY_VISIBILITY to all users when it changed since the last start
|
||||
func SyncForcedActivityVisibility(ctx context.Context) error {
|
||||
lastConfig := new(system.LastConfig)
|
||||
if err := system.AppState.Get(ctx, lastConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
forced := setting.Service.ForceUserActivityVisibility
|
||||
if lastConfig.ForceUserActivityVisibility == forced {
|
||||
return nil
|
||||
}
|
||||
if forced != "" {
|
||||
log.Info("FORCE_USER_ACTIVITY_VISIBILITY changed to %q, updating all users", forced)
|
||||
if err := user_model.UpdateAllUsersKeepActivityPrivate(ctx, forced == "private"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
lastConfig.ForceUserActivityVisibility = forced
|
||||
return system.AppState.Set(ctx, lastConfig)
|
||||
}
|
||||
+3
@@ -36384,6 +36384,9 @@
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/UserSettings"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/error"
|
||||
}
|
||||
},
|
||||
"summary": "Update user settings",
|
||||
|
||||
+3
@@ -23157,6 +23157,9 @@
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/responses/UserSettings"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/responses/error"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,9 +80,9 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<div class="ui checkbox" id="keep-activity-private">
|
||||
<div class="ui checkbox {{if .ForceUserActivityVisibility}}disabled{{end}}" id="keep-activity-private" {{if .ForceUserActivityVisibility}}data-tooltip-content="{{ctx.Locale.Tr "settings.keep_activity_private_disabled"}}"{{end}}>
|
||||
<label data-tooltip-content="{{ctx.Locale.Tr "settings.keep_activity_private_popup"}}"><strong>{{ctx.Locale.Tr "settings.keep_activity_private"}}</strong></label>
|
||||
<input name="keep_activity_private" type="checkbox" {{if .SignedUser.KeepActivityPrivate}}checked{{end}}>
|
||||
<input name="keep_activity_private" type="checkbox" {{if .SignedUser.KeepActivityPrivate}}checked{{end}} {{if .ForceUserActivityVisibility}}disabled{{end}}>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -13,10 +13,14 @@ import (
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/test"
|
||||
user_service "gitea.dev/services/user"
|
||||
"gitea.dev/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -260,3 +264,32 @@ func TestPrivateActivityHeatmapContent(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateActivityForcedVisibility(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
testPrivateActivityHelperEnablePrivateActivity(t)
|
||||
keepActivityPrivate := func() bool {
|
||||
return unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: privateActivityTestUser}).KeepActivityPrivate
|
||||
}
|
||||
|
||||
defer test.MockVariableValue(&setting.Service.ForceUserActivityVisibility, "public")()
|
||||
require.NoError(t, user_service.SyncForcedActivityVisibility(t.Context()))
|
||||
assert.False(t, keepActivityPrivate())
|
||||
|
||||
session := loginUser(t, privateActivityTestUser)
|
||||
resp := session.MakeRequest(t, NewRequest(t, "GET", "/user/settings"), http.StatusOK)
|
||||
AssertHTMLElement(t, NewHTMLParser(t, resp.Body), `#keep-activity-private input[disabled]`, true)
|
||||
testPrivateActivityHelperEnablePrivateActivity(t)
|
||||
assert.False(t, keepActivityPrivate())
|
||||
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser)
|
||||
req := NewRequestWithJSON(t, "PATCH", "/api/v1/user/settings", &api.UserSettingsOptions{HideActivity: new(true)}).AddTokenAuth(token)
|
||||
MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||
req = NewRequestWithJSON(t, "PATCH", "/api/v1/user/settings", &api.UserSettingsOptions{HideActivity: new(false)}).AddTokenAuth(token)
|
||||
MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
setting.Service.ForceUserActivityVisibility = "private"
|
||||
require.NoError(t, user_service.SyncForcedActivityVisibility(t.Context()))
|
||||
assert.True(t, keepActivityPrivate())
|
||||
assert.False(t, unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "org3"}).KeepActivityPrivate)
|
||||
}
|
||||
Reference in new issue
Block a user