gitea源码

web.go 71KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package web
  4. import (
  5. "net/http"
  6. "strings"
  7. auth_model "code.gitea.io/gitea/models/auth"
  8. "code.gitea.io/gitea/models/perm"
  9. "code.gitea.io/gitea/models/unit"
  10. "code.gitea.io/gitea/modules/git"
  11. "code.gitea.io/gitea/modules/graceful"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/metrics"
  14. "code.gitea.io/gitea/modules/public"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/storage"
  17. "code.gitea.io/gitea/modules/structs"
  18. "code.gitea.io/gitea/modules/templates"
  19. "code.gitea.io/gitea/modules/validation"
  20. "code.gitea.io/gitea/modules/web"
  21. "code.gitea.io/gitea/modules/web/middleware"
  22. "code.gitea.io/gitea/modules/web/routing"
  23. "code.gitea.io/gitea/routers/common"
  24. "code.gitea.io/gitea/routers/web/admin"
  25. "code.gitea.io/gitea/routers/web/auth"
  26. "code.gitea.io/gitea/routers/web/devtest"
  27. "code.gitea.io/gitea/routers/web/events"
  28. "code.gitea.io/gitea/routers/web/explore"
  29. "code.gitea.io/gitea/routers/web/feed"
  30. "code.gitea.io/gitea/routers/web/healthcheck"
  31. "code.gitea.io/gitea/routers/web/misc"
  32. "code.gitea.io/gitea/routers/web/org"
  33. org_setting "code.gitea.io/gitea/routers/web/org/setting"
  34. "code.gitea.io/gitea/routers/web/repo"
  35. "code.gitea.io/gitea/routers/web/repo/actions"
  36. repo_setting "code.gitea.io/gitea/routers/web/repo/setting"
  37. shared_actions "code.gitea.io/gitea/routers/web/shared/actions"
  38. "code.gitea.io/gitea/routers/web/shared/project"
  39. "code.gitea.io/gitea/routers/web/user"
  40. user_setting "code.gitea.io/gitea/routers/web/user/setting"
  41. "code.gitea.io/gitea/routers/web/user/setting/security"
  42. auth_service "code.gitea.io/gitea/services/auth"
  43. "code.gitea.io/gitea/services/context"
  44. "code.gitea.io/gitea/services/forms"
  45. _ "code.gitea.io/gitea/modules/session" // to registers all internal adapters
  46. "gitea.com/go-chi/captcha"
  47. chi_middleware "github.com/go-chi/chi/v5/middleware"
  48. "github.com/go-chi/cors"
  49. "github.com/klauspost/compress/gzhttp"
  50. "github.com/prometheus/client_golang/prometheus"
  51. )
  52. var GzipMinSize = 1400 // min size to compress for the body size of response
  53. // optionsCorsHandler return a http handler which sets CORS options if enabled by config, it blocks non-CORS OPTIONS requests.
  54. func optionsCorsHandler() func(next http.Handler) http.Handler {
  55. var corsHandler func(next http.Handler) http.Handler
  56. if setting.CORSConfig.Enabled {
  57. corsHandler = cors.Handler(cors.Options{
  58. AllowedOrigins: setting.CORSConfig.AllowDomain,
  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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  67. if r.Method == http.MethodOptions {
  68. if corsHandler != nil && r.Header.Get("Access-Control-Request-Method") != "" {
  69. corsHandler(next).ServeHTTP(w, r)
  70. } else {
  71. // it should explicitly deny OPTIONS requests if CORS handler is not executed, to avoid the next GET/POST handler being incorrectly called by the OPTIONS request
  72. w.WriteHeader(http.StatusMethodNotAllowed)
  73. }
  74. return
  75. }
  76. // for non-OPTIONS requests, call the CORS handler to add some related headers like "Vary"
  77. if corsHandler != nil {
  78. corsHandler(next).ServeHTTP(w, r)
  79. } else {
  80. next.ServeHTTP(w, r)
  81. }
  82. })
  83. }
  84. }
  85. // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
  86. // in the session (if there is a user id stored in session other plugins might return the user
  87. // object for that id).
  88. //
  89. // The Session plugin is expected to be executed second, in order to skip authentication
  90. // for users that have already signed in.
  91. func buildAuthGroup() *auth_service.Group {
  92. group := auth_service.NewGroup()
  93. group.Add(&auth_service.OAuth2{}) // FIXME: this should be removed and only applied in download and oauth related routers
  94. group.Add(&auth_service.Basic{}) // FIXME: this should be removed and only applied in download and git/lfs routers
  95. if setting.Service.EnableReverseProxyAuth {
  96. group.Add(&auth_service.ReverseProxy{}) // reverse-proxy should before Session, otherwise the header will be ignored if user has login
  97. }
  98. group.Add(&auth_service.Session{})
  99. if setting.IsWindows && auth_model.IsSSPIEnabled(graceful.GetManager().ShutdownContext()) {
  100. group.Add(&auth_service.SSPI{}) // it MUST be the last, see the comment of SSPI
  101. }
  102. return group
  103. }
  104. func webAuth(authMethod auth_service.Method) func(*context.Context) {
  105. return func(ctx *context.Context) {
  106. ar, err := common.AuthShared(ctx.Base, ctx.Session, authMethod)
  107. if err != nil {
  108. log.Error("Failed to verify user: %v", err)
  109. ctx.HTTPError(http.StatusUnauthorized, "Failed to authenticate user")
  110. return
  111. }
  112. ctx.Doer = ar.Doer
  113. ctx.IsSigned = ar.Doer != nil
  114. ctx.IsBasicAuth = ar.IsBasicAuth
  115. if ctx.Doer == nil {
  116. // ensure the session uid is deleted
  117. _ = ctx.Session.Delete("uid")
  118. }
  119. ctx.Csrf.PrepareForSessionUser(ctx)
  120. }
  121. }
  122. // verifyAuthWithOptions checks authentication according to options
  123. func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.Context) {
  124. return func(ctx *context.Context) {
  125. // Check prohibit login users.
  126. if ctx.IsSigned {
  127. if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm {
  128. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  129. ctx.HTML(http.StatusOK, "user/auth/activate")
  130. return
  131. }
  132. if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin {
  133. log.Info("Failed authentication attempt for %s from %s", ctx.Doer.Name, ctx.RemoteAddr())
  134. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  135. ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
  136. return
  137. }
  138. if ctx.Doer.MustChangePassword {
  139. if ctx.Req.URL.Path != "/user/settings/change_password" {
  140. if strings.HasPrefix(ctx.Req.UserAgent(), "git") {
  141. ctx.HTTPError(http.StatusUnauthorized, ctx.Locale.TrString("auth.must_change_password"))
  142. return
  143. }
  144. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  145. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  146. if ctx.Req.URL.Path != "/user/events" {
  147. middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI())
  148. }
  149. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  150. return
  151. }
  152. } else if ctx.Req.URL.Path == "/user/settings/change_password" {
  153. // make sure that the form cannot be accessed by users who don't need this
  154. ctx.Redirect(setting.AppSubURL + "/")
  155. return
  156. }
  157. }
  158. // Redirect to dashboard (or alternate location) if user tries to visit any non-login page.
  159. if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" {
  160. ctx.RedirectToCurrentSite(ctx.FormString("redirect_to"))
  161. return
  162. }
  163. if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == http.MethodPost {
  164. ctx.Csrf.Validate(ctx)
  165. if ctx.Written() {
  166. return
  167. }
  168. }
  169. if options.SignInRequired {
  170. if !ctx.IsSigned {
  171. if ctx.Req.URL.Path != "/user/events" {
  172. middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI())
  173. }
  174. ctx.Redirect(setting.AppSubURL + "/user/login")
  175. return
  176. } else if !ctx.Doer.IsActive && setting.Service.RegisterEmailConfirm {
  177. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  178. ctx.HTML(http.StatusOK, "user/auth/activate")
  179. return
  180. }
  181. }
  182. // Redirect to log in page if auto-signin info is provided and has not signed in.
  183. if !options.SignOutRequired && !ctx.IsSigned &&
  184. ctx.GetSiteCookie(setting.CookieRememberName) != "" {
  185. if ctx.Req.URL.Path != "/user/events" {
  186. middleware.SetRedirectToCookie(ctx.Resp, setting.AppSubURL+ctx.Req.URL.RequestURI())
  187. }
  188. ctx.Redirect(setting.AppSubURL + "/user/login")
  189. return
  190. }
  191. if options.AdminRequired {
  192. if !ctx.Doer.IsAdmin {
  193. ctx.HTTPError(http.StatusForbidden)
  194. return
  195. }
  196. ctx.Data["PageIsAdmin"] = true
  197. }
  198. }
  199. }
  200. func ctxDataSet(args ...any) func(ctx *context.Context) {
  201. return func(ctx *context.Context) {
  202. for i := 0; i < len(args); i += 2 {
  203. ctx.Data[args[i].(string)] = args[i+1]
  204. }
  205. }
  206. }
  207. // Routes returns all web routes
  208. func Routes() *web.Router {
  209. routes := web.NewRouter()
  210. routes.Head("/", misc.DummyOK) // for health check - doesn't need to be passed through gzip handler
  211. routes.Methods("GET, HEAD, OPTIONS", "/assets/*", optionsCorsHandler(), public.FileHandlerFunc())
  212. routes.Methods("GET, HEAD", "/avatars/*", avatarStorageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
  213. routes.Methods("GET, HEAD", "/repo-avatars/*", avatarStorageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
  214. routes.Methods("GET, HEAD", "/apple-touch-icon.png", misc.StaticRedirect("/assets/img/apple-touch-icon.png"))
  215. routes.Methods("GET, HEAD", "/apple-touch-icon-precomposed.png", misc.StaticRedirect("/assets/img/apple-touch-icon.png"))
  216. routes.Methods("GET, HEAD", "/favicon.ico", misc.StaticRedirect("/assets/img/favicon.png"))
  217. _ = templates.HTMLRenderer()
  218. var mid []any
  219. if setting.EnableGzip {
  220. // random jitter is recommended by: https://pkg.go.dev/github.com/klauspost/compress/gzhttp#readme-breach-mitigation
  221. // compression level 6 is the gzip default and a good general tradeoff between speed, CPU usage, and compression
  222. wrapper, err := gzhttp.NewWrapper(gzhttp.RandomJitter(32, 0, false), gzhttp.MinSize(GzipMinSize), gzhttp.CompressionLevel(6))
  223. if err != nil {
  224. log.Fatal("gzhttp.NewWrapper failed: %v", err)
  225. }
  226. mid = append(mid, wrapper)
  227. }
  228. if setting.Service.EnableCaptcha {
  229. // The captcha http.Handler should only fire on /captcha/* so we can just mount this on that url
  230. routes.Methods("GET,HEAD", "/captcha/*", append(mid, captcha.Captchaer(context.GetImageCaptcha()))...)
  231. }
  232. if setting.Metrics.Enabled {
  233. prometheus.MustRegister(metrics.NewCollector())
  234. routes.Get("/metrics", append(mid, Metrics)...)
  235. }
  236. routes.Methods("GET,HEAD", "/robots.txt", append(mid, misc.RobotsTxt)...)
  237. routes.Get("/ssh_info", misc.SSHInfo)
  238. routes.Get("/api/healthz", healthcheck.Check)
  239. mid = append(mid, common.Sessioner(), context.Contexter())
  240. // Get user from session if logged in.
  241. mid = append(mid, webAuth(buildAuthGroup()))
  242. // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route
  243. mid = append(mid, chi_middleware.GetHead)
  244. if setting.API.EnableSwagger {
  245. // Note: The route is here but no in API routes because it renders a web page
  246. routes.Get("/api/swagger", append(mid, misc.Swagger)...) // Render V1 by default
  247. }
  248. mid = append(mid, goGet)
  249. mid = append(mid, common.PageGlobalData)
  250. webRoutes := web.NewRouter()
  251. webRoutes.Use(mid...)
  252. webRoutes.Group("", func() { registerWebRoutes(webRoutes) }, common.BlockExpensive(), common.QoS())
  253. routes.Mount("", webRoutes)
  254. return routes
  255. }
  256. var optSignInIgnoreCsrf = verifyAuthWithOptions(&common.VerifyOptions{DisableCSRF: true})
  257. // registerWebRoutes register routes
  258. func registerWebRoutes(m *web.Router) {
  259. // required to be signed in or signed out
  260. reqSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: true})
  261. reqSignOut := verifyAuthWithOptions(&common.VerifyOptions{SignOutRequired: true})
  262. // optional sign in (if signed in, use the user as doer, if not, no doer)
  263. optSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: setting.Service.RequireSignInViewStrict})
  264. optExploreSignIn := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: setting.Service.RequireSignInViewStrict || setting.Service.Explore.RequireSigninView})
  265. validation.AddBindingRules()
  266. linkAccountEnabled := func(ctx *context.Context) {
  267. if !setting.Service.EnableOpenIDSignIn && !setting.Service.EnableOpenIDSignUp && !setting.OAuth2.Enabled {
  268. ctx.HTTPError(http.StatusForbidden)
  269. return
  270. }
  271. }
  272. openIDSignInEnabled := func(ctx *context.Context) {
  273. if !setting.Service.EnableOpenIDSignIn {
  274. ctx.HTTPError(http.StatusForbidden)
  275. return
  276. }
  277. }
  278. openIDSignUpEnabled := func(ctx *context.Context) {
  279. if !setting.Service.EnableOpenIDSignUp {
  280. ctx.HTTPError(http.StatusForbidden)
  281. return
  282. }
  283. }
  284. oauth2Enabled := func(ctx *context.Context) {
  285. if !setting.OAuth2.Enabled {
  286. ctx.HTTPError(http.StatusForbidden)
  287. return
  288. }
  289. }
  290. reqMilestonesDashboardPageEnabled := func(ctx *context.Context) {
  291. if !setting.Service.ShowMilestonesDashboardPage {
  292. ctx.HTTPError(http.StatusForbidden)
  293. return
  294. }
  295. }
  296. // webhooksEnabled requires webhooks to be enabled by admin.
  297. webhooksEnabled := func(ctx *context.Context) {
  298. if setting.DisableWebhooks {
  299. ctx.HTTPError(http.StatusForbidden)
  300. return
  301. }
  302. }
  303. starsEnabled := func(ctx *context.Context) {
  304. if setting.Repository.DisableStars {
  305. ctx.HTTPError(http.StatusForbidden)
  306. return
  307. }
  308. }
  309. lfsServerEnabled := func(ctx *context.Context) {
  310. if !setting.LFS.StartServer {
  311. ctx.HTTPError(http.StatusNotFound)
  312. return
  313. }
  314. }
  315. federationEnabled := func(ctx *context.Context) {
  316. if !setting.Federation.Enabled {
  317. ctx.HTTPError(http.StatusNotFound)
  318. return
  319. }
  320. }
  321. dlSourceEnabled := func(ctx *context.Context) {
  322. if setting.Repository.DisableDownloadSourceArchives {
  323. ctx.HTTPError(http.StatusNotFound)
  324. return
  325. }
  326. }
  327. sitemapEnabled := func(ctx *context.Context) {
  328. if !setting.Other.EnableSitemap {
  329. ctx.HTTPError(http.StatusNotFound)
  330. return
  331. }
  332. }
  333. packagesEnabled := func(ctx *context.Context) {
  334. if !setting.Packages.Enabled {
  335. ctx.HTTPError(http.StatusForbidden)
  336. return
  337. }
  338. }
  339. feedEnabled := func(ctx *context.Context) {
  340. if !setting.Other.EnableFeed {
  341. ctx.HTTPError(http.StatusNotFound)
  342. return
  343. }
  344. }
  345. reqUnitAccess := func(unitType unit.Type, accessMode perm.AccessMode, ignoreGlobal bool) func(ctx *context.Context) {
  346. return func(ctx *context.Context) {
  347. // only check global disabled units when ignoreGlobal is false
  348. if !ignoreGlobal && unitType.UnitGlobalDisabled() {
  349. ctx.NotFound(nil)
  350. return
  351. }
  352. if ctx.ContextUser == nil {
  353. ctx.NotFound(nil)
  354. return
  355. }
  356. if ctx.ContextUser.IsOrganization() {
  357. if ctx.Org.Organization.UnitPermission(ctx, ctx.Doer, unitType) < accessMode {
  358. ctx.NotFound(nil)
  359. return
  360. }
  361. }
  362. }
  363. }
  364. addWebhookAddRoutes := func() {
  365. m.Get("/{type}/new", repo_setting.WebhooksNew)
  366. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksNewPost)
  367. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksNewPost)
  368. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksNewPost)
  369. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksNewPost)
  370. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksNewPost)
  371. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksNewPost)
  372. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksNewPost)
  373. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksNewPost)
  374. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksNewPost)
  375. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksNewPost)
  376. m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksNewPost)
  377. }
  378. addWebhookEditRoutes := func() {
  379. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo_setting.GiteaHooksEditPost)
  380. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo_setting.GogsHooksEditPost)
  381. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo_setting.SlackHooksEditPost)
  382. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo_setting.DiscordHooksEditPost)
  383. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo_setting.DingtalkHooksEditPost)
  384. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo_setting.TelegramHooksEditPost)
  385. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo_setting.MatrixHooksEditPost)
  386. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo_setting.MSTeamsHooksEditPost)
  387. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo_setting.FeishuHooksEditPost)
  388. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo_setting.WechatworkHooksEditPost)
  389. m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksEditPost)
  390. }
  391. addSettingsVariablesRoutes := func() {
  392. m.Group("/variables", func() {
  393. m.Get("", shared_actions.Variables)
  394. m.Post("/new", web.Bind(forms.EditVariableForm{}), shared_actions.VariableCreate)
  395. m.Post("/{variable_id}/edit", web.Bind(forms.EditVariableForm{}), shared_actions.VariableUpdate)
  396. m.Post("/{variable_id}/delete", shared_actions.VariableDelete)
  397. })
  398. }
  399. addSettingsSecretsRoutes := func() {
  400. m.Group("/secrets", func() {
  401. m.Get("", repo_setting.Secrets)
  402. m.Post("", web.Bind(forms.AddSecretForm{}), repo_setting.SecretsPost)
  403. m.Post("/delete", repo_setting.SecretsDelete)
  404. })
  405. }
  406. addSettingsRunnersRoutes := func() {
  407. m.Group("/runners", func() {
  408. m.Get("", shared_actions.Runners)
  409. m.Combo("/{runnerid}").Get(shared_actions.RunnersEdit).
  410. Post(web.Bind(forms.EditRunnerForm{}), shared_actions.RunnersEditPost)
  411. m.Post("/{runnerid}/delete", shared_actions.RunnerDeletePost)
  412. m.Post("/reset_registration_token", shared_actions.ResetRunnerRegistrationToken)
  413. })
  414. }
  415. // FIXME: not all routes need go through same middleware.
  416. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  417. m.Get("/", Home)
  418. m.Get("/sitemap.xml", sitemapEnabled, optExploreSignIn, HomeSitemap)
  419. m.Group("/.well-known", func() {
  420. m.Get("/openid-configuration", auth.OIDCWellKnown)
  421. m.Group("", func() {
  422. m.Get("/nodeinfo", NodeInfoLinks)
  423. m.Get("/webfinger", WebfingerQuery)
  424. }, federationEnabled)
  425. m.Get("/change-password", func(ctx *context.Context) {
  426. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  427. })
  428. m.Get("/passkey-endpoints", passkeyEndpoints)
  429. m.Methods("GET, HEAD", "/*", public.FileHandlerFunc())
  430. }, optionsCorsHandler())
  431. m.Post("/-/markup", reqSignIn, web.Bind(structs.MarkupOption{}), misc.Markup)
  432. m.Group("/explore", func() {
  433. m.Get("", func(ctx *context.Context) {
  434. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  435. })
  436. m.Get("/repos", explore.Repos)
  437. m.Get("/repos/sitemap-{idx}.xml", sitemapEnabled, explore.Repos)
  438. m.Get("/users", explore.Users)
  439. m.Get("/users/sitemap-{idx}.xml", sitemapEnabled, explore.Users)
  440. m.Get("/organizations", explore.Organizations)
  441. m.Get("/code", func(ctx *context.Context) {
  442. if unit.TypeCode.UnitGlobalDisabled() {
  443. ctx.NotFound(nil)
  444. return
  445. }
  446. }, explore.Code)
  447. m.Get("/topics/search", explore.TopicSearch)
  448. }, optExploreSignIn)
  449. m.Group("/issues", func() {
  450. m.Get("", user.Issues)
  451. m.Get("/search", repo.SearchIssues)
  452. }, reqSignIn)
  453. m.Get("/pulls", reqSignIn, user.Pulls)
  454. m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
  455. // ***** START: User *****
  456. // "user/login" doesn't need signOut, then logged-in users can still access this route for redirection purposes by "/user/login?redirec_to=..."
  457. m.Get("/user/login", auth.SignIn)
  458. m.Group("/user", func() {
  459. m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost)
  460. m.Group("", func() {
  461. m.Combo("/login/openid").
  462. Get(auth.SignInOpenID).
  463. Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost)
  464. }, openIDSignInEnabled)
  465. m.Group("/openid", func() {
  466. m.Combo("/connect").
  467. Get(auth.ConnectOpenID).
  468. Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost)
  469. m.Group("/register", func() {
  470. m.Combo("").
  471. Get(auth.RegisterOpenID, openIDSignUpEnabled).
  472. Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost)
  473. }, openIDSignUpEnabled)
  474. }, openIDSignInEnabled)
  475. m.Get("/sign_up", auth.SignUp)
  476. m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost)
  477. m.Get("/link_account", linkAccountEnabled, auth.LinkAccount)
  478. m.Post("/link_account_signin", linkAccountEnabled, web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn)
  479. m.Post("/link_account_signup", linkAccountEnabled, web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister)
  480. m.Group("/two_factor", func() {
  481. m.Get("", auth.TwoFactor)
  482. m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost)
  483. m.Get("/scratch", auth.TwoFactorScratch)
  484. m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost)
  485. })
  486. m.Group("/webauthn", func() {
  487. m.Get("", auth.WebAuthn)
  488. m.Get("/passkey/assertion", auth.WebAuthnPasskeyAssertion)
  489. m.Post("/passkey/login", auth.WebAuthnPasskeyLogin)
  490. m.Get("/assertion", auth.WebAuthnLoginAssertion)
  491. m.Post("/assertion", auth.WebAuthnLoginAssertionPost)
  492. })
  493. }, reqSignOut)
  494. m.Any("/user/events", routing.MarkLongPolling, events.Events)
  495. m.Group("/login/oauth", func() {
  496. m.Group("", func() {
  497. m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  498. m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth)
  499. // TODO manage redirection
  500. m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  501. }, optSignInIgnoreCsrf, reqSignIn)
  502. m.Methods("GET, POST, OPTIONS", "/userinfo", optionsCorsHandler(), optSignInIgnoreCsrf, auth.InfoOAuth)
  503. m.Methods("POST, OPTIONS", "/access_token", optionsCorsHandler(), web.Bind(forms.AccessTokenForm{}), optSignInIgnoreCsrf, auth.AccessTokenOAuth)
  504. m.Methods("GET, OPTIONS", "/keys", optionsCorsHandler(), optSignInIgnoreCsrf, auth.OIDCKeys)
  505. m.Methods("POST, OPTIONS", "/introspect", optionsCorsHandler(), web.Bind(forms.IntrospectTokenForm{}), optSignInIgnoreCsrf, auth.IntrospectOAuth)
  506. }, oauth2Enabled)
  507. m.Group("/user/settings", func() {
  508. m.Get("", user_setting.Profile)
  509. m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost)
  510. m.Post("/update_preferences", user_setting.UpdatePreferences)
  511. m.Get("/change_password", auth.MustChangePassword)
  512. m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost)
  513. m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost)
  514. m.Post("/avatar/delete", user_setting.DeleteAvatar)
  515. m.Group("/account", func() {
  516. m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost)
  517. m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost)
  518. m.Post("/email/delete", user_setting.DeleteEmail)
  519. m.Post("/delete", user_setting.DeleteAccount)
  520. })
  521. m.Group("/appearance", func() {
  522. m.Get("", user_setting.Appearance)
  523. m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang)
  524. m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments)
  525. m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost)
  526. })
  527. m.Group("/notifications", func() {
  528. m.Get("", user_setting.Notifications)
  529. m.Post("/email", user_setting.NotificationsEmailPost)
  530. m.Post("/actions", user_setting.NotificationsActionsEmailPost)
  531. })
  532. m.Group("/security", func() {
  533. m.Get("", security.Security)
  534. m.Group("/two_factor", func() {
  535. m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor)
  536. m.Post("/disable", security.DisableTwoFactor)
  537. m.Get("/enroll", security.EnrollTwoFactor)
  538. m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost)
  539. })
  540. m.Group("/webauthn", func() {
  541. m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister)
  542. m.Post("/register", security.WebauthnRegisterPost)
  543. m.Post("/delete", web.Bind(forms.WebauthnDeleteForm{}), security.WebauthnDelete)
  544. })
  545. m.Group("/openid", func() {
  546. m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost)
  547. m.Post("/delete", security.DeleteOpenID)
  548. m.Post("/toggle_visibility", security.ToggleOpenIDVisibility)
  549. }, openIDSignInEnabled)
  550. m.Post("/account_link", linkAccountEnabled, security.DeleteAccountLink)
  551. })
  552. m.Group("/applications", func() {
  553. // oauth2 applications
  554. m.Group("/oauth2", func() {
  555. m.Get("/{id}", user_setting.OAuth2ApplicationShow)
  556. m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit)
  557. m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret)
  558. m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost)
  559. m.Post("/{id}/delete", user_setting.DeleteOAuth2Application)
  560. m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant)
  561. }, oauth2Enabled)
  562. // access token applications
  563. m.Combo("").Get(user_setting.Applications).
  564. Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost)
  565. m.Post("/delete", user_setting.DeleteApplication)
  566. })
  567. m.Combo("/keys").Get(user_setting.Keys).
  568. Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost)
  569. m.Post("/keys/delete", user_setting.DeleteKey)
  570. m.Group("/packages", func() {
  571. m.Get("", user_setting.Packages)
  572. m.Group("/rules", func() {
  573. m.Group("/add", func() {
  574. m.Get("", user_setting.PackagesRuleAdd)
  575. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost)
  576. })
  577. m.Group("/{id}", func() {
  578. m.Get("", user_setting.PackagesRuleEdit)
  579. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost)
  580. m.Get("/preview", user_setting.PackagesRulePreview)
  581. })
  582. })
  583. m.Group("/cargo", func() {
  584. m.Post("/initialize", user_setting.InitializeCargoIndex)
  585. m.Post("/rebuild", user_setting.RebuildCargoIndex)
  586. })
  587. m.Post("/chef/regenerate_keypair", user_setting.RegenerateChefKeyPair)
  588. }, packagesEnabled)
  589. m.Group("/actions", func() {
  590. m.Get("", user_setting.RedirectToDefaultSetting)
  591. addSettingsRunnersRoutes()
  592. addSettingsSecretsRoutes()
  593. addSettingsVariablesRoutes()
  594. }, actions.MustEnableActions)
  595. m.Get("/organization", user_setting.Organization)
  596. m.Get("/repos", user_setting.Repos)
  597. m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository)
  598. m.Group("/hooks", func() {
  599. m.Get("", user_setting.Webhooks)
  600. m.Post("/delete", user_setting.DeleteWebhook)
  601. addWebhookAddRoutes()
  602. m.Group("/{id}", func() {
  603. m.Get("", repo_setting.WebHooksEdit)
  604. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  605. })
  606. addWebhookEditRoutes()
  607. }, webhooksEnabled)
  608. m.Group("/blocked_users", func() {
  609. m.Get("", user_setting.BlockedUsers)
  610. m.Post("", web.Bind(forms.BlockUserForm{}), user_setting.BlockedUsersPost)
  611. })
  612. }, reqSignIn, ctxDataSet("PageIsUserSettings", true, "EnablePackages", setting.Packages.Enabled, "EnableNotifyMail", setting.Service.EnableNotifyMail))
  613. m.Group("/user", func() {
  614. m.Get("/activate", auth.Activate)
  615. m.Post("/activate", auth.ActivatePost)
  616. m.Any("/activate_email", auth.ActivateEmail)
  617. m.Get("/avatar/{username}/{size}", user.AvatarByUsernameSize)
  618. m.Get("/recover_account", auth.ResetPasswd)
  619. m.Post("/recover_account", auth.ResetPasswdPost)
  620. m.Get("/forgot_password", auth.ForgotPasswd)
  621. m.Post("/forgot_password", auth.ForgotPasswdPost)
  622. m.Post("/logout", auth.SignOut)
  623. m.Get("/stopwatches", reqSignIn, user.GetStopwatches)
  624. m.Get("/search_candidates", optExploreSignIn, user.SearchCandidates)
  625. m.Group("/oauth2", func() {
  626. m.Get("/{provider}", auth.SignInOAuth)
  627. m.Get("/{provider}/callback", auth.SignInOAuthCallback)
  628. })
  629. })
  630. // ***** END: User *****
  631. m.Get("/avatar/{hash}", user.AvatarByEmailHash)
  632. adminReq := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: true, AdminRequired: true})
  633. // ***** START: Admin *****
  634. m.Group("/-/admin", func() {
  635. m.Get("", admin.Dashboard)
  636. m.Get("/system_status", admin.SystemStatus)
  637. m.Post("", web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost)
  638. m.Get("/self_check", admin.SelfCheck)
  639. m.Post("/self_check", admin.SelfCheckPost)
  640. m.Group("/config", func() {
  641. m.Get("", admin.Config)
  642. m.Post("", admin.ChangeConfig)
  643. m.Post("/test_mail", admin.SendTestMail)
  644. m.Post("/test_cache", admin.TestCache)
  645. m.Get("/settings", admin.ConfigSettings)
  646. })
  647. m.Group("/monitor", func() {
  648. m.Get("/stats", admin.MonitorStats)
  649. m.Get("/cron", admin.CronTasks)
  650. m.Get("/perftrace", admin.PerfTrace)
  651. m.Get("/stacktrace", admin.Stacktrace)
  652. m.Post("/stacktrace/cancel/{pid}", admin.StacktraceCancel)
  653. m.Get("/queue", admin.Queues)
  654. m.Group("/queue/{qid}", func() {
  655. m.Get("", admin.QueueManage)
  656. m.Post("/set", admin.QueueSet)
  657. m.Post("/remove-all-items", admin.QueueRemoveAllItems)
  658. })
  659. m.Get("/diagnosis", admin.MonitorDiagnosis)
  660. })
  661. m.Group("/users", func() {
  662. m.Get("", admin.Users)
  663. m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost)
  664. m.Get("/{userid}", admin.ViewUser)
  665. m.Combo("/{userid}/edit").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost)
  666. m.Post("/{userid}/delete", admin.DeleteUser)
  667. m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost)
  668. m.Post("/{userid}/avatar/delete", admin.DeleteAvatar)
  669. })
  670. m.Group("/emails", func() {
  671. m.Get("", admin.Emails)
  672. m.Post("/activate", admin.ActivateEmail)
  673. m.Post("/delete", admin.DeleteEmail)
  674. })
  675. m.Group("/orgs", func() {
  676. m.Get("", admin.Organizations)
  677. })
  678. m.Group("/repos", func() {
  679. m.Get("", admin.Repos)
  680. m.Combo("/unadopted").Get(admin.UnadoptedRepos).Post(admin.AdoptOrDeleteRepository)
  681. m.Post("/delete", admin.DeleteRepo)
  682. })
  683. m.Group("/packages", func() {
  684. m.Get("", admin.Packages)
  685. m.Post("/delete", admin.DeletePackageVersion)
  686. m.Post("/cleanup", admin.CleanupExpiredData)
  687. }, packagesEnabled)
  688. m.Group("/hooks", func() {
  689. m.Get("", admin.DefaultOrSystemWebhooks)
  690. m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
  691. m.Group("/{id}", func() {
  692. m.Get("", repo_setting.WebHooksEdit)
  693. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  694. })
  695. addWebhookEditRoutes()
  696. }, webhooksEnabled)
  697. m.Group("/{configType:default-hooks|system-hooks}", func() {
  698. addWebhookAddRoutes()
  699. })
  700. m.Group("/auths", func() {
  701. m.Get("", admin.Authentications)
  702. m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost)
  703. m.Combo("/{authid}").Get(admin.EditAuthSource).
  704. Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost)
  705. m.Post("/{authid}/delete", admin.DeleteAuthSource)
  706. })
  707. m.Group("/notices", func() {
  708. m.Get("", admin.Notices)
  709. m.Post("/delete", admin.DeleteNotices)
  710. m.Post("/empty", admin.EmptyNotices)
  711. })
  712. m.Group("/applications", func() {
  713. m.Get("", admin.Applications)
  714. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost)
  715. m.Group("/oauth2/{id}", func() {
  716. m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost)
  717. m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret)
  718. m.Post("/delete", admin.DeleteApplication)
  719. })
  720. }, oauth2Enabled)
  721. m.Group("/actions", func() {
  722. m.Get("", admin.RedirectToDefaultSetting)
  723. addSettingsRunnersRoutes()
  724. addSettingsVariablesRoutes()
  725. })
  726. }, adminReq, ctxDataSet("EnableOAuth2", setting.OAuth2.Enabled, "EnablePackages", setting.Packages.Enabled))
  727. // ***** END: Admin *****
  728. m.Group("", func() {
  729. m.Get("/{username}", user.UsernameSubRoute)
  730. m.Methods("GET, OPTIONS", "/attachments/{uuid}", optionsCorsHandler(), repo.GetAttachment)
  731. }, optSignIn)
  732. m.Post("/{username}", reqSignIn, context.UserAssignmentWeb(), user.ActionUserFollow)
  733. reqRepoAdmin := context.RequireRepoAdmin()
  734. reqRepoCodeWriter := context.RequireUnitWriter(unit.TypeCode)
  735. reqRepoReleaseWriter := context.RequireUnitWriter(unit.TypeReleases)
  736. reqRepoReleaseReader := context.RequireUnitReader(unit.TypeReleases)
  737. reqRepoIssuesOrPullsWriter := context.RequireUnitWriter(unit.TypeIssues, unit.TypePullRequests)
  738. reqRepoIssuesOrPullsReader := context.RequireUnitReader(unit.TypeIssues, unit.TypePullRequests)
  739. reqRepoProjectsReader := context.RequireUnitReader(unit.TypeProjects)
  740. reqRepoProjectsWriter := context.RequireUnitWriter(unit.TypeProjects)
  741. reqRepoActionsReader := context.RequireUnitReader(unit.TypeActions)
  742. reqRepoActionsWriter := context.RequireUnitWriter(unit.TypeActions)
  743. // the legacy names "reqRepoXxx" should be renamed to the correct name "reqUnitXxx", these permissions are for units, not repos
  744. reqUnitsWithMarkdown := context.RequireUnitReader(unit.TypeCode, unit.TypeIssues, unit.TypePullRequests, unit.TypeReleases, unit.TypeWiki)
  745. reqUnitCodeReader := context.RequireUnitReader(unit.TypeCode)
  746. reqUnitIssuesReader := context.RequireUnitReader(unit.TypeIssues)
  747. reqUnitPullsReader := context.RequireUnitReader(unit.TypePullRequests)
  748. reqUnitWikiReader := context.RequireUnitReader(unit.TypeWiki)
  749. reqUnitWikiWriter := context.RequireUnitWriter(unit.TypeWiki)
  750. reqPackageAccess := func(accessMode perm.AccessMode) func(ctx *context.Context) {
  751. return func(ctx *context.Context) {
  752. if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
  753. ctx.NotFound(nil)
  754. }
  755. }
  756. }
  757. individualPermsChecker := func(ctx *context.Context) {
  758. // org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked.
  759. if ctx.ContextUser.IsIndividual() {
  760. switch ctx.ContextUser.Visibility {
  761. case structs.VisibleTypePrivate:
  762. if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) {
  763. ctx.NotFound(nil)
  764. return
  765. }
  766. case structs.VisibleTypeLimited:
  767. if ctx.Doer == nil {
  768. ctx.NotFound(nil)
  769. return
  770. }
  771. }
  772. }
  773. }
  774. m.Group("/org", func() {
  775. m.Group("/{org}", func() {
  776. m.Get("/members", org.Members)
  777. }, context.OrgAssignment(context.OrgAssignmentOptions{}))
  778. }, optSignIn)
  779. // end "/org": members
  780. m.Group("/org", func() {
  781. m.Group("", func() {
  782. m.Get("/create", org.Create)
  783. m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost)
  784. })
  785. m.Group("/invite/{token}", func() {
  786. m.Get("", org.TeamInvite)
  787. m.Post("", org.TeamInvitePost)
  788. })
  789. m.Group("/{org}", func() {
  790. m.Get("/dashboard", user.Dashboard)
  791. m.Get("/dashboard/{team}", user.Dashboard)
  792. m.Get("/issues", user.Issues)
  793. m.Get("/issues/{team}", user.Issues)
  794. m.Get("/pulls", user.Pulls)
  795. m.Get("/pulls/{team}", user.Pulls)
  796. m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
  797. m.Get("/milestones/{team}", reqMilestonesDashboardPageEnabled, user.Milestones)
  798. m.Post("/members/action/{action}", org.MembersAction)
  799. m.Get("/teams", org.Teams)
  800. }, context.OrgAssignment(context.OrgAssignmentOptions{RequireMember: true, RequireTeamMember: true}))
  801. m.Group("/{org}", func() {
  802. m.Get("/teams/{team}", org.TeamMembers)
  803. m.Get("/teams/{team}/repositories", org.TeamRepositories)
  804. m.Post("/teams/{team}/action/{action}", org.TeamsAction)
  805. m.Post("/teams/{team}/action/repo/{action}", org.TeamsRepoAction)
  806. }, context.OrgAssignment(context.OrgAssignmentOptions{RequireMember: true, RequireTeamMember: true}))
  807. // require member/team-admin permission (old logic is: requireMember=true, requireTeamAdmin=true)
  808. // but it doesn't seem right: requireTeamAdmin does nothing
  809. m.Group("/{org}", func() {
  810. m.Get("/teams/-/search", org.SearchTeam)
  811. }, context.OrgAssignment(context.OrgAssignmentOptions{RequireMember: true, RequireTeamAdmin: true}))
  812. // require owner permission
  813. m.Group("/{org}", func() {
  814. m.Get("/teams/new", org.NewTeam)
  815. m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost)
  816. m.Get("/teams/{team}/edit", org.EditTeam)
  817. m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost)
  818. m.Post("/teams/{team}/delete", org.DeleteTeam)
  819. m.Get("/worktime", context.OrgAssignment(context.OrgAssignmentOptions{RequireOwner: true}), org.Worktime)
  820. m.Group("/settings", func() {
  821. m.Combo("").Get(org.Settings).
  822. Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost)
  823. m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar)
  824. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  825. m.Group("/applications", func() {
  826. m.Get("", org.Applications)
  827. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost)
  828. m.Group("/oauth2/{id}", func() {
  829. m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit)
  830. m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret)
  831. m.Post("/delete", org.DeleteOAuth2Application)
  832. })
  833. }, oauth2Enabled)
  834. m.Group("/hooks", func() {
  835. m.Get("", org.Webhooks)
  836. m.Post("/delete", org.DeleteWebhook)
  837. addWebhookAddRoutes()
  838. m.Group("/{id}", func() {
  839. m.Get("", repo_setting.WebHooksEdit)
  840. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  841. })
  842. addWebhookEditRoutes()
  843. }, webhooksEnabled)
  844. m.Group("/labels", func() {
  845. m.Get("", org.RetrieveLabels, org.Labels)
  846. m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel)
  847. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel)
  848. m.Post("/delete", org.DeleteLabel)
  849. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels)
  850. })
  851. m.Group("/actions", func() {
  852. m.Get("", org_setting.RedirectToDefaultSetting)
  853. addSettingsRunnersRoutes()
  854. addSettingsSecretsRoutes()
  855. addSettingsVariablesRoutes()
  856. }, actions.MustEnableActions)
  857. m.Post("/rename", web.Bind(forms.RenameOrgForm{}), org.SettingsRenamePost)
  858. m.Post("/delete", org.SettingsDeleteOrgPost)
  859. m.Post("/visibility", org.SettingsChangeVisibilityPost)
  860. m.Group("/packages", func() {
  861. m.Get("", org.Packages)
  862. m.Group("/rules", func() {
  863. m.Group("/add", func() {
  864. m.Get("", org.PackagesRuleAdd)
  865. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost)
  866. })
  867. m.Group("/{id}", func() {
  868. m.Get("", org.PackagesRuleEdit)
  869. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost)
  870. m.Get("/preview", org.PackagesRulePreview)
  871. })
  872. })
  873. m.Group("/cargo", func() {
  874. m.Post("/initialize", org.InitializeCargoIndex)
  875. m.Post("/rebuild", org.RebuildCargoIndex)
  876. })
  877. }, packagesEnabled)
  878. m.Group("/blocked_users", func() {
  879. m.Get("", org.BlockedUsers)
  880. m.Post("", web.Bind(forms.BlockUserForm{}), org.BlockedUsersPost)
  881. })
  882. }, ctxDataSet("EnableOAuth2", setting.OAuth2.Enabled, "EnablePackages", setting.Packages.Enabled, "PageIsOrgSettings", true))
  883. }, context.OrgAssignment(context.OrgAssignmentOptions{RequireOwner: true}))
  884. }, reqSignIn)
  885. // end "/org": most org routes
  886. m.Group("/repo", func() {
  887. m.Get("/create", repo.Create)
  888. m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost)
  889. m.Get("/migrate", repo.Migrate)
  890. m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost)
  891. m.Get("/search", repo.SearchRepo)
  892. }, reqSignIn)
  893. // end "/repo": create, migrate, search
  894. m.Group("/{username}/-", func() {
  895. if setting.Packages.Enabled {
  896. m.Group("/packages", func() {
  897. m.Get("", user.ListPackages)
  898. m.Group("/{type}/{name}", func() {
  899. m.Get("", user.RedirectToLastVersion)
  900. m.Get("/versions", user.ListPackageVersions)
  901. m.Group("/{version}", func() {
  902. m.Get("", user.ViewPackageVersion)
  903. m.Get("/{version_sub}", user.ViewPackageVersion)
  904. m.Get("/files/{fileid}", user.DownloadPackageFile)
  905. m.Group("/settings", func() {
  906. m.Get("", user.PackageSettings)
  907. m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost)
  908. }, reqPackageAccess(perm.AccessModeWrite))
  909. })
  910. })
  911. }, context.PackageAssignment(), reqPackageAccess(perm.AccessModeRead))
  912. }
  913. m.Get("/repositories", org.Repositories)
  914. m.Group("/projects", func() {
  915. m.Group("", func() {
  916. m.Get("", org.Projects)
  917. m.Get("/{id}", org.ViewProject)
  918. }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true))
  919. m.Group("", func() { //nolint:dupl // duplicates lines 1421-1441
  920. m.Get("/new", org.RenderNewProject)
  921. m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost)
  922. m.Group("/{id}", func() {
  923. m.Post("/delete", org.DeleteProject)
  924. m.Get("/edit", org.RenderEditProject)
  925. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), org.EditProjectPost)
  926. m.Post("/{action:open|close}", org.ChangeProjectStatus)
  927. // TODO: improper name. Others are "delete project", "edit project", but this one is "move columns"
  928. m.Post("/move", project.MoveColumns)
  929. m.Post("/columns/new", web.Bind(forms.EditProjectColumnForm{}), org.AddColumnToProjectPost)
  930. m.Group("/{columnID}", func() {
  931. m.Put("", web.Bind(forms.EditProjectColumnForm{}), org.EditProjectColumn)
  932. m.Delete("", org.DeleteProjectColumn)
  933. m.Post("/default", org.SetDefaultProjectColumn)
  934. m.Post("/move", org.MoveIssues)
  935. })
  936. })
  937. }, reqSignIn, reqUnitAccess(unit.TypeProjects, perm.AccessModeWrite, true), func(ctx *context.Context) {
  938. if ctx.ContextUser.IsIndividual() && ctx.ContextUser.ID != ctx.Doer.ID {
  939. ctx.NotFound(nil)
  940. return
  941. }
  942. })
  943. }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true), individualPermsChecker)
  944. m.Group("", func() {
  945. m.Get("/code", user.CodeSearch)
  946. }, reqUnitAccess(unit.TypeCode, perm.AccessModeRead, false), individualPermsChecker)
  947. }, optSignIn, context.UserAssignmentWeb(), context.OrgAssignment(context.OrgAssignmentOptions{}))
  948. // end "/{username}/-": packages, projects, code
  949. m.Group("/{username}/{reponame}/-", func() {
  950. m.Group("/migrate", func() {
  951. m.Get("/status", repo.MigrateStatus)
  952. })
  953. }, optSignIn, context.RepoAssignment, reqUnitCodeReader)
  954. // end "/{username}/{reponame}/-": migrate
  955. m.Group("/{username}/{reponame}/settings", func() {
  956. m.Group("", func() {
  957. m.Combo("").Get(repo_setting.Settings).
  958. Post(web.Bind(forms.RepoSettingForm{}), repo_setting.SettingsPost)
  959. }, repo_setting.SettingsCtxData)
  960. m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo_setting.SettingsAvatar)
  961. m.Post("/avatar/delete", repo_setting.SettingsDeleteAvatar)
  962. m.Combo("/public_access").Get(repo_setting.PublicAccess).Post(repo_setting.PublicAccessPost)
  963. m.Group("/collaboration", func() {
  964. m.Combo("").Get(repo_setting.Collaboration).Post(repo_setting.CollaborationPost)
  965. m.Post("/access_mode", repo_setting.ChangeCollaborationAccessMode)
  966. m.Post("/delete", repo_setting.DeleteCollaboration)
  967. m.Group("/team", func() {
  968. m.Post("", repo_setting.AddTeamPost)
  969. m.Post("/delete", repo_setting.DeleteTeam)
  970. })
  971. })
  972. m.Group("/branches", func() {
  973. m.Post("/", repo_setting.SetDefaultBranchPost)
  974. }, repo.MustBeNotEmpty)
  975. m.Group("/branches", func() {
  976. m.Get("/", repo_setting.ProtectedBranchRules)
  977. m.Combo("/edit").Get(repo_setting.SettingsProtectedBranch).
  978. Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.SettingsProtectedBranchPost)
  979. m.Post("/{id}/delete", repo_setting.DeleteProtectedBranchRulePost)
  980. m.Post("/priority", web.Bind(forms.ProtectBranchPriorityForm{}), context.RepoMustNotBeArchived(), repo_setting.UpdateBranchProtectionPriories)
  981. })
  982. m.Group("/tags", func() {
  983. m.Get("", repo_setting.ProtectedTags)
  984. m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.NewProtectedTagPost)
  985. m.Post("/delete", context.RepoMustNotBeArchived(), repo_setting.DeleteProtectedTagPost)
  986. m.Get("/{id}", repo_setting.EditProtectedTag)
  987. m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.EditProtectedTagPost)
  988. })
  989. m.Group("/hooks/git", func() {
  990. m.Get("", repo_setting.GitHooks)
  991. m.Combo("/{name}").Get(repo_setting.GitHooksEdit).
  992. Post(repo_setting.GitHooksEditPost)
  993. }, context.GitHookService())
  994. m.Group("/hooks", func() {
  995. m.Get("", repo_setting.Webhooks)
  996. m.Post("/delete", repo_setting.DeleteWebhook)
  997. addWebhookAddRoutes()
  998. m.Group("/{id}", func() {
  999. m.Get("", repo_setting.WebHooksEdit)
  1000. m.Post("/test", repo_setting.TestWebhook)
  1001. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  1002. })
  1003. addWebhookEditRoutes()
  1004. }, webhooksEnabled)
  1005. m.Group("/keys", func() {
  1006. m.Combo("").Get(repo_setting.DeployKeys).
  1007. Post(web.Bind(forms.AddKeyForm{}), repo_setting.DeployKeysPost)
  1008. m.Post("/delete", repo_setting.DeleteDeployKey)
  1009. })
  1010. m.Group("/lfs", func() {
  1011. m.Get("/", repo_setting.LFSFiles)
  1012. m.Get("/show/{oid}", repo_setting.LFSFileGet)
  1013. m.Post("/delete/{oid}", repo_setting.LFSDelete)
  1014. m.Get("/pointers", repo_setting.LFSPointerFiles)
  1015. m.Post("/pointers/associate", repo_setting.LFSAutoAssociate)
  1016. m.Get("/find", repo_setting.LFSFileFind)
  1017. m.Group("/locks", func() {
  1018. m.Get("/", repo_setting.LFSLocks)
  1019. m.Post("/", repo_setting.LFSLockFile)
  1020. m.Post("/{lid}/unlock", repo_setting.LFSUnlock)
  1021. })
  1022. })
  1023. m.Group("/actions", func() {
  1024. m.Get("", shared_actions.RedirectToDefaultSetting)
  1025. addSettingsRunnersRoutes()
  1026. addSettingsSecretsRoutes()
  1027. addSettingsVariablesRoutes()
  1028. }, actions.MustEnableActions)
  1029. // the follow handler must be under "settings", otherwise this incomplete repo can't be accessed
  1030. m.Group("/migrate", func() {
  1031. m.Post("/retry", repo.MigrateRetryPost)
  1032. m.Post("/cancel", repo.MigrateCancelPost)
  1033. })
  1034. },
  1035. reqSignIn, context.RepoAssignment, reqRepoAdmin,
  1036. ctxDataSet("PageIsRepoSettings", true, "LFSStartServer", setting.LFS.StartServer),
  1037. )
  1038. // end "/{username}/{reponame}/settings"
  1039. // user/org home, including rss feeds like "/{username}/{reponame}.rss"
  1040. m.Get("/{username}/{reponame}", optSignIn, context.RepoAssignment, context.RepoRefByType(git.RefTypeBranch), repo.SetEditorconfigIfExists, repo.Home)
  1041. m.Post("/{username}/{reponame}/markup", optSignIn, context.RepoAssignment, reqUnitsWithMarkdown, web.Bind(structs.MarkupOption{}), misc.Markup)
  1042. m.Group("/{username}/{reponame}", func() {
  1043. m.Get("/find/*", repo.FindFiles)
  1044. m.Group("/tree-list", func() {
  1045. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.TreeList)
  1046. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.TreeList)
  1047. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.TreeList)
  1048. })
  1049. m.Group("/tree-view", func() {
  1050. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.TreeViewNodes)
  1051. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.TreeViewNodes)
  1052. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.TreeViewNodes)
  1053. })
  1054. m.Get("/compare", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
  1055. m.Combo("/compare/*", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists).
  1056. Get(repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
  1057. Post(reqSignIn, context.RepoMustNotBeArchived(), reqUnitPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
  1058. m.Get("/pulls/new/*", repo.PullsNewRedirect)
  1059. }, optSignIn, context.RepoAssignment, reqUnitCodeReader)
  1060. // end "/{username}/{reponame}": repo code: find, compare, list
  1061. addIssuesPullsViewRoutes := func() {
  1062. // for /{username}/{reponame}/issues" or "/{username}/{reponame}/pulls"
  1063. m.Get("/posters", repo.IssuePullPosters)
  1064. m.Group("/{index}", func() {
  1065. m.Get("/info", repo.GetIssueInfo)
  1066. m.Get("/attachments", repo.GetIssueAttachments)
  1067. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1068. m.Group("/content-history", func() {
  1069. m.Get("/overview", repo.GetContentHistoryOverview)
  1070. m.Get("/list", repo.GetContentHistoryList)
  1071. m.Get("/detail", repo.GetContentHistoryDetail)
  1072. })
  1073. })
  1074. }
  1075. // FIXME: many "pulls" requests are sent to "issues" endpoints correctly, so the issue endpoints have to tolerate pull request permissions at the moment
  1076. m.Group("/{username}/{reponame}/{type:issues}", addIssuesPullsViewRoutes, optSignIn, context.RepoAssignment, context.RequireUnitReader(unit.TypeIssues, unit.TypePullRequests))
  1077. m.Group("/{username}/{reponame}/{type:pulls}", addIssuesPullsViewRoutes, optSignIn, context.RepoAssignment, reqUnitPullsReader)
  1078. m.Group("/{username}/{reponame}", func() {
  1079. m.Get("/comments/{id}/attachments", repo.GetCommentAttachments)
  1080. m.Get("/labels", repo.RetrieveLabelsForList, repo.Labels)
  1081. m.Get("/milestones", repo.Milestones)
  1082. m.Get("/milestone/{id}", repo.MilestoneIssuesAndPulls)
  1083. m.Get("/issues/suggestions", repo.IssueSuggestions)
  1084. }, optSignIn, context.RepoAssignment, reqRepoIssuesOrPullsReader) // issue/pull attachments, labels, milestones
  1085. // end "/{username}/{reponame}": view milestone, label, issue, pull, etc
  1086. m.Group("/{username}/{reponame}/{type:issues}", func() {
  1087. // these handlers also check unit permissions internally
  1088. m.Get("", repo.Issues)
  1089. m.Get("/{index}", repo.ViewIssue) // also do pull-request redirection (".../issues/{PR-number}" -> ".../pulls/{PR-number}")
  1090. }, optSignIn, context.RepoAssignment, context.RequireUnitReader(unit.TypeIssues, unit.TypePullRequests, unit.TypeExternalTracker))
  1091. // end "/{username}/{reponame}": issue list, issue view (pull-request redirection), external tracker
  1092. m.Group("/{username}/{reponame}", func() { // edit issues, pulls, labels, milestones, etc
  1093. m.Group("/issues", func() {
  1094. m.Group("/new", func() {
  1095. m.Combo("").Get(repo.NewIssue).
  1096. Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost)
  1097. m.Get("/choose", repo.NewIssueChooseTemplate)
  1098. })
  1099. m.Get("/search", repo.SearchRepoIssuesJSON)
  1100. }, reqUnitIssuesReader)
  1101. addIssuesPullsUpdateRoutes := func() {
  1102. // for "/{username}/{reponame}/issues" or "/{username}/{reponame}/pulls"
  1103. m.Group("/{index}", func() {
  1104. m.Post("/title", repo.UpdateIssueTitle)
  1105. m.Post("/content", repo.UpdateIssueContent)
  1106. m.Post("/deadline", repo.UpdateIssueDeadline)
  1107. m.Post("/watch", repo.IssueWatch)
  1108. m.Post("/ref", repo.UpdateIssueRef)
  1109. m.Post("/pin", reqRepoAdmin, repo.IssuePinOrUnpin)
  1110. m.Post("/viewed-files", repo.UpdateViewedFiles)
  1111. m.Group("/dependency", func() {
  1112. m.Post("/add", repo.AddDependency)
  1113. m.Post("/delete", repo.RemoveDependency)
  1114. })
  1115. m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment)
  1116. m.Group("/times", func() {
  1117. m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually)
  1118. m.Post("/{timeid}/delete", repo.DeleteTime)
  1119. m.Group("/stopwatch", func() {
  1120. m.Post("/start", repo.IssueStartStopwatch)
  1121. m.Post("/stop", repo.IssueStopStopwatch)
  1122. m.Post("/cancel", repo.CancelStopwatch)
  1123. })
  1124. })
  1125. m.Post("/time_estimate", repo.UpdateIssueTimeEstimate)
  1126. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction)
  1127. m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue)
  1128. m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue)
  1129. m.Post("/delete", reqRepoAdmin, repo.DeleteIssue)
  1130. m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory)
  1131. })
  1132. m.Post("/attachments", repo.UploadIssueAttachment)
  1133. m.Post("/attachments/remove", repo.DeleteAttachment)
  1134. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  1135. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  1136. m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject)
  1137. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  1138. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  1139. m.Post("/delete", reqRepoAdmin, repo.BatchDeleteIssues)
  1140. m.Delete("/unpin/{index}", reqRepoAdmin, repo.IssueUnpin)
  1141. m.Post("/move_pin", reqRepoAdmin, repo.IssuePinMove)
  1142. }
  1143. // FIXME: many "pulls" requests are sent to "issues" endpoints incorrectly, so the issue endpoints have to tolerate pull request permissions at the moment
  1144. m.Group("/{type:issues}", addIssuesPullsUpdateRoutes, context.RequireUnitReader(unit.TypeIssues, unit.TypePullRequests), context.RepoMustNotBeArchived())
  1145. m.Group("/{type:pulls}", addIssuesPullsUpdateRoutes, reqUnitPullsReader, context.RepoMustNotBeArchived())
  1146. m.Group("/comments/{id}", func() {
  1147. m.Post("", repo.UpdateCommentContent)
  1148. m.Post("/delete", repo.DeleteComment)
  1149. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction)
  1150. }, reqRepoIssuesOrPullsReader) // edit issue/pull comment
  1151. m.Group("/labels", func() {
  1152. m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel)
  1153. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel)
  1154. m.Post("/delete", repo.DeleteLabel)
  1155. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels)
  1156. }, reqRepoIssuesOrPullsWriter)
  1157. m.Group("/milestones", func() {
  1158. m.Combo("/new").Get(repo.NewMilestone).
  1159. Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost)
  1160. m.Get("/{id}/edit", repo.EditMilestone)
  1161. m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost)
  1162. m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
  1163. m.Post("/delete", repo.DeleteMilestone)
  1164. }, reqRepoIssuesOrPullsWriter)
  1165. // FIXME: many "pulls" requests are sent to "issues" endpoints incorrectly, need to move these routes to the proper place
  1166. m.Group("/issues", func() {
  1167. m.Post("/request_review", repo.UpdatePullReviewRequest)
  1168. m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview)
  1169. m.Post("/resolve_conversation", repo.SetShowOutdatedComments, repo.UpdateResolveConversation)
  1170. }, reqUnitPullsReader)
  1171. m.Post("/pull/{index}/target_branch", reqUnitPullsReader, repo.UpdatePullRequestTarget)
  1172. }, reqSignIn, context.RepoAssignment, context.RepoMustNotBeArchived())
  1173. // end "/{username}/{reponame}": create or edit issues, pulls, labels, milestones
  1174. m.Group("/{username}/{reponame}", func() { // repo code (at least "code reader")
  1175. m.Group("", func() {
  1176. m.Group("", func() {
  1177. // "GET" requests only need "code reader" permission, "POST" requests need "code writer" permission.
  1178. // Because reader can "fork and edit"
  1179. canWriteToBranch := context.CanWriteToBranch()
  1180. m.Post("/_preview/*", repo.DiffPreviewPost) // read-only, fine with "code reader"
  1181. m.Post("/_fork/*", repo.ForkToEditPost) // read-only, fork to own repo, fine with "code reader"
  1182. // the path params are used in PrepareCommitFormOptions to construct the correct form action URL
  1183. m.Combo("/{editor_action:_edit}/*").
  1184. Get(repo.EditFile).
  1185. Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.EditFilePost)
  1186. m.Combo("/{editor_action:_new}/*").
  1187. Get(repo.EditFile).
  1188. Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.EditFilePost)
  1189. m.Combo("/{editor_action:_delete}/*").
  1190. Get(repo.DeleteFile).
  1191. Post(web.Bind(forms.DeleteRepoFileForm{}), canWriteToBranch, repo.DeleteFilePost)
  1192. m.Combo("/{editor_action:_upload}/*", repo.MustBeAbleToUpload).
  1193. Get(repo.UploadFile).
  1194. Post(web.Bind(forms.UploadRepoFileForm{}), canWriteToBranch, repo.UploadFilePost)
  1195. m.Combo("/{editor_action:_diffpatch}/*").
  1196. Get(repo.NewDiffPatch).
  1197. Post(web.Bind(forms.EditRepoFileForm{}), canWriteToBranch, repo.NewDiffPatchPost)
  1198. m.Combo("/{editor_action:_cherrypick}/{sha:([a-f0-9]{7,64})}/*").
  1199. Get(repo.CherryPick).
  1200. Post(web.Bind(forms.CherryPickForm{}), canWriteToBranch, repo.CherryPickPost)
  1201. }, context.RepoRefByType(git.RefTypeBranch), repo.WebGitOperationCommonData)
  1202. m.Group("", func() {
  1203. m.Post("/upload-file", repo.UploadFileToServer)
  1204. m.Post("/upload-remove", repo.RemoveUploadFileFromServer)
  1205. }, repo.MustBeAbleToUpload, reqRepoCodeWriter)
  1206. }, repo.MustBeEditable, context.RepoMustNotBeArchived())
  1207. m.Group("/branches", func() {
  1208. m.Group("/_new", func() {
  1209. m.Post("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.CreateBranch)
  1210. m.Post("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.CreateBranch)
  1211. m.Post("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.CreateBranch)
  1212. }, web.Bind(forms.NewBranchForm{}))
  1213. m.Post("/delete", repo.DeleteBranchPost)
  1214. m.Post("/restore", repo.RestoreBranchPost)
  1215. m.Post("/rename", web.Bind(forms.RenameBranchForm{}), repo_setting.RenameBranchPost)
  1216. m.Post("/merge-upstream", repo.MergeUpstream)
  1217. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  1218. m.Combo("/fork").Get(repo.Fork).Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost)
  1219. }, reqSignIn, context.RepoAssignment, reqUnitCodeReader)
  1220. // end "/{username}/{reponame}": repo code
  1221. m.Group("/{username}/{reponame}", func() { // repo tags
  1222. m.Group("/tags", func() {
  1223. m.Get("", context.RepoRefByDefaultBranch() /* for the "commits" tab */, repo.TagsList)
  1224. m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
  1225. m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
  1226. m.Get("/list", repo.GetTagList)
  1227. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed))
  1228. m.Post("/tags/delete", reqSignIn, reqRepoCodeWriter, context.RepoMustNotBeArchived(), repo.DeleteTag)
  1229. }, optSignIn, context.RepoAssignment, repo.MustBeNotEmpty, reqUnitCodeReader)
  1230. // end "/{username}/{reponame}": repo tags
  1231. m.Group("/{username}/{reponame}", func() { // repo releases
  1232. m.Group("/releases", func() {
  1233. m.Get("", repo.Releases)
  1234. m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
  1235. m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
  1236. m.Get("/tag/*", repo.SingleRelease)
  1237. m.Get("/latest", repo.LatestRelease)
  1238. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed))
  1239. m.Get("/releases/attachments/{uuid}", repo.GetAttachment)
  1240. m.Get("/releases/download/{vTag}/{fileName}", repo.RedirectDownload)
  1241. m.Group("/releases", func() {
  1242. m.Get("/new", repo.NewRelease)
  1243. m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost)
  1244. m.Post("/delete", repo.DeleteRelease)
  1245. m.Post("/attachments", repo.UploadReleaseAttachment)
  1246. m.Post("/attachments/remove", repo.DeleteAttachment)
  1247. }, reqSignIn, context.RepoMustNotBeArchived(), reqRepoReleaseWriter)
  1248. m.Group("/releases", func() {
  1249. m.Get("/edit/*", repo.EditRelease)
  1250. m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
  1251. }, reqSignIn, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, repo.CommitInfoCache)
  1252. }, optSignIn, context.RepoAssignment, repo.MustBeNotEmpty, reqRepoReleaseReader)
  1253. // end "/{username}/{reponame}": repo releases
  1254. m.Group("/{username}/{reponame}", func() { // to maintain compatibility with old attachments
  1255. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1256. }, optSignIn, context.RepoAssignment)
  1257. // end "/{username}/{reponame}": compatibility with old attachments
  1258. m.Group("/{username}/{reponame}", func() {
  1259. m.Post("/topics", repo.TopicsPost)
  1260. }, context.RepoAssignment, reqRepoAdmin, context.RepoMustNotBeArchived())
  1261. m.Group("/{username}/{reponame}", func() {
  1262. if setting.Packages.Enabled {
  1263. m.Get("/packages", repo.Packages)
  1264. }
  1265. }, optSignIn, context.RepoAssignment)
  1266. m.Group("/{username}/{reponame}/projects", func() {
  1267. m.Get("", repo.Projects)
  1268. m.Get("/{id}", repo.ViewProject)
  1269. m.Group("", func() { //nolint:dupl // duplicates lines 1034-1054
  1270. m.Get("/new", repo.RenderNewProject)
  1271. m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
  1272. m.Group("/{id}", func() {
  1273. m.Post("/delete", repo.DeleteProject)
  1274. m.Get("/edit", repo.RenderEditProject)
  1275. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost)
  1276. m.Post("/{action:open|close}", repo.ChangeProjectStatus)
  1277. // TODO: improper name. Others are "delete project", "edit project", but this one is "move columns"
  1278. m.Post("/move", project.MoveColumns)
  1279. m.Post("/columns/new", web.Bind(forms.EditProjectColumnForm{}), repo.AddColumnToProjectPost)
  1280. m.Group("/{columnID}", func() {
  1281. m.Put("", web.Bind(forms.EditProjectColumnForm{}), repo.EditProjectColumn)
  1282. m.Delete("", repo.DeleteProjectColumn)
  1283. m.Post("/default", repo.SetDefaultProjectColumn)
  1284. m.Post("/move", repo.MoveIssues)
  1285. })
  1286. })
  1287. }, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
  1288. }, optSignIn, context.RepoAssignment, reqRepoProjectsReader, repo.MustEnableRepoProjects)
  1289. // end "/{username}/{reponame}/projects"
  1290. m.Group("/{username}/{reponame}/actions", func() {
  1291. m.Get("", actions.List)
  1292. m.Post("/disable", reqRepoAdmin, actions.DisableWorkflowFile)
  1293. m.Post("/enable", reqRepoAdmin, actions.EnableWorkflowFile)
  1294. m.Post("/run", reqRepoActionsWriter, actions.Run)
  1295. m.Get("/workflow-dispatch-inputs", reqRepoActionsWriter, actions.WorkflowDispatchInputs)
  1296. m.Group("/runs/{run}", func() {
  1297. m.Combo("").
  1298. Get(actions.View).
  1299. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1300. m.Group("/jobs/{job}", func() {
  1301. m.Combo("").
  1302. Get(actions.View).
  1303. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1304. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1305. m.Get("/logs", actions.Logs)
  1306. })
  1307. m.Get("/workflow", actions.ViewWorkflowFile)
  1308. m.Post("/cancel", reqRepoActionsWriter, actions.Cancel)
  1309. m.Post("/approve", reqRepoActionsWriter, actions.Approve)
  1310. m.Post("/delete", reqRepoActionsWriter, actions.Delete)
  1311. m.Get("/artifacts/{artifact_name}", actions.ArtifactsDownloadView)
  1312. m.Delete("/artifacts/{artifact_name}", reqRepoActionsWriter, actions.ArtifactsDeleteView)
  1313. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1314. })
  1315. m.Group("/workflows/{workflow_name}", func() {
  1316. m.Get("/badge.svg", actions.GetWorkflowBadge)
  1317. })
  1318. }, optSignIn, context.RepoAssignment, repo.MustBeNotEmpty, reqRepoActionsReader, actions.MustEnableActions)
  1319. // end "/{username}/{reponame}/actions"
  1320. m.Group("/{username}/{reponame}/wiki", func() {
  1321. m.Combo("").
  1322. Get(repo.Wiki).
  1323. Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1324. m.Combo("/*").
  1325. Get(repo.Wiki).
  1326. Post(context.RepoMustNotBeArchived(), reqSignIn, reqUnitWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1327. m.Get("/blob_excerpt/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1328. m.Get("/commit/{sha:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1329. m.Get("/commit/{sha:[a-f0-9]{7,64}}.{ext:patch|diff}", repo.RawDiff)
  1330. m.Get("/raw/*", repo.WikiRaw)
  1331. }, optSignIn, context.RepoAssignment, repo.MustEnableWiki, reqUnitWikiReader, func(ctx *context.Context) {
  1332. ctx.Data["PageIsWiki"] = true
  1333. ctx.Data["CloneButtonOriginLink"] = ctx.Repo.Repository.WikiCloneLink(ctx, ctx.Doer)
  1334. })
  1335. // end "/{username}/{reponame}/wiki"
  1336. m.Group("/{username}/{reponame}/activity", func() {
  1337. // activity has its own permission checks
  1338. m.Get("", repo.Activity)
  1339. m.Get("/{period}", repo.Activity)
  1340. m.Group("", func() {
  1341. m.Group("/contributors", func() {
  1342. m.Get("", repo.Contributors)
  1343. m.Get("/data", repo.ContributorsData)
  1344. })
  1345. m.Group("/code-frequency", func() {
  1346. m.Get("", repo.CodeFrequency)
  1347. m.Get("/data", repo.CodeFrequencyData)
  1348. })
  1349. m.Group("/recent-commits", func() {
  1350. m.Get("", repo.RecentCommits)
  1351. m.Get("/data", repo.CodeFrequencyData) // "recent-commits" also uses the same data as "code-frequency"
  1352. })
  1353. }, reqUnitCodeReader)
  1354. },
  1355. optSignIn, context.RepoAssignment, repo.MustBeNotEmpty,
  1356. context.RequireUnitReader(unit.TypeCode, unit.TypeIssues, unit.TypePullRequests, unit.TypeReleases),
  1357. )
  1358. // end "/{username}/{reponame}/activity"
  1359. m.Group("/{username}/{reponame}", func() {
  1360. m.Get("/{type:pulls}", repo.Issues)
  1361. m.Group("/{type:pulls}/{index}", func() {
  1362. m.Get("", repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewIssue)
  1363. m.Get(".diff", repo.DownloadPullDiff)
  1364. m.Get(".patch", repo.DownloadPullPatch)
  1365. m.Get("/merge_box", repo.ViewPullMergeBox)
  1366. m.Group("/commits", func() {
  1367. m.Get("", repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewPullCommits)
  1368. m.Get("/list", repo.GetPullCommits)
  1369. m.Get("/{sha:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForSingleCommit)
  1370. })
  1371. m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
  1372. m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest)
  1373. m.Post("/update", repo.UpdatePullRequest)
  1374. m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits)
  1375. m.Post("/cleanup", context.RepoMustNotBeArchived(), repo.CleanUpPullRequest)
  1376. m.Group("/files", func() {
  1377. m.Get("", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForAllCommitsOfPr)
  1378. m.Get("/{shaFrom:[a-f0-9]{7,64}}..{shaTo:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForRange)
  1379. m.Group("/reviews", func() {
  1380. m.Get("/new_comment", repo.RenderNewCodeCommentForm)
  1381. m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.SetShowOutdatedComments, repo.CreateCodeComment)
  1382. m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview)
  1383. }, context.RepoMustNotBeArchived())
  1384. })
  1385. })
  1386. }, optSignIn, context.RepoAssignment, repo.MustAllowPulls, reqUnitPullsReader)
  1387. // end "/{username}/{reponame}/pulls/{index}": repo pull request
  1388. m.Group("/{username}/{reponame}", func() {
  1389. m.Group("/activity_author_data", func() {
  1390. m.Get("", repo.ActivityAuthors)
  1391. m.Get("/{period}", repo.ActivityAuthors)
  1392. }, repo.MustBeNotEmpty)
  1393. m.Group("/archive", func() {
  1394. m.Get("/*", repo.Download)
  1395. m.Post("/*", repo.InitiateDownload)
  1396. }, repo.MustBeNotEmpty, dlSourceEnabled)
  1397. m.Group("/branches", func() {
  1398. m.Get("/list", repo.GetBranchesList)
  1399. m.Get("", context.RepoRefByDefaultBranch() /* for the "commits" tab */, repo.Branches)
  1400. }, repo.MustBeNotEmpty)
  1401. m.Group("/media", func() {
  1402. m.Get("/blob/{sha}", repo.DownloadByIDOrLFS)
  1403. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.SingleDownloadOrLFS)
  1404. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.SingleDownloadOrLFS)
  1405. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.SingleDownloadOrLFS)
  1406. m.Get("/*", context.RepoRefByType(""), repo.SingleDownloadOrLFS) // "/*" route is deprecated, and kept for backward compatibility
  1407. }, repo.MustBeNotEmpty)
  1408. m.Group("/raw", func() {
  1409. m.Get("/blob/{sha}", repo.DownloadByID)
  1410. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.SingleDownload)
  1411. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.SingleDownload)
  1412. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.SingleDownload)
  1413. m.Get("/*", context.RepoRefByType(""), repo.SingleDownload) // "/*" route is deprecated, and kept for backward compatibility
  1414. }, repo.MustBeNotEmpty)
  1415. m.Group("/render", func() {
  1416. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.RenderFile)
  1417. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.RenderFile)
  1418. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.RenderFile)
  1419. m.Get("/blob/{sha}", repo.RenderFile)
  1420. }, repo.MustBeNotEmpty)
  1421. m.Group("/commits", func() {
  1422. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.RefCommits)
  1423. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.RefCommits)
  1424. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.RefCommits)
  1425. m.Get("/*", context.RepoRefByType(""), repo.RefCommits) // "/*" route is deprecated, and kept for backward compatibility
  1426. }, repo.MustBeNotEmpty)
  1427. m.Group("/blame", func() {
  1428. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.RefBlame)
  1429. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.RefBlame)
  1430. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.RefBlame)
  1431. }, repo.MustBeNotEmpty)
  1432. m.Get("/blob_excerpt/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1433. m.Group("", func() {
  1434. m.Get("/graph", repo.Graph)
  1435. m.Get("/commit/{sha:([a-f0-9]{7,64})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1436. m.Get("/commit/{sha:([a-f0-9]{7,64})$}/load-branches-and-tags", repo.LoadBranchesAndTags)
  1437. // FIXME: this route `/cherry-pick/{sha}` doesn't seem useful or right, the new code always uses `/_cherrypick/` which could handle branch name correctly
  1438. m.Get("/cherry-pick/{sha:([a-f0-9]{7,64})$}", repo.SetEditorconfigIfExists, context.RepoRefByDefaultBranch(), repo.CherryPick)
  1439. }, repo.MustBeNotEmpty)
  1440. m.Get("/rss/branch/*", context.RepoRefByType(git.RefTypeBranch), feedEnabled, feed.RenderBranchFeedRSS)
  1441. m.Get("/atom/branch/*", context.RepoRefByType(git.RefTypeBranch), feedEnabled, feed.RenderBranchFeedAtom)
  1442. m.Group("/src", func() {
  1443. m.Get("", func(ctx *context.Context) { ctx.Redirect(ctx.Repo.RepoLink) }) // there is no "{owner}/{repo}/src" page, so redirect to "{owner}/{repo}" to avoid 404
  1444. m.Get("/branch/*", context.RepoRefByType(git.RefTypeBranch), repo.Home)
  1445. m.Get("/tag/*", context.RepoRefByType(git.RefTypeTag), repo.Home)
  1446. m.Get("/commit/*", context.RepoRefByType(git.RefTypeCommit), repo.Home)
  1447. m.Get("/*", context.RepoRefByType(""), repo.Home) // "/*" route is deprecated, and kept for backward compatibility
  1448. }, repo.SetEditorconfigIfExists)
  1449. m.Get("/tree/*", repo.RedirectRepoTreeToSrc) // redirect "/owner/repo/tree/*" requests to "/owner/repo/src/*"
  1450. m.Get("/blob/*", repo.RedirectRepoBlobToCommit) // redirect "/owner/repo/blob/*" requests to "/owner/repo/src/commit/*"
  1451. m.Get("/forks", repo.Forks)
  1452. m.Get("/commit/{sha:([a-f0-9]{7,64})}.{ext:patch|diff}", repo.MustBeNotEmpty, repo.RawDiff)
  1453. m.Post("/lastcommit/*", context.RepoRefByType(git.RefTypeCommit), repo.LastCommit)
  1454. }, optSignIn, context.RepoAssignment, reqUnitCodeReader)
  1455. // end "/{username}/{reponame}": repo code
  1456. m.Group("/{username}/{reponame}", func() {
  1457. m.Get("/stars", starsEnabled, repo.Stars)
  1458. m.Get("/watchers", repo.Watchers)
  1459. m.Get("/search", reqUnitCodeReader, repo.Search)
  1460. m.Post("/action/{action:star|unstar}", reqSignIn, starsEnabled, repo.ActionStar)
  1461. m.Post("/action/{action:watch|unwatch}", reqSignIn, repo.ActionWatch)
  1462. m.Post("/action/{action:accept_transfer|reject_transfer}", reqSignIn, repo.ActionTransfer)
  1463. }, optSignIn, context.RepoAssignment)
  1464. common.AddOwnerRepoGitLFSRoutes(m, optSignInIgnoreCsrf, lfsServerEnabled) // "/{username}/{reponame}/{lfs-paths}": git-lfs support
  1465. addOwnerRepoGitHTTPRouters(m) // "/{username}/{reponame}/{git-paths}": git http support
  1466. m.Group("/notifications", func() {
  1467. m.Get("", user.Notifications)
  1468. m.Get("/subscriptions", user.NotificationSubscriptions)
  1469. m.Get("/watching", user.NotificationWatching)
  1470. m.Post("/status", user.NotificationStatusPost)
  1471. m.Post("/purge", user.NotificationPurgePost)
  1472. m.Get("/new", user.NewAvailable)
  1473. }, reqSignIn)
  1474. if setting.API.EnableSwagger {
  1475. m.Get("/swagger.v1.json", SwaggerV1Json)
  1476. }
  1477. if !setting.IsProd {
  1478. m.Group("/devtest", func() {
  1479. m.Any("", devtest.List)
  1480. m.Any("/fetch-action-test", devtest.FetchActionTest)
  1481. m.Any("/mail-preview", devtest.MailPreview)
  1482. m.Any("/mail-preview/*", devtest.MailPreviewRender)
  1483. m.Any("/{sub}", devtest.TmplCommon)
  1484. m.Get("/repo-action-view/{run}/{job}", devtest.MockActionsView)
  1485. m.Post("/actions-mock/runs/{run}/jobs/{job}", web.Bind(actions.ViewRequest{}), devtest.MockActionsRunsJobs)
  1486. })
  1487. }
  1488. m.NotFound(func(w http.ResponseWriter, req *http.Request) {
  1489. ctx := context.GetWebContext(req.Context())
  1490. defer routing.RecordFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))()
  1491. ctx.NotFound(nil)
  1492. })
  1493. }