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.

web.go 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package web
  4. import (
  5. gocontext "context"
  6. "net/http"
  7. "code.gitea.io/gitea/models/perm"
  8. "code.gitea.io/gitea/models/unit"
  9. "code.gitea.io/gitea/modules/context"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/metrics"
  12. "code.gitea.io/gitea/modules/public"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/storage"
  15. "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/templates"
  17. "code.gitea.io/gitea/modules/validation"
  18. "code.gitea.io/gitea/modules/web"
  19. "code.gitea.io/gitea/modules/web/routing"
  20. "code.gitea.io/gitea/routers/common"
  21. "code.gitea.io/gitea/routers/web/admin"
  22. "code.gitea.io/gitea/routers/web/auth"
  23. "code.gitea.io/gitea/routers/web/devtest"
  24. "code.gitea.io/gitea/routers/web/events"
  25. "code.gitea.io/gitea/routers/web/explore"
  26. "code.gitea.io/gitea/routers/web/feed"
  27. "code.gitea.io/gitea/routers/web/healthcheck"
  28. "code.gitea.io/gitea/routers/web/misc"
  29. "code.gitea.io/gitea/routers/web/org"
  30. org_setting "code.gitea.io/gitea/routers/web/org/setting"
  31. "code.gitea.io/gitea/routers/web/repo"
  32. "code.gitea.io/gitea/routers/web/repo/actions"
  33. repo_setting "code.gitea.io/gitea/routers/web/repo/setting"
  34. "code.gitea.io/gitea/routers/web/user"
  35. user_setting "code.gitea.io/gitea/routers/web/user/setting"
  36. "code.gitea.io/gitea/routers/web/user/setting/security"
  37. auth_service "code.gitea.io/gitea/services/auth"
  38. context_service "code.gitea.io/gitea/services/context"
  39. "code.gitea.io/gitea/services/forms"
  40. "code.gitea.io/gitea/services/lfs"
  41. _ "code.gitea.io/gitea/modules/session" // to registers all internal adapters
  42. "gitea.com/go-chi/captcha"
  43. "github.com/NYTimes/gziphandler"
  44. "github.com/go-chi/chi/v5/middleware"
  45. "github.com/go-chi/cors"
  46. "github.com/prometheus/client_golang/prometheus"
  47. )
  48. const (
  49. // GzipMinSize represents min size to compress for the body size of response
  50. GzipMinSize = 1400
  51. )
  52. // CorsHandler return a http handler who set CORS options if enabled by config
  53. func CorsHandler() func(next http.Handler) http.Handler {
  54. if setting.CORSConfig.Enabled {
  55. return cors.Handler(cors.Options{
  56. // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option
  57. AllowedOrigins: setting.CORSConfig.AllowDomain,
  58. // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option
  59. AllowedMethods: setting.CORSConfig.Methods,
  60. AllowCredentials: setting.CORSConfig.AllowCredentials,
  61. AllowedHeaders: setting.CORSConfig.Headers,
  62. MaxAge: int(setting.CORSConfig.MaxAge.Seconds()),
  63. })
  64. }
  65. return func(next http.Handler) http.Handler {
  66. return next
  67. }
  68. }
  69. // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
  70. // in the session (if there is a user id stored in session other plugins might return the user
  71. // object for that id).
  72. //
  73. // The Session plugin is expected to be executed second, in order to skip authentication
  74. // for users that have already signed in.
  75. func buildAuthGroup() *auth_service.Group {
  76. group := auth_service.NewGroup(
  77. &auth_service.OAuth2{}, // FIXME: this should be removed and only applied in download and oauth related routers
  78. &auth_service.Basic{}, // FIXME: this should be removed and only applied in download and git/lfs routers
  79. &auth_service.Session{},
  80. )
  81. if setting.Service.EnableReverseProxyAuth {
  82. group.Add(&auth_service.ReverseProxy{})
  83. }
  84. specialAdd(group)
  85. return group
  86. }
  87. func ctxDataSet(args ...any) func(ctx *context.Context) {
  88. return func(ctx *context.Context) {
  89. for i := 0; i < len(args); i += 2 {
  90. ctx.Data[args[i].(string)] = args[i+1]
  91. }
  92. }
  93. }
  94. // Routes returns all web routes
  95. func Routes() *web.Route {
  96. routes := web.NewRoute()
  97. routes.Head("/", misc.DummyOK) // for health check - doesn't need to be passed through gzip handler
  98. routes.Methods("GET, HEAD", "/assets/*", CorsHandler(), public.FileHandlerFunc())
  99. routes.Methods("GET, HEAD", "/avatars/*", storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
  100. routes.Methods("GET, HEAD", "/repo-avatars/*", storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
  101. routes.Methods("GET, HEAD", "/apple-touch-icon.png", misc.StaticRedirect("/assets/img/apple-touch-icon.png"))
  102. routes.Methods("GET, HEAD", "/apple-touch-icon-precomposed.png", misc.StaticRedirect("/assets/img/apple-touch-icon.png"))
  103. routes.Methods("GET, HEAD", "/favicon.ico", misc.StaticRedirect("/assets/img/favicon.png"))
  104. _ = templates.HTMLRenderer()
  105. var mid []any
  106. if setting.EnableGzip {
  107. h, err := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(GzipMinSize))
  108. if err != nil {
  109. log.Fatal("GzipHandlerWithOpts failed: %v", err)
  110. }
  111. mid = append(mid, h)
  112. }
  113. if setting.Service.EnableCaptcha {
  114. // The captcha http.Handler should only fire on /captcha/* so we can just mount this on that url
  115. routes.Methods("GET,HEAD", "/captcha/*", append(mid, captcha.Captchaer(context.GetImageCaptcha()))...)
  116. }
  117. if setting.Metrics.Enabled {
  118. prometheus.MustRegister(metrics.NewCollector())
  119. routes.Get("/metrics", append(mid, Metrics)...)
  120. }
  121. routes.Get("/robots.txt", append(mid, misc.RobotsTxt)...)
  122. routes.Get("/ssh_info", misc.SSHInfo)
  123. routes.Get("/api/healthz", healthcheck.Check)
  124. mid = append(mid, common.Sessioner(), context.Contexter())
  125. // Get user from session if logged in.
  126. mid = append(mid, auth_service.Auth(buildAuthGroup()))
  127. // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route
  128. mid = append(mid, middleware.GetHead)
  129. if setting.API.EnableSwagger {
  130. // Note: The route is here but no in API routes because it renders a web page
  131. routes.Get("/api/swagger", append(mid, misc.Swagger)...) // Render V1 by default
  132. }
  133. // TODO: These really seem like things that could be folded into Contexter or as helper functions
  134. mid = append(mid, user.GetNotificationCount)
  135. mid = append(mid, repo.GetActiveStopwatch)
  136. mid = append(mid, goGet)
  137. others := web.NewRoute()
  138. others.Use(mid...)
  139. registerRoutes(others)
  140. routes.Mount("", others)
  141. return routes
  142. }
  143. // registerRoutes register routes
  144. func registerRoutes(m *web.Route) {
  145. reqSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: true})
  146. reqSignOut := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignOutRequired: true})
  147. // TODO: rename them to "optSignIn", which means that the "sign-in" could be optional, depends on the VerifyOptions (RequireSignInView)
  148. ignSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView})
  149. ignExploreSignIn := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView})
  150. ignSignInAndCsrf := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{DisableCSRF: true})
  151. validation.AddBindingRules()
  152. linkAccountEnabled := func(ctx *context.Context) {
  153. if !setting.Service.EnableOpenIDSignIn && !setting.Service.EnableOpenIDSignUp && !setting.OAuth2.Enable {
  154. ctx.Error(http.StatusForbidden)
  155. return
  156. }
  157. }
  158. openIDSignInEnabled := func(ctx *context.Context) {
  159. if !setting.Service.EnableOpenIDSignIn {
  160. ctx.Error(http.StatusForbidden)
  161. return
  162. }
  163. }
  164. openIDSignUpEnabled := func(ctx *context.Context) {
  165. if !setting.Service.EnableOpenIDSignUp {
  166. ctx.Error(http.StatusForbidden)
  167. return
  168. }
  169. }
  170. reqMilestonesDashboardPageEnabled := func(ctx *context.Context) {
  171. if !setting.Service.ShowMilestonesDashboardPage {
  172. ctx.Error(http.StatusForbidden)
  173. return
  174. }
  175. }
  176. // webhooksEnabled requires webhooks to be enabled by admin.
  177. webhooksEnabled := func(ctx *context.Context) {
  178. if setting.DisableWebhooks {
  179. ctx.Error(http.StatusForbidden)
  180. return
  181. }
  182. }
  183. lfsServerEnabled := func(ctx *context.Context) {
  184. if !setting.LFS.StartServer {
  185. ctx.Error(http.StatusNotFound)
  186. return
  187. }
  188. }
  189. federationEnabled := func(ctx *context.Context) {
  190. if !setting.Federation.Enabled {
  191. ctx.Error(http.StatusNotFound)
  192. return
  193. }
  194. }
  195. dlSourceEnabled := func(ctx *context.Context) {
  196. if setting.Repository.DisableDownloadSourceArchives {
  197. ctx.Error(http.StatusNotFound)
  198. return
  199. }
  200. }
  201. sitemapEnabled := func(ctx *context.Context) {
  202. if !setting.Other.EnableSitemap {
  203. ctx.Error(http.StatusNotFound)
  204. return
  205. }
  206. }
  207. packagesEnabled := func(ctx *context.Context) {
  208. if !setting.Packages.Enabled {
  209. ctx.Error(http.StatusForbidden)
  210. return
  211. }
  212. }
  213. feedEnabled := func(ctx *context.Context) {
  214. if !setting.Other.EnableFeed {
  215. ctx.Error(http.StatusNotFound)
  216. return
  217. }
  218. }
  219. reqUnitAccess := func(unitType unit.Type, accessMode perm.AccessMode, ignoreGlobal bool) func(ctx *context.Context) {
  220. return func(ctx *context.Context) {
  221. // only check global disabled units when ignoreGlobal is false
  222. if !ignoreGlobal && unitType.UnitGlobalDisabled() {
  223. ctx.NotFound(unitType.String(), nil)
  224. return
  225. }
  226. if ctx.ContextUser == nil {
  227. ctx.NotFound(unitType.String(), nil)
  228. return
  229. }
  230. if ctx.ContextUser.IsOrganization() {
  231. if ctx.Org.Organization.UnitPermission(ctx, ctx.Doer, unitType) < accessMode {
  232. ctx.NotFound(unitType.String(), nil)
  233. return
  234. }
  235. }
  236. }
  237. }
  238. addWebhookAddRoutes := func() {
  239. m.Get("/{type}/new", repo_setting.WebhooksNew)
  240. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksNewPost)
  241. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksNewPost)
  242. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksNewPost)
  243. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksNewPost)
  244. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksNewPost)
  245. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksNewPost)
  246. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksNewPost)
  247. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksNewPost)
  248. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksNewPost)
  249. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksNewPost)
  250. m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksNewPost)
  251. }
  252. addWebhookEditRoutes := func() {
  253. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksEditPost)
  254. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksEditPost)
  255. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksEditPost)
  256. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksEditPost)
  257. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksEditPost)
  258. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksEditPost)
  259. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksEditPost)
  260. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksEditPost)
  261. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksEditPost)
  262. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksEditPost)
  263. m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksEditPost)
  264. }
  265. addSettingVariablesRoutes := func() {
  266. m.Group("/variables", func() {
  267. m.Get("", repo_setting.Variables)
  268. m.Post("/new", web.Bind(forms.EditVariableForm{}), repo_setting.VariableCreate)
  269. m.Post("/{variable_id}/edit", web.Bind(forms.EditVariableForm{}), repo_setting.VariableUpdate)
  270. m.Post("/{variable_id}/delete", repo_setting.VariableDelete)
  271. })
  272. }
  273. addSettingsSecretsRoutes := func() {
  274. m.Group("/secrets", func() {
  275. m.Get("", repo_setting.Secrets)
  276. m.Post("", web.Bind(forms.AddSecretForm{}), repo_setting.SecretsPost)
  277. m.Post("/delete", repo_setting.SecretsDelete)
  278. })
  279. }
  280. addSettingsRunnersRoutes := func() {
  281. m.Group("/runners", func() {
  282. m.Get("", repo_setting.Runners)
  283. m.Combo("/{runnerid}").Get(repo_setting.RunnersEdit).
  284. Post(web.Bind(forms.EditRunnerForm{}), repo_setting.RunnersEditPost)
  285. m.Post("/{runnerid}/delete", repo_setting.RunnerDeletePost)
  286. m.Get("/reset_registration_token", repo_setting.ResetRunnerRegistrationToken)
  287. })
  288. }
  289. // FIXME: not all routes need go through same middleware.
  290. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  291. m.Get("/", Home)
  292. m.Get("/sitemap.xml", sitemapEnabled, ignExploreSignIn, HomeSitemap)
  293. m.Group("/.well-known", func() {
  294. m.Get("/openid-configuration", auth.OIDCWellKnown)
  295. m.Group("", func() {
  296. m.Get("/nodeinfo", NodeInfoLinks)
  297. m.Get("/webfinger", WebfingerQuery)
  298. }, federationEnabled)
  299. m.Get("/change-password", func(ctx *context.Context) {
  300. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  301. })
  302. m.Any("/*", CorsHandler(), public.FileHandlerFunc())
  303. }, CorsHandler())
  304. m.Group("/explore", func() {
  305. m.Get("", func(ctx *context.Context) {
  306. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  307. })
  308. m.Get("/repos", explore.Repos)
  309. m.Get("/repos/sitemap-{idx}.xml", sitemapEnabled, explore.Repos)
  310. m.Get("/users", explore.Users)
  311. m.Get("/users/sitemap-{idx}.xml", sitemapEnabled, explore.Users)
  312. m.Get("/organizations", explore.Organizations)
  313. m.Get("/code", func(ctx *context.Context) {
  314. if unit.TypeCode.UnitGlobalDisabled() {
  315. ctx.NotFound(unit.TypeCode.String(), nil)
  316. return
  317. }
  318. }, explore.Code)
  319. m.Get("/topics/search", explore.TopicSearch)
  320. }, ignExploreSignIn)
  321. m.Group("/issues", func() {
  322. m.Get("", user.Issues)
  323. m.Get("/search", repo.SearchIssues)
  324. }, reqSignIn)
  325. m.Get("/pulls", reqSignIn, user.Pulls)
  326. m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
  327. // ***** START: User *****
  328. // "user/login" doesn't need signOut, then logged-in users can still access this route for redirection purposes by "/user/login?redirec_to=..."
  329. m.Get("/user/login", auth.SignIn)
  330. m.Group("/user", func() {
  331. m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost)
  332. m.Group("", func() {
  333. m.Combo("/login/openid").
  334. Get(auth.SignInOpenID).
  335. Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost)
  336. }, openIDSignInEnabled)
  337. m.Group("/openid", func() {
  338. m.Combo("/connect").
  339. Get(auth.ConnectOpenID).
  340. Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost)
  341. m.Group("/register", func() {
  342. m.Combo("").
  343. Get(auth.RegisterOpenID, openIDSignUpEnabled).
  344. Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost)
  345. }, openIDSignUpEnabled)
  346. }, openIDSignInEnabled)
  347. m.Get("/sign_up", auth.SignUp)
  348. m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost)
  349. m.Get("/link_account", linkAccountEnabled, auth.LinkAccount)
  350. m.Post("/link_account_signin", linkAccountEnabled, web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn)
  351. m.Post("/link_account_signup", linkAccountEnabled, web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister)
  352. m.Group("/two_factor", func() {
  353. m.Get("", auth.TwoFactor)
  354. m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost)
  355. m.Get("/scratch", auth.TwoFactorScratch)
  356. m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost)
  357. })
  358. m.Group("/webauthn", func() {
  359. m.Get("", auth.WebAuthn)
  360. m.Get("/assertion", auth.WebAuthnLoginAssertion)
  361. m.Post("/assertion", auth.WebAuthnLoginAssertionPost)
  362. })
  363. }, reqSignOut)
  364. m.Any("/user/events", routing.MarkLongPolling, events.Events)
  365. m.Group("/login/oauth", func() {
  366. m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  367. m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth)
  368. // TODO manage redirection
  369. m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  370. }, ignSignInAndCsrf, reqSignIn)
  371. m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth)
  372. m.Post("/login/oauth/access_token", CorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth)
  373. m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys)
  374. m.Post("/login/oauth/introspect", CorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth)
  375. m.Group("/user/settings", func() {
  376. m.Get("", user_setting.Profile)
  377. m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost)
  378. m.Get("/change_password", auth.MustChangePassword)
  379. m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost)
  380. m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost)
  381. m.Post("/avatar/delete", user_setting.DeleteAvatar)
  382. m.Group("/account", func() {
  383. m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost)
  384. m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost)
  385. m.Post("/email/delete", user_setting.DeleteEmail)
  386. m.Post("/delete", user_setting.DeleteAccount)
  387. })
  388. m.Group("/appearance", func() {
  389. m.Get("", user_setting.Appearance)
  390. m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang)
  391. m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments)
  392. m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost)
  393. })
  394. m.Group("/security", func() {
  395. m.Get("", security.Security)
  396. m.Group("/two_factor", func() {
  397. m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor)
  398. m.Post("/disable", security.DisableTwoFactor)
  399. m.Get("/enroll", security.EnrollTwoFactor)
  400. m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost)
  401. })
  402. m.Group("/webauthn", func() {
  403. m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister)
  404. m.Post("/register", security.WebauthnRegisterPost)
  405. m.Post("/delete", web.Bind(forms.WebauthnDeleteForm{}), security.WebauthnDelete)
  406. })
  407. m.Group("/openid", func() {
  408. m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost)
  409. m.Post("/delete", security.DeleteOpenID)
  410. m.Post("/toggle_visibility", security.ToggleOpenIDVisibility)
  411. }, openIDSignInEnabled)
  412. m.Post("/account_link", linkAccountEnabled, security.DeleteAccountLink)
  413. })
  414. m.Group("/applications/oauth2", func() {
  415. m.Get("/{id}", user_setting.OAuth2ApplicationShow)
  416. m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit)
  417. m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret)
  418. m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost)
  419. m.Post("/{id}/delete", user_setting.DeleteOAuth2Application)
  420. m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant)
  421. })
  422. m.Combo("/applications").Get(user_setting.Applications).
  423. Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost)
  424. m.Post("/applications/delete", user_setting.DeleteApplication)
  425. m.Combo("/keys").Get(user_setting.Keys).
  426. Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost)
  427. m.Post("/keys/delete", user_setting.DeleteKey)
  428. m.Group("/packages", func() {
  429. m.Get("", user_setting.Packages)
  430. m.Group("/rules", func() {
  431. m.Group("/add", func() {
  432. m.Get("", user_setting.PackagesRuleAdd)
  433. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost)
  434. })
  435. m.Group("/{id}", func() {
  436. m.Get("", user_setting.PackagesRuleEdit)
  437. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost)
  438. m.Get("/preview", user_setting.PackagesRulePreview)
  439. })
  440. })
  441. m.Group("/cargo", func() {
  442. m.Post("/initialize", user_setting.InitializeCargoIndex)
  443. m.Post("/rebuild", user_setting.RebuildCargoIndex)
  444. })
  445. m.Post("/chef/regenerate_keypair", user_setting.RegenerateChefKeyPair)
  446. }, packagesEnabled)
  447. m.Group("/actions", func() {
  448. m.Get("", user_setting.RedirectToDefaultSetting)
  449. addSettingsRunnersRoutes()
  450. addSettingsSecretsRoutes()
  451. addSettingVariablesRoutes()
  452. }, actions.MustEnableActions)
  453. m.Get("/organization", user_setting.Organization)
  454. m.Get("/repos", user_setting.Repos)
  455. m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository)
  456. m.Group("/hooks", func() {
  457. m.Get("", user_setting.Webhooks)
  458. m.Post("/delete", user_setting.DeleteWebhook)
  459. addWebhookAddRoutes()
  460. m.Group("/{id}", func() {
  461. m.Get("", repo_setting.WebHooksEdit)
  462. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  463. })
  464. addWebhookEditRoutes()
  465. }, webhooksEnabled)
  466. }, reqSignIn, ctxDataSet("PageIsUserSettings", true, "AllThemes", setting.UI.Themes, "EnablePackages", setting.Packages.Enabled))
  467. m.Group("/user", func() {
  468. m.Get("/activate", auth.Activate)
  469. m.Post("/activate", auth.ActivatePost)
  470. m.Any("/activate_email", auth.ActivateEmail)
  471. m.Get("/avatar/{username}/{size}", user.AvatarByUserName)
  472. m.Get("/recover_account", auth.ResetPasswd)
  473. m.Post("/recover_account", auth.ResetPasswdPost)
  474. m.Get("/forgot_password", auth.ForgotPasswd)
  475. m.Post("/forgot_password", auth.ForgotPasswdPost)
  476. m.Post("/logout", auth.SignOut)
  477. m.Get("/task/{task}", reqSignIn, user.TaskStatus)
  478. m.Get("/stopwatches", reqSignIn, user.GetStopwatches)
  479. m.Get("/search", ignExploreSignIn, user.Search)
  480. m.Group("/oauth2", func() {
  481. m.Get("/{provider}", auth.SignInOAuth)
  482. m.Get("/{provider}/callback", auth.SignInOAuthCallback)
  483. })
  484. })
  485. // ***** END: User *****
  486. m.Get("/avatar/{hash}", user.AvatarByEmailHash)
  487. adminReq := auth_service.VerifyAuthWithOptions(&auth_service.VerifyOptions{SignInRequired: true, AdminRequired: true})
  488. // ***** START: Admin *****
  489. m.Group("/admin", func() {
  490. m.Get("", admin.Dashboard)
  491. m.Post("", web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost)
  492. m.Group("/config", func() {
  493. m.Get("", admin.Config)
  494. m.Post("", admin.ChangeConfig)
  495. m.Post("/test_mail", admin.SendTestMail)
  496. })
  497. m.Group("/monitor", func() {
  498. m.Get("/stats", admin.MonitorStats)
  499. m.Get("/cron", admin.CronTasks)
  500. m.Get("/stacktrace", admin.Stacktrace)
  501. m.Post("/stacktrace/cancel/{pid}", admin.StacktraceCancel)
  502. m.Get("/queue", admin.Queues)
  503. m.Group("/queue/{qid}", func() {
  504. m.Get("", admin.QueueManage)
  505. m.Post("/set", admin.QueueSet)
  506. m.Post("/remove-all-items", admin.QueueRemoveAllItems)
  507. })
  508. m.Get("/diagnosis", admin.MonitorDiagnosis)
  509. })
  510. m.Group("/users", func() {
  511. m.Get("", admin.Users)
  512. m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost)
  513. m.Combo("/{userid}").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost)
  514. m.Post("/{userid}/delete", admin.DeleteUser)
  515. m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost)
  516. m.Post("/{userid}/avatar/delete", admin.DeleteAvatar)
  517. })
  518. m.Group("/emails", func() {
  519. m.Get("", admin.Emails)
  520. m.Post("/activate", admin.ActivateEmail)
  521. })
  522. m.Group("/orgs", func() {
  523. m.Get("", admin.Organizations)
  524. })
  525. m.Group("/repos", func() {
  526. m.Get("", admin.Repos)
  527. m.Combo("/unadopted").Get(admin.UnadoptedRepos).Post(admin.AdoptOrDeleteRepository)
  528. m.Post("/delete", admin.DeleteRepo)
  529. })
  530. m.Group("/packages", func() {
  531. m.Get("", admin.Packages)
  532. m.Post("/delete", admin.DeletePackageVersion)
  533. m.Post("/cleanup", admin.CleanupExpiredData)
  534. }, packagesEnabled)
  535. m.Group("/hooks", func() {
  536. m.Get("", admin.DefaultOrSystemWebhooks)
  537. m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
  538. m.Group("/{id}", func() {
  539. m.Get("", repo_setting.WebHooksEdit)
  540. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  541. })
  542. addWebhookEditRoutes()
  543. }, webhooksEnabled)
  544. m.Group("/{configType:default-hooks|system-hooks}", func() {
  545. addWebhookAddRoutes()
  546. })
  547. m.Group("/auths", func() {
  548. m.Get("", admin.Authentications)
  549. m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost)
  550. m.Combo("/{authid}").Get(admin.EditAuthSource).
  551. Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost)
  552. m.Post("/{authid}/delete", admin.DeleteAuthSource)
  553. })
  554. m.Group("/notices", func() {
  555. m.Get("", admin.Notices)
  556. m.Post("/delete", admin.DeleteNotices)
  557. m.Post("/empty", admin.EmptyNotices)
  558. })
  559. m.Group("/applications", func() {
  560. m.Get("", admin.Applications)
  561. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost)
  562. m.Group("/oauth2/{id}", func() {
  563. m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost)
  564. m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret)
  565. m.Post("/delete", admin.DeleteApplication)
  566. })
  567. }, func(ctx *context.Context) {
  568. if !setting.OAuth2.Enable {
  569. ctx.Error(http.StatusForbidden)
  570. return
  571. }
  572. })
  573. m.Group("/actions", func() {
  574. m.Get("", admin.RedirectToDefaultSetting)
  575. addSettingsRunnersRoutes()
  576. })
  577. }, adminReq, ctxDataSet("EnableOAuth2", setting.OAuth2.Enable, "EnablePackages", setting.Packages.Enabled))
  578. // ***** END: Admin *****
  579. m.Group("", func() {
  580. m.Get("/{username}", user.UsernameSubRoute)
  581. m.Get("/attachments/{uuid}", repo.GetAttachment)
  582. }, ignSignIn)
  583. m.Post("/{username}", reqSignIn, context_service.UserAssignmentWeb(), user.Action)
  584. reqRepoAdmin := context.RequireRepoAdmin()
  585. reqRepoCodeWriter := context.RequireRepoWriter(unit.TypeCode)
  586. canEnableEditor := context.CanEnableEditor()
  587. reqRepoCodeReader := context.RequireRepoReader(unit.TypeCode)
  588. reqRepoReleaseWriter := context.RequireRepoWriter(unit.TypeReleases)
  589. reqRepoReleaseReader := context.RequireRepoReader(unit.TypeReleases)
  590. reqRepoWikiWriter := context.RequireRepoWriter(unit.TypeWiki)
  591. reqRepoIssueReader := context.RequireRepoReader(unit.TypeIssues)
  592. reqRepoPullsReader := context.RequireRepoReader(unit.TypePullRequests)
  593. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(unit.TypeIssues, unit.TypePullRequests)
  594. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(unit.TypeIssues, unit.TypePullRequests)
  595. reqRepoProjectsReader := context.RequireRepoReader(unit.TypeProjects)
  596. reqRepoProjectsWriter := context.RequireRepoWriter(unit.TypeProjects)
  597. reqRepoActionsReader := context.RequireRepoReader(unit.TypeActions)
  598. reqRepoActionsWriter := context.RequireRepoWriter(unit.TypeActions)
  599. reqPackageAccess := func(accessMode perm.AccessMode) func(ctx *context.Context) {
  600. return func(ctx *context.Context) {
  601. if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
  602. ctx.NotFound("", nil)
  603. }
  604. }
  605. }
  606. // ***** START: Organization *****
  607. m.Group("/org", func() {
  608. m.Group("/{org}", func() {
  609. m.Get("/members", org.Members)
  610. }, context.OrgAssignment())
  611. }, ignSignIn)
  612. m.Group("/org", func() {
  613. m.Group("", func() {
  614. m.Get("/create", org.Create)
  615. m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost)
  616. })
  617. m.Group("/invite/{token}", func() {
  618. m.Get("", org.TeamInvite)
  619. m.Post("", org.TeamInvitePost)
  620. })
  621. m.Group("/{org}", func() {
  622. m.Get("/dashboard", user.Dashboard)
  623. m.Get("/dashboard/{team}", user.Dashboard)
  624. m.Get("/issues", user.Issues)
  625. m.Get("/issues/{team}", user.Issues)
  626. m.Get("/pulls", user.Pulls)
  627. m.Get("/pulls/{team}", user.Pulls)
  628. m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
  629. m.Get("/milestones/{team}", reqMilestonesDashboardPageEnabled, user.Milestones)
  630. m.Post("/members/action/{action}", org.MembersAction)
  631. m.Get("/teams", org.Teams)
  632. }, context.OrgAssignment(true, false, true))
  633. m.Group("/{org}", func() {
  634. m.Get("/teams/{team}", org.TeamMembers)
  635. m.Get("/teams/{team}/repositories", org.TeamRepositories)
  636. m.Post("/teams/{team}/action/{action}", org.TeamsAction)
  637. m.Post("/teams/{team}/action/repo/{action}", org.TeamsRepoAction)
  638. }, context.OrgAssignment(true, false, true))
  639. m.Group("/{org}", func() {
  640. m.Get("/teams/new", org.NewTeam)
  641. m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost)
  642. m.Get("/teams/-/search", org.SearchTeam)
  643. m.Get("/teams/{team}/edit", org.EditTeam)
  644. m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost)
  645. m.Post("/teams/{team}/delete", org.DeleteTeam)
  646. m.Group("/settings", func() {
  647. m.Combo("").Get(org.Settings).
  648. Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost)
  649. m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar)
  650. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  651. m.Group("/applications", func() {
  652. m.Get("", org.Applications)
  653. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost)
  654. m.Group("/oauth2/{id}", func() {
  655. m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit)
  656. m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret)
  657. m.Post("/delete", org.DeleteOAuth2Application)
  658. })
  659. }, func(ctx *context.Context) {
  660. if !setting.OAuth2.Enable {
  661. ctx.Error(http.StatusForbidden)
  662. return
  663. }
  664. })
  665. m.Group("/hooks", func() {
  666. m.Get("", org.Webhooks)
  667. m.Post("/delete", org.DeleteWebhook)
  668. addWebhookAddRoutes()
  669. m.Group("/{id}", func() {
  670. m.Get("", repo_setting.WebHooksEdit)
  671. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  672. })
  673. addWebhookEditRoutes()
  674. }, webhooksEnabled)
  675. m.Group("/labels", func() {
  676. m.Get("", org.RetrieveLabels, org.Labels)
  677. m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel)
  678. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel)
  679. m.Post("/delete", org.DeleteLabel)
  680. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels)
  681. })
  682. m.Group("/actions", func() {
  683. m.Get("", org_setting.RedirectToDefaultSetting)
  684. addSettingsRunnersRoutes()
  685. addSettingsSecretsRoutes()
  686. addSettingVariablesRoutes()
  687. }, actions.MustEnableActions)
  688. m.Methods("GET,POST", "/delete", org.SettingsDelete)
  689. m.Group("/packages", func() {
  690. m.Get("", org.Packages)
  691. m.Group("/rules", func() {
  692. m.Group("/add", func() {
  693. m.Get("", org.PackagesRuleAdd)
  694. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost)
  695. })
  696. m.Group("/{id}", func() {
  697. m.Get("", org.PackagesRuleEdit)
  698. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost)
  699. m.Get("/preview", org.PackagesRulePreview)
  700. })
  701. })
  702. m.Group("/cargo", func() {
  703. m.Post("/initialize", org.InitializeCargoIndex)
  704. m.Post("/rebuild", org.RebuildCargoIndex)
  705. })
  706. }, packagesEnabled)
  707. }, ctxDataSet("EnableOAuth2", setting.OAuth2.Enable, "EnablePackages", setting.Packages.Enabled, "PageIsOrgSettings", true))
  708. }, context.OrgAssignment(true, true))
  709. }, reqSignIn)
  710. // ***** END: Organization *****
  711. // ***** START: Repository *****
  712. m.Group("/repo", func() {
  713. m.Get("/create", repo.Create)
  714. m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost)
  715. m.Get("/migrate", repo.Migrate)
  716. m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost)
  717. m.Group("/fork", func() {
  718. m.Combo("/{repoid}").Get(repo.Fork).
  719. Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost)
  720. }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
  721. m.Get("/search", repo.SearchRepo)
  722. }, reqSignIn)
  723. m.Group("/{username}/-", func() {
  724. if setting.Packages.Enabled {
  725. m.Group("/packages", func() {
  726. m.Get("", user.ListPackages)
  727. m.Group("/{type}/{name}", func() {
  728. m.Get("", user.RedirectToLastVersion)
  729. m.Get("/versions", user.ListPackageVersions)
  730. m.Group("/{version}", func() {
  731. m.Get("", user.ViewPackageVersion)
  732. m.Get("/files/{fileid}", user.DownloadPackageFile)
  733. m.Group("/settings", func() {
  734. m.Get("", user.PackageSettings)
  735. m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost)
  736. }, reqPackageAccess(perm.AccessModeWrite))
  737. })
  738. })
  739. }, context.PackageAssignment(), reqPackageAccess(perm.AccessModeRead))
  740. }
  741. m.Group("/projects", func() {
  742. m.Group("", func() {
  743. m.Get("", org.Projects)
  744. m.Get("/{id}", org.ViewProject)
  745. }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true))
  746. m.Group("", func() { //nolint:dupl
  747. m.Get("/new", org.RenderNewProject)
  748. m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost)
  749. m.Group("/{id}", func() {
  750. m.Post("", web.Bind(forms.EditProjectBoardForm{}), org.AddBoardToProjectPost)
  751. m.Post("/delete", org.DeleteProject)
  752. m.Get("/edit", org.RenderEditProject)
  753. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), org.EditProjectPost)
  754. m.Post("/{action:open|close}", org.ChangeProjectStatus)
  755. m.Group("/{boardID}", func() {
  756. m.Put("", web.Bind(forms.EditProjectBoardForm{}), org.EditProjectBoard)
  757. m.Delete("", org.DeleteProjectBoard)
  758. m.Post("/default", org.SetDefaultProjectBoard)
  759. m.Post("/unsetdefault", org.UnsetDefaultProjectBoard)
  760. m.Post("/move", org.MoveIssues)
  761. })
  762. })
  763. }, reqSignIn, reqUnitAccess(unit.TypeProjects, perm.AccessModeWrite, true), func(ctx *context.Context) {
  764. if ctx.ContextUser.IsIndividual() && ctx.ContextUser.ID != ctx.Doer.ID {
  765. ctx.NotFound("NewProject", nil)
  766. return
  767. }
  768. })
  769. })
  770. m.Group("", func() {
  771. m.Get("/code", user.CodeSearch)
  772. }, reqUnitAccess(unit.TypeCode, perm.AccessModeRead, false))
  773. }, ignSignIn, context_service.UserAssignmentWeb(), context.OrgAssignment()) // for "/{username}/-" (packages, projects, code)
  774. // ***** Release Attachment Download without Signin
  775. m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment, repo.MustBeNotEmpty, repo.RedirectDownload)
  776. m.Group("/{username}/{reponame}", func() {
  777. m.Group("/settings", func() {
  778. m.Group("", func() {
  779. m.Combo("").Get(repo_setting.Settings).
  780. Post(web.Bind(forms.RepoSettingForm{}), repo_setting.SettingsPost)
  781. }, repo_setting.SettingsCtxData)
  782. m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo_setting.SettingsAvatar)
  783. m.Post("/avatar/delete", repo_setting.SettingsDeleteAvatar)
  784. m.Group("/collaboration", func() {
  785. m.Combo("").Get(repo_setting.Collaboration).Post(repo_setting.CollaborationPost)
  786. m.Post("/access_mode", repo_setting.ChangeCollaborationAccessMode)
  787. m.Post("/delete", repo_setting.DeleteCollaboration)
  788. m.Group("/team", func() {
  789. m.Post("", repo_setting.AddTeamPost)
  790. m.Post("/delete", repo_setting.DeleteTeam)
  791. })
  792. })
  793. m.Group("/branches", func() {
  794. m.Post("/", repo_setting.SetDefaultBranchPost)
  795. }, repo.MustBeNotEmpty)
  796. m.Group("/branches", func() {
  797. m.Get("/", repo_setting.ProtectedBranchRules)
  798. m.Combo("/edit").Get(repo_setting.SettingsProtectedBranch).
  799. Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.SettingsProtectedBranchPost)
  800. m.Post("/{id}/delete", repo_setting.DeleteProtectedBranchRulePost)
  801. }, repo.MustBeNotEmpty)
  802. m.Post("/rename_branch", web.Bind(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.RenameBranchPost)
  803. m.Group("/tags", func() {
  804. m.Get("", repo_setting.ProtectedTags)
  805. m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.NewProtectedTagPost)
  806. m.Post("/delete", context.RepoMustNotBeArchived(), repo_setting.DeleteProtectedTagPost)
  807. m.Get("/{id}", repo_setting.EditProtectedTag)
  808. m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.EditProtectedTagPost)
  809. })
  810. m.Group("/hooks/git", func() {
  811. m.Get("", repo_setting.GitHooks)
  812. m.Combo("/{name}").Get(repo_setting.GitHooksEdit).
  813. Post(repo_setting.GitHooksEditPost)
  814. }, context.GitHookService())
  815. m.Group("/hooks", func() {
  816. m.Get("", repo_setting.Webhooks)
  817. m.Post("/delete", repo_setting.DeleteWebhook)
  818. addWebhookAddRoutes()
  819. m.Group("/{id}", func() {
  820. m.Get("", repo_setting.WebHooksEdit)
  821. m.Post("/test", repo_setting.TestWebhook)
  822. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  823. })
  824. addWebhookEditRoutes()
  825. }, webhooksEnabled)
  826. m.Group("/keys", func() {
  827. m.Combo("").Get(repo_setting.DeployKeys).
  828. Post(web.Bind(forms.AddKeyForm{}), repo_setting.DeployKeysPost)
  829. m.Post("/delete", repo_setting.DeleteDeployKey)
  830. })
  831. m.Group("/lfs", func() {
  832. m.Get("/", repo_setting.LFSFiles)
  833. m.Get("/show/{oid}", repo_setting.LFSFileGet)
  834. m.Post("/delete/{oid}", repo_setting.LFSDelete)
  835. m.Get("/pointers", repo_setting.LFSPointerFiles)
  836. m.Post("/pointers/associate", repo_setting.LFSAutoAssociate)
  837. m.Get("/find", repo_setting.LFSFileFind)
  838. m.Group("/locks", func() {
  839. m.Get("/", repo_setting.LFSLocks)
  840. m.Post("/", repo_setting.LFSLockFile)
  841. m.Post("/{lid}/unlock", repo_setting.LFSUnlock)
  842. })
  843. })
  844. m.Group("/actions", func() {
  845. m.Get("", repo_setting.RedirectToDefaultSetting)
  846. addSettingsRunnersRoutes()
  847. addSettingsSecretsRoutes()
  848. addSettingVariablesRoutes()
  849. }, actions.MustEnableActions)
  850. // the follow handler must be under "settings", otherwise this incomplete repo can't be accessed
  851. m.Group("/migrate", func() {
  852. m.Post("/retry", repo.MigrateRetryPost)
  853. m.Post("/cancel", repo.MigrateCancelPost)
  854. })
  855. }, ctxDataSet("PageIsRepoSettings", true, "LFSStartServer", setting.LFS.StartServer))
  856. }, reqSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  857. m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment, context.UnitTypes(), repo.Action)
  858. // Grouping for those endpoints not requiring authentication (but should respect ignSignIn)
  859. m.Group("/{username}/{reponame}", func() {
  860. m.Group("/milestone", func() {
  861. m.Get("/{id}", repo.MilestoneIssuesAndPulls)
  862. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  863. m.Get("/find/*", repo.FindFiles)
  864. m.Group("/tree-list", func() {
  865. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.TreeList)
  866. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.TreeList)
  867. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.TreeList)
  868. })
  869. m.Get("/compare", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists, ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
  870. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  871. Get(repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
  872. Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
  873. m.Group("/{type:issues|pulls}", func() {
  874. m.Group("/{index}", func() {
  875. m.Get("/info", repo.GetIssueInfo)
  876. })
  877. })
  878. }, ignSignIn, context.RepoAssignment, context.UnitTypes()) // for "/{username}/{reponame}" which doesn't require authentication
  879. // Grouping for those endpoints that do require authentication
  880. m.Group("/{username}/{reponame}", func() {
  881. m.Group("/issues", func() {
  882. m.Group("/new", func() {
  883. m.Combo("").Get(context.RepoRef(), repo.NewIssue).
  884. Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost)
  885. m.Get("/choose", context.RepoRef(), repo.NewIssueChooseTemplate)
  886. })
  887. m.Get("/search", repo.ListIssues)
  888. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  889. // FIXME: should use different URLs but mostly same logic for comments of issue and pull request.
  890. // So they can apply their own enable/disable logic on routers.
  891. m.Group("/{type:issues|pulls}", func() {
  892. m.Group("/{index}", func() {
  893. m.Post("/title", repo.UpdateIssueTitle)
  894. m.Post("/content", repo.UpdateIssueContent)
  895. m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  896. m.Post("/watch", repo.IssueWatch)
  897. m.Post("/ref", repo.UpdateIssueRef)
  898. m.Post("/pin", reqRepoAdmin, repo.IssuePinOrUnpin)
  899. m.Post("/viewed-files", repo.UpdateViewedFiles)
  900. m.Group("/dependency", func() {
  901. m.Post("/add", repo.AddDependency)
  902. m.Post("/delete", repo.RemoveDependency)
  903. })
  904. m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment)
  905. m.Group("/times", func() {
  906. m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually)
  907. m.Post("/{timeid}/delete", repo.DeleteTime)
  908. m.Group("/stopwatch", func() {
  909. m.Post("/toggle", repo.IssueStopwatch)
  910. m.Post("/cancel", repo.CancelStopwatch)
  911. })
  912. })
  913. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction)
  914. m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue)
  915. m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue)
  916. m.Post("/delete", reqRepoAdmin, repo.DeleteIssue)
  917. }, context.RepoMustNotBeArchived())
  918. m.Group("/{index}", func() {
  919. m.Get("/attachments", repo.GetIssueAttachments)
  920. m.Get("/attachments/{uuid}", repo.GetAttachment)
  921. })
  922. m.Group("/{index}", func() {
  923. m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory)
  924. })
  925. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  926. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  927. m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject)
  928. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  929. m.Post("/request_review", reqRepoIssuesOrPullsReader, repo.UpdatePullReviewRequest)
  930. m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview)
  931. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  932. m.Post("/delete", reqRepoAdmin, repo.BatchDeleteIssues)
  933. m.Post("/resolve_conversation", reqRepoIssuesOrPullsReader, repo.SetShowOutdatedComments, repo.UpdateResolveConversation)
  934. m.Post("/attachments", repo.UploadIssueAttachment)
  935. m.Post("/attachments/remove", repo.DeleteAttachment)
  936. m.Delete("/unpin/{index}", reqRepoAdmin, repo.IssueUnpin)
  937. m.Post("/move_pin", reqRepoAdmin, repo.IssuePinMove)
  938. }, context.RepoMustNotBeArchived())
  939. m.Group("/comments/{id}", func() {
  940. m.Post("", repo.UpdateCommentContent)
  941. m.Post("/delete", repo.DeleteComment)
  942. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction)
  943. }, context.RepoMustNotBeArchived())
  944. m.Group("/comments/{id}", func() {
  945. m.Get("/attachments", repo.GetCommentAttachments)
  946. })
  947. m.Post("/markup", web.Bind(structs.MarkupOption{}), misc.Markup)
  948. m.Group("/labels", func() {
  949. m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel)
  950. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel)
  951. m.Post("/delete", repo.DeleteLabel)
  952. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels)
  953. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  954. m.Group("/milestones", func() {
  955. m.Combo("/new").Get(repo.NewMilestone).
  956. Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost)
  957. m.Get("/{id}/edit", repo.EditMilestone)
  958. m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost)
  959. m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
  960. m.Post("/delete", repo.DeleteMilestone)
  961. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  962. m.Group("/pull", func() {
  963. m.Post("/{index}/target_branch", repo.UpdatePullRequestTarget)
  964. }, context.RepoMustNotBeArchived())
  965. m.Group("", func() {
  966. m.Group("", func() {
  967. m.Combo("/_edit/*").Get(repo.EditFile).
  968. Post(web.Bind(forms.EditRepoFileForm{}), repo.EditFilePost)
  969. m.Combo("/_new/*").Get(repo.NewFile).
  970. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewFilePost)
  971. m.Post("/_preview/*", web.Bind(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  972. m.Combo("/_delete/*").Get(repo.DeleteFile).
  973. Post(web.Bind(forms.DeleteRepoFileForm{}), repo.DeleteFilePost)
  974. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  975. Get(repo.UploadFile).
  976. Post(web.Bind(forms.UploadRepoFileForm{}), repo.UploadFilePost)
  977. m.Combo("/_diffpatch/*").Get(repo.NewDiffPatch).
  978. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewDiffPatchPost)
  979. m.Combo("/_cherrypick/{sha:([a-f0-9]{7,40})}/*").Get(repo.CherryPick).
  980. Post(web.Bind(forms.CherryPickForm{}), repo.CherryPickPost)
  981. }, repo.MustBeEditable)
  982. m.Group("", func() {
  983. m.Post("/upload-file", repo.UploadFileToServer)
  984. m.Post("/upload-remove", web.Bind(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  985. }, repo.MustBeEditable, repo.MustBeAbleToUpload)
  986. }, context.RepoRef(), canEnableEditor, context.RepoMustNotBeArchived())
  987. m.Group("/branches", func() {
  988. m.Group("/_new", func() {
  989. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  990. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  991. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  992. }, web.Bind(forms.NewBranchForm{}))
  993. m.Post("/delete", repo.DeleteBranchPost)
  994. m.Post("/restore", repo.RestoreBranchPost)
  995. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  996. }, reqSignIn, context.RepoAssignment, context.UnitTypes())
  997. // Tags
  998. m.Group("/{username}/{reponame}", func() {
  999. m.Group("/tags", func() {
  1000. m.Get("", repo.TagsList)
  1001. m.Get("/list", repo.GetTagList)
  1002. m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
  1003. m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
  1004. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
  1005. repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
  1006. m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
  1007. repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
  1008. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1009. // Releases
  1010. m.Group("/{username}/{reponame}", func() {
  1011. m.Group("/releases", func() {
  1012. m.Get("/", repo.Releases)
  1013. m.Get("/tag/*", repo.SingleRelease)
  1014. m.Get("/latest", repo.LatestRelease)
  1015. m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
  1016. m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
  1017. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
  1018. repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag, true))
  1019. m.Get("/releases/attachments/{uuid}", repo.MustBeNotEmpty, reqRepoReleaseReader, repo.GetAttachment)
  1020. m.Group("/releases", func() {
  1021. m.Get("/new", repo.NewRelease)
  1022. m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost)
  1023. m.Post("/delete", repo.DeleteRelease)
  1024. m.Post("/attachments", repo.UploadReleaseAttachment)
  1025. m.Post("/attachments/remove", repo.DeleteAttachment)
  1026. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  1027. m.Group("/releases", func() {
  1028. m.Get("/edit/*", repo.EditRelease)
  1029. m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
  1030. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, repo.CommitInfoCache)
  1031. }, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
  1032. // to maintain compatibility with old attachments
  1033. m.Group("/{username}/{reponame}", func() {
  1034. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1035. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1036. m.Group("/{username}/{reponame}", func() {
  1037. m.Post("/topics", repo.TopicsPost)
  1038. }, context.RepoAssignment, context.RepoMustNotBeArchived(), reqRepoAdmin)
  1039. m.Group("/{username}/{reponame}", func() {
  1040. m.Group("", func() {
  1041. m.Get("/issues/posters", repo.IssuePosters) // it can't use {type:issues|pulls} because other routes like "/pulls/{index}" has higher priority
  1042. m.Get("/{type:issues|pulls}", repo.Issues)
  1043. m.Get("/{type:issues|pulls}/{index}", repo.ViewIssue)
  1044. m.Group("/{type:issues|pulls}/{index}/content-history", func() {
  1045. m.Get("/overview", repo.GetContentHistoryOverview)
  1046. m.Get("/list", repo.GetContentHistoryList)
  1047. m.Get("/detail", repo.GetContentHistoryDetail)
  1048. })
  1049. m.Get("/labels", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  1050. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  1051. }, context.RepoRef())
  1052. if setting.Packages.Enabled {
  1053. m.Get("/packages", repo.Packages)
  1054. }
  1055. m.Group("/projects", func() {
  1056. m.Get("", repo.Projects)
  1057. m.Get("/{id}", repo.ViewProject)
  1058. m.Group("", func() { //nolint:dupl
  1059. m.Get("/new", repo.RenderNewProject)
  1060. m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
  1061. m.Group("/{id}", func() {
  1062. m.Post("", web.Bind(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost)
  1063. m.Post("/delete", repo.DeleteProject)
  1064. m.Get("/edit", repo.RenderEditProject)
  1065. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost)
  1066. m.Post("/{action:open|close}", repo.ChangeProjectStatus)
  1067. m.Group("/{boardID}", func() {
  1068. m.Put("", web.Bind(forms.EditProjectBoardForm{}), repo.EditProjectBoard)
  1069. m.Delete("", repo.DeleteProjectBoard)
  1070. m.Post("/default", repo.SetDefaultProjectBoard)
  1071. m.Post("/unsetdefault", repo.UnSetDefaultProjectBoard)
  1072. m.Post("/move", repo.MoveIssues)
  1073. })
  1074. })
  1075. }, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
  1076. }, reqRepoProjectsReader, repo.MustEnableProjects)
  1077. m.Group("/actions", func() {
  1078. m.Get("", actions.List)
  1079. m.Post("/disable", reqRepoAdmin, actions.DisableWorkflowFile)
  1080. m.Post("/enable", reqRepoAdmin, actions.EnableWorkflowFile)
  1081. m.Group("/runs/{run}", func() {
  1082. m.Combo("").
  1083. Get(actions.View).
  1084. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1085. m.Group("/jobs/{job}", func() {
  1086. m.Combo("").
  1087. Get(actions.View).
  1088. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1089. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1090. m.Get("/logs", actions.Logs)
  1091. })
  1092. m.Post("/cancel", reqRepoActionsWriter, actions.Cancel)
  1093. m.Post("/approve", reqRepoActionsWriter, actions.Approve)
  1094. m.Post("/artifacts", actions.ArtifactsView)
  1095. m.Get("/artifacts/{artifact_name}", actions.ArtifactsDownloadView)
  1096. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1097. })
  1098. }, reqRepoActionsReader, actions.MustEnableActions)
  1099. m.Group("/wiki", func() {
  1100. m.Combo("/").
  1101. Get(repo.Wiki).
  1102. Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1103. m.Combo("/*").
  1104. Get(repo.Wiki).
  1105. Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1106. m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1107. m.Get("/commit/{sha:[a-f0-9]{7,40}}.{ext:patch|diff}", repo.RawDiff)
  1108. }, repo.MustEnableWiki, func(ctx *context.Context) {
  1109. ctx.Data["PageIsWiki"] = true
  1110. ctx.Data["CloneButtonOriginLink"] = ctx.Repo.Repository.WikiCloneLink()
  1111. })
  1112. m.Group("/wiki", func() {
  1113. m.Get("/raw/*", repo.WikiRaw)
  1114. }, repo.MustEnableWiki)
  1115. m.Group("/activity", func() {
  1116. m.Get("", repo.Activity)
  1117. m.Get("/{period}", repo.Activity)
  1118. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypePullRequests, unit.TypeIssues, unit.TypeReleases))
  1119. m.Group("/activity_author_data", func() {
  1120. m.Get("", repo.ActivityAuthors)
  1121. m.Get("/{period}", repo.ActivityAuthors)
  1122. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypeCode))
  1123. m.Group("/archive", func() {
  1124. m.Get("/*", repo.Download)
  1125. m.Post("/*", repo.InitiateDownload)
  1126. }, repo.MustBeNotEmpty, dlSourceEnabled, reqRepoCodeReader)
  1127. m.Group("/branches", func() {
  1128. m.Get("/list", repo.GetBranchesList)
  1129. m.Get("", repo.Branches)
  1130. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1131. m.Group("/blob_excerpt", func() {
  1132. m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1133. }, func(ctx *context.Context) gocontext.CancelFunc {
  1134. if ctx.FormBool("wiki") {
  1135. ctx.Data["PageIsWiki"] = true
  1136. repo.MustEnableWiki(ctx)
  1137. return nil
  1138. }
  1139. reqRepoCodeReader(ctx)
  1140. if ctx.Written() {
  1141. return nil
  1142. }
  1143. cancel := context.RepoRef()(ctx)
  1144. if ctx.Written() {
  1145. return cancel
  1146. }
  1147. repo.MustBeNotEmpty(ctx)
  1148. return cancel
  1149. })
  1150. m.Get("/pulls/posters", repo.PullPosters)
  1151. m.Group("/pulls/{index}", func() {
  1152. m.Get("", repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewIssue)
  1153. m.Get(".diff", repo.DownloadPullDiff)
  1154. m.Get(".patch", repo.DownloadPullPatch)
  1155. m.Group("/commits", func() {
  1156. m.Get("", context.RepoRef(), repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewPullCommits)
  1157. m.Get("/list", context.RepoRef(), repo.GetPullCommits)
  1158. m.Get("/{sha:[a-f0-9]{7,40}}", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForSingleCommit)
  1159. })
  1160. m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
  1161. m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest)
  1162. m.Post("/update", repo.UpdatePullRequest)
  1163. m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits)
  1164. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  1165. m.Group("/files", func() {
  1166. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForAllCommitsOfPr)
  1167. m.Get("/{sha:[a-f0-9]{7,40}}", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesStartingFromCommit)
  1168. m.Get("/{shaFrom:[a-f0-9]{7,40}}..{shaTo:[a-f0-9]{7,40}}", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForRange)
  1169. m.Group("/reviews", func() {
  1170. m.Get("/new_comment", repo.RenderNewCodeCommentForm)
  1171. m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.SetShowOutdatedComments, repo.CreateCodeComment)
  1172. m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview)
  1173. }, context.RepoMustNotBeArchived())
  1174. })
  1175. }, repo.MustAllowPulls)
  1176. m.Group("/media", func() {
  1177. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  1178. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  1179. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  1180. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  1181. // "/*" route is deprecated, and kept for backward compatibility
  1182. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  1183. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1184. m.Group("/raw", func() {
  1185. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  1186. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  1187. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  1188. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  1189. // "/*" route is deprecated, and kept for backward compatibility
  1190. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  1191. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1192. m.Group("/render", func() {
  1193. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RenderFile)
  1194. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RenderFile)
  1195. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RenderFile)
  1196. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.RenderFile)
  1197. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1198. m.Group("/commits", func() {
  1199. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  1200. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  1201. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  1202. // "/*" route is deprecated, and kept for backward compatibility
  1203. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  1204. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1205. m.Group("/blame", func() {
  1206. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  1207. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  1208. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  1209. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1210. m.Group("", func() {
  1211. m.Get("/graph", repo.Graph)
  1212. m.Get("/commit/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1213. m.Get("/commit/{sha:([a-f0-9]{7,40})$}/load-branches-and-tags", repo.LoadBranchesAndTags)
  1214. m.Get("/cherry-pick/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.CherryPick)
  1215. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1216. m.Get("/rss/branch/*", context.RepoRefByType(context.RepoRefBranch), feedEnabled, feed.RenderBranchFeed)
  1217. m.Get("/atom/branch/*", context.RepoRefByType(context.RepoRefBranch), feedEnabled, feed.RenderBranchFeed)
  1218. m.Group("/src", func() {
  1219. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  1220. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  1221. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  1222. // "/*" route is deprecated, and kept for backward compatibility
  1223. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  1224. }, repo.SetEditorconfigIfExists)
  1225. m.Group("", func() {
  1226. m.Get("/forks", repo.Forks)
  1227. }, context.RepoRef(), reqRepoCodeReader)
  1228. m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}", repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  1229. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1230. m.Post("/{username}/{reponame}/lastcommit/*", ignSignInAndCsrf, context.RepoAssignment, context.UnitTypes(), context.RepoRefByType(context.RepoRefCommit), reqRepoCodeReader, repo.LastCommit)
  1231. m.Group("/{username}/{reponame}", func() {
  1232. m.Get("/stars", repo.Stars)
  1233. m.Get("/watchers", repo.Watchers)
  1234. m.Get("/search", reqRepoCodeReader, repo.Search)
  1235. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1236. m.Group("/{username}", func() {
  1237. m.Group("/{reponame}", func() {
  1238. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  1239. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1240. m.Group("/{reponame}", func() {
  1241. m.Group("/info/lfs", func() {
  1242. m.Post("/objects/batch", lfs.CheckAcceptMediaType, lfs.BatchHandler)
  1243. m.Put("/objects/{oid}/{size}", lfs.UploadHandler)
  1244. m.Get("/objects/{oid}/{filename}", lfs.DownloadHandler)
  1245. m.Get("/objects/{oid}", lfs.DownloadHandler)
  1246. m.Post("/verify", lfs.CheckAcceptMediaType, lfs.VerifyHandler)
  1247. m.Group("/locks", func() {
  1248. m.Get("/", lfs.GetListLockHandler)
  1249. m.Post("/", lfs.PostLockHandler)
  1250. m.Post("/verify", lfs.VerifyLockHandler)
  1251. m.Post("/{lid}/unlock", lfs.UnLockHandler)
  1252. }, lfs.CheckAcceptMediaType)
  1253. m.Any("/*", func(ctx *context.Context) {
  1254. ctx.NotFound("", nil)
  1255. })
  1256. }, ignSignInAndCsrf, lfsServerEnabled)
  1257. m.Group("", func() {
  1258. m.PostOptions("/git-upload-pack", repo.ServiceUploadPack)
  1259. m.PostOptions("/git-receive-pack", repo.ServiceReceivePack)
  1260. m.GetOptions("/info/refs", repo.GetInfoRefs)
  1261. m.GetOptions("/HEAD", repo.GetTextFile("HEAD"))
  1262. m.GetOptions("/objects/info/alternates", repo.GetTextFile("objects/info/alternates"))
  1263. m.GetOptions("/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates"))
  1264. m.GetOptions("/objects/info/packs", repo.GetInfoPacks)
  1265. m.GetOptions("/objects/info/{file:[^/]*}", repo.GetTextFile(""))
  1266. m.GetOptions("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject)
  1267. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile)
  1268. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile)
  1269. }, ignSignInAndCsrf, repo.HTTPGitEnabledHandler, repo.CorsHandler(), context_service.UserAssignmentWeb())
  1270. })
  1271. })
  1272. // ***** END: Repository *****
  1273. m.Group("/notifications", func() {
  1274. m.Get("", user.Notifications)
  1275. m.Get("/subscriptions", user.NotificationSubscriptions)
  1276. m.Get("/watching", user.NotificationWatching)
  1277. m.Post("/status", user.NotificationStatusPost)
  1278. m.Post("/purge", user.NotificationPurgePost)
  1279. m.Get("/new", user.NewAvailable)
  1280. }, reqSignIn)
  1281. if setting.API.EnableSwagger {
  1282. m.Get("/swagger.v1.json", SwaggerV1Json)
  1283. }
  1284. if !setting.IsProd {
  1285. m.Any("/devtest", devtest.List)
  1286. m.Any("/devtest/fetch-action-test", devtest.FetchActionTest)
  1287. m.Any("/devtest/{sub}", devtest.Tmpl)
  1288. }
  1289. m.NotFound(func(w http.ResponseWriter, req *http.Request) {
  1290. ctx := context.GetWebContext(req)
  1291. ctx.NotFound("", nil)
  1292. })
  1293. }