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

routes.go 28 kB

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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. m.Get("/code", routers.ExploreCode)
  156. }, ignSignIn)
  157. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  158. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  159. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  160. // ***** START: User *****
  161. m.Group("/user", func() {
  162. m.Get("/login", user.SignIn)
  163. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  164. m.Group("", func() {
  165. m.Combo("/login/openid").
  166. Get(user.SignInOpenID).
  167. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  168. }, openIDSignInEnabled)
  169. m.Group("/openid", func() {
  170. m.Combo("/connect").
  171. Get(user.ConnectOpenID).
  172. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  173. m.Group("/register", func() {
  174. m.Combo("").
  175. Get(user.RegisterOpenID, openIDSignUpEnabled).
  176. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  177. }, openIDSignUpEnabled)
  178. }, openIDSignInEnabled)
  179. m.Get("/sign_up", user.SignUp)
  180. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  181. m.Get("/reset_password", user.ResetPasswd)
  182. m.Post("/reset_password", user.ResetPasswdPost)
  183. m.Group("/oauth2", func() {
  184. m.Get("/:provider", user.SignInOAuth)
  185. m.Get("/:provider/callback", user.SignInOAuthCallback)
  186. })
  187. m.Get("/link_account", user.LinkAccount)
  188. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  189. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  190. m.Group("/two_factor", func() {
  191. m.Get("", user.TwoFactor)
  192. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  193. m.Get("/scratch", user.TwoFactorScratch)
  194. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  195. })
  196. }, reqSignOut)
  197. m.Group("/user/settings", func() {
  198. m.Get("", user.Settings)
  199. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  200. m.Combo("/avatar").Get(user.SettingsAvatar).
  201. Post(binding.MultipartForm(auth.AvatarForm{}), user.SettingsAvatarPost)
  202. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  203. m.Combo("/email").Get(user.SettingsEmails).
  204. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  205. m.Post("/email/delete", user.DeleteEmail)
  206. m.Get("/security", user.SettingsSecurity)
  207. m.Post("/security", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsSecurityPost)
  208. m.Group("/openid", func() {
  209. m.Combo("").Get(user.SettingsOpenID).
  210. Post(bindIgnErr(auth.AddOpenIDForm{}), user.SettingsOpenIDPost)
  211. m.Post("/delete", user.DeleteOpenID)
  212. m.Post("/toggle_visibility", user.ToggleOpenIDVisibility)
  213. }, openIDSignInEnabled)
  214. m.Combo("/keys").Get(user.SettingsKeys).
  215. Post(bindIgnErr(auth.AddKeyForm{}), user.SettingsKeysPost)
  216. m.Post("/keys/delete", user.DeleteKey)
  217. m.Combo("/applications").Get(user.SettingsApplications).
  218. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  219. m.Post("/applications/delete", user.SettingsDeleteApplication)
  220. m.Route("/delete", "GET,POST", user.SettingsDelete)
  221. m.Combo("/account_link").Get(user.SettingsAccountLinks).Post(user.SettingsDeleteAccountLink)
  222. m.Get("/organization", user.SettingsOrganization)
  223. m.Get("/repos", user.SettingsRepos)
  224. m.Group("/security/two_factor", func() {
  225. m.Post("/regenerate_scratch", user.SettingsTwoFactorRegenerateScratch)
  226. m.Post("/disable", user.SettingsTwoFactorDisable)
  227. m.Get("/enroll", user.SettingsTwoFactorEnroll)
  228. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), user.SettingsTwoFactorEnrollPost)
  229. })
  230. }, reqSignIn, func(ctx *context.Context) {
  231. ctx.Data["PageIsUserSettings"] = true
  232. })
  233. m.Group("/user", func() {
  234. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  235. m.Any("/activate", user.Activate)
  236. m.Any("/activate_email", user.ActivateEmail)
  237. m.Get("/email2user", user.Email2User)
  238. m.Get("/forgot_password", user.ForgotPasswd)
  239. m.Post("/forgot_password", user.ForgotPasswdPost)
  240. m.Get("/logout", user.SignOut)
  241. })
  242. // ***** END: User *****
  243. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  244. // ***** START: Admin *****
  245. m.Group("/admin", func() {
  246. m.Get("", adminReq, admin.Dashboard)
  247. m.Get("/config", admin.Config)
  248. m.Post("/config/test_mail", admin.SendTestMail)
  249. m.Get("/monitor", admin.Monitor)
  250. m.Group("/users", func() {
  251. m.Get("", admin.Users)
  252. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  253. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  254. m.Post("/:userid/delete", admin.DeleteUser)
  255. })
  256. m.Group("/orgs", func() {
  257. m.Get("", admin.Organizations)
  258. })
  259. m.Group("/repos", func() {
  260. m.Get("", admin.Repos)
  261. m.Post("/delete", admin.DeleteRepo)
  262. })
  263. m.Group("/auths", func() {
  264. m.Get("", admin.Authentications)
  265. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  266. m.Combo("/:authid").Get(admin.EditAuthSource).
  267. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  268. m.Post("/:authid/delete", admin.DeleteAuthSource)
  269. })
  270. m.Group("/notices", func() {
  271. m.Get("", admin.Notices)
  272. m.Post("/delete", admin.DeleteNotices)
  273. m.Get("/empty", admin.EmptyNotices)
  274. })
  275. }, adminReq)
  276. // ***** END: Admin *****
  277. m.Group("", func() {
  278. m.Group("/:username", func() {
  279. m.Get("", user.Profile)
  280. m.Get("/followers", user.Followers)
  281. m.Get("/following", user.Following)
  282. })
  283. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  284. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  285. if err != nil {
  286. if models.IsErrAttachmentNotExist(err) {
  287. ctx.Error(404)
  288. } else {
  289. ctx.ServerError("GetAttachmentByUUID", err)
  290. }
  291. return
  292. }
  293. fr, err := os.Open(attach.LocalPath())
  294. if err != nil {
  295. ctx.ServerError("Open", err)
  296. return
  297. }
  298. defer fr.Close()
  299. if err := attach.IncreaseDownloadCount(); err != nil {
  300. ctx.ServerError("Update", err)
  301. return
  302. }
  303. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  304. ctx.ServerError("ServeData", err)
  305. return
  306. }
  307. })
  308. m.Post("/attachments", repo.UploadAttachment)
  309. }, ignSignIn)
  310. m.Group("/:username", func() {
  311. m.Get("/action/:action", user.Action)
  312. }, reqSignIn)
  313. if macaron.Env == macaron.DEV {
  314. m.Get("/template/*", dev.TemplatePreview)
  315. }
  316. reqRepoAdmin := context.RequireRepoAdmin()
  317. reqRepoWriter := context.RequireRepoWriter()
  318. // ***** START: Organization *****
  319. m.Group("/org", func() {
  320. m.Group("", func() {
  321. m.Get("/create", org.Create)
  322. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  323. })
  324. m.Group("/:org", func() {
  325. m.Get("/dashboard", user.Dashboard)
  326. m.Get("/^:type(issues|pulls)$", user.Issues)
  327. m.Get("/members", org.Members)
  328. m.Get("/members/action/:action", org.MembersAction)
  329. m.Get("/teams", org.Teams)
  330. }, context.OrgAssignment(true))
  331. m.Group("/:org", func() {
  332. m.Get("/teams/:team", org.TeamMembers)
  333. m.Get("/teams/:team/repositories", org.TeamRepositories)
  334. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  335. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  336. }, context.OrgAssignment(true, false, true))
  337. m.Group("/:org", func() {
  338. m.Get("/teams/new", org.NewTeam)
  339. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  340. m.Get("/teams/:team/edit", org.EditTeam)
  341. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  342. m.Post("/teams/:team/delete", org.DeleteTeam)
  343. m.Group("/settings", func() {
  344. m.Combo("").Get(org.Settings).
  345. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  346. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  347. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  348. m.Group("/hooks", func() {
  349. m.Get("", org.Webhooks)
  350. m.Post("/delete", org.DeleteWebhook)
  351. m.Get("/:type/new", repo.WebhooksNew)
  352. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  353. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  354. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  355. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  356. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  357. m.Get("/:id", repo.WebHooksEdit)
  358. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  359. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  360. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  361. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  362. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  363. })
  364. m.Route("/delete", "GET,POST", org.SettingsDelete)
  365. })
  366. }, context.OrgAssignment(true, true))
  367. }, reqSignIn)
  368. // ***** END: Organization *****
  369. // ***** START: Repository *****
  370. m.Group("/repo", func() {
  371. m.Get("/create", repo.Create)
  372. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  373. m.Get("/migrate", repo.Migrate)
  374. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  375. m.Group("/fork", func() {
  376. m.Combo("/:repoid").Get(repo.Fork).
  377. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  378. }, context.RepoIDAssignment(), context.UnitTypes(), context.LoadRepoUnits(), context.CheckUnit(models.UnitTypeCode))
  379. }, reqSignIn)
  380. m.Group("/:username/:reponame", func() {
  381. m.Group("/settings", func() {
  382. m.Combo("").Get(repo.Settings).
  383. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  384. m.Group("/collaboration", func() {
  385. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  386. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  387. m.Post("/delete", repo.DeleteCollaboration)
  388. })
  389. m.Group("/branches", func() {
  390. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  391. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  392. Post(bindIgnErr(auth.ProtectBranchForm{}), repo.SettingsProtectedBranchPost)
  393. }, repo.MustBeNotBare)
  394. m.Group("/hooks", func() {
  395. m.Get("", repo.Webhooks)
  396. m.Post("/delete", repo.DeleteWebhook)
  397. m.Get("/:type/new", repo.WebhooksNew)
  398. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  399. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  400. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  401. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  402. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  403. m.Get("/:id", repo.WebHooksEdit)
  404. m.Post("/:id/test", repo.TestWebhook)
  405. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  406. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  407. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  408. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  409. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  410. m.Group("/git", func() {
  411. m.Get("", repo.GitHooks)
  412. m.Combo("/:name").Get(repo.GitHooksEdit).
  413. Post(repo.GitHooksEditPost)
  414. }, context.GitHookService())
  415. })
  416. m.Group("/keys", func() {
  417. m.Combo("").Get(repo.DeployKeys).
  418. Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
  419. m.Post("/delete", repo.DeleteDeployKey)
  420. })
  421. }, func(ctx *context.Context) {
  422. ctx.Data["PageIsSettings"] = true
  423. })
  424. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.UnitTypes(), context.LoadRepoUnits(), context.RepoRef())
  425. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  426. m.Group("/:username/:reponame", func() {
  427. m.Group("/issues", func() {
  428. m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
  429. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  430. }, context.CheckUnit(models.UnitTypeIssues))
  431. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  432. // So they can apply their own enable/disable logic on routers.
  433. m.Group("/issues", func() {
  434. m.Group("/:index", func() {
  435. m.Post("/title", repo.UpdateIssueTitle)
  436. m.Post("/content", repo.UpdateIssueContent)
  437. m.Post("/watch", repo.IssueWatch)
  438. m.Combo("/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  439. m.Group("/times", func() {
  440. m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
  441. m.Group("/stopwatch", func() {
  442. m.Post("/toggle", repo.IssueStopwatch)
  443. m.Post("/cancel", repo.CancelStopwatch)
  444. })
  445. })
  446. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
  447. })
  448. m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel)
  449. m.Post("/milestone", reqRepoWriter, repo.UpdateIssueMilestone)
  450. m.Post("/assignee", reqRepoWriter, repo.UpdateIssueAssignee)
  451. m.Post("/status", reqRepoWriter, repo.UpdateIssueStatus)
  452. })
  453. m.Group("/comments/:id", func() {
  454. m.Post("", repo.UpdateCommentContent)
  455. m.Post("/delete", repo.DeleteComment)
  456. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
  457. }, context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  458. m.Group("/labels", func() {
  459. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  460. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  461. m.Post("/delete", repo.DeleteLabel)
  462. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  463. }, reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  464. m.Group("/milestones", func() {
  465. m.Combo("/new").Get(repo.NewMilestone).
  466. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  467. m.Get("/:id/edit", repo.EditMilestone)
  468. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  469. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  470. m.Post("/delete", repo.DeleteMilestone)
  471. }, reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests))
  472. m.Combo("/compare/*", repo.MustAllowPulls, repo.SetEditorconfigIfExists).
  473. Get(repo.CompareAndPullRequest).
  474. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  475. m.Group("", func() {
  476. m.Group("", func() {
  477. m.Combo("/_edit/*").Get(repo.EditFile).
  478. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  479. m.Combo("/_new/*").Get(repo.NewFile).
  480. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  481. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  482. m.Combo("/_delete/*").Get(repo.DeleteFile).
  483. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  484. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  485. Get(repo.UploadFile).
  486. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  487. }, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
  488. m.Group("", func() {
  489. m.Post("/upload-file", repo.UploadFileToServer)
  490. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  491. }, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
  492. }, repo.MustBeNotBare, reqRepoWriter)
  493. m.Group("/branches", func() {
  494. m.Group("/_new/", func() {
  495. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  496. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  497. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  498. }, bindIgnErr(auth.NewBranchForm{}))
  499. m.Post("/delete", repo.DeleteBranchPost)
  500. m.Post("/restore", repo.RestoreBranchPost)
  501. }, reqRepoWriter, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  502. }, reqSignIn, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits())
  503. // Releases
  504. m.Group("/:username/:reponame", func() {
  505. m.Group("/releases", func() {
  506. m.Get("/", repo.MustBeNotBare, repo.Releases)
  507. }, repo.MustBeNotBare, context.RepoRef())
  508. m.Group("/releases", func() {
  509. m.Get("/new", repo.NewRelease)
  510. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  511. m.Post("/delete", repo.DeleteRelease)
  512. }, reqSignIn, repo.MustBeNotBare, reqRepoWriter, context.RepoRef())
  513. m.Group("/releases", func() {
  514. m.Get("/edit/*", repo.EditRelease)
  515. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  516. }, reqSignIn, repo.MustBeNotBare, reqRepoWriter, func(ctx *context.Context) {
  517. var err error
  518. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  519. if err != nil {
  520. ctx.ServerError("GetBranchCommit", err)
  521. return
  522. }
  523. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  524. if err != nil {
  525. ctx.ServerError("GetCommitsCount", err)
  526. return
  527. }
  528. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  529. })
  530. }, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits(), context.CheckUnit(models.UnitTypeReleases))
  531. m.Group("/:username/:reponame", func() {
  532. m.Post("/topics", repo.TopicPost)
  533. }, context.RepoAssignment(), reqRepoAdmin)
  534. m.Group("/:username/:reponame", func() {
  535. m.Group("", func() {
  536. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  537. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  538. m.Get("/labels/", context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests), repo.RetrieveLabels, repo.Labels)
  539. m.Get("/milestones", context.CheckAnyUnit(models.UnitTypeIssues, models.UnitTypePullRequests), repo.Milestones)
  540. }, context.RepoRef())
  541. m.Group("/wiki", func() {
  542. m.Get("/?:page", repo.Wiki)
  543. m.Get("/_pages", repo.WikiPages)
  544. m.Group("", func() {
  545. m.Combo("/_new").Get(repo.NewWiki).
  546. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  547. m.Combo("/:page/_edit").Get(repo.EditWiki).
  548. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  549. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  550. }, reqSignIn, reqRepoWriter)
  551. }, repo.MustEnableWiki, context.RepoRef())
  552. m.Group("/wiki", func() {
  553. m.Get("/raw/*", repo.WikiRaw)
  554. }, repo.MustEnableWiki)
  555. m.Group("/activity", func() {
  556. m.Get("", repo.Activity)
  557. m.Get("/:period", repo.Activity)
  558. }, context.RepoRef(), repo.MustBeNotBare, context.CheckAnyUnit(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
  559. m.Get("/archive/*", repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.Download)
  560. m.Group("/branches", func() {
  561. m.Get("", repo.Branches)
  562. }, repo.MustBeNotBare, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  563. m.Group("/pulls/:index", func() {
  564. m.Get(".diff", repo.DownloadPullDiff)
  565. m.Get(".patch", repo.DownloadPullPatch)
  566. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  567. m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
  568. m.Post("/merge", reqRepoWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
  569. m.Post("/cleanup", context.RepoRef(), repo.CleanUpPullRequest)
  570. }, repo.MustAllowPulls)
  571. m.Group("/raw", func() {
  572. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  573. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  574. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  575. // "/*" route is deprecated, and kept for backward compatibility
  576. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  577. }, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  578. m.Group("/commits", func() {
  579. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  580. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  581. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  582. // "/*" route is deprecated, and kept for backward compatibility
  583. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  584. }, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode))
  585. m.Group("", func() {
  586. m.Get("/graph", repo.Graph)
  587. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  588. }, repo.MustBeNotBare, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  589. m.Group("/src", func() {
  590. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  591. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  592. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  593. // "/*" route is deprecated, and kept for backward compatibility
  594. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  595. }, repo.SetEditorconfigIfExists)
  596. m.Group("", func() {
  597. m.Get("/forks", repo.Forks)
  598. }, context.RepoRef(), context.CheckUnit(models.UnitTypeCode))
  599. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
  600. repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.RawDiff)
  601. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists,
  602. repo.SetDiffViewStyle, repo.MustBeNotBare, context.CheckUnit(models.UnitTypeCode), repo.CompareDiff)
  603. }, ignSignIn, context.RepoAssignment(), context.UnitTypes(), context.LoadRepoUnits())
  604. m.Group("/:username/:reponame", func() {
  605. m.Get("/stars", repo.Stars)
  606. m.Get("/watchers", repo.Watchers)
  607. m.Get("/search", context.CheckUnit(models.UnitTypeCode), repo.Search)
  608. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes(), context.LoadRepoUnits())
  609. m.Group("/:username", func() {
  610. m.Group("/:reponame", func() {
  611. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  612. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  613. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes(), context.LoadRepoUnits())
  614. m.Group("/:reponame", func() {
  615. m.Group("\\.git/info/lfs", func() {
  616. m.Post("/objects/batch", lfs.BatchHandler)
  617. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  618. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  619. m.Post("/objects", lfs.PostHandler)
  620. m.Post("/verify", lfs.VerifyHandler)
  621. m.Group("/locks", func() {
  622. m.Get("/", lfs.GetListLockHandler)
  623. m.Post("/", lfs.PostLockHandler)
  624. m.Post("/verify", lfs.VerifyLockHandler)
  625. m.Post("/:lid/unlock", lfs.UnLockHandler)
  626. }, context.RepoAssignment())
  627. m.Any("/*", func(ctx *context.Context) {
  628. ctx.NotFound("", nil)
  629. })
  630. }, ignSignInAndCsrf)
  631. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  632. m.Head("/tasks/trigger", repo.TriggerTask)
  633. })
  634. })
  635. // ***** END: Repository *****
  636. m.Group("/notifications", func() {
  637. m.Get("", user.Notifications)
  638. m.Post("/status", user.NotificationStatusPost)
  639. m.Post("/purge", user.NotificationPurgePost)
  640. }, reqSignIn)
  641. m.Group("/api", func() {
  642. apiv1.RegisterRoutes(m)
  643. }, ignSignIn)
  644. m.Group("/api/internal", func() {
  645. // package name internal is ideal but Golang is not allowed, so we use private as package name.
  646. private.RegisterRoutes(m)
  647. })
  648. // robots.txt
  649. m.Get("/robots.txt", func(ctx *context.Context) {
  650. if setting.HasRobotsTxt {
  651. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  652. } else {
  653. ctx.NotFound("", nil)
  654. }
  655. })
  656. // Not found handler.
  657. m.NotFound(routers.NotFound)
  658. }