Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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