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.

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