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.

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