refactor: migrate legacy RenderWithErrDeprecated code to "fetch-action" framework (#40565)

The two 2FA login forms relied on the deprecated
`RenderWithErrDeprecated` path, which re-rendered the whole page on a
wrong code and made the submit button send a duplicate request on a
second click. Migrate both forms to `form-fetch-action` and return JSON
errors from the handlers, so the framework's built-in in-flight guard
blocks duplicate submissions and errors are shown as toasts.

Fixes: https://github.com/go-gitea/gitea/issues/27427

Assisted-by: OpenCode:hy4-flash-free

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Vu Nguyen Anh Tuanandwxiaoguang authored and GitHub committed 2026-11-28 08:02:44 +00:00
1 parent 325d40903b
commit 1b073f93b2
47 files changed
+406 -558

No files matched your search

+1
View File
@@ -188,6 +188,7 @@ func checkDatabase(ctx *context.Context, form *forms.InstallForm) bool {
// SubmitInstall response for submit install items
func SubmitInstall(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action must load the post-install page before restartServer shuts down the install server.
if setting.InstallLock {
InstallDone(ctx)
return
+36 -76
View File
@@ -19,7 +19,6 @@ import (
"gitea.dev/modules/setting"
"gitea.dev/modules/templates"
"gitea.dev/modules/util"
"gitea.dev/modules/web"
auth_service "gitea.dev/services/auth"
"gitea.dev/services/auth/source/ldap"
"gitea.dev/services/auth/source/oauth2"
@@ -205,19 +204,16 @@ func parseOAuth2Config(form forms.AuthenticationForm) *oauth2.Source {
}
}
func parseSSPIConfig(ctx *context.Context, form forms.AuthenticationForm) (*sspi.Source, error) {
func parseSSPIConfig(ctx *context.Context, form forms.AuthenticationForm) (*sspi.Source, string, error) {
if form.SSPISeparatorReplacement == "" {
ctx.Data["Err_SSPISeparatorReplacement"] = true
return nil, errors.New(ctx.Locale.TrString("form.require_error", ctx.Locale.TrString("form.SSPISeparatorReplacement")))
return nil, "SSPISeparatorReplacement", errors.New(ctx.Locale.TrString("form.require_error", ctx.Locale.TrString("form.SSPISeparatorReplacement")))
}
if globalVars().separatorAntiPattern.MatchString(form.SSPISeparatorReplacement) {
ctx.Data["Err_SSPISeparatorReplacement"] = true
return nil, errors.New(ctx.Locale.TrString("form.alpha_dash_dot_error", ctx.Locale.TrString("form.SSPISeparatorReplacement")))
return nil, "SSPISeparatorReplacement", errors.New(ctx.Locale.TrString("form.alpha_dash_dot_error", ctx.Locale.TrString("form.SSPISeparatorReplacement")))
}
if form.SSPIDefaultLanguage != "" && !globalVars().langCodePattern.MatchString(form.SSPIDefaultLanguage) {
ctx.Data["Err_SSPIDefaultLanguage"] = true
return nil, errors.New(ctx.Locale.TrString("form.lang_select_error"))
return nil, "SSPIDefaultLanguage", errors.New(ctx.Locale.TrString("form.lang_select_error"))
}
return &sspi.Source{
@@ -226,77 +222,56 @@ func parseSSPIConfig(ctx *context.Context, form forms.AuthenticationForm) (*sspi
StripDomainNames: form.SSPIStripDomainNames,
SeparatorReplacement: form.SSPISeparatorReplacement,
DefaultLanguage: form.SSPIDefaultLanguage,
}, nil
}, "", nil
}
// NewAuthSourcePost response for adding an auth source
func NewAuthSourcePost(ctx *context.Context) {
form := *web.GetForm[*forms.AuthenticationForm](ctx)
ctx.Data["Title"] = ctx.Tr("admin.auths.new")
ctx.Data["PageIsAdminAuthentications"] = true
form := context.GetFetchActionForm[*forms.AuthenticationForm](ctx)
if ctx.Written() {
return
}
ctx.Data["CurrentTypeName"] = auth.Type(form.Type).String()
ctx.Data["CurrentSecurityProtocol"] = ldap.SecurityProtocolNames[ldap.SecurityProtocol(form.SecurityProtocol)]
ctx.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers
ctx.Data["SSPIAutoCreateUsers"] = true
ctx.Data["SSPIAutoActivateUsers"] = true
ctx.Data["SSPIStripDomainNames"] = true
ctx.Data["SSPISeparatorReplacement"] = "_"
ctx.Data["SSPIDefaultLanguage"] = ""
hasTLS := false
var config auth.Config
switch auth.Type(form.Type) {
case auth.LDAP, auth.DLDAP:
config = parseLDAPConfig(form)
hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SecurityProtocolUnencrypted
config = parseLDAPConfig(*form)
case auth.SMTP:
config = parseSMTPConfig(form)
hasTLS = true
config = parseSMTPConfig(*form)
case auth.PAM:
config = &pam_service.Source{
ServiceName: form.PAMServiceName,
EmailDomain: form.PAMEmailDomain,
}
case auth.OAuth2:
oauth2Config := parseOAuth2Config(form)
oauth2Config := parseOAuth2Config(*form)
config = oauth2Config
if oauth2Config.Provider == "openidConnect" {
discoveryURL, err := url.Parse(oauth2Config.OpenIDConnectAutoDiscoveryURL)
if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") {
ctx.Data["Err_DiscoveryURL"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.invalid_openIdConnectAutoDiscoveryURL"), tplAuthNew, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.invalid_openIdConnectAutoDiscoveryURL"), "OpenIDConnectAutoDiscoveryURL")
return
}
}
case auth.SSPI:
var err error
config, err = parseSSPIConfig(ctx, form)
var errorField string
config, errorField, err = parseSSPIConfig(ctx, *form)
if err != nil {
ctx.RenderWithErrDeprecated(err.Error(), tplAuthNew, form)
ctx.JSONErrorWithField(err.Error(), errorField)
return
}
existing, err := db.Find[auth.Source](ctx, auth.FindSourcesOptions{LoginType: auth.SSPI})
if err != nil || len(existing) > 0 {
ctx.Data["Err_Type"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.login_source_of_type_exist"), "Type")
return
}
default:
ctx.HTTPError(http.StatusBadRequest)
return
}
ctx.Data["HasTLS"] = hasTLS
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplAuthNew)
return
}
if err := auth_service.CreateSource(ctx, &auth.Source{
Type: auth.Type(form.Type),
@@ -307,11 +282,9 @@ func NewAuthSourcePost(ctx *context.Context) {
Cfg: config,
}); err != nil {
if errExist, ok := errors.AsType[auth.ErrSourceAlreadyExist](err); ok {
ctx.Data["Err_Name"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.login_source_exist", errExist.Name), tplAuthNew, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.login_source_exist", errExist.Name), "Name")
} else if errInit, ok := err.(oauth2.ErrOpenIDConnectInitialize); ok {
ctx.Data["Err_DiscoveryURL"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.unable_to_initialize_openid", errInit.Unwrap()), tplAuthNew, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.unable_to_initialize_openid", errInit.Unwrap()), "OpenIDConnectAutoDiscoveryURL")
} else {
ctx.ServerErrorAuto(err)
}
@@ -321,7 +294,7 @@ func NewAuthSourcePost(ctx *context.Context) {
log.Trace("Authentication created by admin(%s): %s", ctx.Doer.Name, form.Name)
ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name))
ctx.Redirect(setting.AppSubURL + "/-/admin/auths")
ctx.JSONRedirect(setting.AppSubURL + "/-/admin/auths")
}
// EditAuthSource render editing auth source page
@@ -357,53 +330,43 @@ func EditAuthSource(ctx *context.Context) {
// EditAuthSourcePost response for editing auth source
func EditAuthSourcePost(ctx *context.Context) {
form := *web.GetForm[*forms.AuthenticationForm](ctx)
ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["SMTPAuths"] = smtp.Authenticators
oauth2providers := oauth2.GetSupportedOAuth2Providers(ctx)
ctx.Data["OAuth2Providers"] = oauth2providers
form := context.GetFetchActionForm[*forms.AuthenticationForm](ctx)
if ctx.Written() {
return
}
source, err := auth.GetSourceByID(ctx, ctx.PathParamInt64("authid"))
if err != nil {
ctx.ServerErrorAuto(err)
return
}
ctx.Data["Source"] = source
ctx.Data["HasTLS"] = source.HasTLS()
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplAuthEdit)
return
}
var config auth.Config
switch auth.Type(form.Type) {
case auth.LDAP, auth.DLDAP:
config = parseLDAPConfig(form)
config = parseLDAPConfig(*form)
case auth.SMTP:
config = parseSMTPConfig(form)
config = parseSMTPConfig(*form)
case auth.PAM:
config = &pam_service.Source{
ServiceName: form.PAMServiceName,
EmailDomain: form.PAMEmailDomain,
}
case auth.OAuth2:
oauth2Config := parseOAuth2Config(form)
oauth2Config := parseOAuth2Config(*form)
config = oauth2Config
if oauth2Config.Provider == "openidConnect" {
discoveryURL, err := url.Parse(oauth2Config.OpenIDConnectAutoDiscoveryURL)
if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") {
ctx.Data["Err_DiscoveryURL"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.invalid_openIdConnectAutoDiscoveryURL"), tplAuthEdit, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.invalid_openIdConnectAutoDiscoveryURL"), "OpenIDConnectAutoDiscoveryURL")
return
}
}
case auth.SSPI:
config, err = parseSSPIConfig(ctx, form)
var errorField string
config, errorField, err = parseSSPIConfig(ctx, *form)
if err != nil {
ctx.RenderWithErrDeprecated(err.Error(), tplAuthEdit, form)
ctx.JSONErrorWithField(err.Error(), errorField)
return
}
default:
@@ -418,12 +381,9 @@ func EditAuthSourcePost(ctx *context.Context) {
source.TwoFactorPolicy = form.TwoFactorPolicy
if err := auth_service.UpdateSource(ctx, source); err != nil {
if errExist, ok := errors.AsType[auth.ErrSourceAlreadyExist](err); ok {
ctx.Data["Err_Name"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("admin.auths.login_source_exist", errExist.Name), tplAuthEdit, form)
ctx.JSONErrorWithField(ctx.Tr("admin.auths.login_source_exist", errExist.Name), "Name")
} else if oauth2.IsErrOpenIDConnectInitialize(err) {
ctx.Flash.Error(err.Error(), true)
ctx.Data["Err_DiscoveryURL"] = true
ctx.HTML(http.StatusOK, tplAuthEdit)
ctx.JSONErrorWithField(err.Error(), "OpenIDConnectAutoDiscoveryURL")
} else {
ctx.ServerErrorAuto(err)
}
@@ -432,7 +392,7 @@ func EditAuthSourcePost(ctx *context.Context) {
log.Trace("Authentication changed by admin(%s): %d", ctx.Doer.Name, source.ID)
ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
ctx.Redirect(setting.AppSubURL + "/-/admin/auths/" + strconv.FormatInt(source.ID, 10))
ctx.JSONRedirect(setting.AppSubURL + "/-/admin/auths/" + strconv.FormatInt(source.ID, 10))
}
// DeleteAuthSource response for deleting an auth source
+33 -71
View File
@@ -148,25 +148,8 @@ func NewUser(ctx *context.Context) {
// NewUserPost response for adding a new user
func NewUserPost(ctx *context.Context) {
form := web.GetForm[*forms.AdminCreateUserForm](ctx)
ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
ctx.Data["PageIsAdminUsers"] = true
ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
sources, err := db.Find[auth.Source](ctx, auth.FindSourcesOptions{
IsActive: optional.Some(true),
})
if err != nil {
ctx.ServerErrorAuto(err)
return
}
ctx.Data["Sources"] = sources
ctx.Data["CanSendEmail"] = setting.MailService != nil
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplUserNew)
form := context.GetFetchActionForm[*forms.AdminCreateUserForm](ctx)
if ctx.Written() {
return
}
@@ -196,23 +179,20 @@ func NewUserPost(ctx *context.Context) {
}
if !u.IsTypeBot() && (u.LoginType == auth.NoType || u.LoginType == auth.Plain) {
if len(form.Password) < setting.MinPasswordLength {
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), "Password")
return
}
if !password.IsComplexEnough(form.Password) {
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(password.BuildComplexityError(ctx.Locale), tplUserNew, &form)
ctx.JSONErrorWithField(password.BuildComplexityError(ctx.Locale), "Password")
return
}
if err := password.IsPwned(ctx, form.Password); err != nil {
ctx.Data["Err_Password"] = true
errMsg := ctx.Tr("auth.password_pwned", "https://haveibeenpwned.com/Passwords")
if password.IsErrIsPwnedRequest(err) {
log.Error(err.Error())
errMsg = ctx.Tr("auth.password_pwned_err")
}
ctx.RenderWithErrDeprecated(errMsg, tplUserNew, &form)
ctx.JSONErrorWithField(errMsg, "Password")
return
}
u.MustChangePassword = form.MustChangePassword
@@ -225,23 +205,17 @@ func NewUserPost(ctx *context.Context) {
var errEmailInvalid user_model.ErrEmailInvalid
switch {
case user_model.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.username_been_taken"), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("form.username_been_taken"), "UserName")
case user_model.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_been_used"), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_been_used"), "Email")
case errors.As(err, &errEmailInvalid):
ctx.Data["Err_Email"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_invalid"), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_invalid"), "Email")
case errors.As(err, &errNameReserved):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_reserved", errNameReserved.Name), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_reserved", errNameReserved.Name), "UserName")
case errors.As(err, &errNamePatternNotAllowed):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), "UserName")
case errors.As(err, &errNameCharsNotAllowed):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_chars_not_allowed", errNameCharsNotAllowed.Name), tplUserNew, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_chars_not_allowed", errNameCharsNotAllowed.Name), "UserName")
default:
ctx.ServerErrorAuto(err)
}
@@ -262,7 +236,7 @@ func NewUserPost(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name))
ctx.Redirect(setting.AppSubURL + "/-/admin/users/" + strconv.FormatInt(u.ID, 10))
ctx.JSONRedirect(setting.AppSubURL + "/-/admin/users/" + strconv.FormatInt(u.ID, 10))
}
func prepareUserInfo(ctx *context.Context) *user_model.User {
@@ -417,15 +391,14 @@ func EditUser(ctx *context.Context) {
// EditUserPost response for editing user
func EditUserPost(ctx *context.Context) {
editUserCommon(ctx)
u := prepareUserInfo(ctx)
if ctx.Written() {
u, err := user_model.GetUserByID(ctx, ctx.PathParamInt64("userid"))
if err != nil {
ctx.ServerErrorAuto(err)
return
}
form := web.GetForm[*forms.AdminEditUserForm](ctx)
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplUserEdit)
form := context.GetFetchActionForm[*forms.AdminEditUserForm](ctx)
if ctx.Written() {
return
}
@@ -435,20 +408,15 @@ func EditUserPost(ctx *context.Context) {
if err := user_service.RenameUser(ctx, u, form.UserName, ctx.Doer); err != nil {
switch {
case user_model.IsErrUserIsNotLocal(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.username_change_not_local_user"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("form.username_change_not_local_user"), "UserName")
case user_model.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.username_been_taken"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("form.username_been_taken"), "UserName")
case db.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_reserved", form.UserName), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_reserved", form.UserName), "UserName")
case db.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_pattern_not_allowed", form.UserName), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_pattern_not_allowed", form.UserName), "UserName")
case db.IsErrNameCharsNotAllowed(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("user.form.name_chars_not_allowed", form.UserName), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("user.form.name_chars_not_allowed", form.UserName), "UserName")
default:
ctx.ServerErrorAuto(err)
}
@@ -481,20 +449,16 @@ func EditUserPost(ctx *context.Context) {
if err := user_service.UpdateAuth(ctx, u, authOpts); err != nil {
switch {
case errors.Is(err, password.ErrMinLength):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), "Password")
case errors.Is(err, password.ErrComplexity):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(password.BuildComplexityError(ctx.Locale), tplUserEdit, &form)
ctx.JSONErrorWithField(password.BuildComplexityError(ctx.Locale), "Password")
case errors.Is(err, password.ErrIsPwned):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_pwned", "https://haveibeenpwned.com/Passwords"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_pwned", "https://haveibeenpwned.com/Passwords"), "Password")
case password.IsErrIsPwnedRequest(err):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_pwned_err"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_pwned_err"), "Password")
case errors.Is(err, util.ErrInvalidArgument):
ctx.Flash.Error(err.Error())
ctx.Redirect(userLink)
ctx.JSONRedirect(userLink)
default:
ctx.ServerErrorAuto(err)
}
@@ -505,11 +469,9 @@ func EditUserPost(ctx *context.Context) {
if err := user_service.ReplacePrimaryEmailAddress(ctx, u, form.Email); err != nil {
switch {
case user_model.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_been_used"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_been_used"), "Email")
case errors.Is(err, util.ErrInvalidArgument):
ctx.Data["Err_Email"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_invalid"), tplUserEdit, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_invalid"), "Email")
default:
ctx.ServerErrorAuto(err)
}
@@ -539,13 +501,13 @@ func EditUserPost(ctx *context.Context) {
if err := user_service.UpdateUser(ctx, u, opts); err != nil {
switch {
case user_model.IsErrDeleteLastAdminUser(err):
ctx.RenderWithErrDeprecated(ctx.Tr("auth.last_admin"), tplUserEdit, &form)
ctx.JSONError(ctx.Tr("auth.last_admin"))
case errors.Is(err, user_model.ErrBotCanNotBeAdmin):
ctx.Flash.Error(ctx.Tr("admin.users.convert_type.admin_not_allowed"))
ctx.Redirect(userLink)
ctx.JSONRedirect(userLink)
case errors.Is(err, util.ErrInvalidArgument):
ctx.Flash.Error(err.Error())
ctx.Redirect(userLink)
ctx.JSONRedirect(userLink)
default:
ctx.ServerErrorAuto(err)
}
@@ -566,7 +528,7 @@ func EditUserPost(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success"))
ctx.Redirect(userLink)
ctx.JSONRedirect(userLink)
}
func ImpersonateUser(ctx *context.Context) {
+21 -15
View File
@@ -4,15 +4,16 @@
package admin
import (
"net/http"
"net/url"
"strconv"
"testing"
"gitea.dev/models/unittest"
user_model "gitea.dev/models/user"
"gitea.dev/modules/setting"
api "gitea.dev/modules/structs"
"gitea.dev/modules/web"
"gitea.dev/services/contexttest"
"gitea.dev/services/forms"
"github.com/stretchr/testify/assert"
)
@@ -26,30 +27,35 @@ func TestNewUserPost(t *testing.T) {
}{
{name: "MustChangePassword", email: "gitea@gitea.io", mustChangePassword: true},
{name: "MustChangePasswordFalseAndDefaultVisibility", email: "gitea@gitea.io"},
{name: "InvalidEmail", email: "gitea@gitea.io\r\n"},
{name: "InvalidEmail", email: "gitea@@gitea.io"},
{name: "VisibilityPrivate", email: "gitea@gitea.io", visibility: api.VisibleTypePrivate},
} {
t.Run(tc.name, func(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
ctx, resp := contexttest.MockContext(t, "POST /-/admin/users/new")
ctx.Doer = unittest.AssertExistsAndLoadBean(t, &user_model.User{IsAdmin: true, ID: 2})
web.SetForm(ctx, &forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: "gitea",
Email: tc.email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: tc.mustChangePassword,
Visibility: tc.visibility,
})
ctx.Req.Form = url.Values{
"login_type": {"local"},
"login_name": {"local"},
"user_name": {"gitea"},
"email": {tc.email},
"password": {"abc123ABC!=$"},
"must_change_password": {strconv.FormatBool(tc.mustChangePassword)},
"visibility": {strconv.Itoa(int(tc.visibility))},
}
ctx.Req.PostForm = ctx.Req.Form
ctx.Req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
NewUserPost(ctx)
if tc.name == "InvalidEmail" {
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Contains(t, resp.Body.String(), `"errorFields":["Email"]`)
return
}
assert.Equal(t, http.StatusOK, resp.Code)
assert.Contains(t, resp.Body.String(), `"redirect":`)
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
user, err := user_model.GetUserByName(ctx, "gitea")
assert.NoError(t, err)
+10 -7
View File
@@ -15,7 +15,6 @@ import (
"gitea.dev/modules/setting"
"gitea.dev/modules/templates"
"gitea.dev/modules/util"
"gitea.dev/modules/web"
"gitea.dev/services/audit"
"gitea.dev/services/context"
"gitea.dev/services/forms"
@@ -45,8 +44,10 @@ func TwoFactor(ctx *context.Context) {
// TwoFactorPost validates a user's two-factor authentication token.
func TwoFactorPost(ctx *context.Context) {
form := web.GetForm[*forms.TwoFactorAuthForm](ctx)
ctx.Data["Title"] = ctx.Tr("twofa")
form := context.GetFetchActionForm[*forms.TwoFactorAuthForm](ctx)
if ctx.Written() {
return
}
// Ensure user is in a 2FA session.
id, hasSession := ctx.Session.Get("twofaUid").(int64)
@@ -91,7 +92,7 @@ func TwoFactorPost(ctx *context.Context) {
log.Warn("Failed authentication attempt for %s from %s: invalid two-factor passcode", u.Name, ctx.RemoteAddr())
}
errMsg := ctx.Tr(util.Iif(tfaResult == auth.TwoFactorResultTooManyAttempts, "auth.twofa_too_many_attempts", "auth.twofa_passcode_incorrect"))
ctx.RenderWithErrDeprecated(errMsg, tplTwofa, forms.TwoFactorAuthForm{})
ctx.JSONError(errMsg)
}
// TwoFactorScratch shows the scratch code form for two-factor authentication.
@@ -113,8 +114,10 @@ func TwoFactorScratch(ctx *context.Context) {
// TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
func TwoFactorScratchPost(ctx *context.Context) {
form := web.GetForm[*forms.TwoFactorScratchAuthForm](ctx)
ctx.Data["Title"] = ctx.Tr("twofa_scratch")
form := context.GetFetchActionForm[*forms.TwoFactorScratchAuthForm](ctx)
if ctx.Written() {
return
}
// Ensure user is in a 2FA session.
id, hasSession := ctx.Session.Get("twofaUid").(int64)
@@ -166,5 +169,5 @@ func TwoFactorScratchPost(ctx *context.Context) {
if u, err := user_model.GetUserByID(ctx, id); err == nil {
audit.RecordAs(ctx, u, audit_model.UserAuthenticationFailTwoFactor, u)
}
ctx.RenderWithErrDeprecated(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, forms.TwoFactorScratchAuthForm{})
ctx.JSONError(ctx.Tr("auth.twofa_scratch_token_incorrect"))
}
+2
View File
@@ -286,6 +286,7 @@ func SignIn(ctx *context.Context) {
// SignInPost response for sign in request
func SignInPost(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs CAPTCHA refresh support and navigation for the prohibited-login page.
if !setting.Service.EnablePasswordSignInForm {
ctx.HTTPError(http.StatusForbidden)
return
@@ -550,6 +551,7 @@ func SignUp(ctx *context.Context) {
// SignUpPost response for sign up information submission
func SignUpPost(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs the shared CAPTCHA and account-activation helpers to stop rendering HTML first.
if !prepareSignUpPageData(ctx) {
return
}
+2
View File
@@ -114,6 +114,7 @@ func handleSignInError(ctx *context.Context, userName string, ptrForm any, tmpl
// LinkAccountPostSignIn handle the coupling of external account with another account using signIn
func LinkAccountPostSignIn(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs navigation for the prohibited-login page rendered by handleSignInError.
signInForm := web.GetForm[*forms.SignInForm](ctx)
ctx.Data["LinkAccountModeSignIn"] = true
@@ -177,6 +178,7 @@ func oauth2LinkAccount(ctx *context.Context, u *user_model.User, linkAccountData
// LinkAccountPostRegister handle the creation of a new account for an external account using signUp
func LinkAccountPostRegister(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs the shared CAPTCHA and account-activation helpers to stop rendering HTML first.
form := web.GetForm[*forms.RegisterForm](ctx)
ctx.Data["LinkAccountModeRegister"] = true
+9 -16
View File
@@ -17,7 +17,6 @@ import (
"gitea.dev/modules/templates"
"gitea.dev/modules/timeutil"
"gitea.dev/modules/util"
"gitea.dev/modules/web"
"gitea.dev/routers/common"
"gitea.dev/services/audit"
"gitea.dev/services/context"
@@ -52,6 +51,7 @@ func ForgotPasswd(ctx *context.Context) {
// ForgotPasswdPost response for forget password request
func ForgotPasswdPost(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs navigation for the sent-email and resend-limit views currently rendered by this POST.
ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
if setting.MailService == nil {
@@ -164,6 +164,7 @@ func ResetPasswd(ctx *context.Context) {
// ResetPasswdPost response from account recovery request
func ResetPasswdPost(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs JSON errors from commonResetPassword, which currently sets template flash errors.
u, twofa := commonResetPassword(ctx)
if ctx.Written() {
return
@@ -280,11 +281,8 @@ func MustChangePassword(ctx *context.Context) {
// MustChangePasswordPost response for updating a user's password after their
// account was created by an admin
func MustChangePasswordPost(ctx *context.Context) {
form := web.GetForm[*forms.MustChangePasswordForm](ctx)
ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplMustChangePassword)
form := context.GetFetchActionForm[*forms.MustChangePasswordForm](ctx)
if ctx.Written() {
return
}
@@ -295,8 +293,7 @@ func MustChangePasswordPost(ctx *context.Context) {
}
if form.Password != form.Retype {
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.password_not_match"), tplMustChangePassword, &form)
ctx.JSONErrorWithField(ctx.Tr("form.password_not_match"), "Password")
return
}
@@ -307,17 +304,13 @@ func MustChangePasswordPost(ctx *context.Context) {
if err := user_service.UpdateAuth(ctx, ctx.Doer, opts); err != nil {
switch {
case errors.Is(err, password.ErrMinLength):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplMustChangePassword, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), "Password")
case errors.Is(err, password.ErrComplexity):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(password.BuildComplexityError(ctx.Locale), tplMustChangePassword, &form)
ctx.JSONErrorWithField(password.BuildComplexityError(ctx.Locale), "Password")
case errors.Is(err, password.ErrIsPwned):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_pwned", "https://haveibeenpwned.com/Passwords"), tplMustChangePassword, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_pwned", "https://haveibeenpwned.com/Passwords"), "Password")
case password.IsErrIsPwnedRequest(err):
ctx.Data["Err_Password"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("auth.password_pwned_err"), tplMustChangePassword, &form)
ctx.JSONErrorWithField(ctx.Tr("auth.password_pwned_err"), "Password")
default:
ctx.ServerErrorAuto(err)
}
+9 -14
View File
@@ -15,7 +15,6 @@ import (
"gitea.dev/modules/log"
"gitea.dev/modules/setting"
"gitea.dev/modules/templates"
"gitea.dev/modules/web"
"gitea.dev/services/audit"
"gitea.dev/services/context"
"gitea.dev/services/forms"
@@ -42,16 +41,13 @@ func Create(ctx *context.Context) {
// CreatePost response for create organization
func CreatePost(ctx *context.Context) {
form := *web.GetForm[*forms.CreateOrgForm](ctx)
ctx.Data["Title"] = ctx.Tr("new_org")
if !ctx.Doer.CanCreateOrganization() {
ctx.ServerErrorAuto(errors.New(ctx.Locale.TrString("org.form.create_org_not_allowed")))
form := context.GetFetchActionForm[*forms.CreateOrgForm](ctx)
if ctx.Written() {
return
}
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplCreateOrg)
if !ctx.Doer.CanCreateOrganization() {
ctx.ServerErrorAuto(errors.New(ctx.Locale.TrString("org.form.create_org_not_allowed")))
return
}
@@ -64,18 +60,17 @@ func CreatePost(ctx *context.Context) {
}
if err := organization.CreateOrganization(ctx, org, ctx.Doer); err != nil {
ctx.Data["Err_OrgName"] = true
var errNameReserved db.ErrNameReserved
var errNamePatternNotAllowed db.ErrNamePatternNotAllowed
switch {
case user_model.IsErrUserAlreadyExist(err):
ctx.RenderWithErrDeprecated(ctx.Tr("form.org_name_been_taken"), tplCreateOrg, &form)
ctx.JSONErrorWithField(ctx.Tr("form.org_name_been_taken"), "OrgName")
case errors.As(err, &errNameReserved):
ctx.RenderWithErrDeprecated(ctx.Tr("org.form.name_reserved", errNameReserved.Name), tplCreateOrg, &form)
ctx.JSONErrorWithField(ctx.Tr("org.form.name_reserved", errNameReserved.Name), "OrgName")
case errors.As(err, &errNamePatternNotAllowed):
ctx.RenderWithErrDeprecated(ctx.Tr("org.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), tplCreateOrg, &form)
ctx.JSONErrorWithField(ctx.Tr("org.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), "OrgName")
case organization.IsErrUserNotAllowedCreateOrg(err):
ctx.RenderWithErrDeprecated(ctx.Tr("org.form.create_org_not_allowed"), tplCreateOrg, &form)
ctx.JSONError(ctx.Tr("org.form.create_org_not_allowed"))
default:
ctx.ServerErrorAuto(err)
}
@@ -85,5 +80,5 @@ func CreatePost(ctx *context.Context) {
log.Trace("Organization created: %s", org.Name)
ctx.Redirect(org.AsUser().DashboardLink())
ctx.JSONRedirect(org.AsUser().DashboardLink())
}
+4 -11
View File
@@ -59,22 +59,15 @@ func Settings(ctx *context.Context) {
// SettingsPost response for settings change submitted
func SettingsPost(ctx *context.Context) {
form := web.GetForm[*forms.UpdateOrgSettingForm](ctx)
ctx.Data["Title"] = ctx.Tr("org.settings.options")
ctx.Data["PageIsOrgSettings"] = true
ctx.Data["PageIsSettingsOptions"] = true
ctx.Data["CurrentVisibility"] = ctx.Org.Organization.Visibility
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSettingsOptions)
form := context.GetFetchActionForm[*forms.UpdateOrgSettingForm](ctx)
if ctx.Written() {
return
}
org := ctx.Org.Organization
if err := org_service.UpdateOrgEmailAddress(ctx, org, form.Email); err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
ctx.Data["Err_Email"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_invalid"), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_invalid"), "Email")
return
}
ctx.ServerErrorAuto(err)
@@ -99,7 +92,7 @@ func SettingsPost(ctx *context.Context) {
log.Trace("Organization setting updated: %s", org.Name)
ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success"))
ctx.Redirect(ctx.Org.OrgLink + "/settings")
ctx.JSONRedirect(ctx.Org.OrgLink + "/settings")
}
// SettingsAvatar response for change avatar on settings page
+14 -32
View File
@@ -24,7 +24,6 @@ import (
"gitea.dev/modules/structs"
"gitea.dev/modules/templates"
"gitea.dev/modules/util"
"gitea.dev/modules/web"
shared_user "gitea.dev/routers/web/shared/user"
"gitea.dev/services/context"
"gitea.dev/services/convert"
@@ -342,7 +341,10 @@ func paresFormTeamUnits(orgID int64, forms url.Values) (units []*org_model.TeamU
// NewTeamPost response for create new team
func NewTeamPost(ctx *context.Context) {
form := web.GetForm[*forms.CreateTeamForm](ctx)
form := context.GetFetchActionForm[*forms.CreateTeamForm](ctx)
if ctx.Written() {
return
}
includesAllRepositories := form.RepoAccess == "all"
teamPermission := perm.ParseAccessMode(form.Permission, perm.AccessModeNone, perm.AccessModeWrite, perm.AccessModeAdmin)
@@ -356,37 +358,25 @@ func NewTeamPost(ctx *context.Context) {
Visibility: org_model.NormalizeTeamVisibility(form.Visibility),
}
ctx.Data["Title"] = ctx.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamsNew"] = true
ctx.Data["Units"] = unit_model.Units
ctx.Data["Team"] = t
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplTeamNew)
return
}
if t.AccessMode == perm.AccessModeNone {
t.Units = paresFormTeamUnits(ctx.Org.Organization.ID, ctx.Req.Form)
if len(t.Units) == 0 {
ctx.RenderWithErrDeprecated(ctx.Tr("form.team_no_units_error"), tplTeamNew, &form)
ctx.JSONError(ctx.Tr("form.team_no_units_error"))
return
}
}
if err := org_service.NewTeam(ctx, t); err != nil {
ctx.Data["Err_TeamName"] = true
switch {
case org_model.IsErrTeamAlreadyExist(err):
ctx.RenderWithErrDeprecated(ctx.Tr("form.team_name_been_taken"), tplTeamNew, &form)
ctx.JSONErrorWithField(ctx.Tr("form.team_name_been_taken"), "TeamName")
default:
ctx.ServerErrorAuto(err)
}
return
}
log.Trace("Team created: %s/%s", ctx.Org.Organization.Name, t.Name)
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + url.PathEscape(t.LowerName))
ctx.JSONRedirect(ctx.Org.OrgLink + "/teams/" + url.PathEscape(t.LowerName))
}
// TeamMembers render team members page
@@ -510,18 +500,16 @@ func EditTeam(ctx *context.Context) {
// EditTeamPost response for modify team information
func EditTeamPost(ctx *context.Context) {
form := web.GetForm[*forms.CreateTeamForm](ctx)
form := context.GetFetchActionForm[*forms.CreateTeamForm](ctx)
if ctx.Written() {
return
}
t := ctx.Org.Team
teamPermission := perm.ParseAccessMode(form.Permission, perm.AccessModeNone, perm.AccessModeWrite, perm.AccessModeAdmin)
isIncludeAllChanged := false
includesAllRepositories := form.RepoAccess == "all"
ctx.Data["Title"] = ctx.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true
ctx.Data["Team"] = t
ctx.Data["Units"] = unit_model.Units
oldTeamAccessMode := t.AccessMode
if !t.IsOwnerTeam() {
t.Name = form.TeamName
@@ -542,29 +530,23 @@ func EditTeamPost(ctx *context.Context) {
if t.AccessMode == perm.AccessModeNone {
t.Units = paresFormTeamUnits(ctx.Org.Organization.ID, ctx.Req.Form)
if len(t.Units) == 0 {
ctx.RenderWithErrDeprecated(ctx.Tr("form.team_no_units_error"), tplTeamNew, &form)
ctx.JSONError(ctx.Tr("form.team_no_units_error"))
return
}
}
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplTeamNew)
return
}
isAuthChanged := oldTeamAccessMode != t.AccessMode || !maps.Equal(oldTeamUnitsMap, t.GetUnitsMap())
t.Description = form.Description
if err := org_service.UpdateTeam(ctx, t, isAuthChanged, isIncludeAllChanged); err != nil {
ctx.Data["Err_TeamName"] = true
switch {
case org_model.IsErrTeamAlreadyExist(err):
ctx.RenderWithErrDeprecated(ctx.Tr("form.team_name_been_taken"), tplTeamNew, &form)
ctx.JSONErrorWithField(ctx.Tr("form.team_name_been_taken"), "TeamName")
default:
ctx.ServerErrorAuto(err)
}
return
}
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + url.PathEscape(t.LowerName))
ctx.JSONRedirect(ctx.Org.OrgLink + "/teams/" + url.PathEscape(t.LowerName))
}
// DeleteTeam response for the delete team request
+8 -21
View File
@@ -14,7 +14,6 @@ import (
"gitea.dev/modules/optional"
"gitea.dev/modules/setting"
"gitea.dev/modules/templates"
"gitea.dev/modules/web"
"gitea.dev/routers/common"
"gitea.dev/services/context"
"gitea.dev/services/forms"
@@ -104,20 +103,14 @@ func NewMilestone(ctx *context.Context) {
// NewMilestonePost response for creating milestone
func NewMilestonePost(ctx *context.Context) {
form := web.GetForm[*forms.CreateMilestoneForm](ctx)
ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
ctx.Data["PageIsIssueList"] = true
ctx.Data["PageIsMilestones"] = true
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplMilestoneNew)
form := context.GetFetchActionForm[*forms.CreateMilestoneForm](ctx)
if ctx.Written() {
return
}
deadlineUnix, err := common.ParseDeadlineDateToEndOfDay(form.Deadline)
if err != nil {
ctx.Data["Err_Deadline"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.milestones.invalid_due_date_format"), "Deadline")
return
}
@@ -132,7 +125,7 @@ func NewMilestonePost(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/milestones")
}
// EditMilestone render editing milestone page
@@ -156,20 +149,14 @@ func EditMilestone(ctx *context.Context) {
// EditMilestonePost response for editing milestone
func EditMilestonePost(ctx *context.Context) {
form := web.GetForm[*forms.CreateMilestoneForm](ctx)
ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
ctx.Data["PageIsMilestones"] = true
ctx.Data["PageIsEditMilestone"] = true
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplMilestoneNew)
form := context.GetFetchActionForm[*forms.CreateMilestoneForm](ctx)
if ctx.Written() {
return
}
deadlineUnix, err := common.ParseDeadlineDateToEndOfDay(form.Deadline)
if err != nil {
ctx.Data["Err_Deadline"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.milestones.invalid_due_date_format"), "Deadline")
return
}
@@ -187,7 +174,7 @@ func EditMilestonePost(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/milestones")
}
// ChangeMilestoneStatus response for changing a milestone's status
+14 -31
View File
@@ -26,7 +26,6 @@ import (
api "gitea.dev/modules/structs"
"gitea.dev/modules/templates"
"gitea.dev/modules/util"
"gitea.dev/modules/web"
"gitea.dev/services/context"
"gitea.dev/services/convert"
"gitea.dev/services/forms"
@@ -164,26 +163,22 @@ func Create(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplCreate)
}
func handleCreateError(ctx *context.Context, owner *user_model.User, err error, tpl templates.TplName, form any) {
func handleCreateError(ctx *context.Context, owner *user_model.User, err error) {
var errNameReserved db.ErrNameReserved
var errNamePatternNotAllowed db.ErrNamePatternNotAllowed
switch {
case repo_model.IsErrReachLimitOfRepo(err):
maxCreationLimit := owner.MaxCreationLimit()
msg := ctx.TrN(maxCreationLimit, "repo.form.reach_limit_of_creation_1", "repo.form.reach_limit_of_creation_n", maxCreationLimit)
ctx.RenderWithErrDeprecated(msg, tpl, form)
ctx.JSONError(msg)
case repo_model.IsErrRepoAlreadyExist(err):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.repo_name_been_taken"), tpl, form)
ctx.JSONErrorWithField(ctx.Tr("form.repo_name_been_taken"), "RepoName")
case repo_model.IsErrRepoFilesAlreadyExist(err):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.repository_files_already_exist"), tpl, form)
ctx.JSONErrorWithField(ctx.Tr("form.repository_files_already_exist"), "RepoName")
case errors.As(err, &errNameReserved):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.form.name_reserved", errNameReserved.Name), tpl, form)
ctx.JSONErrorWithField(ctx.Tr("repo.form.name_reserved", errNameReserved.Name), "RepoName")
case errors.As(err, &errNamePatternNotAllowed):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), tpl, form)
ctx.JSONErrorWithField(ctx.Tr("repo.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), "RepoName")
default:
ctx.ServerErrorAuto(err)
}
@@ -191,25 +186,13 @@ func handleCreateError(ctx *context.Context, owner *user_model.User, err error,
// CreatePost response for creating repository
func CreatePost(ctx *context.Context) {
createCommon(ctx)
form := web.GetForm[*forms.CreateRepoForm](ctx)
ctxUser := checkContextUser(ctx, form.UID)
form := context.GetFetchActionForm[*forms.CreateRepoForm](ctx)
if ctx.Written() {
return
}
ctx.Data["ContextUser"] = ctxUser
if form.RepoTemplate > 0 {
templateRepo, err := repo_model.GetRepositoryByID(ctx, form.RepoTemplate)
if err == nil && access_model.CheckRepoUnitUser(ctx, templateRepo, ctxUser, unit.TypeCode) {
ctx.Data["repo_template"] = form.RepoTemplate
ctx.Data["repo_template_name"] = templateRepo.Name
}
}
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplCreate)
ctxUser := checkContextUser(ctx, form.UID)
if ctx.Written() {
return
}
@@ -230,7 +213,7 @@ func CreatePost(ctx *context.Context) {
}
if !opts.IsValid() {
ctx.RenderWithErrDeprecated(ctx.Tr("repo.template.one_item"), tplCreate, form)
ctx.JSONError(ctx.Tr("repo.template.one_item"))
return
}
@@ -240,14 +223,14 @@ func CreatePost(ctx *context.Context) {
}
if !templateRepo.IsTemplate {
ctx.RenderWithErrDeprecated(ctx.Tr("repo.template.invalid"), tplCreate, form)
ctx.JSONError(ctx.Tr("repo.template.invalid"))
return
}
repo, err = repo_service.GenerateRepository(ctx, ctx.Doer, ctxUser, templateRepo, opts)
if err == nil {
log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
ctx.Redirect(repo.Link())
ctx.JSONRedirect(repo.Link())
return
}
} else {
@@ -267,12 +250,12 @@ func CreatePost(ctx *context.Context) {
})
if err == nil {
log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
ctx.Redirect(repo.Link())
ctx.JSONRedirect(repo.Link())
return
}
}
handleCreateError(ctx, ctxUser, err, tplCreate, &form)
handleCreateError(ctx, ctxUser, err)
}
func handleRepoActionError(ctx *context.Context, err error) {
+89 -103
View File
@@ -30,7 +30,6 @@ import (
"gitea.dev/modules/templates"
"gitea.dev/modules/util"
"gitea.dev/modules/validation"
"gitea.dev/modules/web"
repo_router "gitea.dev/routers/web/repo"
actions_service "gitea.dev/services/actions"
"gitea.dev/services/audit"
@@ -67,9 +66,8 @@ func canManageRepoDangerZone(ctx *context.Context) bool {
return true
}
// SettingsCtxData is a middleware that sets all the general context data for the
// settings template.
func SettingsCtxData(ctx *context.Context) {
// Settings shows a repository's settings page.
func Settings(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.options")
ctx.Data["PageIsSettingsOptions"] = true
ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
@@ -114,6 +112,7 @@ func SettingsCtxData(ctx *context.Context) {
if ctx.Written() {
return
}
ctx.HTML(http.StatusOK, tplSettingsOptions)
}
func preparePullRequestSettings(ctx *context.Context) {
@@ -145,25 +144,8 @@ func preparePullRequestSettings(ctx *context.Context) {
}
}
// Settings show a repository's settings page
func Settings(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplSettingsOptions)
}
// SettingsPost response for changes of a repository
func SettingsPost(ctx *context.Context) {
ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
ctx.Data["MirrorsEnabled"] = setting.Mirror.Enabled
ctx.Data["DisableNewPullMirrors"] = setting.Mirror.DisableNewPull
ctx.Data["DisableNewPushMirrors"] = setting.Mirror.DisableNewPush
ctx.Data["DefaultMirrorInterval"] = setting.Mirror.DefaultInterval
ctx.Data["MinimumMirrorInterval"] = setting.Mirror.MinInterval
signing, _ := git.GetSigningKey(ctx)
ctx.Data["SigningKeyAvailable"] = signing != nil
ctx.Data["SigningSettings"] = setting.Repository.Signing
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
switch ctx.FormString("action") {
case "update":
handleSettingsPostUpdate(ctx)
@@ -211,10 +193,14 @@ func SettingsPost(ctx *context.Context) {
}
func handleSettingsPostUpdate(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSettingsOptions)
if form.RepoName == "" {
ctx.JSONErrorWithField(ctx.Tr("form.require_error", ctx.Tr("form.RepoName")), "RepoName")
return
}
@@ -227,19 +213,17 @@ func handleSettingsPostUpdate(ctx *context.Context) {
ctx.Repo.GitRepo = nil
}
if err := repo_service.ChangeRepositoryName(ctx, ctx.Doer, repo, newRepoName); err != nil {
ctx.Data["Err_RepoName"] = true
var errNameReserved db.ErrNameReserved
var errNamePatternNotAllowed db.ErrNamePatternNotAllowed
switch {
case repo_model.IsErrRepoAlreadyExist(err):
ctx.RenderWithErrDeprecated(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("form.repo_name_been_taken"), "RepoName")
case errors.As(err, &errNameReserved):
ctx.RenderWithErrDeprecated(ctx.Tr("repo.form.name_reserved", errNameReserved.Name), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.form.name_reserved", errNameReserved.Name), "RepoName")
case repo_model.IsErrRepoFilesAlreadyExist(err):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("form.repository_files_already_exist"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("form.repository_files_already_exist"), "RepoName")
case errors.As(err, &errNamePatternNotAllowed):
ctx.RenderWithErrDeprecated(ctx.Tr("repo.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.form.name_pattern_not_allowed", errNamePatternNotAllowed.Pattern), "RepoName")
default:
ctx.ServerErrorAuto(err)
}
@@ -262,11 +246,14 @@ func handleSettingsPostUpdate(ctx *context.Context) {
log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostMirror(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if !setting.Mirror.Enabled || !repo.IsMirror || repo.IsArchived {
ctx.NotFound()
@@ -278,14 +265,10 @@ func handleSettingsPostMirror(ctx *context.Context) {
ctx.ServerErrorAuto(err)
return
}
// This section doesn't require repo_name/RepoName to be set in the form, don't show it
// as an error on the UI for this action
ctx.Data["Err_RepoName"] = nil
interval, err := time.ParseDuration(form.Interval)
if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
ctx.Data["Err_Interval"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.mirror_interval_invalid"), "Interval")
return
}
@@ -299,8 +282,7 @@ func handleSettingsPostMirror(ctx *context.Context) {
u, err := git.ParseRemoteAddressURL(ctx, ctx.Repo.Repository, pullMirror.GetRemoteName())
if err != nil {
ctx.Data["Err_MirrorAddress"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "MirrorAddress")
return
}
storedAddr := *u.URL
@@ -320,8 +302,7 @@ func handleSettingsPostMirror(ctx *context.Context) {
err = migrations.IsMigrateURLAllowed(address, ctx.Doer)
}
if err != nil {
ctx.Data["Err_MirrorAddress"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "MirrorAddress")
return
}
@@ -332,8 +313,7 @@ func handleSettingsPostMirror(ctx *context.Context) {
remoteAddress, err := util.SanitizeURL(form.MirrorAddress)
if err != nil {
ctx.Data["Err_MirrorAddress"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "MirrorAddress")
return
}
pullMirror.RemoteAddress = remoteAddress
@@ -343,14 +323,12 @@ func handleSettingsPostMirror(ctx *context.Context) {
if len(form.LFSEndpoint) > 0 {
ep := lfs.DetermineEndpoint("", form.LFSEndpoint)
if ep == nil {
ctx.Data["Err_LFSEndpoint"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.migrate.invalid_lfs_endpoint"), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.migrate.invalid_lfs_endpoint"), "mirror_lfs_endpoint")
return
}
err = migrations.IsMigrateURLAllowed(ep.String(), ctx.Doer)
if err != nil {
ctx.Data["Err_LFSEndpoint"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "mirror_lfs_endpoint")
return
}
}
@@ -363,7 +341,7 @@ func handleSettingsPostMirror(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostMirrorSync(ctx *context.Context) {
@@ -376,11 +354,14 @@ func handleSettingsPostMirrorSync(ctx *context.Context) {
mirror_service.AddPullMirrorToQueue(repo.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.pull_mirror_sync_in_progress", repo.OriginalURL))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostPushMirrorSync(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if !setting.Mirror.Enabled {
@@ -397,11 +378,14 @@ func handleSettingsPostPushMirrorSync(ctx *context.Context) {
mirror_service.AddPushMirrorToQueue(m.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.push_mirror_sync_in_progress", m.RemoteAddress))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostPushMirrorUpdate(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if !setting.Mirror.Enabled || repo.IsArchived {
@@ -409,13 +393,9 @@ func handleSettingsPostPushMirrorUpdate(ctx *context.Context) {
return
}
// This section doesn't require repo_name/RepoName to be set in the form, don't show it
// as an error on the UI for this action
ctx.Data["Err_RepoName"] = nil
interval, err := time.ParseDuration(form.PushMirrorInterval)
if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
ctx.RenderWithErrDeprecated(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &forms.RepoSettingForm{})
ctx.JSONErrorWithField(ctx.Tr("repo.mirror_interval_invalid"), "PushMirrorInterval")
return
}
@@ -439,11 +419,14 @@ func handleSettingsPostPushMirrorUpdate(ctx *context.Context) {
mirror_service.AddPushMirrorToQueue(m.ID)
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostPushMirrorRemove(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if !setting.Mirror.Enabled || repo.IsArchived {
@@ -463,11 +446,14 @@ func handleSettingsPostPushMirrorRemove(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if setting.Mirror.DisableNewPush || repo.IsArchived {
@@ -475,14 +461,9 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
return
}
// This section doesn't require repo_name/RepoName to be set in the form, don't show it
// as an error on the UI for this action
ctx.Data["Err_RepoName"] = nil
interval, err := time.ParseDuration(form.PushMirrorInterval)
if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
ctx.Data["Err_PushMirrorInterval"] = true
ctx.RenderWithErrDeprecated(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
ctx.JSONErrorWithField(ctx.Tr("repo.mirror_interval_invalid"), "PushMirrorInterval")
return
}
@@ -491,8 +472,7 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
err = migrations.IsMigrateURLAllowed(address, ctx.Doer)
}
if err != nil {
ctx.Data["Err_PushMirrorAddress"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "PushMirrorAddress")
return
}
@@ -500,8 +480,7 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
remoteAddress, err := util.SanitizeURL(form.PushMirrorAddress)
if err != nil {
ctx.Data["Err_PushMirrorAddress"] = true
handleSettingRemoteAddrError(ctx, err, form)
handleSettingRemoteAddrError(ctx, err, "PushMirrorAddress")
return
}
@@ -526,7 +505,7 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
audit.Record(ctx, audit_model.RepositoryMirrorPushAdd, repo, "mirror_id", m.ID, "remote_address", m.RemoteAddress)
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func newRepoUnit(repo *repo_model.Repository, unitType unit_model.Type, config convert.Conversion) repo_model.RepoUnit {
@@ -541,7 +520,10 @@ func newRepoUnit(repo *repo_model.Repository, unitType unit_model.Type, config c
}
func handleSettingsPostAdvanced(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
var repoChanged bool
var units []repo_model.RepoUnit
@@ -696,7 +678,10 @@ func handleSettingsPostAdvanced(ctx *context.Context) {
}
func handleSettingsPostSigning(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
trustModel := repo_model.ToTrustModel(form.TrustModel)
if trustModel != repo.TrustModel {
@@ -712,7 +697,7 @@ func handleSettingsPostSigning(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingsPostAdmin(ctx *context.Context) {
@@ -722,7 +707,10 @@ func handleSettingsPostAdmin(ctx *context.Context) {
}
repo := ctx.Repo.Repository
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
if repo.IsFsckEnabled != form.EnableHealthCheck {
repo.IsFsckEnabled = form.EnableHealthCheck
if err := repo_model.UpdateRepositoryColsNoAutoTime(ctx, repo, "is_fsck_enabled"); err != nil {
@@ -733,11 +721,14 @@ func handleSettingsPostAdmin(ctx *context.Context) {
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingsPostAdminIndex(ctx *context.Context) {
form := web.GetForm[*forms.RepoSettingForm](ctx)
form := context.GetFetchActionForm[*forms.RepoSettingForm](ctx)
if ctx.Written() {
return
}
repo := ctx.Repo.Repository
if !ctx.Doer.IsAdmin {
ctx.HTTPError(http.StatusForbidden)
@@ -764,7 +755,7 @@ func handleSettingsPostAdminIndex(ctx *context.Context) {
log.Trace("Repository reindex for %s requested: %s/%s", form.RequestReindexType, ctx.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.reindex_requested"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingsPostConvert(ctx *context.Context) {
@@ -772,9 +763,8 @@ func handleSettingsPostConvert(ctx *context.Context) {
return
}
form := web.GetForm[*forms.RepoSettingForm](ctx)
repo := ctx.Repo.Repository
if repo.FullName() != form.RepoName {
if repo.FullName() != strings.TrimSpace(ctx.FormString("repo_name")) {
ctx.JSONError(ctx.Tr("form.enterred_invalid_repo_name"))
return
}
@@ -805,13 +795,12 @@ func handleSettingsPostConvertFork(ctx *context.Context) {
return
}
form := web.GetForm[*forms.RepoSettingForm](ctx)
repo := ctx.Repo.Repository
if err := repo.LoadOwner(ctx); err != nil {
ctx.ServerErrorAuto(err)
return
}
if repo.FullName() != form.RepoName {
if repo.FullName() != strings.TrimSpace(ctx.FormString("repo_name")) {
ctx.JSONError(ctx.Tr("form.enterred_invalid_repo_name"))
return
}
@@ -845,9 +834,8 @@ func handleSettingsPostTransfer(ctx *context.Context) {
return
}
form := web.GetForm[*forms.RepoSettingForm](ctx)
repo := ctx.Repo.Repository
if repo.FullName() != form.RepoName {
if repo.FullName() != strings.TrimSpace(ctx.FormString("repo_name")) {
ctx.JSONError(ctx.Tr("form.enterred_invalid_repo_name"))
return
}
@@ -914,7 +902,7 @@ func handleSettingsPostCancelTransfer(ctx *context.Context) {
if err != nil {
if repo_model.IsErrNoPendingTransfer(err) {
ctx.Flash.Error("repo.settings.transfer_abort_invalid")
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
} else {
ctx.ServerErrorAuto(err)
}
@@ -928,7 +916,7 @@ func handleSettingsPostCancelTransfer(ctx *context.Context) {
log.Trace("Repository transfer process was cancelled: %s/%s ", ctx.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.transfer_abort_success", repoTransfer.Recipient.Name))
ctx.Redirect(repo.Link() + "/settings")
ctx.JSONRedirect(repo.Link() + "/settings")
}
func handleSettingsPostDelete(ctx *context.Context) {
@@ -936,9 +924,8 @@ func handleSettingsPostDelete(ctx *context.Context) {
return
}
form := web.GetForm[*forms.RepoSettingForm](ctx)
repo := ctx.Repo.Repository
if repo.FullName() != form.RepoName {
if repo.FullName() != strings.TrimSpace(ctx.FormString("repo_name")) {
ctx.JSONError(ctx.Tr("form.enterred_invalid_repo_name"))
return
}
@@ -962,9 +949,8 @@ func handleSettingsPostDeleteWiki(ctx *context.Context) {
if !canManageRepoDangerZone(ctx) {
return
}
form := web.GetForm[*forms.RepoSettingForm](ctx)
repo := ctx.Repo.Repository
if repo.FullName() != form.RepoName {
if repo.FullName() != strings.TrimSpace(ctx.FormString("repo_name")) {
ctx.JSONError(ctx.Tr("form.enterred_invalid_repo_name"))
return
}
@@ -987,14 +973,14 @@ func handleSettingsPostArchive(ctx *context.Context) {
repo := ctx.Repo.Repository
if repo.IsMirror {
ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
return
}
if err := repo_model.SetArchiveRepoState(ctx, repo, true); err != nil {
log.Error("Tried to archive a repo: %s", err)
ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
return
}
@@ -1010,7 +996,7 @@ func handleSettingsPostArchive(ctx *context.Context) {
ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingsPostUnarchive(ctx *context.Context) {
@@ -1022,7 +1008,7 @@ func handleSettingsPostUnarchive(ctx *context.Context) {
if err := repo_model.SetArchiveRepoState(ctx, repo, false); err != nil {
log.Error("Tried to unarchive a repo: %s", err)
ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
return
}
@@ -1040,7 +1026,7 @@ func handleSettingsPostUnarchive(ctx *context.Context) {
ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingsPostVisibility(ctx *context.Context) {
@@ -1077,25 +1063,25 @@ func handleSettingsPostVisibility(ctx *context.Context) {
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings")
}
func handleSettingRemoteAddrError(ctx *context.Context, err error, form *forms.RepoSettingForm) {
func handleSettingRemoteAddrError(ctx *context.Context, err error, field string) {
if addrErr, ok := err.(*git.ErrInvalidCloneAddr); ok {
switch {
case addrErr.IsProtocolInvalid:
ctx.RenderWithErrDeprecated(ctx.Tr("repo.mirror_address_protocol_invalid"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("repo.mirror_address_protocol_invalid"), field)
case addrErr.IsURLError:
ctx.RenderWithErrDeprecated(ctx.Tr("form.url_error", addrErr.Host), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("form.url_error", addrErr.Host), field)
case addrErr.IsPermissionDenied:
if addrErr.LocalPath {
ctx.RenderWithErrDeprecated(ctx.Tr("repo.migrate.permission_denied"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("repo.migrate.permission_denied"), field)
} else {
ctx.RenderWithErrDeprecated(ctx.Tr("repo.migrate.permission_denied_blocked"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("repo.migrate.permission_denied_blocked"), field)
}
case addrErr.IsInvalidPath:
ctx.RenderWithErrDeprecated(ctx.Tr("repo.migrate.invalid_local_path"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("repo.migrate.invalid_local_path"), field)
default:
ctx.ServerErrorAuto(err)
}
return
}
ctx.RenderWithErrDeprecated(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, form)
ctx.JSONErrorWithField(ctx.Tr("repo.mirror_address_url_invalid"), field)
}
+8 -5
View File
@@ -21,7 +21,6 @@ import (
"gitea.dev/modules/git"
"gitea.dev/modules/setting"
"gitea.dev/modules/test"
"gitea.dev/modules/web"
"gitea.dev/services/context"
"gitea.dev/services/contexttest"
"gitea.dev/services/forms"
@@ -196,13 +195,17 @@ func TestHandleSettingsPostMirrorReusesCredentialsOnlyForSameAddress(t *testing.
require.NoError(t, mirror_service.UpdateAddress(t.Context(), mirror, "https://existing-user:existing-password@example.com/user2/repo1.git"))
postMirrorSettings := func(form *forms.RepoSettingForm) string {
ctx, _ := contexttest.MockContext(t, mirrorRepo.Link()+"/settings")
ctx, resp := contexttest.MockContext(t, mirrorRepo.Link()+"/settings")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, mirrorRepo.ID)
form.Interval = "8h"
web.SetForm(ctx, form)
ctx.Req.Form = url.Values{
"interval": {"8h"},
"mirror_address": {form.MirrorAddress},
"mirror_username": {form.MirrorUsername},
"mirror_password": {form.MirrorPassword},
}
handleSettingsPostMirror(ctx)
require.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
require.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus(), resp.Body.String())
remoteURL, err := git.ParseRemoteAddressURL(t.Context(), mirrorRepo, mirror.GetRemoteName())
require.NoError(t, err)
return remoteURL.User.String()
+13 -23
View File
@@ -107,17 +107,13 @@ func EmailPost(ctx *context.Context) {
return
}
form := web.GetForm[*forms.AddEmailForm](ctx)
ctx.Data["PageIsSettingsAccount"] = true
ctx.Data["Email"] = ctx.Doer.Email
// Make email address primary.
if ctx.FormString("_method") == "PRIMARY" {
emailID := ctx.FormInt64("id")
if err := user_model.MakeActiveEmailPrimary(ctx, ctx.Doer.ID, emailID); err != nil {
if user_model.IsErrEmailAddressNotExist(err) {
ctx.Flash.Error(ctx.Tr("settings.email_primary_not_found"))
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
ctx.ServerErrorAuto(err)
@@ -130,7 +126,7 @@ func EmailPost(ctx *context.Context) {
audit.Record(ctx, audit_model.UserEmailPrimaryChange, ctx.Doer, "email", email.Email)
}
log.Trace("Email made primary: %s", ctx.Doer.Name)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
// Send activation Email
@@ -138,7 +134,7 @@ func EmailPost(ctx *context.Context) {
var address string
if ctx.Cache.IsExist("MailResendLimit_" + ctx.Doer.LowerName) {
log.Error("Send activation: activation still pending")
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
@@ -146,23 +142,23 @@ func EmailPost(ctx *context.Context) {
email, err := user_model.GetEmailAddressByID(ctx, ctx.Doer.ID, id)
if err != nil {
log.Error("GetEmailAddressByID(%d,%d) error: %v", ctx.Doer.ID, id, err)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
if email == nil {
log.Warn("Send activation failed: EmailAddress[%d] not found for user: %-v", id, ctx.Doer)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
if email.IsActivated {
log.Debug("Send activation failed: email %s is already activated for user: %-v", email.Email, ctx.Doer)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
if email.IsPrimary {
if ctx.Doer.IsActive && !setting.Service.RegisterEmailConfirm {
log.Debug("Send activation failed: email %s is already activated for user: %-v", email.Email, ctx.Doer)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
// Only fired when the primary email is inactive (Wrong state)
@@ -177,26 +173,20 @@ func EmailPost(ctx *context.Context) {
}
ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale)))
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
return
}
if ctx.HasError() {
loadAccountData(ctx)
ctx.HTML(http.StatusOK, tplSettingsAccount)
form := context.GetFetchActionForm[*forms.AddEmailForm](ctx)
if ctx.Written() {
return
}
if err := user.AddEmailAddresses(ctx, ctx.Doer, []string{form.Email}); err != nil {
if user_model.IsErrEmailAlreadyUsed(err) {
loadAccountData(ctx)
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_been_used"), tplSettingsAccount, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_been_used"), "Email")
} else if errors.Is(err, util.ErrInvalidArgument) {
loadAccountData(ctx)
ctx.RenderWithErrDeprecated(ctx.Tr("form.email_invalid"), tplSettingsAccount, &form)
ctx.JSONErrorWithField(ctx.Tr("form.email_invalid"), "Email")
} else {
ctx.ServerErrorAuto(err)
}
@@ -216,7 +206,7 @@ func EmailPost(ctx *context.Context) {
}
log.Trace("Email address added: %s", form.Email)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
ctx.JSONRedirect(setting.AppSubURL + "/user/settings/account")
}
// DeleteEmail response for delete user's email
+1
View File
@@ -44,6 +44,7 @@ func Keys(ctx *context.Context) {
// KeysPost response for change user's SSH/GPG keys
func KeysPost(ctx *context.Context) {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action cannot just show a JSON error: GPG errors must reveal signing instructions and a signature input.
form := web.GetForm[*forms.AddKeyForm](ctx)
ctx.Data["PageIsSettingsKeys"] = true
ctx.Data["DisableSSH"] = setting.SSH.Disabled
+17 -19
View File
@@ -583,9 +583,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Post("/link_account_signup", web.Bind[*forms.RegisterForm](), auth.LinkAccountPostRegister)
m.Group("/two_factor", func() {
m.Get("", auth.TwoFactor)
m.Post("", web.Bind[*forms.TwoFactorAuthForm](), auth.TwoFactorPost)
m.Post("", auth.TwoFactorPost)
m.Get("/scratch", auth.TwoFactorScratch)
m.Post("/scratch", web.Bind[*forms.TwoFactorScratchAuthForm](), auth.TwoFactorScratchPost)
m.Post("/scratch", auth.TwoFactorScratchPost)
})
m.Group("/webauthn", func() {
m.Get("", auth.WebAuthn)
@@ -619,12 +619,12 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Post("", user_setting.ProfilePost)
m.Post("/update_preferences", user_setting.UpdatePreferences)
m.Get("/change_password", auth.MustChangePassword)
m.Post("/change_password", web.Bind[*forms.MustChangePasswordForm](), auth.MustChangePasswordPost)
m.Post("/change_password", auth.MustChangePasswordPost)
m.Post("/avatar", web.Bind[*forms.AvatarForm](), user_setting.AvatarPost)
m.Post("/avatar/delete", user_setting.DeleteAvatar)
m.Group("/account", func() {
m.Combo("").Get(user_setting.Account).Post(web.Bind[*forms.ChangePasswordForm](), user_setting.AccountPost)
m.Post("/email", web.Bind[*forms.AddEmailForm](), user_setting.EmailPost)
m.Post("/email", user_setting.EmailPost)
m.Post("/email/delete", user_setting.DeleteEmail)
m.Post("/delete", user_setting.DeleteAccount)
})
@@ -781,9 +781,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Group("/users", func() {
m.Get("", admin.Users)
m.Combo("/new").Get(admin.NewUser).Post(web.Bind[*forms.AdminCreateUserForm](), admin.NewUserPost)
m.Combo("/new").Get(admin.NewUser).Post(admin.NewUserPost)
m.Get("/{userid}", admin.ViewUser)
m.Combo("/{userid}/edit").Get(admin.EditUser).Post(web.Bind[*forms.AdminEditUserForm](), admin.EditUserPost)
m.Combo("/{userid}/edit").Get(admin.EditUser).Post(admin.EditUserPost)
m.Post("/{userid}/impersonate", admin.ImpersonateUser)
m.Post("/{userid}/delete", admin.DeleteUser)
m.Post("/{userid}/avatar", web.Bind[*forms.AvatarForm](), admin.AvatarPost)
@@ -843,9 +843,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Group("/auths", func() {
m.Get("", admin.Authentications)
m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind[*forms.AuthenticationForm](), admin.NewAuthSourcePost)
m.Combo("/new").Get(admin.NewAuthSource).Post(admin.NewAuthSourcePost)
m.Combo("/{authid}").Get(admin.EditAuthSource).
Post(web.Bind[*forms.AuthenticationForm](), admin.EditAuthSourcePost)
Post(admin.EditAuthSourcePost)
m.Post("/{authid}/delete", admin.DeleteAuthSource)
})
@@ -945,7 +945,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Group("/org", func() {
m.Group("", func() {
m.Get("/create", org.Create)
m.Post("/create", web.Bind[*forms.CreateOrgForm](), org.CreatePost)
m.Post("/create", org.CreatePost)
})
m.Group("/invite/{token}", func() {
@@ -982,16 +982,16 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
// require owner permission
m.Group("/{org}", func() {
m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", web.Bind[*forms.CreateTeamForm](), org.NewTeamPost)
m.Post("/teams/new", org.NewTeamPost)
m.Get("/teams/{team}/edit", org.EditTeam)
m.Post("/teams/{team}/edit", web.Bind[*forms.CreateTeamForm](), org.EditTeamPost)
m.Post("/teams/{team}/edit", org.EditTeamPost)
m.Post("/teams/{team}/delete", org.DeleteTeam)
m.Get("/worktime", context.OrgAssignment(context.OrgAssignmentOptions{RequireOwner: true}), org.Worktime)
m.Group("/settings", func() {
m.Combo("").Get(org.Settings).
Post(web.Bind[*forms.UpdateOrgSettingForm](), org.SettingsPost)
Post(org.SettingsPost)
m.Post("/avatar", web.Bind[*forms.AvatarForm](), org.SettingsAvatar)
m.Post("/avatar/delete", org.SettingsDeleteAvatar)
m.Group("/applications", func() {
@@ -1062,7 +1062,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Group("/repo", func() {
m.Get("/create", repo.Create)
m.Post("/create", web.Bind[*forms.CreateRepoForm](), repo.CreatePost)
m.Post("/create", repo.CreatePost)
m.Get("/migrate", repo.Migrate)
m.Post("/migrate", repo.MigratePost)
m.Get("/search", repo.SearchRepo)
@@ -1148,10 +1148,8 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
// end "/{username}/{reponame}/-": mentions
m.Group("/{username}/{reponame}/settings", func() {
m.Group("", func() {
m.Combo("").Get(repo_setting.Settings).
Post(web.Bind[*forms.RepoSettingForm](), repo_setting.SettingsPost)
}, repo_setting.SettingsCtxData)
m.Get("", repo_setting.Settings)
m.Post("", repo_setting.SettingsPost)
m.Post("/avatar", web.Bind[*forms.AvatarForm](), repo_setting.SettingsAvatar)
m.Post("/avatar/delete", repo_setting.SettingsDeleteAvatar)
@@ -1387,9 +1385,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
m.Group("/milestones", func() {
m.Combo("/new").Get(repo.NewMilestone).
Post(web.Bind[*forms.CreateMilestoneForm](), repo.NewMilestonePost)
Post(repo.NewMilestonePost)
m.Get("/{id}/edit", repo.EditMilestone)
m.Post("/{id}/edit", web.Bind[*forms.CreateMilestoneForm](), repo.EditMilestonePost)
m.Post("/{id}/edit", repo.EditMilestonePost)
m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
m.Post("/delete", repo.DeleteMilestone)
}, context.RequireUnitWriter(unit.TypeIssues, unit.TypePullRequests))
+1
View File
@@ -27,6 +27,7 @@ const (
// VerifyCaptcha returns whether the captcha is solved or disabled, otherwise it renders tpl with an error
func VerifyCaptcha(ctx *Context, tpl templates.TplName, form any) bool {
// TODO: REFACTOR-RENDER-WITH-ERR: form-fetch-action needs CAPTCHA refresh support before callers can stop re-rendering on verification failure.
if !setting.Service.EnableCaptcha {
return true
}
+1 -1
View File
@@ -79,7 +79,7 @@ type MigrateRepoForm struct {
// RepoSettingForm form for changing repository settings
type RepoSettingForm struct {
middleware.FormDefaultValidator
RepoName string `binding:"TrimSpace;Required;AlphaDashDot;MaxSize(100)"`
RepoName string `binding:"TrimSpace;AlphaDashDot;MaxSize(100)"`
Description string `binding:"MaxSize(2048)"`
Website string `binding:"ValidUrl;MaxSize(1024)"`
Interval string
+3 -3
View File
@@ -4,7 +4,7 @@
{{ctx.Locale.Tr "admin.auths.edit"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="{{.Link}}" method="post">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
{{template "base/disable_form_autofill"}}
<input type="hidden" name="id" value="{{.Source.ID}}">
<div class="inline field">
@@ -12,7 +12,7 @@
<input type="hidden" id="auth_type" name="type" value="{{.Source.Type.Int}}">
<span>{{.Source.TypeName}}</span>
</div>
<div class="required inline field {{if .Err_Name}}error{{end}}">
<div class="required inline field">
<label for="auth_name">{{ctx.Locale.Tr "admin.auths.auth_name"}}</label>
<input id="auth_name" name="name" value="{{.Source.Name}}" required>
</div>
@@ -27,7 +27,7 @@
<!-- LDAP and DLDAP -->
{{if or .Source.IsLDAP .Source.IsDLDAP}}
{{$cfg:=.Source.Cfg}}
<div class="inline required field {{if .Err_SecurityProtocol}}error{{end}}">
<div class="inline required field">
<label>{{ctx.Locale.Tr "admin.auths.security_protocol"}}</label>
<div class="ui selection security-protocol dropdown">
<input type="hidden" id="security_protocol" name="security_protocol" value="{{$cfg.SecurityProtocol.Int}}">
+3 -3
View File
@@ -4,10 +4,10 @@
{{ctx.Locale.Tr "admin.auths.new"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="{{.Link}}" method="post">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
{{template "base/disable_form_autofill"}}
<!-- Types and name -->
<div class="inline required field {{if .Err_Type}}error{{end}}">
<div class="inline required field">
<label>{{ctx.Locale.Tr "admin.auths.auth_type"}}</label>
<div class="ui selection type dropdown">
<input type="hidden" id="auth_type" name="type" value="{{.type}}">
@@ -20,7 +20,7 @@
</div>
</div>
</div>
<div class="required inline field {{if .Err_Name}}error{{end}}">
<div class="required inline field">
<label for="auth_name">{{ctx.Locale.Tr "admin.auths.auth_name"}}</label>
<input id="auth_name" name="name" value="{{.name}}" autofocus required>
</div>
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="ldap dldap field {{if not (or (eq .type 2) (eq .type 5))}}tw-hidden{{end}}">
<div class="inline required field {{if .Err_SecurityProtocol}}error{{end}}">
<div class="inline required field">
<label>{{ctx.Locale.Tr "admin.auths.security_protocol"}}</label>
<div class="ui selection security-protocol dropdown">
<input type="hidden" id="security_protocol" name="security_protocol" value="{{.security_protocol}}">
+1 -1
View File
@@ -24,7 +24,7 @@
<label for="oauth2_icon_url">{{ctx.Locale.Tr "admin.auths.oauth2_icon_url"}}</label>
<input id="oauth2_icon_url" name="oauth2_icon_url" value="{{.oauth2_icon_url}}">
</div>
<div class="open_id_connect_auto_discovery_url required field{{if .Err_DiscoveryURL}} error{{end}}">
<div class="open_id_connect_auto_discovery_url required field">
<label for="open_id_connect_auto_discovery_url">{{ctx.Locale.Tr "admin.auths.openIdConnectAutoDiscoveryURL"}}</label>
<input id="open_id_connect_auto_discovery_url" name="open_id_connect_auto_discovery_url" value="{{.open_id_connect_auto_discovery_url}}">
</div>
+12 -12
View File
@@ -4,9 +4,9 @@
{{ctx.Locale.Tr "admin.users.edit_account"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="./edit" method="post">
<form class="ui form form-fetch-action" action="./edit" method="post">
{{template "base/disable_form_autofill"}}
<div class="field {{if .Err_UserName}}error{{end}}">
<div class="field">
<label for="user_name">{{ctx.Locale.Tr "username"}}</label>
<input id="user_name" name="user_name" value="{{.User.Name}}" maxlength="40">
</div>
@@ -25,7 +25,7 @@
</div>
{{end}}
{{if not .User.IsTypeBot}}
<div class="required js-non-bot field {{if .Err_LoginType}}error{{end}}">
<div class="required js-non-bot field">
<label for="login_type">{{ctx.Locale.Tr "admin.users.auth_source"}}</label>
<div class="ui selection type dropdown">
<input type="hidden" id="login_type" name="login_type" value="{{.LoginSource.Type.Int}}-{{.LoginSource.ID}}" required>
@@ -43,7 +43,7 @@
<input type="hidden" name="login_type" value="0-0">
{{end}}
<div class="required field {{if .Err_Visibility}}error{{end}}">
<div class="required field">
<label for="visibility">{{ctx.Locale.Tr "settings.visibility"}}</label>
<div class="ui selection type dropdown">
<input type="hidden" id="visibility" name="visibility" value="{{if .User.Visibility.IsPublic}}0{{else if .User.Visibility.IsLimited}}1{{else}}2{{end}}">
@@ -67,27 +67,27 @@
</div>
</div>
<div class="required js-non-local js-non-bot field {{if .Err_LoginName}}error{{end}} {{if eq .User.LoginSource 0}}tw-hidden{{end}}">
<div class="required js-non-local js-non-bot field {{if eq .User.LoginSource 0}}tw-hidden{{end}}">
<label for="login_name">{{ctx.Locale.Tr "admin.users.auth_login_name"}}</label>
<input id="login_name" name="login_name" value="{{.User.LoginName}}">
</div>
<div class="field {{if .Err_FullName}}error{{end}}">
<div class="field">
<label for="full_name">{{ctx.Locale.Tr "settings.full_name"}}</label>
<input id="full_name" name="full_name" value="{{.User.FullName}}" maxlength="100">
</div>
<div class="required field {{if .Err_Email}}error{{end}}">
<div class="required field">
<label for="email">{{ctx.Locale.Tr "email"}}</label>
<input id="email" name="email" type="email" value="{{.User.Email}}" required>
</div>
{{if not .User.IsTypeBot}}
<div class="js-local js-non-bot field {{if .Err_Password}}error{{end}} {{if not (or .User.IsLocal .User.IsOAuth2)}}tw-hidden{{end}}">
<div class="js-local js-non-bot field {{if not (or .User.IsLocal .User.IsOAuth2)}}tw-hidden{{end}}">
<label for="password">{{ctx.Locale.Tr "password"}}</label>
<input id="password" name="password" type="password" autocomplete="new-password">
<p class="help">{{ctx.Locale.Tr "admin.users.password_helper"}}</p>
</div>
{{end}}
<div class="field {{if .Err_Language}}error{{end}}">
<div class="field">
<label for="language">{{ctx.Locale.Tr "settings.language"}}</label>
<div class="ui selection dropdown">
<input name="language" type="hidden" value="{{.User.Language}}">
@@ -101,18 +101,18 @@
</div>
</div>
<div class="field {{if .Err_Website}}error{{end}}">
<div class="field">
<label for="website">{{ctx.Locale.Tr "settings.website"}}</label>
<input id="website" name="website" type="url" value="{{.User.Website}}" placeholder="http://mydomain.com or https://mydomain.com" maxlength="255">
</div>
<div class="field {{if .Err_Location}}error{{end}}">
<div class="field">
<label for="location">{{ctx.Locale.Tr "settings.location"}}</label>
<input id="location" name="location" value="{{.User.Location}}" maxlength="50">
</div>
<div class="divider"></div>
<div class="inline field {{if .Err_MaxRepoCreation}}error{{end}}">
<div class="inline field">
<label for="max_repo_creation">{{ctx.Locale.Tr "admin.users.max_repo_creation"}}</label>
<input id="max_repo_creation" name="max_repo_creation" type="number" min="-1" value="{{.User.MaxRepoCreation}}">
<p class="help">{{ctx.Locale.Tr "admin.users.max_repo_creation_desc"}}</p>
+7 -7
View File
@@ -4,9 +4,9 @@
{{ctx.Locale.Tr "admin.users.new_account"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="{{.Link}}" method="post">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
{{template "base/disable_form_autofill"}}
<div class="required field {{if .Err_UserName}}error{{end}}">
<div class="required field">
<label for="user_name">{{ctx.Locale.Tr "username"}}</label>
<input id="user_name" type="text" name="user_name" value="{{.user_name}}" autofocus required maxlength="40">
</div>
@@ -22,7 +22,7 @@
</div>
</div>
</div>
<div class="required field js-non-bot {{if .Err_LoginType}}error{{end}}">
<div class="required field js-non-bot">
<label for="login_type">{{ctx.Locale.Tr "admin.users.auth_source"}}</label>
<div class="ui selection type dropdown">
<input type="hidden" id="login_type" name="login_type" value="{{.login_type}}" required>
@@ -37,7 +37,7 @@
</div>
</div>
<div class="required field {{if .Err_Visibility}}error{{end}}">
<div class="required field">
<label for="visibility">{{ctx.Locale.Tr "settings.visibility"}}</label>
<div class="ui selection type dropdown">
<input type="hidden" id="visibility" name="visibility" value="{{if .visibility}}{{printf "%d" .visibility}}{{else}}{{printf "%d" .DefaultUserVisibilityMode}}{{end}}">
@@ -61,15 +61,15 @@
</div>
</div>
<div class="required js-non-local js-non-bot field {{if .Err_LoginName}}error{{end}} {{if eq .login_type "0-0"}}tw-hidden{{end}}">
<div class="required js-non-local js-non-bot field {{if eq .login_type "0-0"}}tw-hidden{{end}}">
<label for="login_name">{{ctx.Locale.Tr "admin.users.auth_login_name"}}</label>
<input id="login_name" name="login_name" value="{{.login_name}}">
</div>
<div class="required field {{if .Err_Email}}error{{end}}">
<div class="required field">
<label for="email">{{ctx.Locale.Tr "email"}}</label>
<input id="email" name="email" type="email" value="{{.email}}" required>
</div>
<div class="required js-local js-non-bot field {{if .Err_Password}}error{{end}} {{if not (eq .login_type "0-0")}}tw-hidden{{end}}">
<div class="required js-local js-non-bot field {{if not (eq .login_type "0-0")}}tw-hidden{{end}}">
<label for="password">{{ctx.Locale.Tr "password"}}</label>
<input id="password" name="password" type="password" autocomplete="new-password" value="{{.password}}" {{if eq .login_type "0-0"}}required{{end}}>
</div>
+3 -3
View File
@@ -6,14 +6,14 @@
{{ctx.Locale.Tr "new_org"}}
</h3>
<div class="ui attached segment">
<form class="ui form left-right-form" action="{{.Link}}" method="post">
<div class="inline required field {{if .Err_OrgName}}error{{end}}">
<form class="ui form form-fetch-action left-right-form" action="{{.Link}}" method="post">
<div class="inline required field">
<label for="org_name">{{ctx.Locale.Tr "org.org_name_holder"}}</label>
<input id="org_name" name="org_name" value="{{.org_name}}" autofocus required maxlength="40">
<span class="help">{{ctx.Locale.Tr "org.org_name_helper"}}</span>
</div>
<div class="inline field required {{if .Err_OrgVisibility}}error{{end}}">
<div class="inline field required">
<label for="visibility">{{ctx.Locale.Tr "org.settings.visibility"}}</label>
<div class="inline-right">
<div class="ui radio checkbox">
+6 -6
View File
@@ -5,21 +5,21 @@
{{ctx.Locale.Tr "org.settings.options"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="{{.Link}}" method="post">
<div class="field {{if .Err_FullName}}error{{end}}">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
<div class="field">
<label for="full_name">{{ctx.Locale.Tr "org.org_full_name_holder"}}</label>
<input id="full_name" name="full_name" value="{{.Org.FullName}}" maxlength="100">
</div>
<div class="field {{if .Err_Email}}error{{end}}">
<div class="field">
<label for="email">{{ctx.Locale.Tr "org.settings.email"}}</label>
<input id="email" name="email" type="email" value="{{.Org.Email}}" maxlength="255">
</div>
<div class="field {{if .Err_Description}}error{{end}}">
<div class="field">
{{/* it is rendered as markdown, but the length is limited, so at the moment we do not use the markdown editor here */}}
<label for="description">{{ctx.Locale.Tr "org.org_desc"}}</label>
<textarea id="description" name="description" rows="2" maxlength="255">{{.Org.Description}}</textarea>
</div>
<div class="field {{if .Err_Website}}error{{end}}">
<div class="field">
<label for="website">{{ctx.Locale.Tr "org.settings.website"}}</label>
<input id="website" name="website" type="url" value="{{.Org.Website}}" maxlength="255">
</div>
@@ -41,7 +41,7 @@
{{if .SignedUser.IsAdmin}}
<div class="divider"></div>
<div class="inline field {{if .Err_MaxRepoCreation}}error{{end}}">
<div class="inline field">
<label for="max_repo_creation">{{ctx.Locale.Tr "admin.users.max_repo_creation"}}</label>
<input id="max_repo_creation" name="max_repo_creation" type="number" min="-1" value="{{.Org.MaxRepoCreation}}">
<p class="help">{{ctx.Locale.Tr "admin.users.max_repo_creation_desc"}}</p>
+3 -3
View File
@@ -4,13 +4,13 @@
<div class="ui container">
<div class="ui grid">
<div class="column">
<form class="ui form" action="{{if .PageIsOrgTeamsNew}}{{.OrgLink}}/teams/new{{else}}{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/edit{{end}}" data-delete-url="{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/delete" method="post">
<form class="ui form form-fetch-action" action="{{if .PageIsOrgTeamsNew}}{{.OrgLink}}/teams/new{{else}}{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/edit{{end}}" data-delete-url="{{.OrgLink}}/teams/{{.Team.LowerName | PathEscape}}/delete" method="post">
<h3 class="ui top attached header">
{{if .PageIsOrgTeamsNew}}{{ctx.Locale.Tr "org.create_new_team"}}{{else}}{{ctx.Locale.Tr "org.teams.settings"}}{{end}}
</h3>
<div class="ui attached segment">
{{template "base/alert" .}}
<div class="required field {{if .Err_TeamName}}error{{end}}">
<div class="required field">
<label for="team_name">{{ctx.Locale.Tr "org.team_name"}}</label>
{{if .Team.IsOwnerTeam}}
<input type="hidden" name="team_name" value="{{.Team.Name}}">
@@ -18,7 +18,7 @@
<input id="team_name" name="team_name" value="{{.Team.Name}}" required {{if .Team.IsOwnerTeam}}disabled{{end}} autofocus>
<span class="help">{{ctx.Locale.Tr "org.team_name_helper"}}</span>
</div>
<div class="field {{if .Err_Description}}error{{end}}">
<div class="field">
<label for="description">{{ctx.Locale.Tr "org.team_desc"}}</label>
<input id="description" name="description" value="{{.Team.Description}}" maxlength="255">
<span class="help">{{ctx.Locale.Tr "org.team_desc_helper"}}</span>
+4 -4
View File
@@ -7,9 +7,9 @@
<div class="ui attached segment">
{{template "base/alert" .}}
{{template "repo/create_helper" .}}
<form class="ui form left-right-form" action="{{.Link}}" method="post" data-global-init="initRepoNew">
<form class="ui form form-fetch-action left-right-form" action="{{.Link}}" method="post" data-global-init="initRepoNew">
<div id="create-repo-error-message" class="ui negative message tw-text-center tw-hidden"></div>
<div class="inline required field {{if .Err_Owner}}error{{end}}">
<div class="inline required field">
<label>{{ctx.Locale.Tr "repo.owner"}}</label>
<div class="ui selection dropdown ellipsis-text-items" id="repo_owner_dropdown">
<input type="hidden" name="uid" value="{{.ContextUser.ID}}">
@@ -35,7 +35,7 @@
<span class="help">{{ctx.Locale.Tr "repo.owner_helper"}}</span>
</div>
<div class="inline required field {{if .Err_RepoName}}error{{end}}">
<div class="inline required field">
<label for="repo_name">{{ctx.Locale.Tr "repo.repo_name"}}</label>
<input id="repo_name" name="repo_name" value="{{.repo_name}}" autofocus required maxlength="100">
<span class="help" data-help-for-repo-name>{{ctx.Locale.Tr "repo.repo_name_helper"}}</span>
@@ -56,7 +56,7 @@
</div>
<span class="help">{{ctx.Locale.Tr "repo.visibility_description"}}</span>
</div>
<div class="inline field {{if .Err_Description}}error{{end}}">
<div class="inline field">
<label for="description">{{ctx.Locale.Tr "repo.repo_desc"}}</label>
<textarea id="description" rows="2" name="description" placeholder="{{ctx.Locale.Tr "repo.repo_desc_helper"}}" maxlength="2048">{{.description}}</textarea>
</div>
+3 -3
View File
@@ -21,12 +21,12 @@
{{end}}
</h2>
{{template "base/alert" .}}
<form class="ui form" action="{{.Link}}" method="post">
<div class="field {{if .Err_Title}}error{{end}}">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
<div class="field">
<label>{{ctx.Locale.Tr "repo.milestones.title"}}</label>
<input name="title" placeholder="{{ctx.Locale.Tr "repo.milestones.title"}}" value="{{.title}}" autofocus required maxlength="50">
</div>
<div class="field {{if .Err_Deadline}}error{{end}}">
<div class="field">
<label>
{{ctx.Locale.Tr "repo.milestones.due_date"}}
<button type="button" class="interact-fg" id="milestone-clear-deadline">{{ctx.Locale.Tr "repo.milestones.clear"}}</button>
+28 -28
View File
@@ -4,10 +4,10 @@
{{ctx.Locale.Tr "repo.settings.basic_settings"}}
</h4>
<div class="ui attached segment">
<form class="ui form" action="{{.Link}}" method="post">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
{{template "base/disable_form_autofill"}}
<input type="hidden" name="action" value="update">
<div class="required field {{if .Err_RepoName}}error{{end}}">
<div class="required field">
<label>{{ctx.Locale.Tr "repo.repo_name"}}</label>
<input name="repo_name" value="{{.Repository.Name}}" data-repo-name="{{.Repository.Name}}" required>
</div>
@@ -22,11 +22,11 @@
<label>{{ctx.Locale.Tr "repo.template_helper"}}</label>
</div>
</div>
<div class="field {{if .Err_Description}}error{{end}}">
<div class="field">
<label for="description">{{ctx.Locale.Tr "repo.repo_desc"}}</label>
<textarea id="description" name="description" rows="2" maxlength="2048">{{.Repository.Description}}</textarea>
</div>
<div class="field {{if .Err_Website}}error{{end}}">
<div class="field">
<label for="website">{{ctx.Locale.Tr "repo.settings.site"}}</label>
<input id="website" name="website" type="url" maxlength="1024" value="{{.Repository.Website}}">
</div>
@@ -126,7 +126,7 @@
<td>{{ctx.Locale.Tr "repo.settings.mirror_settings.direction.pull"}}</td>
<td>{{DateUtils.FullTime .PullMirror.UpdatedUnix}}</td>
<td class="tw-text-right">
<form method="post" class="tw-inline-block">
<form method="post" class="form-fetch-action tw-inline-block">
<input type="hidden" name="action" value="mirror-sync">
<button type="submit" class="ui primary tiny button inline">{{ctx.Locale.Tr "repo.settings.sync_mirror"}}</button>
</form>
@@ -134,22 +134,22 @@
</tr>
<tr>
<td colspan="4">
<form class="ui form" method="post">
<form class="ui form form-fetch-action" method="post">
{{template "base/disable_form_autofill"}}
<input type="hidden" name="action" value="mirror">
<div class="inline field {{if .Err_EnablePrune}}error{{end}}">
<div class="inline field">
<label>{{ctx.Locale.Tr "repo.mirror_prune"}}</label>
<div class="ui checkbox">
<input id="enable_prune" name="enable_prune" type="checkbox" {{if .PullMirror.EnablePrune}}checked{{end}}>
<label>{{ctx.Locale.Tr "repo.mirror_prune_desc"}}</label>
</div>
</div>
<div class="inline field {{if .Err_Interval}}error{{end}}">
<div class="inline field">
<label for="interval">{{ctx.Locale.Tr "repo.mirror_interval" .MinimumMirrorInterval}}</label>
<input id="interval" name="interval" value="{{.PullMirror.Interval}}">
</div>
{{$address := MirrorRemoteAddress ctx .Repository .PullMirror.GetRemoteName}}
<div class="field {{if .Err_MirrorAddress}}error{{end}}">
<div class="field">
<label for="mirror_address">{{ctx.Locale.Tr "repo.mirror_address"}}</label>
<input id="mirror_address" name="mirror_address" value="{{$address.Address}}" required>
<p class="help">{{ctx.Locale.Tr "repo.mirror_address_desc"}}</p>
@@ -179,7 +179,7 @@
<label>{{ctx.Locale.Tr "repo.mirror_lfs_desc"}}</label>
</div>
</div>
<div class="field {{if .Err_LFSEndpoint}}error{{end}}">
<div class="field">
<label for="mirror_lfs_endpoint">{{ctx.Locale.Tr "repo.mirror_lfs_endpoint"}}</label>
<input id="mirror_lfs_endpoint" name="mirror_lfs_endpoint" value="{{.PullMirror.LFSEndpoint}}" placeholder="{{ctx.Locale.Tr "repo.migrate_options_lfs_endpoint.placeholder"}}">
<p class="help">{{ctx.Locale.Tr "repo.mirror_lfs_endpoint_desc" "https://github.com/git-lfs/git-lfs/blob/main/docs/api/server-discovery.md#server-discovery"}}</p>
@@ -232,12 +232,12 @@
>
{{svg "octicon-pencil" 14}}
</button>
<form method="post" class="tw-inline-block">
<form method="post" class="form-fetch-action tw-inline-block">
<input type="hidden" name="action" value="push-mirror-sync">
<input type="hidden" name="push_mirror_id" value="{{.ID}}">
<button type="submit" class="ui primary tiny button" data-tooltip-content="{{ctx.Locale.Tr "repo.settings.sync_mirror"}}">{{svg "octicon-sync" 14}}</button>
</form>
<form method="post" class="tw-inline-block">
<form method="post" class="form-fetch-action tw-inline-block">
<input type="hidden" name="action" value="push-mirror-remove">
<input type="hidden" name="push_mirror_id" value="{{.ID}}">
<button type="submit" class="ui basic red tiny button" data-tooltip-content="{{ctx.Locale.Tr "remove"}}">{{svg "octicon-trash" 14}}</button>
@@ -252,38 +252,38 @@
{{if (not .DisableNewPushMirrors)}}
<tr>
<td colspan="4">
<form class="ui form" method="post">
<form class="ui form form-fetch-action" method="post">
{{template "base/disable_form_autofill"}}
<input type="hidden" name="action" value="push-mirror-add">
<div class="field {{if .Err_PushMirrorAddress}}error{{end}}">
<div class="field">
<label for="push_mirror_address">{{ctx.Locale.Tr "repo.settings.mirror_settings.push_mirror.remote_url"}}</label>
<input id="push_mirror_address" name="push_mirror_address" value="{{.push_mirror_address}}" required>
<input id="push_mirror_address" name="push_mirror_address" required>
<p class="help">{{ctx.Locale.Tr "repo.mirror_address_desc"}}</p>
</div>
<details class="ui optional field" {{if or .Err_PushMirrorAuth .push_mirror_username}}open{{end}}>
<details class="ui optional field">
<summary class="tw-p-1">
{{ctx.Locale.Tr "repo.need_auth"}}
</summary>
<div class="tw-p-1">
<div class="inline field {{if .Err_PushMirrorAuth}}error{{end}}">
<div class="inline field">
<label for="push_mirror_username">{{ctx.Locale.Tr "username"}}</label>
<input id="push_mirror_username" name="push_mirror_username" value="{{.push_mirror_username}}">
<input id="push_mirror_username" name="push_mirror_username">
</div>
<div class="inline field {{if .Err_PushMirrorAuth}}error{{end}}">
<div class="inline field">
<label for="push_mirror_password">{{ctx.Locale.Tr "password"}}</label>
<input id="push_mirror_password" name="push_mirror_password" type="password" value="{{.push_mirror_password}}" autocomplete="off">
<input id="push_mirror_password" name="push_mirror_password" type="password" autocomplete="off">
</div>
</div>
</details>
<div class="field">
<div class="ui checkbox">
<input id="push_mirror_sync_on_commit" name="push_mirror_sync_on_commit" type="checkbox" {{if .push_mirror_sync_on_commit}}checked{{end}}>
<input id="push_mirror_sync_on_commit" name="push_mirror_sync_on_commit" type="checkbox">
<label for="push_mirror_sync_on_commit">{{ctx.Locale.Tr "repo.mirror_sync_on_commit"}}</label>
</div>
</div>
<div class="inline field {{if .Err_PushMirrorInterval}}error{{end}}">
<div class="inline field">
<label for="push_mirror_interval">{{ctx.Locale.Tr "repo.mirror_interval" .MinimumMirrorInterval}}</label>
<input id="push_mirror_interval" name="push_mirror_interval" value="{{if .push_mirror_interval}}{{.push_mirror_interval}}{{else}}{{.DefaultMirrorInterval}}{{end}}">
<input id="push_mirror_interval" name="push_mirror_interval" value="{{.DefaultMirrorInterval}}">
</div>
<div class="field">
<button type="submit" class="ui primary button">{{ctx.Locale.Tr "repo.settings.mirror_settings.push_mirror.add"}}</button>
@@ -714,7 +714,7 @@
{{ctx.Locale.Tr "repo.settings.signing_settings"}}
</h4>
<div class="ui attached segment">
<form class="ui form" method="post">
<form class="ui form form-fetch-action" method="post">
<input type="hidden" name="action" value="signing">
<div class="field">
<label>{{ctx.Locale.Tr "repo.settings.trust_model"}}</label><br>
@@ -760,7 +760,7 @@
{{ctx.Locale.Tr "repo.settings.admin_settings"}}
</h4>
<div class="ui attached segment">
<form class="ui form" method="post">
<form class="ui form form-fetch-action" method="post">
<input type="hidden" name="action" value="admin">
<div class="field">
<div class="ui checkbox">
@@ -775,7 +775,7 @@
</form>
<div class="divider"></div>
<form class="ui form" method="post">
<form class="ui form form-fetch-action" method="post">
<input type="hidden" name="action" value="admin_index">
{{if .IsRepoIndexerEnabled}}
<h4 class="ui header">{{ctx.Locale.Tr "repo.settings.admin_code_indexer"}}</h4>
@@ -879,7 +879,7 @@
</div>
<div class="item-trailing">
{{if .RepoTransfer}}
<form class="ui form" action="{{.Link}}" method="post">
<form class="ui form form-fetch-action" action="{{.Link}}" method="post">
<input type="hidden" name="action" value="cancel_transfer">
<button type="submit" class="ui red button">{{ctx.Locale.Tr "repo.settings.transfer_abort"}}</button>
</form>
@@ -1099,7 +1099,7 @@
{{end}}
</p>
</div>
<form action="{{.Link}}" method="post">
<form class="form-fetch-action" action="{{.Link}}" method="post">
<input type="hidden" name="action" value="{{if .Repository.IsArchived}}unarchive{{else}}archive{{end}}">
<input type="hidden" name="repo_id" value="{{.Repository.ID}}">
{{template "base/modal_actions_confirm" .}}
@@ -2,7 +2,7 @@
<div class="header">
{{ctx.Locale.Tr "repo.settings.mirror_settings.push_mirror.edit_sync_time"}}
</div>
<form class="content ui form ignore-dirty" method="post">
<form class="content ui form ignore-dirty form-fetch-action" method="post">
<input type="hidden" name="action" value="push-mirror-update">
<input type="hidden" name="push_mirror_id" id="push-mirror-edit-id">
<div class="field">
+4 -4
View File
@@ -5,12 +5,12 @@
{{ctx.Locale.Tr "settings.change_password"}}
</h4>
<div class="ui attached segment">
<form class="ui form tw-max-w-2xl tw-m-auto" action="{{.ChangePasscodeLink}}" method="post">
<div class="required field {{if and (.Err_Password) (or (not .LinkAccountMode) (and .LinkAccountMode .LinkAccountModeSignIn))}}error{{end}}">
<form class="ui form tw-max-w-2xl tw-m-auto form-fetch-action" action="{{.ChangePasscodeLink}}" method="post">
<div class="required field">
<label for="password">{{ctx.Locale.Tr "password"}}</label>
<input id="password" name="password" type="password" value="{{.password}}" autocomplete="new-password" required>
<input id="password" name="password" type="password" autocomplete="new-password" required>
</div>
<div class="required field {{if and (.Err_Password) (or (not .LinkAccountMode) (and .LinkAccountMode .LinkAccountModeRegister))}}error{{end}}">
<div class="required field">
<label for="retype">{{ctx.Locale.Tr "re_type"}}</label>
<input id="retype" name="retype" type="password" autocomplete="new-password" required>
</div>
+1 -1
View File
@@ -2,7 +2,7 @@
<div role="main" aria-label="{{.Title}}" class="page-content user signin">
<div class="ui middle very relaxed page grid">
<div class="column">
<form class="ui form tw-max-w-2xl tw-m-auto" action="{{.Link}}" method="post">
<form class="ui form tw-max-w-2xl tw-m-auto form-fetch-action" action="{{.Link}}" method="post">
<h3 class="ui top attached header">
{{ctx.Locale.Tr "twofa"}}
</h3>
+1 -1
View File
@@ -2,7 +2,7 @@
<div role="main" aria-label="{{.Title}}" class="page-content user signin">
<div class="ui middle very relaxed page grid">
<div class="column">
<form class="ui form tw-max-w-2xl tw-m-auto" action="{{.Link}}" method="post">
<form class="ui form tw-max-w-2xl tw-m-auto form-fetch-action" action="{{.Link}}" method="post">
<h3 class="ui top attached header">
{{ctx.Locale.Tr "twofa_scratch"}}
</h3>
+3 -3
View File
@@ -60,7 +60,7 @@
{{ctx.Locale.Tr "settings.delete_email"}}
</button>
{{if .CanBePrimary}}
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
<form class="form-fetch-action" action="{{AppSubUrl}}/user/settings/account/email" method="post">
<input name="_method" type="hidden" value="PRIMARY">
<input name="id" type="hidden" value="{{.ID}}">
<button type="submit" class="ui primary tiny button">{{ctx.Locale.Tr "settings.primary_email"}}</button>
@@ -68,7 +68,7 @@
{{end}}
{{end}}
{{if not .IsActivated}}
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
<form class="form-fetch-action" action="{{AppSubUrl}}/user/settings/account/email" method="post">
<input name="_method" type="hidden" value="SENDACTIVATION">
<input name="id" type="hidden" value="{{.ID}}">
{{if $.ActivationsPending}}
@@ -88,7 +88,7 @@
{{if not ($.UserDisabledFeatures.Contains "manage_credentials")}}
<div class="ui bottom attached segment">
<form class="ui form" action="{{AppSubUrl}}/user/settings/account/email" method="post">
<form class="ui form form-fetch-action" action="{{AppSubUrl}}/user/settings/account/email" method="post">
<div class="required field {{if .Err_Email}}error{{end}}">
<label for="email">{{ctx.Locale.Tr "settings.add_new_email"}}</label>
<input id="email" name="email" type="email" required {{if not .CanAddEmails}}disabled{{end}}>
+2 -3
View File
@@ -58,9 +58,8 @@ test('totp sign-in and attempt limit', async ({page, request}) => {
await page.waitForURL('**/user/two_factor');
for (let attempt = 0; attempt < 5; attempt++) {
await submitPasscode(page, '0000000');
await expect(page.getByLabel('Passcode')).toHaveValue('');
}
await expect(page.getByText('Your passcode is incorrect')).toBeVisible();
await expect(page.getByText('Your passcode is incorrect').last()).toBeVisible();
await submitPasscode(page, '0000000');
await expect(page.getByText('Too many incorrect passcodes')).toBeVisible();
await expect(page.getByText('Too many incorrect passcodes').last()).toBeVisible();
});
+3 -3
View File
@@ -252,7 +252,7 @@ func TestAuditLogUserEvents(t *testing.T) {
loginUser(t, "user2").MakeRequest(t, NewRequestWithValues(t, "POST", "/user/settings/account/email", map[string]string{
"_method": "PRIMARY",
"id": strconv.FormatInt(email.ID, 10),
}), http.StatusSeeOther)
}), http.StatusOK)
assert.Equal(t, email.Email, audit_model.DecodeMetadata(findEvent(t, audit_model.UserEmailPrimaryChange, 2).Metadata)["email"])
@@ -274,7 +274,7 @@ func TestAuditLogUserEvents(t *testing.T) {
t.Run("TwoFactorFailOnSignInAndPasswordReset", func(t *testing.T) {
loginUser(t, "user24").MakeRequest(t, NewRequestWithValues(t, "POST", "/user/two_factor/scratch", map[string]string{
"token": "wrong-token",
}), http.StatusOK)
}), http.StatusBadRequest)
findEvent(t, audit_model.UserAuthenticationFailTwoFactor, 24)
code := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeResetPassword}, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 24}))
@@ -307,7 +307,7 @@ func TestAuditLogUserEvents(t *testing.T) {
"email": "user24@example.com",
"active": "on",
"reset_2fa": "on",
}), http.StatusSeeOther)
}), http.StatusOK)
}
assert.Equal(t, int64(1), findEvent(t, audit_model.UserTwoFactorDisable, 24).ActorID)
})
+4 -4
View File
@@ -96,7 +96,7 @@ func TestAdminEditUser(t *testing.T) {
}
func testSuccessfulEdit(t *testing.T, formData user_model.User) {
makeRequest(t, formData, http.StatusSeeOther)
makeRequest(t, formData, http.StatusOK)
}
func makeRequest(t *testing.T, formData user_model.User, headerCode int) {
@@ -207,7 +207,7 @@ func TestAdminBotUser(t *testing.T) {
"email": "bot-user@example.com",
"visibility": "0",
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
bot := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "bot-user"})
assert.True(t, bot.IsTypeBot())
@@ -231,7 +231,7 @@ func TestAdminBotUser(t *testing.T) {
"email": "bot-user@example.com",
"full_name": "Bot User",
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "Bot User", unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: bot.ID}).FullName)
})
@@ -314,7 +314,7 @@ func TestAdminBotUser(t *testing.T) {
"email": user.Email,
"user_type": userType,
"visibility": "0",
}), http.StatusSeeOther)
}), http.StatusOK)
}
MakeRequest(t, NewRequestWithJSON(t, "PATCH", "/api/v1/admin/users/org3", map[string]string{"type": "Organization"}).AddBasicAuth("user1"), http.StatusOK)
+4 -4
View File
@@ -176,10 +176,10 @@ func (te *ldapTestEnv) setupAuthSource(t *testing.T, params map[string]string) {
existing := &auth_model.Source{Name: params["name"]}
if ok, _ := db.GetEngine(t.Context()).Get(existing); ok {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/-/admin/auths/%d", existing.ID), params)
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
} else {
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", params)
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
}
}
@@ -229,7 +229,7 @@ func testLDAPAuthChange(t *testing.T) {
assert.Equal(t, "uid=gitea,ou=service,dc=planetexpress,dc=com", bindDN)
req = NewRequestWithValues(t, "POST", hrefAuthSource, te.buildAuthSourcePayload(map[string]string{"group_team_map_removal": ""}))
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
req = NewRequest(t, "GET", hrefAuthSource)
resp = session.MakeRequest(t, req, http.StatusOK)
@@ -494,7 +494,7 @@ func testLDAPPreventInvalidGroupTeamMap(t *testing.T) {
session := loginUser(t, "user1")
payload := te.buildAuthSourcePayload(map[string]string{"group_team_map": `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, "group_team_map_removal": ""})
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusOK) // StatusOK = failed, StatusSeeOther = ok
session.MakeRequest(t, req, http.StatusBadRequest)
}
func testLDAPEmailSignin(t *testing.T) {
+1 -1
View File
@@ -413,7 +413,7 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
"action": "archive",
},
)
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
// Check editing archived repository is disabled
req = NewRequest(t, "GET", "/"+path.Join(owner, repo, "_edit", branch, filePath)).SetHeader("Accept", "text/html")
+3 -3
View File
@@ -202,7 +202,7 @@ func testCreatePushMirror(t *testing.T, session *TestSession, owner, repo, addre
"push_mirror_password": password,
"push_mirror_interval": interval,
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
flashMsg := session.GetCookieFlashMessage()
assert.NotEmpty(t, flashMsg.SuccessMsg)
@@ -215,7 +215,7 @@ func doRemovePushMirror(t *testing.T, session *TestSession, owner, repo string,
})
resp := session.MakeRequest(t, req, NoExpectedStatus)
flashMsg := session.GetCookieFlashMessage()
return resp.Code == http.StatusSeeOther && assert.NotEmpty(t, flashMsg.SuccessMsg)
return resp.Code == http.StatusOK && assert.NotEmpty(t, flashMsg.SuccessMsg)
}
func doUpdatePushMirror(t *testing.T, session *TestSession, owner, repo string, pushMirrorID int64, interval string) bool {
@@ -226,5 +226,5 @@ func doUpdatePushMirror(t *testing.T, session *TestSession, owner, repo string,
"push_mirror_defer_sync": "true",
})
resp := session.MakeRequest(t, req, NoExpectedStatus)
return resp.Code == http.StatusSeeOther
return resp.Code == http.StatusOK
}
+5 -5
View File
@@ -34,11 +34,11 @@ func TestOrgProjectAccess(t *testing.T) {
// change the org's visibility to private
session := loginUser(t, "user2")
req = NewRequestWithValues(t, "POST", "/org/org3/settings", map[string]string{
"name": "org3",
"visibility": "2",
req = NewRequestWithValues(t, "POST", "/org/org3/settings/visibility", map[string]string{
"visibility": "private",
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
MakeRequest(t, NewRequest(t, "GET", "/org3/-/projects"), http.StatusNotFound)
// user4 can still access the org's project because its team(team1) has the permission
session = loginUser(t, "user4")
@@ -53,7 +53,7 @@ func TestOrgProjectAccess(t *testing.T) {
"permission": "read",
"unit_" + strconv.Itoa(unit_model.TypeProjects.Value()): "0",
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
// user4 can no longer access the org's project
session = loginUser(t, "user4")
+3 -3
View File
@@ -296,7 +296,7 @@ func testTeamsPage(t *testing.T) {
"unit_9": "1",
"unit_10": "1",
})
ownerSession.MakeRequest(t, req, http.StatusSeeOther)
ownerSession.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, []string{"Owners", "review_team", "test_team"}, listTeams(t, memberSession, ""))
// Non-member is denied
@@ -326,7 +326,7 @@ func testOrgSettings(t *testing.T) {
"full_name": "org3 new full name",
"email": "org3-new-email@example.com",
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
assert.Equal(t, "org3 new full name", org.FullName)
assert.Equal(t, "org3-new-email@example.com", org.Email)
@@ -334,7 +334,7 @@ func testOrgSettings(t *testing.T) {
req = NewRequestWithValues(t, "POST", "/org/org3/settings", map[string]string{
"email": "", // empty email means "clear email"
})
session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusOK)
org = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
assert.Equal(t, "org3 new full name", org.FullName)
assert.Empty(t, org.Email)
+2 -1
View File
@@ -49,7 +49,8 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateID, templateOw
"repo_template": templateID,
"git_content": "true",
})
session.MakeRequest(t, req, http.StatusSeeOther)
resp = session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "/"+generateOwnerName+"/"+generateRepoName, DecodeJSON(t, resp, map[string]string{})["redirect"])
// Step4: check the existence of the generated repo
req = NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)
+2 -2
View File
@@ -189,8 +189,8 @@ func testUserSettingsUpdateEmail(t *testing.T) {
"_method": "PRIMARY",
"id": testCase.id,
})
resp := session.MakeRequest(t, req, http.StatusSeeOther)
assert.Equal(t, "/user/settings/account", resp.Header().Get("Location"))
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "/user/settings/account", DecodeJSON(t, resp, map[string]string{})["redirect"])
flashMsg := session.GetCookieFlashMessage()
assert.Equal(t, "The selected email address could not be found.", flashMsg.ErrorMsg)
})