Browse Source

refactoring: modules/auth/*_form.go -> modules/form

pull/4240/head
Unknwon 8 years ago
parent
commit
4f9c5981a9
No known key found for this signature in database
GPG Key ID: 25B575AE3213B2B3
  1. 112
      cmd/web.go
  2. 130
      modules/auth/auth.go
  3. 55
      modules/auth/org.go
  4. 7
      modules/context/context.go
  5. 13
      modules/form/admin.go
  6. 6
      modules/form/auth.go
  7. 135
      modules/form/form.go
  8. 41
      modules/form/org.go
  9. 112
      modules/form/repo.go
  10. 44
      modules/form/user.go
  11. 94
      routers/admin/auths.go
  12. 58
      routers/admin/users.go
  13. 4
      routers/api/v1/api.go
  14. 20
      routers/api/v1/repo/repo.go
  15. 184
      routers/install.go
  16. 14
      routers/org/org.go
  17. 38
      routers/org/setting.go
  18. 24
      routers/org/teams.go
  19. 154
      routers/repo/editor.go
  20. 86
      routers/repo/issue.go
  21. 28
      routers/repo/pull.go
  22. 40
      routers/repo/release.go
  23. 52
      routers/repo/repo.go
  24. 78
      routers/repo/setting.go
  25. 100
      routers/repo/webhook.go
  26. 16
      routers/repo/wiki.go
  27. 32
      routers/user/auth.go
  28. 62
      routers/user/setting.go

112
cmd/web.go

@ -34,9 +34,9 @@ import (
"github.com/gogits/go-gogs-client" "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/bindata" "github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template" "github.com/gogits/gogs/modules/template"
@ -219,35 +219,35 @@ func runWeb(ctx *cli.Context) error {
m.Get("/organizations", routers.ExploreOrganizations) m.Get("/organizations", routers.ExploreOrganizations)
}, ignSignIn) }, ignSignIn)
m.Combo("/install", routers.InstallInit).Get(routers.Install). m.Combo("/install", routers.InstallInit).Get(routers.Install).
Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost) Post(bindIgnErr(form.Install{}), routers.InstallPost)
m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues) m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
// ***** START: User ***** // ***** START: User *****
m.Group("/user", func() { m.Group("/user", func() {
m.Get("/login", user.SignIn) m.Get("/login", user.SignIn)
m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost) m.Post("/login", bindIgnErr(form.SignIn{}), user.SignInPost)
m.Get("/sign_up", user.SignUp) m.Get("/sign_up", user.SignUp)
m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost) m.Post("/sign_up", bindIgnErr(form.Register{}), user.SignUpPost)
m.Get("/reset_password", user.ResetPasswd) m.Get("/reset_password", user.ResetPasswd)
m.Post("/reset_password", user.ResetPasswdPost) m.Post("/reset_password", user.ResetPasswdPost)
}, reqSignOut) }, reqSignOut)
m.Group("/user/settings", func() { m.Group("/user/settings", func() {
m.Get("", user.Settings) m.Get("", user.Settings)
m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost) m.Post("", bindIgnErr(form.UpdateProfile{}), user.SettingsPost)
m.Combo("/avatar").Get(user.SettingsAvatar). m.Combo("/avatar").Get(user.SettingsAvatar).
Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost) Post(binding.MultipartForm(form.Avatar{}), user.SettingsAvatarPost)
m.Post("/avatar/delete", user.SettingsDeleteAvatar) m.Post("/avatar/delete", user.SettingsDeleteAvatar)
m.Combo("/email").Get(user.SettingsEmails). m.Combo("/email").Get(user.SettingsEmails).
Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost) Post(bindIgnErr(form.AddEmail{}), user.SettingsEmailPost)
m.Post("/email/delete", user.DeleteEmail) m.Post("/email/delete", user.DeleteEmail)
m.Get("/password", user.SettingsPassword) m.Get("/password", user.SettingsPassword)
m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost) m.Post("/password", bindIgnErr(form.ChangePassword{}), user.SettingsPasswordPost)
m.Combo("/ssh").Get(user.SettingsSSHKeys). m.Combo("/ssh").Get(user.SettingsSSHKeys).
Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost) Post(bindIgnErr(form.AddSSHKey{}), user.SettingsSSHKeysPost)
m.Post("/ssh/delete", user.DeleteSSHKey) m.Post("/ssh/delete", user.DeleteSSHKey)
m.Combo("/applications").Get(user.SettingsApplications). m.Combo("/applications").Get(user.SettingsApplications).
Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost) Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost)
m.Post("/applications/delete", user.SettingsDeleteApplication) m.Post("/applications/delete", user.SettingsDeleteApplication)
m.Group("/organizations", func() { m.Group("/organizations", func() {
@ -261,7 +261,7 @@ func runWeb(ctx *cli.Context) error {
}) })
m.Group("/user", func() { m.Group("/user", func() {
// r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds) // r.Get("/feeds", binding.Bind(form.Feeds{}), user.Feeds)
m.Any("/activate", user.Activate) m.Any("/activate", user.Activate)
m.Any("/activate_email", user.ActivateEmail) m.Any("/activate_email", user.ActivateEmail)
m.Get("/email2user", user.Email2User) m.Get("/email2user", user.Email2User)
@ -282,8 +282,8 @@ func runWeb(ctx *cli.Context) error {
m.Group("/users", func() { m.Group("/users", func() {
m.Get("", admin.Users) m.Get("", admin.Users)
m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost) m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(form.AdminCrateUser{}), admin.NewUserPost)
m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost) m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(form.AdminEditUser{}), admin.EditUserPost)
m.Post("/:userid/delete", admin.DeleteUser) m.Post("/:userid/delete", admin.DeleteUser)
}) })
@ -298,9 +298,9 @@ func runWeb(ctx *cli.Context) error {
m.Group("/auths", func() { m.Group("/auths", func() {
m.Get("", admin.Authentications) m.Get("", admin.Authentications)
m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost) m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(form.Authentication{}), admin.NewAuthSourcePost)
m.Combo("/:authid").Get(admin.EditAuthSource). m.Combo("/:authid").Get(admin.EditAuthSource).
Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost) Post(bindIgnErr(form.Authentication{}), admin.EditAuthSourcePost)
m.Post("/:authid/delete", admin.DeleteAuthSource) m.Post("/:authid/delete", admin.DeleteAuthSource)
}) })
@ -365,7 +365,7 @@ func runWeb(ctx *cli.Context) error {
m.Group("/org", func() { m.Group("/org", func() {
m.Group("", func() { m.Group("", func() {
m.Get("/create", org.Create) m.Get("/create", org.Create)
m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost) m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
}, func(ctx *context.Context) { }, func(ctx *context.Context) {
if !ctx.User.CanCreateOrganization() { if !ctx.User.CanCreateOrganization() {
ctx.NotFound() ctx.NotFound()
@ -390,28 +390,28 @@ func runWeb(ctx *cli.Context) error {
m.Group("/:org", func() { m.Group("/:org", func() {
m.Get("/teams/new", org.NewTeam) m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost) m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
m.Get("/teams/:team/edit", org.EditTeam) m.Get("/teams/:team/edit", org.EditTeam)
m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost) m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
m.Post("/teams/:team/delete", org.DeleteTeam) m.Post("/teams/:team/delete", org.DeleteTeam)
m.Group("/settings", func() { m.Group("/settings", func() {
m.Combo("").Get(org.Settings). m.Combo("").Get(org.Settings).
Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost) Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar) m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
m.Post("/avatar/delete", org.SettingsDeleteAvatar) m.Post("/avatar/delete", org.SettingsDeleteAvatar)
m.Group("/hooks", func() { m.Group("/hooks", func() {
m.Get("", org.Webhooks) m.Get("", org.Webhooks)
m.Post("/delete", org.DeleteWebhook) m.Post("/delete", org.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew) m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost) m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost) m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost) m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
m.Get("/:id", repo.WebHooksEdit) m.Get("/:id", repo.WebHooksEdit)
m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost) m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost) m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost) m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
}) })
m.Route("/delete", "GET,POST", org.SettingsDelete) m.Route("/delete", "GET,POST", org.SettingsDelete)
@ -425,17 +425,17 @@ func runWeb(ctx *cli.Context) error {
// ***** START: Repository ***** // ***** START: Repository *****
m.Group("/repo", func() { m.Group("/repo", func() {
m.Get("/create", repo.Create) m.Get("/create", repo.Create)
m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost) m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
m.Get("/migrate", repo.Migrate) m.Get("/migrate", repo.Migrate)
m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost) m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
m.Combo("/fork/:repoid").Get(repo.Fork). m.Combo("/fork/:repoid").Get(repo.Fork).
Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost) Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
}, reqSignIn) }, reqSignIn)
m.Group("/:username/:reponame", func() { m.Group("/:username/:reponame", func() {
m.Group("/settings", func() { m.Group("/settings", func() {
m.Combo("").Get(repo.Settings). m.Combo("").Get(repo.Settings).
Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost) Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
m.Group("/collaboration", func() { m.Group("/collaboration", func() {
m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost) m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
m.Post("/access_mode", repo.ChangeCollaborationAccessMode) m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
@ -445,7 +445,7 @@ func runWeb(ctx *cli.Context) error {
m.Get("", repo.SettingsBranches) m.Get("", repo.SettingsBranches)
m.Post("/default_branch", repo.UpdateDefaultBranch) m.Post("/default_branch", repo.UpdateDefaultBranch)
m.Combo("/*").Get(repo.SettingsProtectedBranch). m.Combo("/*").Get(repo.SettingsProtectedBranch).
Post(bindIgnErr(auth.ProtectBranchForm{}), repo.SettingsProtectedBranchPost) Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
}, func(ctx *context.Context) { }, func(ctx *context.Context) {
if ctx.Repo.Repository.IsMirror { if ctx.Repo.Repository.IsMirror {
ctx.NotFound() ctx.NotFound()
@ -457,14 +457,14 @@ func runWeb(ctx *cli.Context) error {
m.Get("", repo.Webhooks) m.Get("", repo.Webhooks)
m.Post("/delete", repo.DeleteWebhook) m.Post("/delete", repo.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew) m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost) m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost) m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost) m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
m.Get("/:id", repo.WebHooksEdit) m.Get("/:id", repo.WebHooksEdit)
m.Post("/:id/test", repo.TestWebhook) m.Post("/:id/test", repo.TestWebhook)
m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost) m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost) m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost) m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
m.Group("/git", func() { m.Group("/git", func() {
m.Get("", repo.SettingsGitHooks) m.Get("", repo.SettingsGitHooks)
@ -475,7 +475,7 @@ func runWeb(ctx *cli.Context) error {
m.Group("/keys", func() { m.Group("/keys", func() {
m.Combo("").Get(repo.SettingsDeployKeys). m.Combo("").Get(repo.SettingsDeployKeys).
Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.SettingsDeployKeysPost) Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
m.Post("/delete", repo.DeleteDeployKey) m.Post("/delete", repo.DeleteDeployKey)
}) })
@ -490,7 +490,7 @@ func runWeb(ctx *cli.Context) error {
// So they can apply their own enable/disable logic on routers. // So they can apply their own enable/disable logic on routers.
m.Group("/issues", func() { m.Group("/issues", func() {
m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue). m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost) Post(bindIgnErr(form.CreateIssue{}), repo.NewIssuePost)
m.Group("/:index", func() { m.Group("/:index", func() {
m.Post("/label", repo.UpdateIssueLabel) m.Post("/label", repo.UpdateIssueLabel)
@ -501,7 +501,7 @@ func runWeb(ctx *cli.Context) error {
m.Group("/:index", func() { m.Group("/:index", func() {
m.Post("/title", repo.UpdateIssueTitle) m.Post("/title", repo.UpdateIssueTitle)
m.Post("/content", repo.UpdateIssueContent) m.Post("/content", repo.UpdateIssueContent)
m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment) m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
}) })
}) })
m.Group("/comments/:id", func() { m.Group("/comments/:id", func() {
@ -509,26 +509,26 @@ func runWeb(ctx *cli.Context) error {
m.Post("/delete", repo.DeleteComment) m.Post("/delete", repo.DeleteComment)
}) })
m.Group("/labels", func() { m.Group("/labels", func() {
m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel) m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel) m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
m.Post("/delete", repo.DeleteLabel) m.Post("/delete", repo.DeleteLabel)
m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels) m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
}, reqRepoWriter, context.RepoRef()) }, reqRepoWriter, context.RepoRef())
m.Group("/milestones", func() { m.Group("/milestones", func() {
m.Combo("/new").Get(repo.NewMilestone). m.Combo("/new").Get(repo.NewMilestone).
Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost) Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
m.Get("/:id/edit", repo.EditMilestone) m.Get("/:id/edit", repo.EditMilestone)
m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost) m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
m.Get("/:id/:action", repo.ChangeMilestonStatus) m.Get("/:id/:action", repo.ChangeMilestonStatus)
m.Post("/delete", repo.DeleteMilestone) m.Post("/delete", repo.DeleteMilestone)
}, reqRepoWriter, context.RepoRef()) }, reqRepoWriter, context.RepoRef())
m.Group("/releases", func() { m.Group("/releases", func() {
m.Get("/new", repo.NewRelease) m.Get("/new", repo.NewRelease)
m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost) m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
m.Post("/delete", repo.DeleteRelease) m.Post("/delete", repo.DeleteRelease)
m.Get("/edit/*", repo.EditRelease) m.Get("/edit/*", repo.EditRelease)
m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost) m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
}, reqRepoWriter, context.RepoRef()) }, reqRepoWriter, context.RepoRef())
// FIXME: Should use ctx.Repo.PullRequest to unify template, currently we have inconsistent URL // FIXME: Should use ctx.Repo.PullRequest to unify template, currently we have inconsistent URL
@ -536,22 +536,22 @@ func runWeb(ctx *cli.Context) error {
// e.g. /org1/test-repo/compare/master...org1:develop // e.g. /org1/test-repo/compare/master...org1:develop
// which should be /org1/test-repo/compare/master...develop // which should be /org1/test-repo/compare/master...develop
m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest). m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost) Post(bindIgnErr(form.CreateIssue{}), repo.CompareAndPullRequestPost)
m.Group("", func() { m.Group("", func() {
m.Combo("/_edit/*").Get(repo.EditFile). m.Combo("/_edit/*").Get(repo.EditFile).
Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost) Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
m.Combo("/_new/*").Get(repo.NewFile). m.Combo("/_new/*").Get(repo.NewFile).
Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost) Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost) m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
m.Combo("/_delete/*").Get(repo.DeleteFile). m.Combo("/_delete/*").Get(repo.DeleteFile).
Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost) Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
m.Group("", func() { m.Group("", func() {
m.Combo("/_upload/*").Get(repo.UploadFile). m.Combo("/_upload/*").Get(repo.UploadFile).
Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost) Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
m.Post("/upload-file", repo.UploadFileToServer) m.Post("/upload-file", repo.UploadFileToServer)
m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer) m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
}, func(ctx *context.Context) { }, func(ctx *context.Context) {
if !setting.Repository.Upload.Enabled { if !setting.Repository.Upload.Enabled {
ctx.NotFound() ctx.NotFound()
@ -584,9 +584,9 @@ func runWeb(ctx *cli.Context) error {
m.Group("", func() { m.Group("", func() {
m.Combo("/_new").Get(repo.NewWiki). m.Combo("/_new").Get(repo.NewWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost) Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
m.Combo("/:page/_edit").Get(repo.EditWiki). m.Combo("/:page/_edit").Get(repo.EditWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost) Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
m.Post("/:page/delete", repo.DeleteWikiPagePost) m.Post("/:page/delete", repo.DeleteWikiPagePost)
}, reqSignIn, reqRepoWriter) }, reqSignIn, reqRepoWriter)
}, repo.MustEnableWiki, context.RepoRef()) }, repo.MustEnableWiki, context.RepoRef())

130
modules/auth/auth.go

@ -5,12 +5,9 @@
package auth package auth
import ( import (
"reflect"
"strings" "strings"
"time" "time"
"github.com/Unknwon/com"
"github.com/go-macaron/binding"
"github.com/go-macaron/session" "github.com/go-macaron/session"
gouuid "github.com/satori/go.uuid" gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
@ -147,130 +144,3 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool)
} }
return u, false return u, false
} }
type Form interface {
binding.Validator
}
func init() {
binding.SetNameMapper(com.ToSnakeCase)
}
// AssignForm assign form values back to the template data.
func AssignForm(form interface{}, data map[string]interface{}) {
typ := reflect.TypeOf(form)
val := reflect.ValueOf(form)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
} else if len(fieldName) == 0 {
fieldName = com.ToSnakeCase(field.Name)
}
data[fieldName] = val.Field(i).Interface()
}
}
func getRuleBody(field reflect.StructField, prefix string) string {
for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
if strings.HasPrefix(rule, prefix) {
return rule[len(prefix) : len(rule)-1]
}
}
return ""
}
func GetSize(field reflect.StructField) string {
return getRuleBody(field, "Size(")
}
func GetMinSize(field reflect.StructField) string {
return getRuleBody(field, "MinSize(")
}
func GetMaxSize(field reflect.StructField) string {
return getRuleBody(field, "MaxSize(")
}
func GetInclude(field reflect.StructField) string {
return getRuleBody(field, "Include(")
}
// FIXME: struct contains a struct
func validateStruct(obj interface{}) binding.Errors {
return nil
}
func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
if errs.Len() == 0 {
return errs
}
data["HasError"] = true
AssignForm(f, data)
typ := reflect.TypeOf(f)
val := reflect.ValueOf(f)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
}
if errs[0].FieldNames[0] == field.Name {
data["Err_"+field.Name] = true
trName := field.Tag.Get("locale")
if len(trName) == 0 {
trName = l.Tr("form." + field.Name)
} else {
trName = l.Tr(trName)
}
switch errs[0].Classification {
case binding.ERR_REQUIRED:
data["ErrorMsg"] = trName + l.Tr("form.require_error")
case binding.ERR_ALPHA_DASH:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
case binding.ERR_ALPHA_DASH_DOT:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
case binding.ERR_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field))
case binding.ERR_MIN_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
case binding.ERR_MAX_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
case binding.ERR_EMAIL:
data["ErrorMsg"] = trName + l.Tr("form.email_error")
case binding.ERR_URL:
data["ErrorMsg"] = trName + l.Tr("form.url_error")
case binding.ERR_INCLUDE:
data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field))
default:
data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
}
return errs
}
}
return errs
}

55
modules/auth/org.go

@ -1,55 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package auth
import (
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
// ________ .__ __ .__
// \_____ \_______ _________ ____ |__|____________ _/ |_|__| ____ ____
// / | \_ __ \/ ___\__ \ / \| \___ /\__ \\ __\ |/ _ \ / \
// / | \ | \/ /_/ > __ \| | \ |/ / / __ \| | | ( <_> ) | \
// \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| /
// \/ /_____/ \/ \/ \/ \/ \/
type CreateOrgForm struct {
OrgName string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
}
func (f *CreateOrgForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type UpdateOrgSettingForm struct {
Name string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
FullName string `binding:"MaxSize(100)"`
Description string `binding:"MaxSize(255)"`
Website string `binding:"Url;MaxSize(100)"`
Location string `binding:"MaxSize(50)"`
MaxRepoCreation int
}
func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ___________
// \__ ___/___ _____ _____
// | |_/ __ \\__ \ / \
// | |\ ___/ / __ \| Y Y \
// |____| \___ >____ /__|_| /
// \/ \/ \/
type CreateTeamForm struct {
TeamName string `binding:"Required;AlphaDashDot;MaxSize(30)"`
Description string `binding:"MaxSize(255)"`
Permission string
}
func (f *CreateTeamForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

7
modules/context/context.go

@ -22,6 +22,7 @@ import (
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -78,9 +79,9 @@ func (ctx *Context) HTML(status int, name base.TplName) {
} }
// RenderWithErr used for page has form validation but need to prompt error to users. // RenderWithErr used for page has form validation but need to prompt error to users.
func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) { func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, f interface{}) {
if form != nil { if f != nil {
auth.AssignForm(form, ctx.Data) form.Assign(f, ctx.Data)
} }
ctx.Flash.ErrorMsg = msg ctx.Flash.ErrorMsg = msg
ctx.Data["Flash"] = ctx.Flash ctx.Data["Flash"] = ctx.Flash

13
modules/auth/admin.go → modules/form/admin.go

@ -2,15 +2,14 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package auth package form
import ( import (
"gopkg.in/macaron.v1"
"github.com/go-macaron/binding" "github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
) )
type AdminCrateUserForm struct { type AdminCrateUser struct {
LoginType string `binding:"Required"` LoginType string `binding:"Required"`
LoginName string LoginName string
UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"`
@ -19,11 +18,11 @@ type AdminCrateUserForm struct {
SendNotify bool SendNotify bool
} }
func (f *AdminCrateUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *AdminCrateUser) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type AdminEditUserForm struct { type AdminEditUser struct {
LoginType string `binding:"Required"` LoginType string `binding:"Required"`
LoginName string LoginName string
FullName string `binding:"MaxSize(100)"` FullName string `binding:"MaxSize(100)"`
@ -39,6 +38,6 @@ type AdminEditUserForm struct {
ProhibitLogin bool ProhibitLogin bool
} }
func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *AdminEditUser) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }

6
modules/auth/auth_form.go → modules/form/auth.go

@ -2,14 +2,14 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package auth package form
import ( import (
"github.com/go-macaron/binding" "github.com/go-macaron/binding"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
type AuthenticationForm struct { type Authentication struct {
ID int64 ID int64
Type int `binding:"Range(2,5)"` Type int `binding:"Range(2,5)"`
Name string `binding:"Required;MaxSize(30)"` Name string `binding:"Required;MaxSize(30)"`
@ -37,6 +37,6 @@ type AuthenticationForm struct {
PAMServiceName string PAMServiceName string
} }
func (f *AuthenticationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *Authentication) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }

135
modules/form/form.go

@ -0,0 +1,135 @@
// Copyright 2017 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"reflect"
"strings"
"github.com/Unknwon/com"
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
func init() {
binding.SetNameMapper(com.ToSnakeCase)
}
type Form interface {
binding.Validator
}
// Assign assign form values back to the template data.
func Assign(form interface{}, data map[string]interface{}) {
typ := reflect.TypeOf(form)
val := reflect.ValueOf(form)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
} else if len(fieldName) == 0 {
fieldName = com.ToSnakeCase(field.Name)
}
data[fieldName] = val.Field(i).Interface()
}
}
func getRuleBody(field reflect.StructField, prefix string) string {
for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
if strings.HasPrefix(rule, prefix) {
return rule[len(prefix) : len(rule)-1]
}
}
return ""
}
func getSize(field reflect.StructField) string {
return getRuleBody(field, "Size(")
}
func getMinSize(field reflect.StructField) string {
return getRuleBody(field, "MinSize(")
}
func getMaxSize(field reflect.StructField) string {
return getRuleBody(field, "MaxSize(")
}
func getInclude(field reflect.StructField) string {
return getRuleBody(field, "Include(")
}
func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
if errs.Len() == 0 {
return errs
}
data["HasError"] = true
Assign(f, data)
typ := reflect.TypeOf(f)
val := reflect.ValueOf(f)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Tag.Get("form")
// Allow ignored fields in the struct
if fieldName == "-" {
continue
}
if errs[0].FieldNames[0] == field.Name {
data["Err_"+field.Name] = true
trName := field.Tag.Get("locale")
if len(trName) == 0 {
trName = l.Tr("form." + field.Name)
} else {
trName = l.Tr(trName)
}
switch errs[0].Classification {
case binding.ERR_REQUIRED:
data["ErrorMsg"] = trName + l.Tr("form.require_error")
case binding.ERR_ALPHA_DASH:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
case binding.ERR_ALPHA_DASH_DOT:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
case binding.ERR_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.size_error", getSize(field))
case binding.ERR_MIN_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.min_size_error", getMinSize(field))
case binding.ERR_MAX_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.max_size_error", getMaxSize(field))
case binding.ERR_EMAIL:
data["ErrorMsg"] = trName + l.Tr("form.email_error")
case binding.ERR_URL:
data["ErrorMsg"] = trName + l.Tr("form.url_error")
case binding.ERR_INCLUDE:
data["ErrorMsg"] = trName + l.Tr("form.include_error", getInclude(field))
default:
data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
}
return errs
}
}
return errs
}

41
modules/form/org.go

@ -0,0 +1,41 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package form
import (
"github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
)
type CreateOrg struct {
OrgName string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
}
func (f *CreateOrg) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type UpdateOrgSetting struct {
Name string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"`
FullName string `binding:"MaxSize(100)"`
Description string `binding:"MaxSize(255)"`
Website string `binding:"Url;MaxSize(100)"`
Location string `binding:"MaxSize(50)"`
MaxRepoCreation int
}
func (f *UpdateOrgSetting) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type CreateTeam struct {
TeamName string `binding:"Required;AlphaDashDot;MaxSize(30)"`
Description string `binding:"MaxSize(255)"`
Permission string
}
func (f *CreateTeam) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

112
modules/auth/repo_form.go → modules/form/repo.go

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package auth package form
import ( import (
"net/url" "net/url"
@ -22,7 +22,7 @@ import (
// |____|_ /_______ / |____| \_______ /_______ /|___| |____| \_______ /____|_ // ______| // |____|_ /_______ / |____| \_______ /_______ /|___| |____| \_______ /____|_ // ______|
// \/ \/ \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/ \/ \/
type CreateRepoForm struct { type CreateRepo struct {
Uid int64 `binding:"Required"` Uid int64 `binding:"Required"`
RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"`
Private bool Private bool
@ -33,11 +33,11 @@ type CreateRepoForm struct {
Readme string Readme string
} }
func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *CreateRepo) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type MigrateRepoForm struct { type MigrateRepo struct {
CloneAddr string `json:"clone_addr" binding:"Required"` CloneAddr string `json:"clone_addr" binding:"Required"`
AuthUsername string `json:"auth_username"` AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"` AuthPassword string `json:"auth_password"`
@ -48,7 +48,7 @@ type MigrateRepoForm struct {
Description string `json:"description" binding:"MaxSize(255)"` Description string `json:"description" binding:"MaxSize(255)"`
} }
func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *MigrateRepo) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -56,7 +56,7 @@ func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) bi
// and returns composed URL with needed username and password. // and returns composed URL with needed username and password.
// It also checks if given user has permission when remote address // It also checks if given user has permission when remote address
// is actually a local path. // is actually a local path.
func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) { func (f MigrateRepo) ParseRemoteAddr(user *models.User) (string, error) {
remoteAddr := strings.TrimSpace(f.CloneAddr) remoteAddr := strings.TrimSpace(f.CloneAddr)
// Remote address can be HTTP/HTTPS/Git URL or local path. // Remote address can be HTTP/HTTPS/Git URL or local path.
@ -80,7 +80,7 @@ func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) {
return remoteAddr, nil return remoteAddr, nil
} }
type RepoSettingForm struct { type RepoSetting struct {
RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"`
Description string `binding:"MaxSize(255)"` Description string `binding:"MaxSize(255)"`
Website string `binding:"Url;MaxSize(100)"` Website string `binding:"Url;MaxSize(100)"`
@ -102,7 +102,7 @@ type RepoSettingForm struct {
EnablePulls bool EnablePulls bool
} }
func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *RepoSetting) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -113,7 +113,7 @@ func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) bi
// |______ / |__| (____ /___| /\___ >___| / // |______ / |__| (____ /___| /\___ >___| /
// \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/
type ProtectBranchForm struct { type ProtectBranch struct {
Protected bool Protected bool
RequirePullRequest bool RequirePullRequest bool
EnableWhitelist bool EnableWhitelist bool
@ -121,7 +121,7 @@ type ProtectBranchForm struct {
WhitelistTeams string WhitelistTeams string
} }
func (f *ProtectBranchForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *ProtectBranch) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -132,7 +132,7 @@ func (f *ProtectBranchForm) Validate(ctx *macaron.Context, errs binding.Errors)
// \__/\ / \___ >___ /___| /___| /\____/|__|_ \ // \__/\ / \___ >___ /___| /___| /\____/|__|_ \
// \/ \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/ \/
type WebhookForm struct { type Webhook struct {
Events string Events string
Create bool Create bool
Push bool Push bool
@ -140,51 +140,51 @@ type WebhookForm struct {
Active bool Active bool
} }
func (f WebhookForm) PushOnly() bool { func (f Webhook) PushOnly() bool {
return f.Events == "push_only" return f.Events == "push_only"
} }
func (f WebhookForm) SendEverything() bool { func (f Webhook) SendEverything() bool {
return f.Events == "send_everything" return f.Events == "send_everything"
} }
func (f WebhookForm) ChooseEvents() bool { func (f Webhook) ChooseEvents() bool {
return f.Events == "choose_events" return f.Events == "choose_events"
} }
type NewWebhookForm struct { type NewWebhook struct {
PayloadURL string `binding:"Required;Url"` PayloadURL string `binding:"Required;Url"`
ContentType int `binding:"Required"` ContentType int `binding:"Required"`
Secret string Secret string
WebhookForm Webhook
} }
func (f *NewWebhookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewWebhook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type NewSlackHookForm struct { type NewSlackHook struct {
PayloadURL string `binding:"Required;Url"` PayloadURL string `binding:"Required;Url"`
Channel string `binding:"Required"` Channel string `binding:"Required"`
Username string Username string
IconURL string IconURL string
Color string Color string
WebhookForm Webhook
} }
func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewSlackHook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type NewDiscordHookForm struct { type NewDiscordHook struct {
PayloadURL string `binding:"Required;Url"` PayloadURL string `binding:"Required;Url"`
Username string Username string
IconURL string IconURL string
Color string Color string
WebhookForm Webhook
} }
func (f *NewDiscordHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewDiscordHook) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -195,7 +195,7 @@ func (f *NewDiscordHookForm) Validate(ctx *macaron.Context, errs binding.Errors)
// |___/____ >____ >____/ \___ > // |___/____ >____ >____/ \___ >
// \/ \/ \/ // \/ \/ \/
type CreateIssueForm struct { type CreateIssue struct {
Title string `binding:"Required;MaxSize(255)"` Title string `binding:"Required;MaxSize(255)"`
LabelIDs string `form:"label_ids"` LabelIDs string `form:"label_ids"`
MilestoneID int64 MilestoneID int64
@ -204,17 +204,17 @@ type CreateIssueForm struct {
Files []string Files []string
} }
func (f *CreateIssueForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *CreateIssue) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type CreateCommentForm struct { type CreateComment struct {
Content string Content string
Status string `binding:"OmitEmpty;In(reopen,close)"` Status string `binding:"OmitEmpty;In(reopen,close)"`
Files []string Files []string
} }
func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *CreateComment) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -225,13 +225,13 @@ func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors)
// \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ > // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
// \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/
type CreateMilestoneForm struct { type CreateMilestone struct {
Title string `binding:"Required;MaxSize(50)"` Title string `binding:"Required;MaxSize(50)"`
Content string Content string
Deadline string Deadline string
} }
func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *CreateMilestone) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -242,21 +242,21 @@ func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors
// |_______ (____ /___ /\___ >____/ // |_______ (____ /___ /\___ >____/
// \/ \/ \/ \/ // \/ \/ \/ \/
type CreateLabelForm struct { type CreateLabel struct {
ID int64 ID int64
Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_name"` Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_name"`
Color string `binding:"Required;Size(7)" locale:"repo.issues.label_color"` Color string `binding:"Required;Size(7)" locale:"repo.issues.label_color"`
} }
func (f *CreateLabelForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *CreateLabel) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type InitializeLabelsForm struct { type InitializeLabels struct {
TemplateName string `binding:"Required"` TemplateName string `binding:"Required"`
} }
func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *InitializeLabels) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -267,7 +267,7 @@ func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Error
// |____|_ /\___ >____/\___ >____ /____ >\___ > // |____|_ /\___ >____/\___ >____ /____ >\___ >
// \/ \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/ \/
type NewReleaseForm struct { type NewRelease struct {
TagName string `binding:"Required"` TagName string `binding:"Required"`
Target string `form:"tag_target" binding:"Required"` Target string `form:"tag_target" binding:"Required"`
Title string `binding:"Required"` Title string `binding:"Required"`
@ -276,18 +276,18 @@ type NewReleaseForm struct {
Prerelease bool Prerelease bool
} }
func (f *NewReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewRelease) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type EditReleaseForm struct { type EditRelease struct {
Title string `form:"title" binding:"Required"` Title string `binding:"Required"`
Content string `form:"content"` Content string
Draft string `form:"draft"` Draft string
Prerelease bool `form:"prerelease"` Prerelease bool
} }
func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *EditRelease) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -298,7 +298,7 @@ func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) bi
// \__/\ / |__|__|_ \__| // \__/\ / |__|__|_ \__|
// \/ \/ // \/ \/
type NewWikiForm struct { type NewWiki struct {
OldTitle string OldTitle string
Title string `binding:"Required"` Title string `binding:"Required"`
Content string `binding:"Required"` Content string `binding:"Required"`
@ -306,7 +306,7 @@ type NewWikiForm struct {
} }
// FIXME: use code generation to generate this method. // FIXME: use code generation to generate this method.
func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewWiki) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -317,7 +317,7 @@ func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin
// /_______ /\____ | |__||__| // /_______ /\____ | |__||__|
// \/ \/ // \/ \/
type EditRepoFileForm struct { type EditRepoFile struct {
TreePath string `binding:"Required;MaxSize(500)"` TreePath string `binding:"Required;MaxSize(500)"`
Content string `binding:"Required"` Content string `binding:"Required"`
CommitSummary string `binding:"MaxSize(100)` CommitSummary string `binding:"MaxSize(100)`
@ -327,19 +327,19 @@ type EditRepoFileForm struct {
LastCommit string LastCommit string
} }
func (f *EditRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *EditRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
func (f *EditRepoFileForm) IsNewBrnach() bool { func (f *EditRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch" return f.CommitChoice == "commit-to-new-branch"
} }
type EditPreviewDiffForm struct { type EditPreviewDiff struct {
Content string Content string
} }
func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *EditPreviewDiff) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -351,7 +351,7 @@ func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors
// |__| \/ \/ // |__| \/ \/
// //
type UploadRepoFileForm struct { type UploadRepoFile struct {
TreePath string `binding:MaxSize(500)"` TreePath string `binding:MaxSize(500)"`
CommitSummary string `binding:"MaxSize(100)` CommitSummary string `binding:"MaxSize(100)`
CommitMessage string CommitMessage string
@ -360,19 +360,19 @@ type UploadRepoFileForm struct {
Files []string Files []string
} }
func (f *UploadRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *UploadRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
func (f *UploadRepoFileForm) IsNewBrnach() bool { func (f *UploadRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch" return f.CommitChoice == "commit-to-new-branch"
} }
type RemoveUploadFileForm struct { type RemoveUploadFile struct {
File string `binding:"Required;MaxSize(50)"` File string `binding:"Required;MaxSize(50)"`
} }
func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *RemoveUploadFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -383,17 +383,17 @@ func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Error
// /_______ /\___ >____/\___ >__| \___ > // /_______ /\___ >____/\___ >__| \___ >
// \/ \/ \/ \/ // \/ \/ \/ \/
type DeleteRepoFileForm struct { type DeleteRepoFile struct {
CommitSummary string `binding:"MaxSize(100)` CommitSummary string `binding:"MaxSize(100)`
CommitMessage string CommitMessage string
CommitChoice string `binding:"Required;MaxSize(50)"` CommitChoice string `binding:"Required;MaxSize(50)"`
NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"` NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"`
} }
func (f *DeleteRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *DeleteRepoFile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
func (f *DeleteRepoFileForm) IsNewBrnach() bool { func (f *DeleteRepoFile) IsNewBrnach() bool {
return f.CommitChoice == "commit-to-new-branch" return f.CommitChoice == "commit-to-new-branch"
} }

44
modules/auth/user_form.go → modules/form/user.go

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package auth package form
import ( import (
"mime/multipart" "mime/multipart"
@ -11,7 +11,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
type InstallForm struct { type Install struct {
DbType string `binding:"Required"` DbType string `binding:"Required"`
DbHost string DbHost string
DbUser string DbUser string
@ -50,7 +50,7 @@ type InstallForm struct {
AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"` AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"`
} }
func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *Install) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -61,24 +61,24 @@ func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin
// \____|__ /______/ |____| \___|_ / // \____|__ /______/ |____| \___|_ /
// \/ \/ // \/ \/
type RegisterForm struct { type Register struct {
UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"`
Email string `binding:"Required;Email;MaxSize(254)"` Email string `binding:"Required;Email;MaxSize(254)"`
Password string `binding:"Required;MaxSize(255)"` Password string `binding:"Required;MaxSize(255)"`
Retype string Retype string
} }
func (f *RegisterForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *Register) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type SignInForm struct { type SignIn struct {
UserName string `binding:"Required;MaxSize(254)"` UserName string `binding:"Required;MaxSize(254)"`
Password string `binding:"Required;MaxSize(255)"` Password string `binding:"Required;MaxSize(255)"`
Remember bool Remember bool
} }
func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *SignIn) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -89,7 +89,7 @@ func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding
// /_______ //_______ / |____| |____| |___\____|__ /\______ /_______ / // /_______ //_______ / |____| |____| |___\____|__ /\______ /_______ /
// \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/
type UpdateProfileForm struct { type UpdateProfile struct {
Name string `binding:"OmitEmpty;MaxSize(35)"` Name string `binding:"OmitEmpty;MaxSize(35)"`
FullName string `binding:"MaxSize(100)"` FullName string `binding:"MaxSize(100)"`
Email string `binding:"Required;Email;MaxSize(254)"` Email string `binding:"Required;Email;MaxSize(254)"`
@ -97,7 +97,7 @@ type UpdateProfileForm struct {
Location string `binding:"MaxSize(50)"` Location string `binding:"MaxSize(50)"`
} }
func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *UpdateProfile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
@ -106,48 +106,48 @@ const (
AVATAR_BYMAIL string = "bymail" AVATAR_BYMAIL string = "bymail"
) )
type AvatarForm struct { type Avatar struct {
Source string Source string
Avatar *multipart.FileHeader Avatar *multipart.FileHeader
Gravatar string `binding:"OmitEmpty;Email;MaxSize(254)"` Gravatar string `binding:"OmitEmpty;Email;MaxSize(254)"`
Federavatar bool Federavatar bool
} }
func (f *AvatarForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *Avatar) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type AddEmailForm struct { type AddEmail struct {
Email string `binding:"Required;Email;MaxSize(254)"` Email string `binding:"Required;Email;MaxSize(254)"`
} }
func (f *AddEmailForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *AddEmail) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type ChangePasswordForm struct { type ChangePassword struct {
OldPassword string `form:"old_password" binding:"Required;MinSize(1);MaxSize(255)"` OldPassword string `binding:"Required;MinSize(1);MaxSize(255)"`
Password string `form:"password" binding:"Required;MaxSize(255)"` Password string `binding:"Required;MaxSize(255)"`
Retype string `form:"retype"` Retype string
} }
func (f *ChangePasswordForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *ChangePassword) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type AddSSHKeyForm struct { type AddSSHKey struct {
Title string `binding:"Required;MaxSize(50)"` Title string `binding:"Required;MaxSize(50)"`
Content string `binding:"Required"` Content string `binding:"Required"`
} }
func (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *AddSSHKey) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }
type NewAccessTokenForm struct { type NewAccessToken struct {
Name string `binding:"Required"` Name string `binding:"Required"`
} }
func (f *NewAccessTokenForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { func (f *NewAccessToken) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale) return validate(errs, ctx.Data, f, ctx.Locale)
} }

94
routers/admin/auths.go

@ -12,10 +12,10 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/auth/ldap" "github.com/gogits/gogs/modules/auth/ldap"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -76,64 +76,64 @@ func NewAuthSource(ctx *context.Context) {
ctx.HTML(200, AUTH_NEW) ctx.HTML(200, AUTH_NEW)
} }
func parseLDAPConfig(form auth.AuthenticationForm) *models.LDAPConfig { func parseLDAPConfig(f form.Authentication) *models.LDAPConfig {
return &models.LDAPConfig{ return &models.LDAPConfig{
Source: &ldap.Source{ Source: &ldap.Source{
Name: form.Name, Name: f.Name,
Host: form.Host, Host: f.Host,
Port: form.Port, Port: f.Port,
SecurityProtocol: ldap.SecurityProtocol(form.SecurityProtocol), SecurityProtocol: ldap.SecurityProtocol(f.SecurityProtocol),
SkipVerify: form.SkipVerify, SkipVerify: f.SkipVerify,
BindDN: form.BindDN, BindDN: f.BindDN,
UserDN: form.UserDN, UserDN: f.UserDN,
BindPassword: form.BindPassword, BindPassword: f.BindPassword,
UserBase: form.UserBase, UserBase: f.UserBase,
AttributeUsername: form.AttributeUsername, AttributeUsername: f.AttributeUsername,
AttributeName: form.AttributeName, AttributeName: f.AttributeName,
AttributeSurname: form.AttributeSurname, AttributeSurname: f.AttributeSurname,
AttributeMail: form.AttributeMail, AttributeMail: f.AttributeMail,
AttributesInBind: form.AttributesInBind, AttributesInBind: f.AttributesInBind,
Filter: form.Filter, Filter: f.Filter,
AdminFilter: form.AdminFilter, AdminFilter: f.AdminFilter,
Enabled: true, Enabled: true,
}, },
} }
} }
func parseSMTPConfig(form auth.AuthenticationForm) *models.SMTPConfig { func parseSMTPConfig(f form.Authentication) *models.SMTPConfig {
return &models.SMTPConfig{ return &models.SMTPConfig{
Auth: form.SMTPAuth, Auth: f.SMTPAuth,
Host: form.SMTPHost, Host: f.SMTPHost,
Port: form.SMTPPort, Port: f.SMTPPort,
AllowedDomains: form.AllowedDomains, AllowedDomains: f.AllowedDomains,
TLS: form.TLS, TLS: f.TLS,
SkipVerify: form.SkipVerify, SkipVerify: f.SkipVerify,
} }
} }
func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { func NewAuthSourcePost(ctx *context.Context, f form.Authentication) {
ctx.Data["Title"] = ctx.Tr("admin.auths.new") ctx.Data["Title"] = ctx.Tr("admin.auths.new")
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(form.Type)] ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(f.Type)]
ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(form.SecurityProtocol)] ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(f.SecurityProtocol)]
ctx.Data["AuthSources"] = authSources ctx.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols ctx.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = models.SMTPAuths ctx.Data["SMTPAuths"] = models.SMTPAuths
hasTLS := false hasTLS := false
var config core.Conversion var config core.Conversion
switch models.LoginType(form.Type) { switch models.LoginType(f.Type) {
case models.LOGIN_LDAP, models.LOGIN_DLDAP: case models.LOGIN_LDAP, models.LOGIN_DLDAP:
config = parseLDAPConfig(form) config = parseLDAPConfig(f)
hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SECURITY_PROTOCOL_UNENCRYPTED hasTLS = ldap.SecurityProtocol(f.SecurityProtocol) > ldap.SECURITY_PROTOCOL_UNENCRYPTED
case models.LOGIN_SMTP: case models.LOGIN_SMTP:
config = parseSMTPConfig(form) config = parseSMTPConfig(f)
hasTLS = true hasTLS = true
case models.LOGIN_PAM: case models.LOGIN_PAM:
config = &models.PAMConfig{ config = &models.PAMConfig{
ServiceName: form.PAMServiceName, ServiceName: f.PAMServiceName,
} }
default: default:
ctx.Error(400) ctx.Error(400)
@ -147,23 +147,23 @@ func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
} }
if err := models.CreateLoginSource(&models.LoginSource{ if err := models.CreateLoginSource(&models.LoginSource{
Type: models.LoginType(form.Type), Type: models.LoginType(f.Type),
Name: form.Name, Name: f.Name,
IsActived: form.IsActive, IsActived: f.IsActive,
Cfg: config, Cfg: config,
}); err != nil { }); err != nil {
if models.IsErrLoginSourceAlreadyExist(err) { if models.IsErrLoginSourceAlreadyExist(err) {
ctx.Data["Err_Name"] = true ctx.Data["Err_Name"] = true
ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, form) ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, f)
} else { } else {
ctx.Handle(500, "CreateSource", err) ctx.Handle(500, "CreateSource", err)
} }
return return
} }
log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.Name) log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, f.Name)
ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name)) ctx.Flash.Success(ctx.Tr("admin.auths.new_success", f.Name))
ctx.Redirect(setting.AppSubUrl + "/admin/auths") ctx.Redirect(setting.AppSubUrl + "/admin/auths")
} }
@ -186,7 +186,7 @@ func EditAuthSource(ctx *context.Context) {
ctx.HTML(200, AUTH_EDIT) ctx.HTML(200, AUTH_EDIT)
} }
func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { func EditAuthSourcePost(ctx *context.Context, f form.Authentication) {
ctx.Data["Title"] = ctx.Tr("admin.auths.edit") ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["PageIsAdminAuthentications"] = true
@ -207,22 +207,22 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
} }
var config core.Conversion var config core.Conversion
switch models.LoginType(form.Type) { switch models.LoginType(f.Type) {
case models.LOGIN_LDAP, models.LOGIN_DLDAP: case models.LOGIN_LDAP, models.LOGIN_DLDAP:
config = parseLDAPConfig(form) config = parseLDAPConfig(f)
case models.LOGIN_SMTP: case models.LOGIN_SMTP:
config = parseSMTPConfig(form) config = parseSMTPConfig(f)
case models.LOGIN_PAM: case models.LOGIN_PAM:
config = &models.PAMConfig{ config = &models.PAMConfig{
ServiceName: form.PAMServiceName, ServiceName: f.PAMServiceName,
} }
default: default:
ctx.Error(400) ctx.Error(400)
return return
} }
source.Name = form.Name source.Name = f.Name
source.IsActived = form.IsActive source.IsActived = f.IsActive
source.Cfg = config source.Cfg = config
if err := models.UpdateSource(source); err != nil { if err := models.UpdateSource(source); err != nil {
ctx.Handle(500, "UpdateSource", err) ctx.Handle(500, "UpdateSource", err)
@ -231,7 +231,7 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID) log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID)
ctx.Flash.Success(ctx.Tr("admin.auths.update_success")) ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
ctx.Redirect(setting.AppSubUrl + "/admin/auths/" + com.ToStr(form.ID)) ctx.Redirect(setting.AppSubUrl + "/admin/auths/" + com.ToStr(f.ID))
} }
func DeleteAuthSource(ctx *context.Context) { func DeleteAuthSource(ctx *context.Context) {

58
routers/admin/users.go

@ -11,9 +11,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers"
@ -58,7 +58,7 @@ func NewUser(ctx *context.Context) {
ctx.HTML(200, USER_NEW) ctx.HTML(200, USER_NEW)
} }
func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) { func NewUserPost(ctx *context.Context, f form.AdminCrateUser) {
ctx.Data["Title"] = ctx.Tr("admin.users.new_account") ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true ctx.Data["PageIsAdminUsers"] = true
@ -78,19 +78,19 @@ func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) {
} }
u := &models.User{ u := &models.User{
Name: form.UserName, Name: f.UserName,
Email: form.Email, Email: f.Email,
Passwd: form.Password, Passwd: f.Password,
IsActive: true, IsActive: true,
LoginType: models.LOGIN_PLAIN, LoginType: models.LOGIN_PLAIN,
} }
if len(form.LoginType) > 0 { if len(f.LoginType) > 0 {
fields := strings.Split(form.LoginType, "-") fields := strings.Split(f.LoginType, "-")
if len(fields) == 2 { if len(fields) == 2 {
u.LoginType = models.LoginType(com.StrTo(fields[0]).MustInt()) u.LoginType = models.LoginType(com.StrTo(fields[0]).MustInt())
u.LoginSource = com.StrTo(fields[1]).MustInt64() u.LoginSource = com.StrTo(fields[1]).MustInt64()
u.LoginName = form.LoginName u.LoginName = f.LoginName
} }
} }
@ -98,16 +98,16 @@ func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) {
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &form) ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &f)
case models.IsErrEmailAlreadyUsed(err): case models.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &form) ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &form) ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &form) ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &f)
default: default:
ctx.Handle(500, "CreateUser", err) ctx.Handle(500, "CreateUser", err)
} }
@ -116,7 +116,7 @@ func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) {
log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name) log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)
// Send email notification. // Send email notification.
if form.SendNotify && setting.MailService != nil { if f.SendNotify && setting.MailService != nil {
mailer.SendRegisterNotifyMail(ctx.Context, models.NewMailerUser(u)) mailer.SendRegisterNotifyMail(ctx.Context, models.NewMailerUser(u))
} }
@ -166,7 +166,7 @@ func EditUser(ctx *context.Context) {
ctx.HTML(200, USER_EDIT) ctx.HTML(200, USER_EDIT)
} }
func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) { func EditUserPost(ctx *context.Context, f form.AdminEditUser) {
ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true ctx.Data["PageIsAdminUsers"] = true
@ -182,7 +182,7 @@ func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) {
return return
} }
fields := strings.Split(form.LoginType, "-") fields := strings.Split(f.LoginType, "-")
if len(fields) == 2 { if len(fields) == 2 {
loginType := models.LoginType(com.StrTo(fields[0]).MustInt()) loginType := models.LoginType(com.StrTo(fields[0]).MustInt())
loginSource := com.StrTo(fields[1]).MustInt64() loginSource := com.StrTo(fields[1]).MustInt64()
@ -193,8 +193,8 @@ func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) {
} }
} }
if len(form.Password) > 0 { if len(f.Password) > 0 {
u.Passwd = form.Password u.Passwd = f.Password
var err error var err error
if u.Salt, err = models.GetUserSalt(); err != nil { if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) ctx.Handle(500, "UpdateUser", err)
@ -203,22 +203,22 @@ func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) {
u.EncodePasswd() u.EncodePasswd()
} }
u.LoginName = form.LoginName u.LoginName = f.LoginName
u.FullName = form.FullName u.FullName = f.FullName
u.Email = form.Email u.Email = f.Email
u.Website = form.Website u.Website = f.Website
u.Location = form.Location u.Location = f.Location
u.MaxRepoCreation = form.MaxRepoCreation u.MaxRepoCreation = f.MaxRepoCreation
u.IsActive = form.Active u.IsActive = f.Active
u.IsAdmin = form.Admin u.IsAdmin = f.Admin
u.AllowGitHook = form.AllowGitHook u.AllowGitHook = f.AllowGitHook
u.AllowImportLocal = form.AllowImportLocal u.AllowImportLocal = f.AllowImportLocal
u.ProhibitLogin = form.ProhibitLogin u.ProhibitLogin = f.ProhibitLogin
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.Data["Err_Email"] = true ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &form) ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &f)
} else { } else {
ctx.Handle(500, "UpdateUser", err) ctx.Handle(500, "UpdateUser", err)
} }

4
routers/api/v1/api.go

@ -13,8 +13,8 @@ import (
api "github.com/gogits/go-gogs-client" api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/routers/api/v1/admin" "github.com/gogits/gogs/routers/api/v1/admin"
"github.com/gogits/gogs/routers/api/v1/misc" "github.com/gogits/gogs/routers/api/v1/misc"
"github.com/gogits/gogs/routers/api/v1/org" "github.com/gogits/gogs/routers/api/v1/org"
@ -237,7 +237,7 @@ func RegisterRoutes(m *macaron.Macaron) {
}) })
m.Group("/repos", func() { m.Group("/repos", func() {
m.Post("/migrate", bind(auth.MigrateRepoForm{}), repo.Migrate) m.Post("/migrate", bind(form.MigrateRepo{}), repo.Migrate)
m.Combo("/:username/:reponame").Get(repo.Get). m.Combo("/:username/:reponame").Get(repo.Get).
Delete(repo.Delete) Delete(repo.Delete)

20
routers/api/v1/repo/repo.go

@ -12,8 +12,8 @@ import (
api "github.com/gogits/go-gogs-client" api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/api/v1/convert" "github.com/gogits/gogs/routers/api/v1/convert"
) )
@ -206,12 +206,12 @@ func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate // https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate
func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { func Migrate(ctx *context.APIContext, f form.MigrateRepo) {
ctxUser := ctx.User ctxUser := ctx.User
// Not equal means context user is an organization, // Not equal means context user is an organization,
// or is another user/organization if current user is admin. // or is another user/organization if current user is admin.
if form.Uid != ctxUser.ID { if f.Uid != ctxUser.ID {
org, err := models.GetUserByID(form.Uid) org, err := models.GetUserByID(f.Uid)
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(422, "", err) ctx.Error(422, "", err)
@ -236,7 +236,7 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) {
} }
} }
remoteAddr, err := form.ParseRemoteAddr(ctx.User) remoteAddr, err := f.ParseRemoteAddr(ctx.User)
if err != nil { if err != nil {
if models.IsErrInvalidCloneAddr(err) { if models.IsErrInvalidCloneAddr(err) {
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
@ -257,10 +257,10 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) {
} }
repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{ repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{
Name: form.RepoName, Name: f.RepoName,
Description: form.Description, Description: f.Description,
IsPrivate: form.Private || setting.Repository.ForcePrivate, IsPrivate: f.Private || setting.Repository.ForcePrivate,
IsMirror: form.Mirror, IsMirror: f.Mirror,
RemoteAddr: remoteAddr, RemoteAddr: remoteAddr,
}) })
if err != nil { if err != nil {
@ -273,7 +273,7 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) {
return return
} }
log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true}))
} }

184
routers/install.go

@ -21,10 +21,10 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/cron" "github.com/gogits/gogs/modules/cron"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/markdown" "github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
@ -109,13 +109,13 @@ func InstallInit(ctx *context.Context) {
} }
func Install(ctx *context.Context) { func Install(ctx *context.Context) {
form := auth.InstallForm{} f := form.Install{}
// Database settings // Database settings
form.DbHost = models.DbCfg.Host f.DbHost = models.DbCfg.Host
form.DbUser = models.DbCfg.User f.DbUser = models.DbCfg.User
form.DbName = models.DbCfg.Name f.DbName = models.DbCfg.Name
form.DbPath = models.DbCfg.Path f.DbPath = models.DbCfg.Path
ctx.Data["CurDbOption"] = "MySQL" ctx.Data["CurDbOption"] = "MySQL"
switch models.DbCfg.Type { switch models.DbCfg.Type {
@ -130,47 +130,47 @@ func Install(ctx *context.Context) {
} }
// Application general settings // Application general settings
form.AppName = setting.AppName f.AppName = setting.AppName
form.RepoRootPath = setting.RepoRootPath f.RepoRootPath = setting.RepoRootPath
// Note(unknwon): it's hard for Windows users change a running user, // Note(unknwon): it's hard for Windows users change a running user,
// so just use current one if config says default. // so just use current one if config says default.
if setting.IsWindows && setting.RunUser == "git" { if setting.IsWindows && setting.RunUser == "git" {
form.RunUser = user.CurrentUsername() f.RunUser = user.CurrentUsername()
} else { } else {
form.RunUser = setting.RunUser f.RunUser = setting.RunUser
} }
form.Domain = setting.Domain f.Domain = setting.Domain
form.SSHPort = setting.SSH.Port f.SSHPort = setting.SSH.Port
form.UseBuiltinSSHServer = setting.SSH.StartBuiltinServer f.UseBuiltinSSHServer = setting.SSH.StartBuiltinServer
form.HTTPPort = setting.HTTPPort f.HTTPPort = setting.HTTPPort
form.AppUrl = setting.AppUrl f.AppUrl = setting.AppUrl
form.LogRootPath = setting.LogRootPath f.LogRootPath = setting.LogRootPath
// E-mail service settings // E-mail service settings
if setting.MailService != nil { if setting.MailService != nil {
form.SMTPHost = setting.MailService.Host f.SMTPHost = setting.MailService.Host
form.SMTPFrom = setting.MailService.From f.SMTPFrom = setting.MailService.From
form.SMTPUser = setting.MailService.User f.SMTPUser = setting.MailService.User
} }
form.RegisterConfirm = setting.Service.RegisterEmailConfirm f.RegisterConfirm = setting.Service.RegisterEmailConfirm
form.MailNotify = setting.Service.EnableNotifyMail f.MailNotify = setting.Service.EnableNotifyMail
// Server and other services settings // Server and other services settings
form.OfflineMode = setting.OfflineMode f.OfflineMode = setting.OfflineMode
form.DisableGravatar = setting.DisableGravatar f.DisableGravatar = setting.DisableGravatar
form.EnableFederatedAvatar = setting.EnableFederatedAvatar f.EnableFederatedAvatar = setting.EnableFederatedAvatar
form.DisableRegistration = setting.Service.DisableRegistration f.DisableRegistration = setting.Service.DisableRegistration
form.EnableCaptcha = setting.Service.EnableCaptcha f.EnableCaptcha = setting.Service.EnableCaptcha
form.RequireSignInView = setting.Service.RequireSignInView f.RequireSignInView = setting.Service.RequireSignInView
auth.AssignForm(form, ctx.Data) form.Assign(f, ctx.Data)
ctx.HTML(200, INSTALL) ctx.HTML(200, INSTALL)
} }
func InstallPost(ctx *context.Context, form auth.InstallForm) { func InstallPost(ctx *context.Context, f form.Install) {
ctx.Data["CurDbOption"] = form.DbType ctx.Data["CurDbOption"] = f.DbType
if ctx.HasError() { if ctx.HasError() {
if ctx.HasValue("Err_SMTPEmail") { if ctx.HasValue("Err_SMTPEmail") {
@ -187,24 +187,24 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
} }
if _, err := exec.LookPath("git"); err != nil { if _, err := exec.LookPath("git"); err != nil {
ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &f)
return return
} }
// Pass basic check, now test configuration. // Pass basic check, now test configuration.
// Test database setting. // Test database setting.
dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"} dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"}
models.DbCfg.Type = dbTypes[form.DbType] models.DbCfg.Type = dbTypes[f.DbType]
models.DbCfg.Host = form.DbHost models.DbCfg.Host = f.DbHost
models.DbCfg.User = form.DbUser models.DbCfg.User = f.DbUser
models.DbCfg.Passwd = form.DbPasswd models.DbCfg.Passwd = f.DbPasswd
models.DbCfg.Name = form.DbName models.DbCfg.Name = f.DbName
models.DbCfg.SSLMode = form.SSLMode models.DbCfg.SSLMode = f.SSLMode
models.DbCfg.Path = form.DbPath models.DbCfg.Path = f.DbPath
if models.DbCfg.Type == "sqlite3" && len(models.DbCfg.Path) == 0 { if models.DbCfg.Type == "sqlite3" && len(models.DbCfg.Path) == 0 {
ctx.Data["Err_DbPath"] = true ctx.Data["Err_DbPath"] = true
ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), INSTALL, &f)
return return
} }
@ -213,72 +213,72 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
if err := models.NewTestEngine(x); err != nil { if err := models.NewTestEngine(x); err != nil {
if strings.Contains(err.Error(), `Unknown database type: sqlite3`) { if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
ctx.Data["Err_DbType"] = true ctx.Data["Err_DbType"] = true
ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
} else { } else {
ctx.Data["Err_DbSetting"] = true ctx.Data["Err_DbSetting"] = true
ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &f)
} }
return return
} }
// Test repository root path. // Test repository root path.
form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1) f.RepoRootPath = strings.Replace(f.RepoRootPath, "\\", "/", -1)
if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil { if err := os.MkdirAll(f.RepoRootPath, os.ModePerm); err != nil {
ctx.Data["Err_RepoRootPath"] = true ctx.Data["Err_RepoRootPath"] = true
ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &f)
return return
} }
// Test log root path. // Test log root path.
form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1) f.LogRootPath = strings.Replace(f.LogRootPath, "\\", "/", -1)
if err := os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil { if err := os.MkdirAll(f.LogRootPath, os.ModePerm); err != nil {
ctx.Data["Err_LogRootPath"] = true ctx.Data["Err_LogRootPath"] = true
ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), INSTALL, &f)
return return
} }
currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser) currentUser, match := setting.IsRunUserMatchCurrentUser(f.RunUser)
if !match { if !match {
ctx.Data["Err_RunUser"] = true ctx.Data["Err_RunUser"] = true
ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", f.RunUser, currentUser), INSTALL, &f)
return return
} }
// Make sure FROM field is valid // Make sure FROM field is valid
if len(form.SMTPFrom) > 0 { if len(f.SMTPFrom) > 0 {
_, err := mail.ParseAddress(form.SMTPFrom) _, err := mail.ParseAddress(f.SMTPFrom)
if err != nil { if err != nil {
ctx.Data["Err_SMTP"] = true ctx.Data["Err_SMTP"] = true
ctx.Data["Err_SMTPFrom"] = true ctx.Data["Err_SMTPFrom"] = true
ctx.RenderWithErr(ctx.Tr("install.invalid_smtp_from", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.invalid_smtp_from", err), INSTALL, &f)
return return
} }
} }
// Check logic loophole between disable self-registration and no admin account. // Check logic loophole between disable self-registration and no admin account.
if form.DisableRegistration && len(form.AdminName) == 0 { if f.DisableRegistration && len(f.AdminName) == 0 {
ctx.Data["Err_Services"] = true ctx.Data["Err_Services"] = true
ctx.Data["Err_Admin"] = true ctx.Data["Err_Admin"] = true
ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, form) ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), INSTALL, f)
return return
} }
// Check admin password. // Check admin password.
if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 { if len(f.AdminName) > 0 && len(f.AdminPasswd) == 0 {
ctx.Data["Err_Admin"] = true ctx.Data["Err_Admin"] = true
ctx.Data["Err_AdminPasswd"] = true ctx.Data["Err_AdminPasswd"] = true
ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, form) ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), INSTALL, f)
return return
} }
if form.AdminPasswd != form.AdminConfirmPasswd { if f.AdminPasswd != f.AdminConfirmPasswd {
ctx.Data["Err_Admin"] = true ctx.Data["Err_Admin"] = true
ctx.Data["Err_AdminPasswd"] = true ctx.Data["Err_AdminPasswd"] = true
ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form) ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, f)
return return
} }
if form.AppUrl[len(form.AppUrl)-1] != '/' { if f.AppUrl[len(f.AppUrl)-1] != '/' {
form.AppUrl += "/" f.AppUrl += "/"
} }
// Save settings. // Save settings.
@ -297,39 +297,39 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode) cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path) cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
cfg.Section("").Key("APP_NAME").SetValue(form.AppName) cfg.Section("").Key("APP_NAME").SetValue(f.AppName)
cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath) cfg.Section("repository").Key("ROOT").SetValue(f.RepoRootPath)
cfg.Section("").Key("RUN_USER").SetValue(form.RunUser) cfg.Section("").Key("RUN_USER").SetValue(f.RunUser)
cfg.Section("server").Key("DOMAIN").SetValue(form.Domain) cfg.Section("server").Key("DOMAIN").SetValue(f.Domain)
cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort) cfg.Section("server").Key("HTTP_PORT").SetValue(f.HTTPPort)
cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl) cfg.Section("server").Key("ROOT_URL").SetValue(f.AppUrl)
if form.SSHPort == 0 { if f.SSHPort == 0 {
cfg.Section("server").Key("DISABLE_SSH").SetValue("true") cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
} else { } else {
cfg.Section("server").Key("DISABLE_SSH").SetValue("false") cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort)) cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(f.SSHPort))
cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(form.UseBuiltinSSHServer)) cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(f.UseBuiltinSSHServer))
} }
if len(strings.TrimSpace(form.SMTPHost)) > 0 { if len(strings.TrimSpace(f.SMTPHost)) > 0 {
cfg.Section("mailer").Key("ENABLED").SetValue("true") cfg.Section("mailer").Key("ENABLED").SetValue("true")
cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost) cfg.Section("mailer").Key("HOST").SetValue(f.SMTPHost)
cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom) cfg.Section("mailer").Key("FROM").SetValue(f.SMTPFrom)
cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser) cfg.Section("mailer").Key("USER").SetValue(f.SMTPUser)
cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd) cfg.Section("mailer").Key("PASSWD").SetValue(f.SMTPPasswd)
} else { } else {
cfg.Section("mailer").Key("ENABLED").SetValue("false") cfg.Section("mailer").Key("ENABLED").SetValue("false")
} }
cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm)) cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(f.RegisterConfirm))
cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify)) cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(f.MailNotify))
cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode)) cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(f.OfflineMode))
cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar)) cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(f.DisableGravatar))
cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar)) cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(f.EnableFederatedAvatar))
cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration)) cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(f.DisableRegistration))
cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha)) cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(f.EnableCaptcha))
cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView)) cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(f.RequireSignInView))
cfg.Section("").Key("RUN_MODE").SetValue("prod") cfg.Section("").Key("RUN_MODE").SetValue("prod")
@ -337,30 +337,30 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
cfg.Section("log").Key("MODE").SetValue("file") cfg.Section("log").Key("MODE").SetValue("file")
cfg.Section("log").Key("LEVEL").SetValue("Info") cfg.Section("log").Key("LEVEL").SetValue("Info")
cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath) cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath)
cfg.Section("security").Key("INSTALL_LOCK").SetValue("true") cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
secretKey, err := base.GetRandomString(15) secretKey, err := base.GetRandomString(15)
if err != nil { if err != nil {
ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &f)
return return
} }
cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey) cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm) os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
if err := cfg.SaveTo(setting.CustomConf); err != nil { if err := cfg.SaveTo(setting.CustomConf); err != nil {
ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &f)
return return
} }
GlobalInit() GlobalInit()
// Create admin account // Create admin account
if len(form.AdminName) > 0 { if len(f.AdminName) > 0 {
u := &models.User{ u := &models.User{
Name: form.AdminName, Name: f.AdminName,
Email: form.AdminEmail, Email: f.AdminEmail,
Passwd: form.AdminPasswd, Passwd: f.AdminPasswd,
IsAdmin: true, IsAdmin: true,
IsActive: true, IsActive: true,
} }
@ -369,7 +369,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
setting.InstallLock = false setting.InstallLock = false
ctx.Data["Err_AdminName"] = true ctx.Data["Err_AdminName"] = true
ctx.Data["Err_AdminEmail"] = true ctx.Data["Err_AdminEmail"] = true
ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &f)
return return
} }
log.Info("Admin account already exist") log.Info("Admin account already exist")
@ -383,5 +383,5 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
log.Info("First-time run install finished!") log.Info("First-time run install finished!")
ctx.Flash.Success(ctx.Tr("install.install_success")) ctx.Flash.Success(ctx.Tr("install.install_success"))
ctx.Redirect(form.AppUrl + "user/login") ctx.Redirect(f.AppUrl + "user/login")
} }

14
routers/org/org.go

@ -8,7 +8,7 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
@ -23,7 +23,7 @@ func Create(ctx *context.Context) {
ctx.HTML(200, CREATE) ctx.HTML(200, CREATE)
} }
func CreatePost(ctx *context.Context, form auth.CreateOrgForm) { func CreatePost(ctx *context.Context, f form.CreateOrg) {
ctx.Data["Title"] = ctx.Tr("new_org") ctx.Data["Title"] = ctx.Tr("new_org")
if ctx.HasError() { if ctx.HasError() {
@ -32,7 +32,7 @@ func CreatePost(ctx *context.Context, form auth.CreateOrgForm) {
} }
org := &models.User{ org := &models.User{
Name: form.OrgName, Name: f.OrgName,
IsActive: true, IsActive: true,
Type: models.USER_TYPE_ORGANIZATION, Type: models.USER_TYPE_ORGANIZATION,
} }
@ -41,11 +41,11 @@ func CreatePost(ctx *context.Context, form auth.CreateOrgForm) {
ctx.Data["Err_OrgName"] = true ctx.Data["Err_OrgName"] = true
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("form.org_name_been_taken"), CREATE, &form) ctx.RenderWithErr(ctx.Tr("form.org_name_been_taken"), CREATE, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CREATE, &form) ctx.RenderWithErr(ctx.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CREATE, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.RenderWithErr(ctx.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CREATE, &form) ctx.RenderWithErr(ctx.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CREATE, &f)
default: default:
ctx.Handle(500, "CreateOrganization", err) ctx.Handle(500, "CreateOrganization", err)
} }
@ -53,5 +53,5 @@ func CreatePost(ctx *context.Context, form auth.CreateOrgForm) {
} }
log.Trace("Organization created: %s", org.Name) log.Trace("Organization created: %s", org.Name)
ctx.Redirect(setting.AppSubUrl + "/org/" + form.OrgName + "/dashboard") ctx.Redirect(setting.AppSubUrl + "/org/" + f.OrgName + "/dashboard")
} }

38
routers/org/setting.go

@ -10,9 +10,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/user" "github.com/gogits/gogs/routers/user"
) )
@ -29,7 +29,7 @@ func Settings(ctx *context.Context) {
ctx.HTML(200, SETTINGS_OPTIONS) ctx.HTML(200, SETTINGS_OPTIONS)
} }
func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) { func SettingsPost(ctx *context.Context, f form.UpdateOrgSetting) {
ctx.Data["Title"] = ctx.Tr("org.settings") ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true ctx.Data["PageIsSettingsOptions"] = true
@ -41,40 +41,40 @@ func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) {
org := ctx.Org.Organization org := ctx.Org.Organization
// Check if organization name has been changed. // Check if organization name has been changed.
if org.LowerName != strings.ToLower(form.Name) { if org.LowerName != strings.ToLower(f.Name) {
isExist, err := models.IsUserExist(org.ID, form.Name) isExist, err := models.IsUserExist(org.ID, f.Name)
if err != nil { if err != nil {
ctx.Handle(500, "IsUserExist", err) ctx.Handle(500, "IsUserExist", err)
return return
} else if isExist { } else if isExist {
ctx.Data["OrgName"] = true ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &form) ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &f)
return return
} else if err = models.ChangeUserName(org, form.Name); err != nil { } else if err = models.ChangeUserName(org, f.Name); err != nil {
if err == models.ErrUserNameIllegal { if err == models.ErrUserNameIllegal {
ctx.Data["OrgName"] = true ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &form) ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &f)
} else { } else {
ctx.Handle(500, "ChangeUserName", err) ctx.Handle(500, "ChangeUserName", err)
} }
return return
} }
// reset ctx.org.OrgLink with new name // reset ctx.org.OrgLink with new name
ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + form.Name ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + f.Name
log.Trace("Organization name changed: %s -> %s", org.Name, form.Name) log.Trace("Organization name changed: %s -> %s", org.Name, f.Name)
} }
// In case it's just a case change. // In case it's just a case change.
org.Name = form.Name org.Name = f.Name
org.LowerName = strings.ToLower(form.Name) org.LowerName = strings.ToLower(f.Name)
if ctx.User.IsAdmin { if ctx.User.IsAdmin {
org.MaxRepoCreation = form.MaxRepoCreation org.MaxRepoCreation = f.MaxRepoCreation
} }
org.FullName = form.FullName org.FullName = f.FullName
org.Description = form.Description org.Description = f.Description
org.Website = form.Website org.Website = f.Website
org.Location = form.Location org.Location = f.Location
if err := models.UpdateUser(org); err != nil { if err := models.UpdateUser(org); err != nil {
ctx.Handle(500, "UpdateUser", err) ctx.Handle(500, "UpdateUser", err)
return return
@ -84,9 +84,9 @@ func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) {
ctx.Redirect(ctx.Org.OrgLink + "/settings") ctx.Redirect(ctx.Org.OrgLink + "/settings")
} }
func SettingsAvatar(ctx *context.Context, form auth.AvatarForm) { func SettingsAvatar(ctx *context.Context, f form.Avatar) {
form.Source = auth.AVATAR_LOCAL f.Source = form.AVATAR_LOCAL
if err := user.UpdateAvatarSetting(ctx, form, ctx.Org.Organization); err != nil { if err := user.UpdateAvatarSetting(ctx, f, ctx.Org.Organization); err != nil {
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("org.settings.update_avatar_success")) ctx.Flash.Success(ctx.Tr("org.settings.update_avatar_success"))

24
routers/org/teams.go

@ -11,9 +11,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
) )
const ( const (
@ -149,16 +149,16 @@ func NewTeam(ctx *context.Context) {
ctx.HTML(200, TEAM_NEW) ctx.HTML(200, TEAM_NEW)
} }
func NewTeamPost(ctx *context.Context, form auth.CreateTeamForm) { func NewTeamPost(ctx *context.Context, f form.CreateTeam) {
ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["Title"] = ctx.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamsNew"] = true ctx.Data["PageIsOrgTeamsNew"] = true
t := &models.Team{ t := &models.Team{
OrgID: ctx.Org.Organization.ID, OrgID: ctx.Org.Organization.ID,
Name: form.TeamName, Name: f.TeamName,
Description: form.Description, Description: f.Description,
Authorize: models.ParseAccessMode(form.Permission), Authorize: models.ParseAccessMode(f.Permission),
} }
ctx.Data["Team"] = t ctx.Data["Team"] = t
@ -171,9 +171,9 @@ func NewTeamPost(ctx *context.Context, form auth.CreateTeamForm) {
ctx.Data["Err_TeamName"] = true ctx.Data["Err_TeamName"] = true
switch { switch {
case models.IsErrTeamAlreadyExist(err): case models.IsErrTeamAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &form) ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("org.form.team_name_reserved", err.(models.ErrNameReserved).Name), TEAM_NEW, &form) ctx.RenderWithErr(ctx.Tr("org.form.team_name_reserved", err.(models.ErrNameReserved).Name), TEAM_NEW, &f)
default: default:
ctx.Handle(500, "NewTeam", err) ctx.Handle(500, "NewTeam", err)
} }
@ -211,7 +211,7 @@ func EditTeam(ctx *context.Context) {
ctx.HTML(200, TEAM_NEW) ctx.HTML(200, TEAM_NEW)
} }
func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) { func EditTeamPost(ctx *context.Context, f form.CreateTeam) {
t := ctx.Org.Team t := ctx.Org.Team
ctx.Data["Title"] = ctx.Org.Organization.FullName ctx.Data["Title"] = ctx.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeams"] = true
@ -226,7 +226,7 @@ func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) {
if !t.IsOwnerTeam() { if !t.IsOwnerTeam() {
// Validate permission level. // Validate permission level.
var auth models.AccessMode var auth models.AccessMode
switch form.Permission { switch f.Permission {
case "read": case "read":
auth = models.ACCESS_MODE_READ auth = models.ACCESS_MODE_READ
case "write": case "write":
@ -238,18 +238,18 @@ func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) {
return return
} }
t.Name = form.TeamName t.Name = f.TeamName
if t.Authorize != auth { if t.Authorize != auth {
isAuthChanged = true isAuthChanged = true
t.Authorize = auth t.Authorize = auth
} }
} }
t.Description = form.Description t.Description = f.Description
if err := models.UpdateTeam(t, isAuthChanged); err != nil { if err := models.UpdateTeam(t, isAuthChanged); err != nil {
ctx.Data["Err_TeamName"] = true ctx.Data["Err_TeamName"] = true
switch { switch {
case models.IsErrTeamAlreadyExist(err): case models.IsErrTeamAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &form) ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &f)
default: default:
ctx.Handle(500, "UpdateTeam", err) ctx.Handle(500, "UpdateTeam", err)
} }

154
routers/repo/editor.go

@ -15,9 +15,9 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template" "github.com/gogits/gogs/modules/template"
) )
@ -123,7 +123,7 @@ func NewFile(ctx *context.Context) {
editFile(ctx, true) editFile(ctx, true)
} }
func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bool) { func editFilePost(ctx *context.Context, f form.EditRepoFile, isNewFile bool) {
ctx.Data["PageIsEdit"] = true ctx.Data["PageIsEdit"] = true
ctx.Data["IsNewFile"] = isNewFile ctx.Data["IsNewFile"] = isNewFile
ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireHighlightJS"] = true
@ -132,26 +132,26 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
oldBranchName := ctx.Repo.BranchName oldBranchName := ctx.Repo.BranchName
branchName := oldBranchName branchName := oldBranchName
oldTreePath := ctx.Repo.TreePath oldTreePath := ctx.Repo.TreePath
lastCommit := form.LastCommit lastCommit := f.LastCommit
form.LastCommit = ctx.Repo.Commit.ID.String() f.LastCommit = ctx.Repo.Commit.ID.String()
if form.IsNewBrnach() { if f.IsNewBrnach() {
branchName = form.NewBranchName branchName = f.NewBranchName
} }
form.TreePath = strings.Trim(form.TreePath, " /") f.TreePath = strings.Trim(f.TreePath, " /")
treeNames, treePaths := getParentTreeFields(form.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath)
ctx.Data["TreePath"] = form.TreePath ctx.Data["TreePath"] = f.TreePath
ctx.Data["TreeNames"] = treeNames ctx.Data["TreeNames"] = treeNames
ctx.Data["TreePaths"] = treePaths ctx.Data["TreePaths"] = treePaths
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
ctx.Data["FileContent"] = form.Content ctx.Data["FileContent"] = f.Content
ctx.Data["commit_summary"] = form.CommitSummary ctx.Data["commit_summary"] = f.CommitSummary
ctx.Data["commit_message"] = form.CommitMessage ctx.Data["commit_message"] = f.CommitMessage
ctx.Data["commit_choice"] = form.CommitChoice ctx.Data["commit_choice"] = f.CommitChoice
ctx.Data["new_branch_name"] = branchName ctx.Data["new_branch_name"] = branchName
ctx.Data["last_commit"] = form.LastCommit ctx.Data["last_commit"] = f.LastCommit
ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",") ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",") ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",") ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
@ -161,16 +161,16 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
return return
} }
if len(form.TreePath) == 0 { if len(f.TreePath) == 0 {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.filename_cannot_be_empty"), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.filename_cannot_be_empty"), EDIT_FILE, &f)
return return
} }
if oldBranchName != branchName { if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true ctx.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), EDIT_FILE, &f)
return return
} }
} }
@ -191,17 +191,17 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
if index != len(treeNames)-1 { if index != len(treeNames)-1 {
if !entry.IsDir() { if !entry.IsDir() {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), EDIT_FILE, &f)
return return
} }
} else { } else {
if entry.IsLink() { if entry.IsLink() {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", part), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_is_a_symlink", part), EDIT_FILE, &f)
return return
} else if entry.IsDir() { } else if entry.IsDir() {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &f)
return return
} }
} }
@ -212,7 +212,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &f)
} else { } else {
ctx.Handle(500, "GetTreeEntryByPath", err) ctx.Handle(500, "GetTreeEntryByPath", err)
} }
@ -226,17 +226,17 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
} }
for _, file := range files { for _, file := range files {
if file == form.TreePath { if file == f.TreePath {
ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+lastCommit+"..."+ctx.Repo.CommitID), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+lastCommit+"..."+ctx.Repo.CommitID), EDIT_FILE, &f)
return return
} }
} }
} }
} }
if oldTreePath != form.TreePath { if oldTreePath != f.TreePath {
// We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber. // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(form.TreePath) entry, err := ctx.Repo.Commit.GetTreeEntryByPath(f.TreePath)
if err != nil { if err != nil {
if !git.IsErrNotExist(err) { if !git.IsErrNotExist(err) {
ctx.Handle(500, "GetTreeEntryByPath", err) ctx.Handle(500, "GetTreeEntryByPath", err)
@ -245,23 +245,23 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
} }
if entry != nil { if entry != nil {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", f.TreePath), EDIT_FILE, &f)
return return
} }
} }
message := strings.TrimSpace(form.CommitSummary) message := strings.TrimSpace(f.CommitSummary)
if len(message) == 0 { if len(message) == 0 {
if isNewFile { if isNewFile {
message = ctx.Tr("repo.editor.add", form.TreePath) message = ctx.Tr("repo.editor.add", f.TreePath)
} else { } else {
message = ctx.Tr("repo.editor.update", form.TreePath) message = ctx.Tr("repo.editor.update", f.TreePath)
} }
} }
form.CommitMessage = strings.TrimSpace(form.CommitMessage) f.CommitMessage = strings.TrimSpace(f.CommitMessage)
if len(form.CommitMessage) > 0 { if len(f.CommitMessage) > 0 {
message += "\n\n" + form.CommitMessage message += "\n\n" + f.CommitMessage
} }
if err := ctx.Repo.Repository.UpdateRepoFile(ctx.User, models.UpdateRepoFileOptions{ if err := ctx.Repo.Repository.UpdateRepoFile(ctx.User, models.UpdateRepoFileOptions{
@ -269,32 +269,32 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
OldBranch: oldBranchName, OldBranch: oldBranchName,
NewBranch: branchName, NewBranch: branchName,
OldTreeName: oldTreePath, OldTreeName: oldTreePath,
NewTreeName: form.TreePath, NewTreeName: f.TreePath,
Message: message, Message: message,
Content: strings.Replace(form.Content, "\r", "", -1), Content: strings.Replace(f.Content, "\r", "", -1),
IsNewFile: isNewFile, IsNewFile: isNewFile,
}); err != nil { }); err != nil {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), EDIT_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", f.TreePath, err), EDIT_FILE, &f)
return return
} }
if form.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { if form.IsNewBrnach() && ctx.Repo.PullRequest.Allowed {
ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, form.NewBranchName)) ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, form.NewBranchName))
} else { } else {
ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + template.EscapePound(form.TreePath)) ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + template.EscapePound(f.TreePath))
} }
} }
func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) { func EditFilePost(ctx *context.Context, f form.EditRepoFile) {
editFilePost(ctx, form, false) editFilePost(ctx, f, false)
} }
func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) { func NewFilePost(ctx *context.Context, f form.EditRepoFile) {
editFilePost(ctx, form, true) editFilePost(ctx, f, true)
} }
func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) { func DiffPreviewPost(ctx *context.Context, f form.EditPreviewDiff) {
treePath := ctx.Repo.TreePath treePath := ctx.Repo.TreePath
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath) entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath)
@ -306,7 +306,7 @@ func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) {
return return
} }
diff, err := ctx.Repo.Repository.GetDiffPreview(ctx.Repo.BranchName, treePath, form.Content) diff, err := ctx.Repo.Repository.GetDiffPreview(ctx.Repo.BranchName, treePath, f.Content)
if err != nil { if err != nil {
ctx.Error(500, "GetDiffPreview: "+err.Error()) ctx.Error(500, "GetDiffPreview: "+err.Error())
return return
@ -332,7 +332,7 @@ func DeleteFile(ctx *context.Context) {
ctx.HTML(200, DELETE_FILE) ctx.HTML(200, DELETE_FILE)
} }
func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) {
ctx.Data["PageIsDelete"] = true ctx.Data["PageIsDelete"] = true
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
ctx.Data["TreePath"] = ctx.Repo.TreePath ctx.Data["TreePath"] = ctx.Repo.TreePath
@ -340,12 +340,12 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
oldBranchName := ctx.Repo.BranchName oldBranchName := ctx.Repo.BranchName
branchName := oldBranchName branchName := oldBranchName
if form.IsNewBrnach() { if f.IsNewBrnach() {
branchName = form.NewBranchName branchName = f.NewBranchName
} }
ctx.Data["commit_summary"] = form.CommitSummary ctx.Data["commit_summary"] = f.CommitSummary
ctx.Data["commit_message"] = form.CommitMessage ctx.Data["commit_message"] = f.CommitMessage
ctx.Data["commit_choice"] = form.CommitChoice ctx.Data["commit_choice"] = f.CommitChoice
ctx.Data["new_branch_name"] = branchName ctx.Data["new_branch_name"] = branchName
if ctx.HasError() { if ctx.HasError() {
@ -356,19 +356,19 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
if oldBranchName != branchName { if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true ctx.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f)
return return
} }
} }
message := strings.TrimSpace(form.CommitSummary) message := strings.TrimSpace(f.CommitSummary)
if len(message) == 0 { if len(message) == 0 {
message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath) message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
} }
form.CommitMessage = strings.TrimSpace(form.CommitMessage) f.CommitMessage = strings.TrimSpace(f.CommitMessage)
if len(form.CommitMessage) > 0 { if len(f.CommitMessage) > 0 {
message += "\n\n" + form.CommitMessage message += "\n\n" + f.CommitMessage
} }
if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{ if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{
@ -418,31 +418,31 @@ func UploadFile(ctx *context.Context) {
ctx.HTML(200, UPLOAD_FILE) ctx.HTML(200, UPLOAD_FILE)
} }
func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) {
ctx.Data["PageIsUpload"] = true ctx.Data["PageIsUpload"] = true
renderUploadSettings(ctx) renderUploadSettings(ctx)
oldBranchName := ctx.Repo.BranchName oldBranchName := ctx.Repo.BranchName
branchName := oldBranchName branchName := oldBranchName
if form.IsNewBrnach() { if f.IsNewBrnach() {
branchName = form.NewBranchName branchName = f.NewBranchName
} }
form.TreePath = strings.Trim(form.TreePath, " /") f.TreePath = strings.Trim(f.TreePath, " /")
treeNames, treePaths := getParentTreeFields(form.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath)
if len(treeNames) == 0 { if len(treeNames) == 0 {
// We must at least have one element for user to input. // We must at least have one element for user to input.
treeNames = []string{""} treeNames = []string{""}
} }
ctx.Data["TreePath"] = form.TreePath ctx.Data["TreePath"] = f.TreePath
ctx.Data["TreeNames"] = treeNames ctx.Data["TreeNames"] = treeNames
ctx.Data["TreePaths"] = treePaths ctx.Data["TreePaths"] = treePaths
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
ctx.Data["commit_summary"] = form.CommitSummary ctx.Data["commit_summary"] = f.CommitSummary
ctx.Data["commit_message"] = form.CommitMessage ctx.Data["commit_message"] = f.CommitMessage
ctx.Data["commit_choice"] = form.CommitChoice ctx.Data["commit_choice"] = f.CommitChoice
ctx.Data["new_branch_name"] = branchName ctx.Data["new_branch_name"] = branchName
if ctx.HasError() { if ctx.HasError() {
@ -453,7 +453,7 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
if oldBranchName != branchName { if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true ctx.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f)
return return
} }
} }
@ -475,38 +475,38 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
// User can only upload files to a directory. // User can only upload files to a directory.
if !entry.IsDir() { if !entry.IsDir() {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f)
return return
} }
} }
message := strings.TrimSpace(form.CommitSummary) message := strings.TrimSpace(f.CommitSummary)
if len(message) == 0 { if len(message) == 0 {
message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath) message = ctx.Tr("repo.editor.upload_files_to_dir", f.TreePath)
} }
form.CommitMessage = strings.TrimSpace(form.CommitMessage) f.CommitMessage = strings.TrimSpace(f.CommitMessage)
if len(form.CommitMessage) > 0 { if len(f.CommitMessage) > 0 {
message += "\n\n" + form.CommitMessage message += "\n\n" + f.CommitMessage
} }
if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{ if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{
LastCommitID: ctx.Repo.CommitID, LastCommitID: ctx.Repo.CommitID,
OldBranch: oldBranchName, OldBranch: oldBranchName,
NewBranch: branchName, NewBranch: branchName,
TreePath: form.TreePath, TreePath: f.TreePath,
Message: message, Message: message,
Files: form.Files, Files: f.Files,
}); err != nil { }); err != nil {
ctx.Data["Err_TreePath"] = true ctx.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), UPLOAD_FILE, &form) ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f)
return return
} }
if form.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { if form.IsNewBrnach() && ctx.Repo.PullRequest.Allowed {
ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, form.NewBranchName)) ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, form.NewBranchName))
} else { } else {
ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + form.TreePath) ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
} }
} }
@ -553,17 +553,17 @@ func UploadFileToServer(ctx *context.Context) {
}) })
} }
func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) { func RemoveUploadFileFromServer(ctx *context.Context, f form.RemoveUploadFile) {
if len(form.File) == 0 { if len(f.File) == 0 {
ctx.Status(204) ctx.Status(204)
return return
} }
if err := models.DeleteUploadByUUID(form.File); err != nil { if err := models.DeleteUploadByUUID(f.File); err != nil {
ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err)) ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
return return
} }
log.Trace("Upload file removed: %s", form.File) log.Trace("Upload file removed: %s", f.File)
ctx.Status(204) ctx.Status(204)
} }

86
routers/repo/issue.go

@ -19,9 +19,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/markdown" "github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -348,7 +348,7 @@ func NewIssue(ctx *context.Context) {
ctx.HTML(200, ISSUE_NEW) ctx.HTML(200, ISSUE_NEW)
} }
func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64, int64, int64) { func ValidateRepoMetas(ctx *context.Context, f form.CreateIssue) ([]int64, int64, int64) {
var ( var (
repo = ctx.Repo.Repository repo = ctx.Repo.Repository
err error err error
@ -364,7 +364,7 @@ func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64
} }
// Check labels. // Check labels.
labelIDs := base.StringsToInt64s(strings.Split(form.LabelIDs, ",")) labelIDs := base.StringsToInt64s(strings.Split(f.LabelIDs, ","))
labelIDMark := base.Int64sToMap(labelIDs) labelIDMark := base.Int64sToMap(labelIDs)
hasSelected := false hasSelected := false
for i := range labels { for i := range labels {
@ -374,11 +374,11 @@ func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64
} }
} }
ctx.Data["HasSelectedLabel"] = hasSelected ctx.Data["HasSelectedLabel"] = hasSelected
ctx.Data["label_ids"] = form.LabelIDs ctx.Data["label_ids"] = f.LabelIDs
ctx.Data["Labels"] = labels ctx.Data["Labels"] = labels
// Check milestone. // Check milestone.
milestoneID := form.MilestoneID milestoneID := f.MilestoneID
if milestoneID > 0 { if milestoneID > 0 {
ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID) ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
if err != nil { if err != nil {
@ -389,7 +389,7 @@ func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64
} }
// Check assignee. // Check assignee.
assigneeID := form.AssigneeID assigneeID := f.AssigneeID
if assigneeID > 0 { if assigneeID > 0 {
ctx.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID) ctx.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID)
if err != nil { if err != nil {
@ -402,7 +402,7 @@ func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64
return labelIDs, milestoneID, assigneeID return labelIDs, milestoneID, assigneeID
} }
func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { func NewIssuePost(ctx *context.Context, f form.CreateIssue) {
ctx.Data["Title"] = ctx.Tr("repo.issues.new") ctx.Data["Title"] = ctx.Tr("repo.issues.new")
ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsIssueList"] = true
ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireHighlightJS"] = true
@ -414,13 +414,13 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
attachments []string attachments []string
) )
labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form) labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f)
if ctx.Written() { if ctx.Written() {
return return
} }
if setting.AttachmentEnabled { if setting.AttachmentEnabled {
attachments = form.Files attachments = f.Files
} }
if ctx.HasError() { if ctx.HasError() {
@ -430,12 +430,12 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
issue := &models.Issue{ issue := &models.Issue{
RepoID: repo.ID, RepoID: repo.ID,
Title: form.Title, Title: f.Title,
PosterID: ctx.User.ID, PosterID: ctx.User.ID,
Poster: ctx.User, Poster: ctx.User,
MilestoneID: milestoneID, MilestoneID: milestoneID,
AssigneeID: assigneeID, AssigneeID: assigneeID,
Content: form.Content, Content: f.Content,
} }
if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil { if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil {
ctx.Handle(500, "NewIssue", err) ctx.Handle(500, "NewIssue", err)
@ -805,7 +805,7 @@ func UpdateIssueAssignee(ctx *context.Context) {
}) })
} }
func NewComment(ctx *context.Context, form auth.CreateCommentForm) { func NewComment(ctx *context.Context, f form.CreateComment) {
issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err) ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
@ -814,7 +814,7 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
var attachments []string var attachments []string
if setting.AttachmentEnabled { if setting.AttachmentEnabled {
attachments = form.Files attachments = f.Files
} }
if ctx.HasError() { if ctx.HasError() {
@ -827,13 +827,13 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
defer func() { defer func() {
// Check if issue admin/poster changes the status of issue. // Check if issue admin/poster changes the status of issue.
if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) && if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
(form.Status == "reopen" || form.Status == "close") && (f.Status == "reopen" || f.Status == "close") &&
!(issue.IsPull && issue.PullRequest.HasMerged) { !(issue.IsPull && issue.PullRequest.HasMerged) {
// Duplication and conflict check should apply to reopen pull request. // Duplication and conflict check should apply to reopen pull request.
var pr *models.PullRequest var pr *models.PullRequest
if form.Status == "reopen" && issue.IsPull { if f.Status == "reopen" && issue.IsPull {
pull := issue.PullRequest pull := issue.PullRequest
pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch) pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
if err != nil { if err != nil {
@ -857,7 +857,7 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
if pr != nil { if pr != nil {
ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index)) ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
} else { } else {
if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil { if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, f.Status == "close"); err != nil {
log.Error(4, "ChangeStatus: %v", err) log.Error(4, "ChangeStatus: %v", err)
} else { } else {
log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed) log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
@ -878,11 +878,11 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
}() }()
// Fix #321: Allow empty comments, as long as we have attachments. // Fix #321: Allow empty comments, as long as we have attachments.
if len(form.Content) == 0 && len(attachments) == 0 { if len(f.Content) == 0 && len(attachments) == 0 {
return return
} }
comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments) comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, f.Content, attachments)
if err != nil { if err != nil {
ctx.Handle(500, "CreateIssueComment", err) ctx.Handle(500, "CreateIssueComment", err)
return return
@ -955,14 +955,14 @@ func Labels(ctx *context.Context) {
ctx.HTML(200, LABELS) ctx.HTML(200, LABELS)
} }
func InitializeLabels(ctx *context.Context, form auth.InitializeLabelsForm) { func InitializeLabels(ctx *context.Context, f form.InitializeLabels) {
if ctx.HasError() { if ctx.HasError() {
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.Redirect(ctx.Repo.RepoLink + "/labels")
return return
} }
list, err := models.GetLabelTemplateFile(form.TemplateName) list, err := models.GetLabelTemplateFile(f.TemplateName)
if err != nil { if err != nil {
ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", form.TemplateName, err)) ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err))
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.Redirect(ctx.Repo.RepoLink + "/labels")
return return
} }
@ -982,7 +982,7 @@ func InitializeLabels(ctx *context.Context, form auth.InitializeLabelsForm) {
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.Redirect(ctx.Repo.RepoLink + "/labels")
} }
func NewLabel(ctx *context.Context, form auth.CreateLabelForm) { func NewLabel(ctx *context.Context, f form.CreateLabel) {
ctx.Data["Title"] = ctx.Tr("repo.labels") ctx.Data["Title"] = ctx.Tr("repo.labels")
ctx.Data["PageIsLabels"] = true ctx.Data["PageIsLabels"] = true
@ -994,8 +994,8 @@ func NewLabel(ctx *context.Context, form auth.CreateLabelForm) {
l := &models.Label{ l := &models.Label{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
Name: form.Title, Name: f.Title,
Color: form.Color, Color: f.Color,
} }
if err := models.NewLabels(l); err != nil { if err := models.NewLabels(l); err != nil {
ctx.Handle(500, "NewLabel", err) ctx.Handle(500, "NewLabel", err)
@ -1004,8 +1004,8 @@ func NewLabel(ctx *context.Context, form auth.CreateLabelForm) {
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.Redirect(ctx.Repo.RepoLink + "/labels")
} }
func UpdateLabel(ctx *context.Context, form auth.CreateLabelForm) { func UpdateLabel(ctx *context.Context, f form.CreateLabel) {
l, err := models.GetLabelByID(form.ID) l, err := models.GetLabelByID(f.ID)
if err != nil { if err != nil {
switch { switch {
case models.IsErrLabelNotExist(err): case models.IsErrLabelNotExist(err):
@ -1016,8 +1016,8 @@ func UpdateLabel(ctx *context.Context, form auth.CreateLabelForm) {
return return
} }
l.Name = form.Title l.Name = f.Title
l.Color = form.Color l.Color = f.Color
if err := models.UpdateLabel(l); err != nil { if err := models.UpdateLabel(l); err != nil {
ctx.Handle(500, "UpdateLabel", err) ctx.Handle(500, "UpdateLabel", err)
return return
@ -1090,7 +1090,7 @@ func NewMilestone(ctx *context.Context) {
ctx.HTML(200, MILESTONE_NEW) ctx.HTML(200, MILESTONE_NEW)
} }
func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { func NewMilestonePost(ctx *context.Context, f form.CreateMilestone) {
ctx.Data["Title"] = ctx.Tr("repo.milestones.new") ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsIssueList"] = true
ctx.Data["PageIsMilestones"] = true ctx.Data["PageIsMilestones"] = true
@ -1102,27 +1102,27 @@ func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
return return
} }
if len(form.Deadline) == 0 { if len(f.Deadline) == 0 {
form.Deadline = "9999-12-31" f.Deadline = "9999-12-31"
} }
deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
if err != nil { if err != nil {
ctx.Data["Err_Deadline"] = true ctx.Data["Err_Deadline"] = true
ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
return return
} }
if err = models.NewMilestone(&models.Milestone{ if err = models.NewMilestone(&models.Milestone{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
Name: form.Title, Name: f.Title,
Content: form.Content, Content: f.Content,
Deadline: deadline, Deadline: deadline,
}); err != nil { }); err != nil {
ctx.Handle(500, "NewMilestone", err) ctx.Handle(500, "NewMilestone", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title)) ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", f.Title))
ctx.Redirect(ctx.Repo.RepoLink + "/milestones") ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
} }
@ -1150,7 +1150,7 @@ func EditMilestone(ctx *context.Context) {
ctx.HTML(200, MILESTONE_NEW) ctx.HTML(200, MILESTONE_NEW)
} }
func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { func EditMilestonePost(ctx *context.Context, f form.CreateMilestone) {
ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
ctx.Data["PageIsMilestones"] = true ctx.Data["PageIsMilestones"] = true
ctx.Data["PageIsEditMilestone"] = true ctx.Data["PageIsEditMilestone"] = true
@ -1162,13 +1162,13 @@ func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
return return
} }
if len(form.Deadline) == 0 { if len(f.Deadline) == 0 {
form.Deadline = "9999-12-31" f.Deadline = "9999-12-31"
} }
deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
if err != nil { if err != nil {
ctx.Data["Err_Deadline"] = true ctx.Data["Err_Deadline"] = true
ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
return return
} }
@ -1181,8 +1181,8 @@ func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
} }
return return
} }
m.Name = form.Title m.Name = f.Title
m.Content = form.Content m.Content = f.Content
m.Deadline = deadline m.Deadline = deadline
if err = models.UpdateMilestone(m); err != nil { if err = models.UpdateMilestone(m); err != nil {
ctx.Handle(500, "UpdateMilestone", err) ctx.Handle(500, "UpdateMilestone", err)

28
routers/repo/pull.go

@ -15,9 +15,9 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -85,7 +85,7 @@ func Fork(ctx *context.Context) {
ctx.HTML(200, FORK) ctx.HTML(200, FORK)
} }
func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { func ForkPost(ctx *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_fork") ctx.Data["Title"] = ctx.Tr("new_fork")
forkRepo := getForkRepository(ctx) forkRepo := getForkRepository(ctx)
@ -93,7 +93,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) {
return return
} }
ctxUser := checkContextUser(ctx, form.Uid) ctxUser := checkContextUser(ctx, f.Uid)
if ctx.Written() { if ctx.Written() {
return return
} }
@ -120,20 +120,20 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) {
// Cannot fork to same owner // Cannot fork to same owner
if ctxUser.ID == forkRepo.OwnerID { if ctxUser.ID == forkRepo.OwnerID {
ctx.RenderWithErr(ctx.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &form) ctx.RenderWithErr(ctx.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f)
return return
} }
repo, err := models.ForkRepository(ctxUser, forkRepo, form.RepoName, form.Description) repo, err := models.ForkRepository(ctxUser, forkRepo, f.RepoName, f.Description)
if err != nil { if err != nil {
ctx.Data["Err_RepoName"] = true ctx.Data["Err_RepoName"] = true
switch { switch {
case models.IsErrRepoAlreadyExist(err): case models.IsErrRepoAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &form) ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &form) ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &form) ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f)
default: default:
ctx.Handle(500, "ForkPost", err) ctx.Handle(500, "ForkPost", err)
} }
@ -636,7 +636,7 @@ func CompareAndPullRequest(ctx *context.Context) {
ctx.HTML(200, COMPARE_PULL) ctx.HTML(200, COMPARE_PULL)
} }
func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) { func CompareAndPullRequestPost(ctx *context.Context, f form.CreateIssue) {
ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
ctx.Data["PageIsComparePull"] = true ctx.Data["PageIsComparePull"] = true
ctx.Data["IsDiffCompare"] = true ctx.Data["IsDiffCompare"] = true
@ -653,17 +653,17 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
return return
} }
labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form) labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f)
if ctx.Written() { if ctx.Written() {
return return
} }
if setting.AttachmentEnabled { if setting.AttachmentEnabled {
attachments = form.Files attachments = f.Files
} }
if ctx.HasError() { if ctx.HasError() {
auth.AssignForm(form, ctx.Data) form.Assign(f, ctx.Data)
// This stage is already stop creating new pull request, so it does not matter if it has // This stage is already stop creating new pull request, so it does not matter if it has
// something to compare or not. // something to compare or not.
@ -685,13 +685,13 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
pullIssue := &models.Issue{ pullIssue := &models.Issue{
RepoID: repo.ID, RepoID: repo.ID,
Index: repo.NextIssueIndex(), Index: repo.NextIssueIndex(),
Title: form.Title, Title: f.Title,
PosterID: ctx.User.ID, PosterID: ctx.User.ID,
Poster: ctx.User, Poster: ctx.User,
MilestoneID: milestoneID, MilestoneID: milestoneID,
AssigneeID: assigneeID, AssigneeID: assigneeID,
IsPull: true, IsPull: true,
Content: form.Content, Content: f.Content,
} }
pullRequest := &models.PullRequest{ pullRequest := &models.PullRequest{
HeadRepoID: headRepo.ID, HeadRepoID: headRepo.ID,

40
routers/repo/release.go

@ -10,9 +10,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/markdown" "github.com/gogits/gogs/modules/markdown"
) )
@ -150,7 +150,7 @@ func NewRelease(ctx *context.Context) {
ctx.HTML(200, RELEASE_NEW) ctx.HTML(200, RELEASE_NEW)
} }
func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) { func NewReleasePost(ctx *context.Context, f form.NewRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.new_release") ctx.Data["Title"] = ctx.Tr("repo.release.new_release")
ctx.Data["PageIsReleaseList"] = true ctx.Data["PageIsReleaseList"] = true
@ -159,13 +159,13 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
return return
} }
if !ctx.Repo.GitRepo.IsBranchExist(form.Target) { if !ctx.Repo.GitRepo.IsBranchExist(f.Target) {
ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &form) ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f)
return return
} }
var tagCreatedUnix int64 var tagCreatedUnix int64
tag, err := ctx.Repo.GitRepo.GetTag(form.TagName) tag, err := ctx.Repo.GitRepo.GetTag(f.TagName)
if err == nil { if err == nil {
commit, err := tag.Commit() commit, err := tag.Commit()
if err == nil { if err == nil {
@ -173,7 +173,7 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
} }
} }
commit, err := ctx.Repo.GitRepo.GetBranchCommit(form.Target) commit, err := ctx.Repo.GitRepo.GetBranchCommit(f.Target)
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) ctx.Handle(500, "GetBranchCommit", err)
return return
@ -188,14 +188,14 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
rel := &models.Release{ rel := &models.Release{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
PublisherID: ctx.User.ID, PublisherID: ctx.User.ID,
Title: form.Title, Title: f.Title,
TagName: form.TagName, TagName: f.TagName,
Target: form.Target, Target: f.Target,
Sha1: commit.ID.String(), Sha1: commit.ID.String(),
NumCommits: commitsCount, NumCommits: commitsCount,
Note: form.Content, Note: f.Content,
IsDraft: len(form.Draft) > 0, IsDraft: len(f.Draft) > 0,
IsPrerelease: form.Prerelease, IsPrerelease: f.Prerelease,
CreatedUnix: tagCreatedUnix, CreatedUnix: tagCreatedUnix,
} }
@ -203,15 +203,15 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
ctx.Data["Err_TagName"] = true ctx.Data["Err_TagName"] = true
switch { switch {
case models.IsErrReleaseAlreadyExist(err): case models.IsErrReleaseAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &form) ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &f)
case models.IsErrInvalidTagName(err): case models.IsErrInvalidTagName(err):
ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &form) ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &f)
default: default:
ctx.Handle(500, "CreateRelease", err) ctx.Handle(500, "CreateRelease", err)
} }
return return
} }
log.Trace("Release created: %s/%s:%s", ctx.User.LowerName, ctx.Repo.Repository.Name, form.TagName) log.Trace("Release created: %s/%s:%s", ctx.User.LowerName, ctx.Repo.Repository.Name, f.TagName)
ctx.Redirect(ctx.Repo.RepoLink + "/releases") ctx.Redirect(ctx.Repo.RepoLink + "/releases")
} }
@ -242,7 +242,7 @@ func EditRelease(ctx *context.Context) {
ctx.HTML(200, RELEASE_NEW) ctx.HTML(200, RELEASE_NEW)
} }
func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) { func EditReleasePost(ctx *context.Context, f form.EditRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") ctx.Data["Title"] = ctx.Tr("repo.release.edit_release")
ctx.Data["PageIsReleaseList"] = true ctx.Data["PageIsReleaseList"] = true
ctx.Data["PageIsEditRelease"] = true ctx.Data["PageIsEditRelease"] = true
@ -269,10 +269,10 @@ func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) {
return return
} }
rel.Title = form.Title rel.Title = f.Title
rel.Note = form.Content rel.Note = f.Content
rel.IsDraft = len(form.Draft) > 0 rel.IsDraft = len(f.Draft) > 0
rel.IsPrerelease = form.Prerelease rel.IsPrerelease = f.Prerelease
if err = models.UpdateRelease(ctx.Repo.GitRepo, rel); err != nil { if err = models.UpdateRelease(ctx.Repo.GitRepo, rel); err != nil {
ctx.Handle(500, "UpdateRelease", err) ctx.Handle(500, "UpdateRelease", err)
return return

52
routers/repo/repo.go

@ -16,9 +16,9 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -102,14 +102,14 @@ func handleCreateError(ctx *context.Context, owner *models.User, err error, name
} }
} }
func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { func CreatePost(ctx *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_repo") ctx.Data["Title"] = ctx.Tr("new_repo")
ctx.Data["Gitignores"] = models.Gitignores ctx.Data["Gitignores"] = models.Gitignores
ctx.Data["Licenses"] = models.Licenses ctx.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes ctx.Data["Readmes"] = models.Readmes
ctxUser := checkContextUser(ctx, form.Uid) ctxUser := checkContextUser(ctx, f.Uid)
if ctx.Written() { if ctx.Written() {
return return
} }
@ -121,13 +121,13 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
} }
repo, err := models.CreateRepository(ctxUser, models.CreateRepoOptions{ repo, err := models.CreateRepository(ctxUser, models.CreateRepoOptions{
Name: form.RepoName, Name: f.RepoName,
Description: form.Description, Description: f.Description,
Gitignores: form.Gitignores, Gitignores: f.Gitignores,
License: form.License, License: f.License,
Readme: form.Readme, Readme: f.Readme,
IsPrivate: form.Private || setting.Repository.ForcePrivate, IsPrivate: f.Private || setting.Repository.ForcePrivate,
AutoInit: form.AutoInit, AutoInit: f.AutoInit,
}) })
if err == nil { if err == nil {
log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
@ -141,7 +141,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
} }
} }
handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &form) handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &f)
} }
func Migrate(ctx *context.Context) { func Migrate(ctx *context.Context) {
@ -159,10 +159,10 @@ func Migrate(ctx *context.Context) {
ctx.HTML(200, MIGRATE) ctx.HTML(200, MIGRATE)
} }
func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { func MigratePost(ctx *context.Context, f form.MigrateRepo) {
ctx.Data["Title"] = ctx.Tr("new_migrate") ctx.Data["Title"] = ctx.Tr("new_migrate")
ctxUser := checkContextUser(ctx, form.Uid) ctxUser := checkContextUser(ctx, f.Uid)
if ctx.Written() { if ctx.Written() {
return return
} }
@ -173,18 +173,18 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) {
return return
} }
remoteAddr, err := form.ParseRemoteAddr(ctx.User) remoteAddr, err := f.ParseRemoteAddr(ctx.User)
if err != nil { if err != nil {
if models.IsErrInvalidCloneAddr(err) { if models.IsErrInvalidCloneAddr(err) {
ctx.Data["Err_CloneAddr"] = true ctx.Data["Err_CloneAddr"] = true
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
switch { switch {
case addrErr.IsURLError: case addrErr.IsURLError:
ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form) ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &f)
case addrErr.IsPermissionDenied: case addrErr.IsPermissionDenied:
ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &form) ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &f)
case addrErr.IsInvalidPath: case addrErr.IsInvalidPath:
ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form) ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
default: default:
ctx.Handle(500, "Unknown error", err) ctx.Handle(500, "Unknown error", err)
} }
@ -195,15 +195,15 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) {
} }
repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{ repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{
Name: form.RepoName, Name: f.RepoName,
Description: form.Description, Description: f.Description,
IsPrivate: form.Private || setting.Repository.ForcePrivate, IsPrivate: f.Private || setting.Repository.ForcePrivate,
IsMirror: form.Mirror, IsMirror: f.Mirror,
RemoteAddr: remoteAddr, RemoteAddr: remoteAddr,
}) })
if err == nil { if err == nil {
log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName) log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName)
ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName) ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + f.RepoName)
return return
} }
@ -216,15 +216,15 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) {
if strings.Contains(err.Error(), "Authentication failed") || if strings.Contains(err.Error(), "Authentication failed") ||
strings.Contains(err.Error(), "could not read Username") { strings.Contains(err.Error(), "could not read Username") {
ctx.Data["Err_Auth"] = true ctx.Data["Err_Auth"] = true
ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form) ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &f)
return return
} else if strings.Contains(err.Error(), "fatal:") { } else if strings.Contains(err.Error(), "fatal:") {
ctx.Data["Err_CloneAddr"] = true ctx.Data["Err_CloneAddr"] = true
ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form) ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &f)
return return
} }
handleCreateError(ctx, ctxUser, err, "MigratePost", MIGRATE, &form) handleCreateError(ctx, ctxUser, err, "MigratePost", MIGRATE, &f)
} }
func Action(ctx *context.Context) { func Action(ctx *context.Context) {

78
routers/repo/setting.go

@ -14,9 +14,9 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -37,7 +37,7 @@ func Settings(ctx *context.Context) {
ctx.HTML(200, SETTINGS_OPTIONS) ctx.HTML(200, SETTINGS_OPTIONS)
} }
func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { func SettingsPost(ctx *context.Context, f form.RepoSetting) {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true ctx.Data["PageIsSettingsOptions"] = true
@ -52,7 +52,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
isNameChanged := false isNameChanged := false
oldRepoName := repo.Name oldRepoName := repo.Name
newRepoName := form.RepoName newRepoName := f.RepoName
// Check if repository name has been changed. // Check if repository name has been changed.
if repo.LowerName != strings.ToLower(newRepoName) { if repo.LowerName != strings.ToLower(newRepoName) {
isNameChanged = true isNameChanged = true
@ -60,11 +60,11 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Data["Err_RepoName"] = true ctx.Data["Err_RepoName"] = true
switch { switch {
case models.IsErrRepoAlreadyExist(err): case models.IsErrRepoAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &form) ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &form) ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &form) ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &f)
default: default:
ctx.Handle(500, "ChangeRepositoryName", err) ctx.Handle(500, "ChangeRepositoryName", err)
} }
@ -77,16 +77,16 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
repo.Name = newRepoName repo.Name = newRepoName
repo.LowerName = strings.ToLower(newRepoName) repo.LowerName = strings.ToLower(newRepoName)
repo.Description = form.Description repo.Description = f.Description
repo.Website = form.Website repo.Website = f.Website
// Visibility of forked repository is forced sync with base repository. // Visibility of forked repository is forced sync with base repository.
if repo.IsFork { if repo.IsFork {
form.Private = repo.BaseRepo.IsPrivate f.Private = repo.BaseRepo.IsPrivate
} }
visibilityChanged := repo.IsPrivate != form.Private visibilityChanged := repo.IsPrivate != f.Private
repo.IsPrivate = form.Private repo.IsPrivate = f.Private
if err := models.UpdateRepository(repo, visibilityChanged); err != nil { if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.Handle(500, "UpdateRepository", err) ctx.Handle(500, "UpdateRepository", err)
return return
@ -108,16 +108,16 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
return return
} }
if form.Interval > 0 { if f.Interval > 0 {
ctx.Repo.Mirror.EnablePrune = form.EnablePrune ctx.Repo.Mirror.EnablePrune = f.EnablePrune
ctx.Repo.Mirror.Interval = form.Interval ctx.Repo.Mirror.Interval = f.Interval
ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(form.Interval) * time.Hour) ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(f.Interval) * time.Hour)
if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
ctx.Handle(500, "UpdateMirror", err) ctx.Handle(500, "UpdateMirror", err)
return return
} }
} }
if err := ctx.Repo.Mirror.SaveAddress(form.MirrorAddress); err != nil { if err := ctx.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil {
ctx.Handle(500, "SaveAddress", err) ctx.Handle(500, "SaveAddress", err)
return return
} }
@ -136,15 +136,15 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Redirect(repo.Link() + "/settings") ctx.Redirect(repo.Link() + "/settings")
case "advanced": case "advanced":
repo.EnableWiki = form.EnableWiki repo.EnableWiki = f.EnableWiki
repo.EnableExternalWiki = form.EnableExternalWiki repo.EnableExternalWiki = f.EnableExternalWiki
repo.ExternalWikiURL = form.ExternalWikiURL repo.ExternalWikiURL = f.ExternalWikiURL
repo.EnableIssues = form.EnableIssues repo.EnableIssues = f.EnableIssues
repo.EnableExternalTracker = form.EnableExternalTracker repo.EnableExternalTracker = f.EnableExternalTracker
repo.ExternalTrackerURL = form.ExternalTrackerURL repo.ExternalTrackerURL = f.ExternalTrackerURL
repo.ExternalTrackerFormat = form.TrackerURLFormat repo.ExternalTrackerFormat = f.TrackerURLFormat
repo.ExternalTrackerStyle = form.TrackerIssueStyle repo.ExternalTrackerStyle = f.TrackerIssueStyle
repo.EnablePulls = form.EnablePulls repo.EnablePulls = f.EnablePulls
if err := models.UpdateRepository(repo, false); err != nil { if err := models.UpdateRepository(repo, false); err != nil {
ctx.Handle(500, "UpdateRepository", err) ctx.Handle(500, "UpdateRepository", err)
@ -160,7 +160,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Error(404) ctx.Error(404)
return return
} }
if repo.Name != form.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
@ -194,7 +194,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Error(404) ctx.Error(404)
return return
} }
if repo.Name != form.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
@ -233,7 +233,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Error(404) ctx.Error(404)
return return
} }
if repo.Name != form.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
@ -259,7 +259,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
ctx.Error(404) ctx.Error(404)
return return
} }
if repo.Name != form.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
@ -444,7 +444,7 @@ func SettingsProtectedBranch(ctx *context.Context) {
ctx.HTML(200, SETTINGS_PROTECTED_BRANCH) ctx.HTML(200, SETTINGS_PROTECTED_BRANCH)
} }
func SettingsProtectedBranchPost(ctx *context.Context, form auth.ProtectBranchForm) { func SettingsProtectedBranchPost(ctx *context.Context, f form.ProtectBranch) {
branch := ctx.Params("*") branch := ctx.Params("*")
if !ctx.Repo.GitRepo.IsBranchExist(branch) { if !ctx.Repo.GitRepo.IsBranchExist(branch) {
ctx.NotFound() ctx.NotFound()
@ -465,11 +465,11 @@ func SettingsProtectedBranchPost(ctx *context.Context, form auth.ProtectBranchFo
} }
} }
protectBranch.Protected = form.Protected protectBranch.Protected = f.Protected
protectBranch.RequirePullRequest = form.RequirePullRequest protectBranch.RequirePullRequest = f.RequirePullRequest
protectBranch.EnableWhitelist = form.EnableWhitelist protectBranch.EnableWhitelist = f.EnableWhitelist
if ctx.Repo.Owner.IsOrganization() { if ctx.Repo.Owner.IsOrganization() {
err = models.UpdateOrgProtectBranch(ctx.Repo.Repository, protectBranch, form.WhitelistUsers, form.WhitelistTeams) err = models.UpdateOrgProtectBranch(ctx.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams)
} else { } else {
err = models.UpdateProtectBranch(protectBranch) err = models.UpdateProtectBranch(protectBranch)
} }
@ -547,7 +547,7 @@ func SettingsDeployKeys(ctx *context.Context) {
ctx.HTML(200, SETTINGS_DEPLOY_KEYS) ctx.HTML(200, SETTINGS_DEPLOY_KEYS)
} }
func SettingsDeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { func SettingsDeployKeysPost(ctx *context.Context, f form.AddSSHKey) {
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
ctx.Data["PageIsSettingsKeys"] = true ctx.Data["PageIsSettingsKeys"] = true
@ -563,7 +563,7 @@ func SettingsDeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
return return
} }
content, err := models.CheckPublicKeyString(form.Content) content, err := models.CheckPublicKeyString(f.Content)
if err != nil { if err != nil {
if models.IsErrKeyUnableVerify(err) { if models.IsErrKeyUnableVerify(err) {
ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
@ -576,16 +576,16 @@ func SettingsDeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
} }
} }
key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content) key, err := models.AddDeployKey(ctx.Repo.Repository.ID, f.Title, content)
if err != nil { if err != nil {
ctx.Data["HasError"] = true ctx.Data["HasError"] = true
switch { switch {
case models.IsErrKeyAlreadyExist(err): case models.IsErrKeyAlreadyExist(err):
ctx.Data["Err_Content"] = true ctx.Data["Err_Content"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &form) ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f)
case models.IsErrKeyNameAlreadyUsed(err): case models.IsErrKeyNameAlreadyUsed(err):
ctx.Data["Err_Title"] = true ctx.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &form) ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f)
default: default:
ctx.Handle(500, "AddDeployKey", err) ctx.Handle(500, "AddDeployKey", err)
} }

100
routers/repo/webhook.go

@ -16,9 +16,9 @@ import (
api "github.com/gogits/go-gogs-client" api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -103,20 +103,20 @@ func WebhooksNew(ctx *context.Context) {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(200, orCtx.NewTemplate)
} }
func ParseHookEvent(form auth.WebhookForm) *models.HookEvent { func ParseHookEvent(f form.Webhook) *models.HookEvent {
return &models.HookEvent{ return &models.HookEvent{
PushOnly: form.PushOnly(), PushOnly: f.PushOnly(),
SendEverything: form.SendEverything(), SendEverything: f.SendEverything(),
ChooseEvents: form.ChooseEvents(), ChooseEvents: f.ChooseEvents(),
HookEvents: models.HookEvents{ HookEvents: models.HookEvents{
Create: form.Create, Create: f.Create,
Push: form.Push, Push: f.Push,
PullRequest: form.PullRequest, PullRequest: f.PullRequest,
}, },
} }
} }
func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { func WebHooksNewPost(ctx *context.Context, f form.NewWebhook) {
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["PageIsSettingsHooksNew"] = true
@ -136,17 +136,17 @@ func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) {
} }
contentType := models.JSON contentType := models.JSON
if models.HookContentType(form.ContentType) == models.FORM { if models.HookContentType(f.ContentType) == models.FORM {
contentType = models.FORM contentType = models.FORM
} }
w := &models.Webhook{ w := &models.Webhook{
RepoID: orCtx.RepoID, RepoID: orCtx.RepoID,
URL: form.PayloadURL, URL: f.PayloadURL,
ContentType: contentType, ContentType: contentType,
Secret: form.Secret, Secret: f.Secret,
HookEvent: ParseHookEvent(form.WebhookForm), HookEvent: ParseHookEvent(f.Webhook),
IsActive: form.Active, IsActive: f.Active,
HookTaskType: models.GOGS, HookTaskType: models.GOGS,
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
} }
@ -162,7 +162,7 @@ func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) {
ctx.Redirect(orCtx.Link + "/settings/hooks") ctx.Redirect(orCtx.Link + "/settings/hooks")
} }
func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) { func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["PageIsSettingsHooksNew"] = true
@ -180,10 +180,10 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) {
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
Channel: form.Channel, Channel: f.Channel,
Username: form.Username, Username: f.Username,
IconURL: form.IconURL, IconURL: f.IconURL,
Color: form.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) ctx.Handle(500, "Marshal", err)
@ -192,10 +192,10 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) {
w := &models.Webhook{ w := &models.Webhook{
RepoID: orCtx.RepoID, RepoID: orCtx.RepoID,
URL: form.PayloadURL, URL: f.PayloadURL,
ContentType: models.JSON, ContentType: models.JSON,
HookEvent: ParseHookEvent(form.WebhookForm), HookEvent: ParseHookEvent(f.Webhook),
IsActive: form.Active, IsActive: f.Active,
HookTaskType: models.SLACK, HookTaskType: models.SLACK,
Meta: string(meta), Meta: string(meta),
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
@ -213,7 +213,7 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) {
} }
// FIXME: merge logic to Slack // FIXME: merge logic to Slack
func DiscordHooksNewPost(ctx *context.Context, form auth.NewDiscordHookForm) { func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["PageIsSettingsHooksNew"] = true
@ -231,9 +231,9 @@ func DiscordHooksNewPost(ctx *context.Context, form auth.NewDiscordHookForm) {
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
Username: form.Username, Username: f.Username,
IconURL: form.IconURL, IconURL: f.IconURL,
Color: form.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) ctx.Handle(500, "Marshal", err)
@ -242,10 +242,10 @@ func DiscordHooksNewPost(ctx *context.Context, form auth.NewDiscordHookForm) {
w := &models.Webhook{ w := &models.Webhook{
RepoID: orCtx.RepoID, RepoID: orCtx.RepoID,
URL: form.PayloadURL, URL: f.PayloadURL,
ContentType: models.JSON, ContentType: models.JSON,
HookEvent: ParseHookEvent(form.WebhookForm), HookEvent: ParseHookEvent(f.Webhook),
IsActive: form.Active, IsActive: f.Active,
HookTaskType: models.DISCORD, HookTaskType: models.DISCORD,
Meta: string(meta), Meta: string(meta),
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
@ -319,7 +319,7 @@ func WebHooksEdit(ctx *context.Context) {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(200, orCtx.NewTemplate)
} }
func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) { func WebHooksEditPost(ctx *context.Context, f form.NewWebhook) {
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
@ -336,15 +336,15 @@ func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) {
} }
contentType := models.JSON contentType := models.JSON
if models.HookContentType(form.ContentType) == models.FORM { if models.HookContentType(f.ContentType) == models.FORM {
contentType = models.FORM contentType = models.FORM
} }
w.URL = form.PayloadURL w.URL = f.PayloadURL
w.ContentType = contentType w.ContentType = contentType
w.Secret = form.Secret w.Secret = f.Secret
w.HookEvent = ParseHookEvent(form.WebhookForm) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = form.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) ctx.Handle(500, "UpdateEvent", err)
return return
@ -357,7 +357,7 @@ func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) {
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
} }
func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) { func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
@ -374,20 +374,20 @@ func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) {
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
Channel: form.Channel, Channel: f.Channel,
Username: form.Username, Username: f.Username,
IconURL: form.IconURL, IconURL: f.IconURL,
Color: form.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) ctx.Handle(500, "Marshal", err)
return return
} }
w.URL = form.PayloadURL w.URL = f.PayloadURL
w.Meta = string(meta) w.Meta = string(meta)
w.HookEvent = ParseHookEvent(form.WebhookForm) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = form.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) ctx.Handle(500, "UpdateEvent", err)
return return
@ -401,7 +401,7 @@ func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) {
} }
// FIXME: merge logic to Slack // FIXME: merge logic to Slack
func DiscordHooksEditPost(ctx *context.Context, form auth.NewDiscordHookForm) { func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
@ -418,19 +418,19 @@ func DiscordHooksEditPost(ctx *context.Context, form auth.NewDiscordHookForm) {
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
Username: form.Username, Username: f.Username,
IconURL: form.IconURL, IconURL: f.IconURL,
Color: form.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) ctx.Handle(500, "Marshal", err)
return return
} }
w.URL = form.PayloadURL w.URL = f.PayloadURL
w.Meta = string(meta) w.Meta = string(meta)
w.HookEvent = ParseHookEvent(form.WebhookForm) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = form.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) ctx.Handle(500, "UpdateEvent", err)
return return

16
routers/repo/wiki.go

@ -12,9 +12,9 @@ import (
"github.com/gogits/git-module" "github.com/gogits/git-module"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/markdown" "github.com/gogits/gogs/modules/markdown"
) )
@ -198,7 +198,7 @@ func NewWiki(ctx *context.Context) {
ctx.HTML(200, WIKI_NEW) ctx.HTML(200, WIKI_NEW)
} }
func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) { func NewWikiPost(ctx *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true ctx.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true ctx.Data["RequireSimpleMDE"] = true
@ -208,17 +208,17 @@ func NewWikiPost(ctx *context.Context, form auth.NewWikiForm) {
return return
} }
if err := ctx.Repo.Repository.AddWikiPage(ctx.User, form.Title, form.Content, form.Message); err != nil { if err := ctx.Repo.Repository.AddWikiPage(ctx.User, f.Title, f.Content, f.Message); err != nil {
if models.IsErrWikiAlreadyExist(err) { if models.IsErrWikiAlreadyExist(err) {
ctx.Data["Err_Title"] = true ctx.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &form) ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f)
} else { } else {
ctx.Handle(500, "AddWikiPage", err) ctx.Handle(500, "AddWikiPage", err)
} }
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(form.Title))) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title)))
} }
func EditWiki(ctx *context.Context) { func EditWiki(ctx *context.Context) {
@ -239,7 +239,7 @@ func EditWiki(ctx *context.Context) {
ctx.HTML(200, WIKI_NEW) ctx.HTML(200, WIKI_NEW)
} }
func EditWikiPost(ctx *context.Context, form auth.NewWikiForm) { func EditWikiPost(ctx *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true ctx.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true ctx.Data["RequireSimpleMDE"] = true
@ -249,12 +249,12 @@ func EditWikiPost(ctx *context.Context, form auth.NewWikiForm) {
return return
} }
if err := ctx.Repo.Repository.EditWikiPage(ctx.User, form.OldTitle, form.Title, form.Content, form.Message); err != nil { if err := ctx.Repo.Repository.EditWikiPage(ctx.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil {
ctx.Handle(500, "EditWikiPage", err) ctx.Handle(500, "EditWikiPage", err)
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(form.Title))) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title)))
} }
func DeleteWikiPagePost(ctx *context.Context) { func DeleteWikiPagePost(ctx *context.Context) {

32
routers/user/auth.go

@ -12,9 +12,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -103,7 +103,7 @@ func SignIn(ctx *context.Context) {
ctx.HTML(200, SIGNIN) ctx.HTML(200, SIGNIN)
} }
func SignInPost(ctx *context.Context, form auth.SignInForm) { func SignInPost(ctx *context.Context, f form.SignIn) {
ctx.Data["Title"] = ctx.Tr("sign_in") ctx.Data["Title"] = ctx.Tr("sign_in")
if ctx.HasError() { if ctx.HasError() {
@ -111,17 +111,17 @@ func SignInPost(ctx *context.Context, form auth.SignInForm) {
return return
} }
u, err := models.UserSignIn(form.UserName, form.Password) u, err := models.UserSignIn(f.UserName, f.Password)
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &form) ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &f)
} else { } else {
ctx.Handle(500, "UserSignIn", err) ctx.Handle(500, "UserSignIn", err)
} }
return return
} }
if form.Remember { if f.Remember {
days := 86400 * setting.LogInRememberDays days := 86400 * setting.LogInRememberDays
ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true) ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true)
ctx.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true) ctx.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubUrl, "", setting.CookieSecure, true)
@ -169,7 +169,7 @@ func SignUp(ctx *context.Context) {
ctx.HTML(200, SIGNUP) ctx.HTML(200, SIGNUP)
} }
func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) { func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
ctx.Data["Title"] = ctx.Tr("sign_up") ctx.Data["Title"] = ctx.Tr("sign_up")
ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
@ -186,36 +186,36 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterFo
if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) { if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
ctx.Data["Err_Captcha"] = true ctx.Data["Err_Captcha"] = true
ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &f)
return return
} }
if form.Password != form.Retype { if f.Password != f.Retype {
ctx.Data["Err_Password"] = true ctx.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &f)
return return
} }
u := &models.User{ u := &models.User{
Name: form.UserName, Name: f.UserName,
Email: form.Email, Email: f.Email,
Passwd: form.Password, Passwd: f.Password,
IsActive: !setting.Service.RegisterEmailConfirm, IsActive: !setting.Service.RegisterEmailConfirm,
} }
if err := models.CreateUser(u); err != nil { if err := models.CreateUser(u); err != nil {
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &f)
case models.IsErrEmailAlreadyUsed(err): case models.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &form) ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
default: default:
ctx.Handle(500, "CreateUser", err) ctx.Handle(500, "CreateUser", err)
} }

62
routers/user/setting.go

@ -14,9 +14,9 @@ import (
log "gopkg.in/clog.v1" log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/form"
"github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
) )
@ -76,7 +76,7 @@ func handleUsernameChange(ctx *context.Context, newName string) {
ctx.User.LowerName = strings.ToLower(newName) ctx.User.LowerName = strings.ToLower(newName)
} }
func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) { func SettingsPost(ctx *context.Context, f form.UpdateProfile) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsProfile"] = true ctx.Data["PageIsSettingsProfile"] = true
@ -85,15 +85,15 @@ func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
return return
} }
handleUsernameChange(ctx, form.Name) handleUsernameChange(ctx, f.Name)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.User.FullName = form.FullName ctx.User.FullName = f.FullName
ctx.User.Email = form.Email ctx.User.Email = f.Email
ctx.User.Website = form.Website ctx.User.Website = f.Website
ctx.User.Location = form.Location ctx.User.Location = f.Location
if err := models.UpdateUser(ctx.User); err != nil { if err := models.UpdateUser(ctx.User); err != nil {
ctx.Handle(500, "UpdateUser", err) ctx.Handle(500, "UpdateUser", err)
return return
@ -105,15 +105,15 @@ func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
} }
// FIXME: limit size. // FIXME: limit size.
func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error { func UpdateAvatarSetting(ctx *context.Context, f form.Avatar, ctxUser *models.User) error {
ctxUser.UseCustomAvatar = form.Source == auth.AVATAR_LOCAL ctxUser.UseCustomAvatar = f.Source == form.AVATAR_LOCAL
if len(form.Gravatar) > 0 { if len(f.Gravatar) > 0 {
ctxUser.Avatar = base.EncodeMD5(form.Gravatar) ctxUser.Avatar = base.EncodeMD5(f.Gravatar)
ctxUser.AvatarEmail = form.Gravatar ctxUser.AvatarEmail = f.Gravatar
} }
if form.Avatar != nil { if f.Avatar != nil {
fr, err := form.Avatar.Open() fr, err := f.Avatar.Open()
if err != nil { if err != nil {
return fmt.Errorf("Avatar.Open: %v", err) return fmt.Errorf("Avatar.Open: %v", err)
} }
@ -152,8 +152,8 @@ func SettingsAvatar(ctx *context.Context) {
ctx.HTML(200, SETTINGS_AVATAR) ctx.HTML(200, SETTINGS_AVATAR)
} }
func SettingsAvatarPost(ctx *context.Context, form auth.AvatarForm) { func SettingsAvatarPost(ctx *context.Context, f form.Avatar) {
if err := UpdateAvatarSetting(ctx, form, ctx.User); err != nil { if err := UpdateAvatarSetting(ctx, f, ctx.User); err != nil {
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("settings.update_avatar_success")) ctx.Flash.Success(ctx.Tr("settings.update_avatar_success"))
@ -176,7 +176,7 @@ func SettingsPassword(ctx *context.Context) {
ctx.HTML(200, SETTINGS_PASSWORD) ctx.HTML(200, SETTINGS_PASSWORD)
} }
func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) { func SettingsPasswordPost(ctx *context.Context, f form.ChangePassword) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsPassword"] = true ctx.Data["PageIsSettingsPassword"] = true
@ -185,12 +185,12 @@ func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) {
return return
} }
if !ctx.User.ValidatePassword(form.OldPassword) { if !ctx.User.ValidatePassword(f.OldPassword) {
ctx.Flash.Error(ctx.Tr("settings.password_incorrect")) ctx.Flash.Error(ctx.Tr("settings.password_incorrect"))
} else if form.Password != form.Retype { } else if f.Password != f.Retype {
ctx.Flash.Error(ctx.Tr("form.password_not_match")) ctx.Flash.Error(ctx.Tr("form.password_not_match"))
} else { } else {
ctx.User.Passwd = form.Password ctx.User.Passwd = f.Password
var err error var err error
if ctx.User.Salt, err = models.GetUserSalt(); err != nil { if ctx.User.Salt, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) ctx.Handle(500, "UpdateUser", err)
@ -222,7 +222,7 @@ func SettingsEmails(ctx *context.Context) {
ctx.HTML(200, SETTINGS_EMAILS) ctx.HTML(200, SETTINGS_EMAILS)
} }
func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) { func SettingsEmailPost(ctx *context.Context, f form.AddEmail) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsEmails"] = true ctx.Data["PageIsSettingsEmails"] = true
@ -253,12 +253,12 @@ func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) {
email := &models.EmailAddress{ email := &models.EmailAddress{
UID: ctx.User.ID, UID: ctx.User.ID,
Email: form.Email, Email: f.Email,
IsActivated: !setting.Service.RegisterEmailConfirm, IsActivated: !setting.Service.RegisterEmailConfirm,
} }
if err := models.AddEmailAddress(email); err != nil { if err := models.AddEmailAddress(email); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_EMAILS, &form) ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SETTINGS_EMAILS, &f)
return return
} }
ctx.Handle(500, "AddEmailAddress", err) ctx.Handle(500, "AddEmailAddress", err)
@ -311,7 +311,7 @@ func SettingsSSHKeys(ctx *context.Context) {
ctx.HTML(200, SETTINGS_SSH_KEYS) ctx.HTML(200, SETTINGS_SSH_KEYS)
} }
func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { func SettingsSSHKeysPost(ctx *context.Context, f form.AddSSHKey) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsSSHKeys"] = true ctx.Data["PageIsSettingsSSHKeys"] = true
@ -327,7 +327,7 @@ func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
return return
} }
content, err := models.CheckPublicKeyString(form.Content) content, err := models.CheckPublicKeyString(f.Content)
if err != nil { if err != nil {
if models.IsErrKeyUnableVerify(err) { if models.IsErrKeyUnableVerify(err) {
ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
@ -338,22 +338,22 @@ func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) {
} }
} }
if _, err = models.AddPublicKey(ctx.User.ID, form.Title, content); err != nil { if _, err = models.AddPublicKey(ctx.User.ID, f.Title, content); err != nil {
ctx.Data["HasError"] = true ctx.Data["HasError"] = true
switch { switch {
case models.IsErrKeyAlreadyExist(err): case models.IsErrKeyAlreadyExist(err):
ctx.Data["Err_Content"] = true ctx.Data["Err_Content"] = true
ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &form) ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &f)
case models.IsErrKeyNameAlreadyUsed(err): case models.IsErrKeyNameAlreadyUsed(err):
ctx.Data["Err_Title"] = true ctx.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &form) ctx.RenderWithErr(ctx.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &f)
default: default:
ctx.Handle(500, "AddPublicKey", err) ctx.Handle(500, "AddPublicKey", err)
} }
return return
} }
ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title)) ctx.Flash.Success(ctx.Tr("settings.add_key_success", f.Title))
ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh") ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh")
} }
@ -383,7 +383,7 @@ func SettingsApplications(ctx *context.Context) {
ctx.HTML(200, SETTINGS_APPLICATIONS) ctx.HTML(200, SETTINGS_APPLICATIONS)
} }
func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm) { func SettingsApplicationsPost(ctx *context.Context, f form.NewAccessToken) {
ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["Title"] = ctx.Tr("settings")
ctx.Data["PageIsSettingsApplications"] = true ctx.Data["PageIsSettingsApplications"] = true
@ -400,7 +400,7 @@ func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm
t := &models.AccessToken{ t := &models.AccessToken{
UID: ctx.User.ID, UID: ctx.User.ID,
Name: form.Name, Name: f.Name,
} }
if err := models.NewAccessToken(t); err != nil { if err := models.NewAccessToken(t); err != nil {
ctx.Handle(500, "NewAccessToken", err) ctx.Handle(500, "NewAccessToken", err)

Loading…
Cancel
Save