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.

routes.go 30KB

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