You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

730 lines
28 KiB

Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package routes
  5. import (
  6. "os"
  7. "path"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/auth"
  10. "code.gitea.io/gitea/modules/context"
  11. "code.gitea.io/gitea/modules/lfs"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/options"
  14. "code.gitea.io/gitea/modules/public"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/templates"
  17. "code.gitea.io/gitea/modules/validation"
  18. "code.gitea.io/gitea/routers"
  19. "code.gitea.io/gitea/routers/admin"
  20. apiv1 "code.gitea.io/gitea/routers/api/v1"
  21. "code.gitea.io/gitea/routers/dev"
  22. "code.gitea.io/gitea/routers/org"
  23. "code.gitea.io/gitea/routers/private"
  24. "code.gitea.io/gitea/routers/repo"
  25. "code.gitea.io/gitea/routers/user"
  26. "github.com/go-macaron/binding"
  27. "github.com/go-macaron/cache"
  28. "github.com/go-macaron/captcha"
  29. "github.com/go-macaron/csrf"
  30. "github.com/go-macaron/gzip"
  31. "github.com/go-macaron/i18n"
  32. "github.com/go-macaron/session"
  33. "github.com/go-macaron/toolbox"
  34. "gopkg.in/macaron.v1"
  35. )
  36. // NewMacaron initializes Macaron instance.
  37. func NewMacaron() *macaron.Macaron {
  38. m := macaron.New()
  39. if !setting.DisableRouterLog {
  40. m.Use(macaron.Logger())
  41. }
  42. m.Use(macaron.Recovery())
  43. if setting.EnableGzip {
  44. m.Use(gzip.Gziper())
  45. }
  46. if setting.Protocol == setting.FCGI {
  47. m.SetURLPrefix(setting.AppSubURL)
  48. }
  49. m.Use(public.Custom(
  50. &public.Options{
  51. SkipLogging: setting.DisableRouterLog,
  52. },
  53. ))
  54. m.Use(public.Static(
  55. &public.Options{
  56. Directory: path.Join(setting.StaticRootPath, "public"),
  57. SkipLogging: setting.DisableRouterLog,
  58. },
  59. ))
  60. m.Use(macaron.Static(
  61. setting.AvatarUploadPath,
  62. macaron.StaticOptions{
  63. Prefix: "avatars",
  64. SkipLogging: setting.DisableRouterLog,
  65. ETag: true,
  66. },
  67. ))
  68. m.Use(templates.Renderer())
  69. models.InitMailRender(templates.Mailer())
  70. localeNames, err := options.Dir("locale")
  71. if err != nil {
  72. log.Fatal(4, "Failed to list locale files: %v", err)
  73. }
  74. localFiles := make(map[string][]byte)
  75. for _, name := range localeNames {
  76. localFiles[name], err = options.Locale(name)
  77. if err != nil {
  78. log.Fatal(4, "Failed to load %s locale file. %v", name, err)
  79. }
  80. }
  81. m.Use(i18n.I18n(i18n.Options{
  82. SubURL: setting.AppSubURL,
  83. Files: localFiles,
  84. Langs: setting.Langs,
  85. Names: setting.Names,
  86. DefaultLang: "en-US",
  87. Redirect: true,
  88. }))
  89. m.Use(cache.Cacher(cache.Options{
  90. Adapter: setting.CacheService.Adapter,
  91. AdapterConfig: setting.CacheService.Conn,
  92. Interval: setting.CacheService.Interval,
  93. }))
  94. m.Use(captcha.Captchaer(captcha.Options{
  95. SubURL: setting.AppSubURL,
  96. }))
  97. m.Use(session.Sessioner(setting.SessionConfig))
  98. m.Use(csrf.Csrfer(csrf.Options{
  99. Secret: setting.SecretKey,
  100. Cookie: setting.CSRFCookieName,
  101. SetCookie: true,
  102. Header: "X-Csrf-Token",
  103. CookiePath: setting.AppSubURL,
  104. }))
  105. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  106. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  107. {
  108. Desc: "Database connection",
  109. Func: models.Ping,
  110. },
  111. },
  112. }))
  113. m.Use(context.Contexter())
  114. return m
  115. }
  116. // RegisterRoutes routes routes to Macaron
  117. func RegisterRoutes(m *macaron.Macaron) {
  118. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  119. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  120. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  121. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  122. bindIgnErr := binding.BindIgnErr
  123. validation.AddBindingRules()
  124. openIDSignInEnabled := func(ctx *context.Context) {
  125. if !setting.Service.EnableOpenIDSignIn {
  126. ctx.Error(403)
  127. return
  128. }
  129. }
  130. openIDSignUpEnabled := func(ctx *context.Context) {
  131. if !setting.Service.EnableOpenIDSignUp {
  132. ctx.Error(403)
  133. return
  134. }
  135. }
  136. m.Use(user.GetNotificationCount)
  137. // FIXME: not all routes need go through same middlewares.
  138. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  139. // Routers.
  140. // for health check
  141. m.Head("/", func() string {
  142. return ""
  143. })
  144. m.Get("/", ignSignIn, routers.Home)
  145. m.Group("/explore", func() {
  146. m.Get("", func(ctx *context.Context) {
  147. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  148. })
  149. m.Get("/repos", routers.ExploreRepos)
  150. m.Get("/users", routers.ExploreUsers)
  151. m.Get("/organizations", routers.ExploreOrganizations)
  152. }, ignSignIn)
  153. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  154. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  155. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  156. // ***** START: User *****
  157. m.Group("/user", func() {
  158. m.Get("/login", user.SignIn)
  159. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  160. m.Group("", func() {
  161. m.Combo("/login/openid").
  162. Get(user.SignInOpenID).
  163. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  164. }, openIDSignInEnabled)
  165. m.Group("/openid", func() {
  166. m.Combo("/connect").
  167. Get(user.ConnectOpenID).
  168. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  169. m.Group("/register", func() {
  170. m.Combo("").
  171. Get(user.RegisterOpenID, openIDSignUpEnabled).
  172. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  173. }, openIDSignUpEnabled)
  174. }, openIDSignInEnabled)
  175. m.Get("/sign_up", user.SignUp)
  176. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  177. m.Get("/reset_password", user.ResetPasswd)
  178. m.Post("/reset_password", user.ResetPasswdPost)
  179. m.Group("/oauth2", func() {
  180. m.Get("/:provider", user.SignInOAuth)
  181. m.Get("/:provider/callback", user.SignInOAuthCallback)
  182. })
  183. m.Get("/link_account", user.LinkAccount)
  184. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  185. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  186. m.Group("/two_factor", func() {
  187. m.Get("", user.TwoFactor)
  188. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  189. m.Get("/scratch", user.TwoFactorScratch)
  190. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  191. })
  192. }, reqSignOut)
  193. m.Group("/user/settings", func() {
  194. m.Get("", user.Settings)
  195. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  196. m.Combo("/avatar").Get(user.SettingsAvatar).
  197. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  198. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  199. m.Combo("/email").Get(user.SettingsEmails).
  200. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  201. m.Post("/email/delete", user.DeleteEmail)
  202. m.Get("/security", user.SettingsSecurity)
  203. m.Post("/security", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsSecurityPost)
  204. m.Group("/openid", func() {
  205. m.Combo("").Get(user.SettingsOpenID).
  206. Post(bindIgnErr(auth.AddOpenIDForm{}), user.SettingsOpenIDPost)
  207. m.Post("/delete", user.DeleteOpenID)
  208. m.Post("/toggle_visibility", user.ToggleOpenIDVisibility)
  209. }, openIDSignInEnabled)
  210. m.Combo("/keys").Get(user.SettingsKeys).
  211. Post(bindIgnErr(auth.AddKeyForm{}), user.SettingsKeysPost)
  212. m.Post("/keys/delete", user.DeleteKey)
  213. m.Combo("/applications").Get(user.SettingsApplications).
  214. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  215. m.Post("/applications/delete", user.SettingsDeleteApplication)
  216. m.Route("/delete", "GET,POST", user.SettingsDelete)
  217. m.Combo("/account_link").Get(user.SettingsAccountLinks).Post(user.SettingsDeleteAccountLink)
  218. m.Get("/organization", user.SettingsOrganization)
  219. m.Get("/repos", user.SettingsRepos)
  220. m.Group("/security/two_factor", func() {
  221. m.Post("/regenerate_scratch", user.SettingsTwoFactorRegenerateScratch)
  222. m.Post("/disable", user.SettingsTwoFactorDisable)
  223. m.Get("/enroll", user.SettingsTwoFactorEnroll)
  224. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), user.SettingsTwoFactorEnrollPost)
  225. })
  226. }, reqSignIn, func(ctx *context.Context) {
  227. ctx.Data["PageIsUserSettings"] = true
  228. })
  229. m.Group("/user", func() {
  230. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  231. m.Any("/activate", user.Activate)
  232. m.Any("/activate_email", user.ActivateEmail)
  233. m.Get("/email2user", user.Email2User)
  234. m.Get("/forgot_password", user.ForgotPasswd)
  235. m.Post("/forgot_password", user.ForgotPasswdPost)
  236. m.Get("/logout", user.SignOut)
  237. })
  238. // ***** END: User *****
  239. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  240. // ***** START: Admin *****
  241. m.Group("/admin", func() {
  242. m.Get("", adminReq, admin.Dashboard)
  243. m.Get("/config", admin.Config)
  244. m.Post("/config/test_mail", admin.SendTestMail)
  245. m.Get("/monitor", admin.Monitor)
  246. m.Group("/users", func() {
  247. m.Get("", admin.Users)
  248. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  249. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  250. m.Post("/:userid/delete", admin.DeleteUser)
  251. })
  252. m.Group("/orgs", func() {
  253. m.Get("", admin.Organizations)
  254. })
  255. m.Group("/repos", func() {
  256. m.Get("", admin.Repos)
  257. m.Post("/delete", admin.DeleteRepo)
  258. })
  259. m.Group("/auths", func() {
  260. m.Get("", admin.Authentications)
  261. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  262. m.Combo("/:authid").Get(admin.EditAuthSource).
  263. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  264. m.Post("/:authid/delete", admin.DeleteAuthSource)
  265. })
  266. m.Group("/notices", func() {
  267. m.Get("", admin.Notices)
  268. m.Post("/delete", admin.DeleteNotices)
  269. m.Get("/empty", admin.EmptyNotices)
  270. })
  271. }, adminReq)
  272. // ***** END: Admin *****
  273. m.Group("", func() {
  274. m.Group("/:username", func() {
  275. m.Get("", user.Profile)
  276. m.Get("/followers", user.Followers)
  277. m.Get("/following", user.Following)
  278. })
  279. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  280. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  281. if err != nil {
  282. if models.IsErrAttachmentNotExist(err) {
  283. ctx.Error(404)
  284. } else {
  285. ctx.ServerError("GetAttachmentByUUID", err)
  286. }
  287. return
  288. }
  289. fr, err := os.Open(attach.LocalPath())
  290. if err != nil {
  291. ctx.ServerError("Open", err)
  292. return
  293. }
  294. defer fr.Close()
  295. if err := attach.IncreaseDownloadCount(); err != nil {
  296. ctx.ServerError("Update", err)
  297. return
  298. }
  299. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  300. ctx.ServerError("ServeData", err)
  301. return
  302. }
  303. })
  304. m.Post("/attachments", repo.UploadAttachment)
  305. }, ignSignIn)
  306. m.Group("/:username", func() {
  307. m.Get("/action/:action", user.Action)
  308. }, reqSignIn)
  309. if macaron.Env == macaron.DEV {
  310. m.Get("/template/*", dev.TemplatePreview)
  311. }
  312. reqRepoAdmin := context.RequireRepoAdmin()
  313. reqRepoWriter := context.RequireRepoWriter()
  314. // ***** START: Organization *****
  315. m.Group("/org", func() {
  316. m.Group("", func() {
  317. m.Get("/create", org.Create)
  318. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  319. })
  320. m.Group("/:org", func() {
  321. m.Get("/dashboard", user.Dashboard)
  322. m.Get("/^:type(issues|pulls)$", user.Issues)
  323. m.Get("/members", org.Members)
  324. m.Get("/members/action/:action", org.MembersAction)
  325. m.Get("/teams", org.Teams)
  326. }, context.OrgAssignment(true))
  327. m.Group("/:org", func() {
  328. m.Get("/teams/:team", org.TeamMembers)
  329. m.Get("/teams/:team/repositories", org.TeamRepositories)
  330. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  331. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  332. }, context.OrgAssignment(true, false, true))
  333. m.Group("/:org", func() {
  334. m.Get("/teams/new", org.NewTeam)
  335. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  336. m.Get("/teams/:team/edit", org.EditTeam)
  337. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  338. m.Post("/teams/:team/delete", org.DeleteTeam)
  339. m.Group("/settings", func() {
  340. m.Combo("").Get(org.Settings).
  341. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  342. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  343. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  344. m.Group("/hooks", func() {
  345. m.Get("", org.Webhooks)
  346. m.Post("/delete", org.DeleteWebhook)
  347. m.Get("/:type/new", repo.WebhooksNew)
  348. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  349. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  350. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  351. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  352. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  353. m.Get("/:id", repo.WebHooksEdit)
  354. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  355. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  356. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  357. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  358. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  359. })
  360. m.Route("/delete", "GET,POST", org.SettingsDelete)
  361. })
  362. }, context.OrgAssignment(true, true))
  363. }, reqSignIn)
  364. // ***** END: Organization *****
  365. // ***** START: Repository *****
  366. m.Group("/repo", func() {
  367. m.Get("/create", repo.Create)
  368. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  369. m.Get("/migrate", repo.Migrate)
  370. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  371. m.Group("/fork", func() {
  372. m.Combo("/:repoid").Get(repo.Fork).
  373. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  374. }, context.RepoIDAssignment(), context.UnitTypes(), context.LoadRepoUnits(), context.CheckUnit(models.UnitTypeCode))
  375. }, reqSignIn)
  376. m.Group("/:username/:reponame", func() {
  377. m.Group("/settings", func() {
  378. m.Combo("").Get(repo.Settings).
  379. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  380. m.Group("/collaboration", func() {
  381. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  382. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  383. m.Post("/delete", repo.DeleteCollaboration)
  384. })
  385. m.Group("/branches", func() {
  386. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  387. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  388. Post(bindIgnErr(auth.ProtectBranchForm{}), repo.SettingsProtectedBranchPost)
  389. }, repo.MustBeNotBare)
  390. m.Group("/hooks", func() {
  391. m.Get("", repo.Webhooks)
  392. m.Post("/delete", repo.DeleteWebhook)
  393. m.Get("/:type/new", repo.WebhooksNew)
  394. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  395. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  396. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  397. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  398. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  399. m.Get("/:id", repo.WebHooksEdit)
  400. m.Post("/:id/test", repo.TestWebhook)
  401. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  402. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  403. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  404. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  405. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  406. m.Group("/git", func() {
  407. m.Get("", repo.GitHooks)
  408. m.Combo("/:name").Get(repo.GitHooksEdit).
  409. Post(repo.GitHooksEditPost)
  410. }, context.GitHookService())
  411. })
  412. m.Group("/keys", func() {
  413. m.Combo("").Get(repo.DeployKeys).
  414. Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
  415. m.Post("/delete", repo.DeleteDeployKey)
  416. })
  417. }, func(ctx *context.Context) {
  418. ctx.Data["PageIsSettings"] = true
  419. })
  420. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.UnitTypes(), context.LoadRepoUnits(), context.RepoRef())
  421. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  422. m.Group("/:username/:reponame", func() {
  423. m.Group("/issues", func() {
  424. m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
  425. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  426. }, context.CheckUnit(models.UnitTypeIssues))
  427. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  428. // So they can apply their own enable/disable logic on routers.
  429. m.Group("/issues", func() {
  430. m.Group("/:index", func() {
  431. m.Post("/title", repo.UpdateIssueTitle)
  432. m.Post("/content", repo.UpdateIssueContent)
  433. m.Post("/watch", repo.IssueWatch)
  434. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  435. m.Group("/times", func() {
  436. m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
  437. m.Group("/stopwatch", func() {
  438. m.Post("/toggle", repo.IssueStopwatch)
  439. m.Post("/cancel", repo.CancelStopwatch)
  440. })
  441. })
  442. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
  443. })
  444. m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel)
  445. m.Post("/milestone", reqRepoWriter, repo.UpdateIssueMilestone)
  446. m.Post("/assignee", reqRepoWriter, repo.UpdateIssueAssignee)
  447. m.Post("/status", reqRepoWriter, repo.UpdateIssueStatus)
  448. })
  449. m.Group("/comments/:id", func() {
  450. m.Post("", repo.UpdateCommentContent)
  451. m.Post("/delete", repo.DeleteComment)
  452. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
  453. }, context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  454. m.Group("/labels", func() {
  455. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  456. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  457. m.Post("/delete", repo.DeleteLabel)
  458. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  459. }, reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  460. m.Group("/milestones", func() {
  461. m.Combo("/new").Get(repo.NewMilestone).
  462. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  463. m.Get("/:id/edit", repo.EditMilestone)
  464. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  465. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  466. m.Post("/delete", repo.DeleteMilestone)
  467. }, reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  468. m.Combo("/compare/*", repo.MustAllowPulls, repo.SetEditorconfigIfExists).
  469. Get(repo.CompareAndPullRequest).
  470. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  471. m.Group("", func() {
  472. m.Group("", func() {
  473. m.Combo("/_edit/*").Get(repo.EditFile).
  474. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  475. m.Combo("/_new/*").Get(repo.NewFile).
  476. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  477. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  478. m.Combo("/_delete/*").Get(repo.DeleteFile).
  479. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  480. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  481. Get(repo.UploadFile).
  482. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  483. }, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
  484. m.Group("", func() {
  485. m.Post("/upload-file", repo.UploadFileToServer)
  486. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  487. }, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
  488. }, repo.MustBeNotBare, reqRepoWriter)
  489. m.Group("/branches", func() {
  490. m.Group("/_new/", func() {
  491. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  492. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  493. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  494. }, bindIgnErr(auth.NewBranchForm{}))
  495. m.Post("/delete", repo.DeleteBranchPost)
  496. m.Post("/restore", repo.RestoreBranchPost)
  497. }, reqRepoWriter, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  498. }, reqSignIn, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits())
  499. // Releases
  500. m.Group("/:username/:reponame", func() {
  501. m.Group("/releases", func() {
  502. m.Get("/", repo.MustBeNotBare, repo.Releases)
  503. }, repo.MustBeNotBare, context.RepoRef())
  504. m.Group("/releases", func() {
  505. m.Get("/new", repo.NewRelease)
  506. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  507. m.Post("/delete", repo.DeleteRelease)
  508. }, reqSignIn, repo.MustBeNotBare, reqRepoWriter, context.RepoRef())
  509. m.Group("/releases", func() {
  510. m.Get("/edit/*", repo.EditRelease)
  511. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  512. }, reqSignIn, repo.MustBeNotBare, reqRepoWriter, func(ctx *context.Context) {
  513. var err error
  514. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  515. if err != nil {
  516. ctx.ServerError("GetBranchCommit", err)
  517. return
  518. }
  519. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  520. if err != nil {
  521. ctx.ServerError("GetCommitsCount", err)
  522. return
  523. }
  524. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  525. })
  526. }, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits(), context.CheckUnit(models.UnitTypeReleases))
  527. m.Group("/:username/:reponame", func() {
  528. m.Group("", func() {
  529. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  530. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  531. m.Get("/labels/", context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests), repo.RetrieveLabels, repo.Labels)
  532. m.Get("/milestones", context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests), repo.Milestones)
  533. }, context.RepoRef())
  534. m.Group("/wiki", func() {
  535. m.Get("/?:page", repo.Wiki)
  536. m.Get("/_pages", repo.WikiPages)
  537. m.Group("", func() {
  538. m.Combo("/_new").Get(repo.NewWiki).
  539. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  540. m.Combo("/:page/_edit").Get(repo.EditWiki).
  541. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  542. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  543. }, reqSignIn, reqRepoWriter)
  544. }, repo.MustEnableWiki, context.RepoRef())
  545. m.Group("/wiki", func() {
  546. m.Get("/raw/*", repo.WikiRaw)
  547. }, repo.MustEnableWiki)
  548. m.Group("/activity", func() {
  549. m.Get("", repo.Activity)
  550. m.Get("/:period", repo.Activity)
  551. }, context.RepoRef(), repo.MustBeNotBare, context.CheckAnyUnit(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
  552. m.Get("/archive/*", repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.Download)
  553. m.Group("/branches", func() {
  554. m.Get("", repo.Branches)
  555. }, repo.MustBeNotBare, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  556. m.Group("/pulls/:index", func() {
  557. m.Get(".diff", repo.DownloadPullDiff)
  558. m.Get(".patch", repo.DownloadPullPatch)
  559. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  560. m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
  561. m.Post("/merge", reqRepoWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
  562. m.Post("/cleanup", context.RepoRef(), repo.CleanUpPullRequest)
  563. }, repo.MustAllowPulls)
  564. m.Group("/raw", func() {
  565. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  566. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  567. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  568. // "/*" route is deprecated, and kept for backward compatibility
  569. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  570. }, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  571. m.Group("/commits", func() {
  572. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  573. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  574. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  575. // "/*" route is deprecated, and kept for backward compatibility
  576. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  577. }, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  578. m.Group("", func() {
  579. m.Get("/graph", repo.Graph)
  580. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  581. }, repo.MustBeNotBare, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  582. m.Group("/src", func() {
  583. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  584. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  585. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  586. // "/*" route is deprecated, and kept for backward compatibility
  587. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  588. }, repo.SetEditorconfigIfExists)
  589. m.Group("", func() {
  590. m.Get("/forks", repo.Forks)
  591. }, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  592. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
  593. repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.RawDiff)
  594. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists,
  595. repo.SetDiffViewStyle, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.CompareDiff)
  596. }, ignSignIn, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits())
  597. m.Group("/:username/:reponame", func() {
  598. m.Get("/stars", repo.Stars)
  599. m.Get("/watchers", repo.Watchers)
  600. m.Get("/search", context.CheckUnit(models.UnitTypeCode), repo.Search)
  601. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes(), context.LoadRepoUnits())
  602. m.Group("/:username", func() {
  603. m.Group("/:reponame", func() {
  604. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  605. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  606. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes(), context.LoadRepoUnits())
  607. m.Group("/:reponame", func() {
  608. m.Group("\\.git/info/lfs", func() {
  609. m.Post("/objects/batch", lfs.BatchHandler)
  610. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  611. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  612. m.Post("/objects", lfs.PostHandler)
  613. m.Post("/verify", lfs.VerifyHandler)
  614. m.Group("/locks", func() {
  615. m.Get("/", lfs.GetListLockHandler)
  616. m.Post("/", lfs.PostLockHandler)
  617. m.Post("/verify", lfs.VerifyLockHandler)
  618. m.Post("/:lid/unlock", lfs.UnLockHandler)
  619. }, context.RepoAssignment())
  620. m.Any("/*", func(ctx *context.Context) {
  621. ctx.NotFound("", nil)
  622. })
  623. }, ignSignInAndCsrf)
  624. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  625. m.Head("/tasks/trigger", repo.TriggerTask)
  626. })
  627. })
  628. // ***** END: Repository *****
  629. m.Group("/notifications", func() {
  630. m.Get("", user.Notifications)
  631. m.Post("/status", user.NotificationStatusPost)
  632. m.Post("/purge", user.NotificationPurgePost)
  633. }, reqSignIn)
  634. m.Group("/api", func() {
  635. apiv1.RegisterRoutes(m)
  636. }, ignSignIn)
  637. m.Group("/api/internal", func() {
  638. // package name internal is ideal but Golang is not allowed, so we use private as package name.
  639. private.RegisterRoutes(m)
  640. })
  641. // robots.txt
  642. m.Get("/robots.txt", func(ctx *context.Context) {
  643. if setting.HasRobotsTxt {
  644. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  645. } else {
  646. ctx.NotFound("", nil)
  647. }
  648. })
  649. // Not found handler.
  650. m.NotFound(routers.NotFound)
  651. }