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.

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