You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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. const 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. // FIXME: not all routes need go through same middleware.
  404. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  405. m.Get("/", Home)
  406. m.Get("/sitemap.xml", sitemapEnabled, ignExploreSignIn, HomeSitemap)
  407. m.Group("/.well-known", func() {
  408. m.Get("/openid-configuration", auth.OIDCWellKnown)
  409. m.Group("", func() {
  410. m.Get("/nodeinfo", NodeInfoLinks)
  411. m.Get("/webfinger", WebfingerQuery)
  412. }, federationEnabled)
  413. m.Get("/change-password", func(ctx *context.Context) {
  414. ctx.Redirect(setting.AppSubURL + "/user/settings/account")
  415. })
  416. m.Get("/passkey-endpoints", passkeyEndpoints)
  417. m.Methods("GET, HEAD", "/*", public.FileHandlerFunc())
  418. }, optionsCorsHandler())
  419. m.Group("/explore", func() {
  420. m.Get("", func(ctx *context.Context) {
  421. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  422. })
  423. m.Get("/repos", explore.Repos)
  424. m.Get("/repos/sitemap-{idx}.xml", sitemapEnabled, explore.Repos)
  425. m.Get("/users", explore.Users)
  426. m.Get("/users/sitemap-{idx}.xml", sitemapEnabled, explore.Users)
  427. m.Get("/organizations", explore.Organizations)
  428. m.Get("/code", func(ctx *context.Context) {
  429. if unit.TypeCode.UnitGlobalDisabled() {
  430. ctx.NotFound(unit.TypeCode.String(), nil)
  431. return
  432. }
  433. }, explore.Code)
  434. m.Get("/topics/search", explore.TopicSearch)
  435. }, ignExploreSignIn)
  436. m.Group("/issues", func() {
  437. m.Get("", user.Issues)
  438. m.Get("/search", repo.SearchIssues)
  439. }, reqSignIn)
  440. m.Get("/pulls", reqSignIn, user.Pulls)
  441. m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
  442. // ***** START: User *****
  443. // "user/login" doesn't need signOut, then logged-in users can still access this route for redirection purposes by "/user/login?redirec_to=..."
  444. m.Get("/user/login", auth.SignIn)
  445. m.Group("/user", func() {
  446. m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost)
  447. m.Group("", func() {
  448. m.Combo("/login/openid").
  449. Get(auth.SignInOpenID).
  450. Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost)
  451. }, openIDSignInEnabled)
  452. m.Group("/openid", func() {
  453. m.Combo("/connect").
  454. Get(auth.ConnectOpenID).
  455. Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost)
  456. m.Group("/register", func() {
  457. m.Combo("").
  458. Get(auth.RegisterOpenID, openIDSignUpEnabled).
  459. Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost)
  460. }, openIDSignUpEnabled)
  461. }, openIDSignInEnabled)
  462. m.Get("/sign_up", auth.SignUp)
  463. m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost)
  464. m.Get("/link_account", linkAccountEnabled, auth.LinkAccount)
  465. m.Post("/link_account_signin", linkAccountEnabled, web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn)
  466. m.Post("/link_account_signup", linkAccountEnabled, web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister)
  467. m.Group("/two_factor", func() {
  468. m.Get("", auth.TwoFactor)
  469. m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost)
  470. m.Get("/scratch", auth.TwoFactorScratch)
  471. m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost)
  472. })
  473. m.Group("/webauthn", func() {
  474. m.Get("", auth.WebAuthn)
  475. m.Get("/assertion", auth.WebAuthnLoginAssertion)
  476. m.Post("/assertion", auth.WebAuthnLoginAssertionPost)
  477. })
  478. }, reqSignOut)
  479. m.Any("/user/events", routing.MarkLongPolling, events.Events)
  480. m.Group("/login/oauth", func() {
  481. m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  482. m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth)
  483. // TODO manage redirection
  484. m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  485. }, ignSignInAndCsrf, reqSignIn)
  486. m.Methods("GET, OPTIONS", "/login/oauth/userinfo", optionsCorsHandler(), ignSignInAndCsrf, auth.InfoOAuth)
  487. m.Methods("POST, OPTIONS", "/login/oauth/access_token", optionsCorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth)
  488. m.Methods("GET, OPTIONS", "/login/oauth/keys", optionsCorsHandler(), ignSignInAndCsrf, auth.OIDCKeys)
  489. m.Methods("POST, OPTIONS", "/login/oauth/introspect", optionsCorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth)
  490. m.Group("/user/settings", func() {
  491. m.Get("", user_setting.Profile)
  492. m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost)
  493. m.Get("/change_password", auth.MustChangePassword)
  494. m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost)
  495. m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost)
  496. m.Post("/avatar/delete", user_setting.DeleteAvatar)
  497. m.Group("/account", func() {
  498. m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost)
  499. m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost)
  500. m.Post("/email/delete", user_setting.DeleteEmail)
  501. m.Post("/delete", user_setting.DeleteAccount)
  502. })
  503. m.Group("/appearance", func() {
  504. m.Get("", user_setting.Appearance)
  505. m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang)
  506. m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments)
  507. m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost)
  508. })
  509. m.Group("/security", func() {
  510. m.Get("", security.Security)
  511. m.Group("/two_factor", func() {
  512. m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor)
  513. m.Post("/disable", security.DisableTwoFactor)
  514. m.Get("/enroll", security.EnrollTwoFactor)
  515. m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost)
  516. })
  517. m.Group("/webauthn", func() {
  518. m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister)
  519. m.Post("/register", security.WebauthnRegisterPost)
  520. m.Post("/delete", web.Bind(forms.WebauthnDeleteForm{}), security.WebauthnDelete)
  521. })
  522. m.Group("/openid", func() {
  523. m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost)
  524. m.Post("/delete", security.DeleteOpenID)
  525. m.Post("/toggle_visibility", security.ToggleOpenIDVisibility)
  526. }, openIDSignInEnabled)
  527. m.Post("/account_link", linkAccountEnabled, security.DeleteAccountLink)
  528. })
  529. m.Group("/applications/oauth2", func() {
  530. m.Get("/{id}", user_setting.OAuth2ApplicationShow)
  531. m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit)
  532. m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret)
  533. m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost)
  534. m.Post("/{id}/delete", user_setting.DeleteOAuth2Application)
  535. m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant)
  536. })
  537. m.Combo("/applications").Get(user_setting.Applications).
  538. Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost)
  539. m.Post("/applications/delete", user_setting.DeleteApplication)
  540. m.Combo("/keys").Get(user_setting.Keys).
  541. Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost)
  542. m.Post("/keys/delete", user_setting.DeleteKey)
  543. m.Group("/packages", func() {
  544. m.Get("", user_setting.Packages)
  545. m.Group("/rules", func() {
  546. m.Group("/add", func() {
  547. m.Get("", user_setting.PackagesRuleAdd)
  548. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost)
  549. })
  550. m.Group("/{id}", func() {
  551. m.Get("", user_setting.PackagesRuleEdit)
  552. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost)
  553. m.Get("/preview", user_setting.PackagesRulePreview)
  554. })
  555. })
  556. m.Group("/cargo", func() {
  557. m.Post("/initialize", user_setting.InitializeCargoIndex)
  558. m.Post("/rebuild", user_setting.RebuildCargoIndex)
  559. })
  560. m.Post("/chef/regenerate_keypair", user_setting.RegenerateChefKeyPair)
  561. }, packagesEnabled)
  562. m.Group("/actions", func() {
  563. m.Get("", user_setting.RedirectToDefaultSetting)
  564. addSettingsRunnersRoutes()
  565. addSettingsSecretsRoutes()
  566. addSettingsVariablesRoutes()
  567. }, actions.MustEnableActions)
  568. m.Get("/organization", user_setting.Organization)
  569. m.Get("/repos", user_setting.Repos)
  570. m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository)
  571. m.Group("/hooks", func() {
  572. m.Get("", user_setting.Webhooks)
  573. m.Post("/delete", user_setting.DeleteWebhook)
  574. addWebhookAddRoutes()
  575. m.Group("/{id}", func() {
  576. m.Get("", repo_setting.WebHooksEdit)
  577. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  578. })
  579. addWebhookEditRoutes()
  580. }, webhooksEnabled)
  581. m.Group("/blocked_users", func() {
  582. m.Get("", user_setting.BlockedUsers)
  583. m.Post("", web.Bind(forms.BlockUserForm{}), user_setting.BlockedUsersPost)
  584. })
  585. }, reqSignIn, ctxDataSet("PageIsUserSettings", true, "EnablePackages", setting.Packages.Enabled))
  586. m.Group("/user", func() {
  587. m.Get("/activate", auth.Activate)
  588. m.Post("/activate", auth.ActivatePost)
  589. m.Any("/activate_email", auth.ActivateEmail)
  590. m.Get("/avatar/{username}/{size}", user.AvatarByUserName)
  591. m.Get("/recover_account", auth.ResetPasswd)
  592. m.Post("/recover_account", auth.ResetPasswdPost)
  593. m.Get("/forgot_password", auth.ForgotPasswd)
  594. m.Post("/forgot_password", auth.ForgotPasswdPost)
  595. m.Post("/logout", auth.SignOut)
  596. m.Get("/task/{task}", reqSignIn, user.TaskStatus)
  597. m.Get("/stopwatches", reqSignIn, user.GetStopwatches)
  598. m.Get("/search", ignExploreSignIn, user.Search)
  599. m.Group("/oauth2", func() {
  600. m.Get("/{provider}", auth.SignInOAuth)
  601. m.Get("/{provider}/callback", auth.SignInOAuthCallback)
  602. })
  603. })
  604. // ***** END: User *****
  605. m.Get("/avatar/{hash}", user.AvatarByEmailHash)
  606. adminReq := verifyAuthWithOptions(&common.VerifyOptions{SignInRequired: true, AdminRequired: true})
  607. // ***** START: Admin *****
  608. m.Group("/admin", func() {
  609. m.Get("", admin.Dashboard)
  610. m.Get("/system_status", admin.SystemStatus)
  611. m.Post("", web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost)
  612. m.Get("/self_check", admin.SelfCheck)
  613. m.Group("/config", func() {
  614. m.Get("", admin.Config)
  615. m.Post("", admin.ChangeConfig)
  616. m.Post("/test_mail", admin.SendTestMail)
  617. m.Get("/settings", admin.ConfigSettings)
  618. })
  619. m.Group("/monitor", func() {
  620. m.Get("/stats", admin.MonitorStats)
  621. m.Get("/cron", admin.CronTasks)
  622. m.Get("/stacktrace", admin.Stacktrace)
  623. m.Post("/stacktrace/cancel/{pid}", admin.StacktraceCancel)
  624. m.Get("/queue", admin.Queues)
  625. m.Group("/queue/{qid}", func() {
  626. m.Get("", admin.QueueManage)
  627. m.Post("/set", admin.QueueSet)
  628. m.Post("/remove-all-items", admin.QueueRemoveAllItems)
  629. })
  630. m.Get("/diagnosis", admin.MonitorDiagnosis)
  631. })
  632. m.Group("/users", func() {
  633. m.Get("", admin.Users)
  634. m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost)
  635. m.Get("/{userid}", admin.ViewUser)
  636. m.Combo("/{userid}/edit").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost)
  637. m.Post("/{userid}/delete", admin.DeleteUser)
  638. m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost)
  639. m.Post("/{userid}/avatar/delete", admin.DeleteAvatar)
  640. })
  641. m.Group("/emails", func() {
  642. m.Get("", admin.Emails)
  643. m.Post("/activate", admin.ActivateEmail)
  644. })
  645. m.Group("/orgs", func() {
  646. m.Get("", admin.Organizations)
  647. })
  648. m.Group("/repos", func() {
  649. m.Get("", admin.Repos)
  650. m.Combo("/unadopted").Get(admin.UnadoptedRepos).Post(admin.AdoptOrDeleteRepository)
  651. m.Post("/delete", admin.DeleteRepo)
  652. })
  653. m.Group("/packages", func() {
  654. m.Get("", admin.Packages)
  655. m.Post("/delete", admin.DeletePackageVersion)
  656. m.Post("/cleanup", admin.CleanupExpiredData)
  657. }, packagesEnabled)
  658. m.Group("/hooks", func() {
  659. m.Get("", admin.DefaultOrSystemWebhooks)
  660. m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
  661. m.Group("/{id}", func() {
  662. m.Get("", repo_setting.WebHooksEdit)
  663. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  664. })
  665. addWebhookEditRoutes()
  666. }, webhooksEnabled)
  667. m.Group("/{configType:default-hooks|system-hooks}", func() {
  668. addWebhookAddRoutes()
  669. })
  670. m.Group("/auths", func() {
  671. m.Get("", admin.Authentications)
  672. m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost)
  673. m.Combo("/{authid}").Get(admin.EditAuthSource).
  674. Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost)
  675. m.Post("/{authid}/delete", admin.DeleteAuthSource)
  676. })
  677. m.Group("/notices", func() {
  678. m.Get("", admin.Notices)
  679. m.Post("/delete", admin.DeleteNotices)
  680. m.Post("/empty", admin.EmptyNotices)
  681. })
  682. m.Group("/applications", func() {
  683. m.Get("", admin.Applications)
  684. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost)
  685. m.Group("/oauth2/{id}", func() {
  686. m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost)
  687. m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret)
  688. m.Post("/delete", admin.DeleteApplication)
  689. })
  690. }, func(ctx *context.Context) {
  691. if !setting.OAuth2.Enabled {
  692. ctx.Error(http.StatusForbidden)
  693. return
  694. }
  695. })
  696. m.Group("/actions", func() {
  697. m.Get("", admin.RedirectToDefaultSetting)
  698. addSettingsRunnersRoutes()
  699. addSettingsVariablesRoutes()
  700. })
  701. }, adminReq, ctxDataSet("EnableOAuth2", setting.OAuth2.Enabled, "EnablePackages", setting.Packages.Enabled))
  702. // ***** END: Admin *****
  703. m.Group("", func() {
  704. m.Get("/{username}", user.UsernameSubRoute)
  705. m.Methods("GET, OPTIONS", "/attachments/{uuid}", optionsCorsHandler(), repo.GetAttachment)
  706. }, ignSignIn)
  707. m.Post("/{username}", reqSignIn, context.UserAssignmentWeb(), user.Action)
  708. reqRepoAdmin := context.RequireRepoAdmin()
  709. reqRepoCodeWriter := context.RequireRepoWriter(unit.TypeCode)
  710. canEnableEditor := context.CanEnableEditor()
  711. reqRepoCodeReader := context.RequireRepoReader(unit.TypeCode)
  712. reqRepoReleaseWriter := context.RequireRepoWriter(unit.TypeReleases)
  713. reqRepoReleaseReader := context.RequireRepoReader(unit.TypeReleases)
  714. reqRepoWikiReader := context.RequireRepoReader(unit.TypeWiki)
  715. reqRepoWikiWriter := context.RequireRepoWriter(unit.TypeWiki)
  716. reqRepoIssueReader := context.RequireRepoReader(unit.TypeIssues)
  717. reqRepoPullsReader := context.RequireRepoReader(unit.TypePullRequests)
  718. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(unit.TypeIssues, unit.TypePullRequests)
  719. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(unit.TypeIssues, unit.TypePullRequests)
  720. reqRepoProjectsReader := context.RequireRepoReader(unit.TypeProjects)
  721. reqRepoProjectsWriter := context.RequireRepoWriter(unit.TypeProjects)
  722. reqRepoActionsReader := context.RequireRepoReader(unit.TypeActions)
  723. reqRepoActionsWriter := context.RequireRepoWriter(unit.TypeActions)
  724. reqPackageAccess := func(accessMode perm.AccessMode) func(ctx *context.Context) {
  725. return func(ctx *context.Context) {
  726. if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
  727. ctx.NotFound("", nil)
  728. }
  729. }
  730. }
  731. individualPermsChecker := func(ctx *context.Context) {
  732. // org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked.
  733. if ctx.ContextUser.IsIndividual() {
  734. switch {
  735. case ctx.ContextUser.Visibility == structs.VisibleTypePrivate:
  736. if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) {
  737. ctx.NotFound("Visit Project", nil)
  738. return
  739. }
  740. case ctx.ContextUser.Visibility == structs.VisibleTypeLimited:
  741. if ctx.Doer == nil {
  742. ctx.NotFound("Visit Project", nil)
  743. return
  744. }
  745. }
  746. }
  747. }
  748. m.Group("/org", func() {
  749. m.Group("/{org}", func() {
  750. m.Get("/members", org.Members)
  751. }, context.OrgAssignment())
  752. }, ignSignIn)
  753. // end "/org": members
  754. m.Group("/org", func() {
  755. m.Group("", func() {
  756. m.Get("/create", org.Create)
  757. m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost)
  758. })
  759. m.Group("/invite/{token}", func() {
  760. m.Get("", org.TeamInvite)
  761. m.Post("", org.TeamInvitePost)
  762. })
  763. m.Group("/{org}", func() {
  764. m.Get("/dashboard", user.Dashboard)
  765. m.Get("/dashboard/{team}", user.Dashboard)
  766. m.Get("/issues", user.Issues)
  767. m.Get("/issues/{team}", user.Issues)
  768. m.Get("/pulls", user.Pulls)
  769. m.Get("/pulls/{team}", user.Pulls)
  770. m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
  771. m.Get("/milestones/{team}", reqMilestonesDashboardPageEnabled, user.Milestones)
  772. m.Post("/members/action/{action}", org.MembersAction)
  773. m.Get("/teams", org.Teams)
  774. }, context.OrgAssignment(true, false, true))
  775. m.Group("/{org}", func() {
  776. m.Get("/teams/{team}", org.TeamMembers)
  777. m.Get("/teams/{team}/repositories", org.TeamRepositories)
  778. m.Post("/teams/{team}/action/{action}", org.TeamsAction)
  779. m.Post("/teams/{team}/action/repo/{action}", org.TeamsRepoAction)
  780. }, context.OrgAssignment(true, false, true))
  781. m.Group("/{org}", func() {
  782. m.Get("/teams/new", org.NewTeam)
  783. m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost)
  784. m.Get("/teams/-/search", org.SearchTeam)
  785. m.Get("/teams/{team}/edit", org.EditTeam)
  786. m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost)
  787. m.Post("/teams/{team}/delete", org.DeleteTeam)
  788. m.Group("/settings", func() {
  789. m.Combo("").Get(org.Settings).
  790. Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost)
  791. m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar)
  792. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  793. m.Group("/applications", func() {
  794. m.Get("", org.Applications)
  795. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost)
  796. m.Group("/oauth2/{id}", func() {
  797. m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit)
  798. m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret)
  799. m.Post("/delete", org.DeleteOAuth2Application)
  800. })
  801. }, func(ctx *context.Context) {
  802. if !setting.OAuth2.Enabled {
  803. ctx.Error(http.StatusForbidden)
  804. return
  805. }
  806. })
  807. m.Group("/hooks", func() {
  808. m.Get("", org.Webhooks)
  809. m.Post("/delete", org.DeleteWebhook)
  810. addWebhookAddRoutes()
  811. m.Group("/{id}", func() {
  812. m.Get("", repo_setting.WebHooksEdit)
  813. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  814. })
  815. addWebhookEditRoutes()
  816. }, webhooksEnabled)
  817. m.Group("/labels", func() {
  818. m.Get("", org.RetrieveLabels, org.Labels)
  819. m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel)
  820. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel)
  821. m.Post("/delete", org.DeleteLabel)
  822. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels)
  823. })
  824. m.Group("/actions", func() {
  825. m.Get("", org_setting.RedirectToDefaultSetting)
  826. addSettingsRunnersRoutes()
  827. addSettingsSecretsRoutes()
  828. addSettingsVariablesRoutes()
  829. }, actions.MustEnableActions)
  830. m.Methods("GET,POST", "/delete", org.SettingsDelete)
  831. m.Group("/packages", func() {
  832. m.Get("", org.Packages)
  833. m.Group("/rules", func() {
  834. m.Group("/add", func() {
  835. m.Get("", org.PackagesRuleAdd)
  836. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost)
  837. })
  838. m.Group("/{id}", func() {
  839. m.Get("", org.PackagesRuleEdit)
  840. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost)
  841. m.Get("/preview", org.PackagesRulePreview)
  842. })
  843. })
  844. m.Group("/cargo", func() {
  845. m.Post("/initialize", org.InitializeCargoIndex)
  846. m.Post("/rebuild", org.RebuildCargoIndex)
  847. })
  848. }, packagesEnabled)
  849. m.Group("/blocked_users", func() {
  850. m.Get("", org.BlockedUsers)
  851. m.Post("", web.Bind(forms.BlockUserForm{}), org.BlockedUsersPost)
  852. })
  853. }, ctxDataSet("EnableOAuth2", setting.OAuth2.Enabled, "EnablePackages", setting.Packages.Enabled, "PageIsOrgSettings", true))
  854. }, context.OrgAssignment(true, true))
  855. }, reqSignIn)
  856. // end "/org": most org routes
  857. m.Group("/repo", func() {
  858. m.Get("/create", repo.Create)
  859. m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost)
  860. m.Get("/migrate", repo.Migrate)
  861. m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost)
  862. m.Get("/search", repo.SearchRepo)
  863. }, reqSignIn)
  864. // end "/repo": create, migrate, search
  865. m.Group("/{username}/-", func() {
  866. if setting.Packages.Enabled {
  867. m.Group("/packages", func() {
  868. m.Get("", user.ListPackages)
  869. m.Group("/{type}/{name}", func() {
  870. m.Get("", user.RedirectToLastVersion)
  871. m.Get("/versions", user.ListPackageVersions)
  872. m.Group("/{version}", func() {
  873. m.Get("", user.ViewPackageVersion)
  874. m.Get("/files/{fileid}", user.DownloadPackageFile)
  875. m.Group("/settings", func() {
  876. m.Get("", user.PackageSettings)
  877. m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost)
  878. }, reqPackageAccess(perm.AccessModeWrite))
  879. })
  880. })
  881. }, context.PackageAssignment(), reqPackageAccess(perm.AccessModeRead))
  882. }
  883. m.Group("/projects", func() {
  884. m.Group("", func() {
  885. m.Get("", org.Projects)
  886. m.Get("/{id}", org.ViewProject)
  887. }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true))
  888. m.Group("", func() { //nolint:dupl
  889. m.Get("/new", org.RenderNewProject)
  890. m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost)
  891. m.Group("/{id}", func() {
  892. m.Post("", web.Bind(forms.EditProjectBoardForm{}), org.AddBoardToProjectPost)
  893. m.Post("/delete", org.DeleteProject)
  894. m.Get("/edit", org.RenderEditProject)
  895. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), org.EditProjectPost)
  896. m.Post("/{action:open|close}", org.ChangeProjectStatus)
  897. m.Group("/{boardID}", func() {
  898. m.Put("", web.Bind(forms.EditProjectBoardForm{}), org.EditProjectBoard)
  899. m.Delete("", org.DeleteProjectBoard)
  900. m.Post("/default", org.SetDefaultProjectBoard)
  901. m.Post("/move", org.MoveIssues)
  902. })
  903. })
  904. }, reqSignIn, reqUnitAccess(unit.TypeProjects, perm.AccessModeWrite, true), func(ctx *context.Context) {
  905. if ctx.ContextUser.IsIndividual() && ctx.ContextUser.ID != ctx.Doer.ID {
  906. ctx.NotFound("NewProject", nil)
  907. return
  908. }
  909. })
  910. }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true), individualPermsChecker)
  911. m.Group("", func() {
  912. m.Get("/code", user.CodeSearch)
  913. }, reqUnitAccess(unit.TypeCode, perm.AccessModeRead, false), individualPermsChecker)
  914. }, ignSignIn, context.UserAssignmentWeb(), context.OrgAssignment())
  915. // end "/{username}/-": packages, projects, code
  916. m.Group("/{username}/{reponame}/settings", func() {
  917. m.Group("", func() {
  918. m.Combo("").Get(repo_setting.Settings).
  919. Post(web.Bind(forms.RepoSettingForm{}), repo_setting.SettingsPost)
  920. }, repo_setting.SettingsCtxData)
  921. m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo_setting.SettingsAvatar)
  922. m.Post("/avatar/delete", repo_setting.SettingsDeleteAvatar)
  923. m.Group("/collaboration", func() {
  924. m.Combo("").Get(repo_setting.Collaboration).Post(repo_setting.CollaborationPost)
  925. m.Post("/access_mode", repo_setting.ChangeCollaborationAccessMode)
  926. m.Post("/delete", repo_setting.DeleteCollaboration)
  927. m.Group("/team", func() {
  928. m.Post("", repo_setting.AddTeamPost)
  929. m.Post("/delete", repo_setting.DeleteTeam)
  930. })
  931. })
  932. m.Group("/branches", func() {
  933. m.Post("/", repo_setting.SetDefaultBranchPost)
  934. }, repo.MustBeNotEmpty)
  935. m.Group("/branches", func() {
  936. m.Get("/", repo_setting.ProtectedBranchRules)
  937. m.Combo("/edit").Get(repo_setting.SettingsProtectedBranch).
  938. Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.SettingsProtectedBranchPost)
  939. m.Post("/{id}/delete", repo_setting.DeleteProtectedBranchRulePost)
  940. }, repo.MustBeNotEmpty)
  941. m.Post("/rename_branch", web.Bind(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo_setting.RenameBranchPost)
  942. m.Group("/tags", func() {
  943. m.Get("", repo_setting.ProtectedTags)
  944. m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.NewProtectedTagPost)
  945. m.Post("/delete", context.RepoMustNotBeArchived(), repo_setting.DeleteProtectedTagPost)
  946. m.Get("/{id}", repo_setting.EditProtectedTag)
  947. m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo_setting.EditProtectedTagPost)
  948. })
  949. m.Group("/hooks/git", func() {
  950. m.Get("", repo_setting.GitHooks)
  951. m.Combo("/{name}").Get(repo_setting.GitHooksEdit).
  952. Post(repo_setting.GitHooksEditPost)
  953. }, context.GitHookService())
  954. m.Group("/hooks", func() {
  955. m.Get("", repo_setting.Webhooks)
  956. m.Post("/delete", repo_setting.DeleteWebhook)
  957. addWebhookAddRoutes()
  958. m.Group("/{id}", func() {
  959. m.Get("", repo_setting.WebHooksEdit)
  960. m.Post("/test", repo_setting.TestWebhook)
  961. m.Post("/replay/{uuid}", repo_setting.ReplayWebhook)
  962. })
  963. addWebhookEditRoutes()
  964. }, webhooksEnabled)
  965. m.Group("/keys", func() {
  966. m.Combo("").Get(repo_setting.DeployKeys).
  967. Post(web.Bind(forms.AddKeyForm{}), repo_setting.DeployKeysPost)
  968. m.Post("/delete", repo_setting.DeleteDeployKey)
  969. })
  970. m.Group("/lfs", func() {
  971. m.Get("/", repo_setting.LFSFiles)
  972. m.Get("/show/{oid}", repo_setting.LFSFileGet)
  973. m.Post("/delete/{oid}", repo_setting.LFSDelete)
  974. m.Get("/pointers", repo_setting.LFSPointerFiles)
  975. m.Post("/pointers/associate", repo_setting.LFSAutoAssociate)
  976. m.Get("/find", repo_setting.LFSFileFind)
  977. m.Group("/locks", func() {
  978. m.Get("/", repo_setting.LFSLocks)
  979. m.Post("/", repo_setting.LFSLockFile)
  980. m.Post("/{lid}/unlock", repo_setting.LFSUnlock)
  981. })
  982. })
  983. m.Group("/actions", func() {
  984. m.Get("", repo_setting.RedirectToDefaultSetting)
  985. addSettingsRunnersRoutes()
  986. addSettingsSecretsRoutes()
  987. addSettingsVariablesRoutes()
  988. }, actions.MustEnableActions)
  989. // the follow handler must be under "settings", otherwise this incomplete repo can't be accessed
  990. m.Group("/migrate", func() {
  991. m.Post("/retry", repo.MigrateRetryPost)
  992. m.Post("/cancel", repo.MigrateCancelPost)
  993. })
  994. },
  995. reqSignIn, context.RepoAssignment, reqRepoAdmin, context.RepoRef(),
  996. ctxDataSet("PageIsRepoSettings", true, "LFSStartServer", setting.LFS.StartServer),
  997. )
  998. // end "/{username}/{reponame}/settings"
  999. // user/org home, including rss feeds
  1000. m.Get("/{username}/{reponame}", ignSignIn, context.RepoAssignment, context.RepoRef(), repo.SetEditorconfigIfExists, repo.Home)
  1001. m.Group("/{username}/{reponame}", func() {
  1002. m.Get("/find/*", repo.FindFiles)
  1003. m.Group("/tree-list", func() {
  1004. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.TreeList)
  1005. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.TreeList)
  1006. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.TreeList)
  1007. })
  1008. m.Get("/compare", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
  1009. m.Combo("/compare/*", repo.MustBeNotEmpty, repo.SetEditorconfigIfExists).
  1010. Get(repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
  1011. Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
  1012. }, ignSignIn, context.RepoAssignment, reqRepoCodeReader)
  1013. // end "/{username}/{reponame}": find, compare, list (code related)
  1014. m.Group("/{username}/{reponame}", func() {
  1015. m.Get("/issues/posters", repo.IssuePosters) // it can't use {type:issues|pulls} because it would conflict with other routes like "/pulls/{index}"
  1016. m.Get("/pulls/posters", repo.PullPosters)
  1017. m.Get("/comments/{id}/attachments", repo.GetCommentAttachments)
  1018. m.Get("/labels", repo.RetrieveLabels, repo.Labels)
  1019. m.Get("/milestones", repo.Milestones)
  1020. m.Get("/milestone/{id}", context.RepoRef(), repo.MilestoneIssuesAndPulls)
  1021. m.Group("/{type:issues|pulls}", func() {
  1022. m.Group("/{index}", func() {
  1023. m.Get("/info", repo.GetIssueInfo)
  1024. m.Get("/attachments", repo.GetIssueAttachments)
  1025. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1026. m.Group("/content-history", func() {
  1027. m.Get("/overview", repo.GetContentHistoryOverview)
  1028. m.Get("/list", repo.GetContentHistoryList)
  1029. m.Get("/detail", repo.GetContentHistoryDetail)
  1030. })
  1031. })
  1032. }, context.RepoRef())
  1033. }, ignSignIn, context.RepoAssignment, reqRepoIssuesOrPullsReader)
  1034. // end "/{username}/{reponame}": view milestone, label, issue, pull, etc
  1035. m.Group("/{username}/{reponame}", func() {
  1036. m.Group("/{type:issues|pulls}", func() {
  1037. m.Get("", repo.Issues)
  1038. m.Group("/{index}", func() {
  1039. m.Get("", repo.ViewIssue)
  1040. })
  1041. })
  1042. }, ignSignIn, context.RepoAssignment, context.RequireRepoReaderOr(unit.TypeIssues, unit.TypePullRequests, unit.TypeExternalTracker))
  1043. // end "/{username}/{reponame}": issue/pull list, issue/pull view, external tracker
  1044. m.Group("/{username}/{reponame}", func() { // edit issues, pulls, labels, milestones, etc
  1045. m.Group("/issues", func() {
  1046. m.Group("/new", func() {
  1047. m.Combo("").Get(context.RepoRef(), repo.NewIssue).
  1048. Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost)
  1049. m.Get("/choose", context.RepoRef(), repo.NewIssueChooseTemplate)
  1050. })
  1051. m.Get("/search", repo.ListIssues)
  1052. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  1053. // FIXME: should use different URLs but mostly same logic for comments of issue and pull request.
  1054. // So they can apply their own enable/disable logic on routers.
  1055. m.Group("/{type:issues|pulls}", func() {
  1056. m.Group("/{index}", func() {
  1057. m.Post("/title", repo.UpdateIssueTitle)
  1058. m.Post("/content", repo.UpdateIssueContent)
  1059. m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  1060. m.Post("/watch", repo.IssueWatch)
  1061. m.Post("/ref", repo.UpdateIssueRef)
  1062. m.Post("/pin", reqRepoAdmin, repo.IssuePinOrUnpin)
  1063. m.Post("/viewed-files", repo.UpdateViewedFiles)
  1064. m.Group("/dependency", func() {
  1065. m.Post("/add", repo.AddDependency)
  1066. m.Post("/delete", repo.RemoveDependency)
  1067. })
  1068. m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment)
  1069. m.Group("/times", func() {
  1070. m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually)
  1071. m.Post("/{timeid}/delete", repo.DeleteTime)
  1072. m.Group("/stopwatch", func() {
  1073. m.Post("/toggle", repo.IssueStopwatch)
  1074. m.Post("/cancel", repo.CancelStopwatch)
  1075. })
  1076. })
  1077. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction)
  1078. m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue)
  1079. m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue)
  1080. m.Post("/delete", reqRepoAdmin, repo.DeleteIssue)
  1081. }, context.RepoMustNotBeArchived())
  1082. m.Group("/{index}", func() {
  1083. m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory)
  1084. })
  1085. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  1086. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  1087. m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject)
  1088. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  1089. m.Post("/request_review", repo.UpdatePullReviewRequest)
  1090. m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview)
  1091. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  1092. m.Post("/delete", reqRepoAdmin, repo.BatchDeleteIssues)
  1093. m.Post("/resolve_conversation", repo.SetShowOutdatedComments, repo.UpdateResolveConversation)
  1094. m.Post("/attachments", repo.UploadIssueAttachment)
  1095. m.Post("/attachments/remove", repo.DeleteAttachment)
  1096. m.Delete("/unpin/{index}", reqRepoAdmin, repo.IssueUnpin)
  1097. m.Post("/move_pin", reqRepoAdmin, repo.IssuePinMove)
  1098. }, context.RepoMustNotBeArchived())
  1099. m.Group("/comments/{id}", func() {
  1100. m.Post("", repo.UpdateCommentContent)
  1101. m.Post("/delete", repo.DeleteComment)
  1102. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction)
  1103. }, context.RepoMustNotBeArchived())
  1104. m.Post("/markup", web.Bind(structs.MarkupOption{}), misc.Markup)
  1105. m.Group("/labels", func() {
  1106. m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel)
  1107. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel)
  1108. m.Post("/delete", repo.DeleteLabel)
  1109. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels)
  1110. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  1111. m.Group("/milestones", func() {
  1112. m.Combo("/new").Get(repo.NewMilestone).
  1113. Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost)
  1114. m.Get("/{id}/edit", repo.EditMilestone)
  1115. m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost)
  1116. m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
  1117. m.Post("/delete", repo.DeleteMilestone)
  1118. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  1119. m.Group("/pull", func() {
  1120. m.Post("/{index}/target_branch", repo.UpdatePullRequestTarget)
  1121. }, context.RepoMustNotBeArchived())
  1122. }, reqSignIn, context.RepoAssignment, reqRepoIssuesOrPullsReader)
  1123. // end "/{username}/{reponame}": create or edit issues, pulls, labels, milestones
  1124. m.Group("/{username}/{reponame}", func() { // repo code
  1125. m.Group("", func() {
  1126. m.Group("", func() {
  1127. m.Combo("/_edit/*").Get(repo.EditFile).
  1128. Post(web.Bind(forms.EditRepoFileForm{}), repo.EditFilePost)
  1129. m.Combo("/_new/*").Get(repo.NewFile).
  1130. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewFilePost)
  1131. m.Post("/_preview/*", web.Bind(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  1132. m.Combo("/_delete/*").Get(repo.DeleteFile).
  1133. Post(web.Bind(forms.DeleteRepoFileForm{}), repo.DeleteFilePost)
  1134. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  1135. Get(repo.UploadFile).
  1136. Post(web.Bind(forms.UploadRepoFileForm{}), repo.UploadFilePost)
  1137. m.Combo("/_diffpatch/*").Get(repo.NewDiffPatch).
  1138. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewDiffPatchPost)
  1139. m.Combo("/_cherrypick/{sha:([a-f0-9]{7,64})}/*").Get(repo.CherryPick).
  1140. Post(web.Bind(forms.CherryPickForm{}), repo.CherryPickPost)
  1141. }, repo.MustBeEditable)
  1142. m.Group("", func() {
  1143. m.Post("/upload-file", repo.UploadFileToServer)
  1144. m.Post("/upload-remove", web.Bind(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  1145. }, repo.MustBeEditable, repo.MustBeAbleToUpload)
  1146. }, context.RepoRef(), canEnableEditor, context.RepoMustNotBeArchived())
  1147. m.Group("/branches", func() {
  1148. m.Group("/_new", func() {
  1149. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  1150. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  1151. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  1152. }, web.Bind(forms.NewBranchForm{}))
  1153. m.Post("/delete", repo.DeleteBranchPost)
  1154. m.Post("/restore", repo.RestoreBranchPost)
  1155. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  1156. m.Combo("/fork").Get(repo.Fork).Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost)
  1157. }, reqSignIn, context.RepoAssignment, reqRepoCodeReader)
  1158. // end "/{username}/{reponame}": repo code
  1159. m.Group("/{username}/{reponame}", func() { // repo tags
  1160. m.Group("/tags", func() {
  1161. m.Get("", repo.TagsList)
  1162. m.Get("/list", repo.GetTagList)
  1163. m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
  1164. m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
  1165. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
  1166. repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true))
  1167. m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
  1168. repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
  1169. }, ignSignIn, context.RepoAssignment, reqRepoCodeReader)
  1170. // end "/{username}/{reponame}": repo tags
  1171. m.Group("/{username}/{reponame}", func() { // repo releases
  1172. m.Group("/releases", func() {
  1173. m.Get("", repo.Releases)
  1174. m.Get("/tag/*", repo.SingleRelease)
  1175. m.Get("/latest", repo.LatestRelease)
  1176. m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
  1177. m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
  1178. }, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
  1179. repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true))
  1180. m.Get("/releases/attachments/{uuid}", repo.MustBeNotEmpty, repo.GetAttachment)
  1181. m.Get("/releases/download/{vTag}/{fileName}", repo.MustBeNotEmpty, repo.RedirectDownload)
  1182. m.Group("/releases", func() {
  1183. m.Get("/new", repo.NewRelease)
  1184. m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost)
  1185. m.Post("/delete", repo.DeleteRelease)
  1186. m.Post("/attachments", repo.UploadReleaseAttachment)
  1187. m.Post("/attachments/remove", repo.DeleteAttachment)
  1188. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  1189. m.Group("/releases", func() {
  1190. m.Get("/edit/*", repo.EditRelease)
  1191. m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
  1192. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, repo.CommitInfoCache)
  1193. }, ignSignIn, context.RepoAssignment, reqRepoReleaseReader)
  1194. // end "/{username}/{reponame}": repo releases
  1195. m.Group("/{username}/{reponame}", func() { // to maintain compatibility with old attachments
  1196. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1197. }, ignSignIn, context.RepoAssignment)
  1198. // end "/{username}/{reponame}": compatibility with old attachments
  1199. m.Group("/{username}/{reponame}", func() {
  1200. m.Post("/topics", repo.TopicsPost)
  1201. }, context.RepoAssignment, reqRepoAdmin, context.RepoMustNotBeArchived())
  1202. m.Group("/{username}/{reponame}", func() {
  1203. if setting.Packages.Enabled {
  1204. m.Get("/packages", repo.Packages)
  1205. }
  1206. }, ignSignIn, context.RepoAssignment)
  1207. m.Group("/{username}/{reponame}/projects", func() {
  1208. m.Get("", repo.Projects)
  1209. m.Get("/{id}", repo.ViewProject)
  1210. m.Group("", func() { //nolint:dupl
  1211. m.Get("/new", repo.RenderNewProject)
  1212. m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
  1213. m.Group("/{id}", func() {
  1214. m.Post("", web.Bind(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost)
  1215. m.Post("/delete", repo.DeleteProject)
  1216. m.Get("/edit", repo.RenderEditProject)
  1217. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost)
  1218. m.Post("/{action:open|close}", repo.ChangeProjectStatus)
  1219. m.Group("/{boardID}", func() {
  1220. m.Put("", web.Bind(forms.EditProjectBoardForm{}), repo.EditProjectBoard)
  1221. m.Delete("", repo.DeleteProjectBoard)
  1222. m.Post("/default", repo.SetDefaultProjectBoard)
  1223. m.Post("/move", repo.MoveIssues)
  1224. })
  1225. })
  1226. }, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
  1227. }, ignSignIn, context.RepoAssignment, reqRepoProjectsReader, repo.MustEnableRepoProjects)
  1228. // end "/{username}/{reponame}/projects"
  1229. m.Group("/{username}/{reponame}/actions", func() {
  1230. m.Get("", actions.List)
  1231. m.Post("/disable", reqRepoAdmin, actions.DisableWorkflowFile)
  1232. m.Post("/enable", reqRepoAdmin, actions.EnableWorkflowFile)
  1233. m.Post("/run", reqRepoAdmin, actions.Run)
  1234. m.Group("/runs/{run}", func() {
  1235. m.Combo("").
  1236. Get(actions.View).
  1237. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1238. m.Group("/jobs/{job}", func() {
  1239. m.Combo("").
  1240. Get(actions.View).
  1241. Post(web.Bind(actions.ViewRequest{}), actions.ViewPost)
  1242. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1243. m.Get("/logs", actions.Logs)
  1244. })
  1245. m.Post("/cancel", reqRepoActionsWriter, actions.Cancel)
  1246. m.Post("/approve", reqRepoActionsWriter, actions.Approve)
  1247. m.Get("/artifacts", actions.ArtifactsView)
  1248. m.Get("/artifacts/{artifact_name}", actions.ArtifactsDownloadView)
  1249. m.Delete("/artifacts/{artifact_name}", actions.ArtifactsDeleteView)
  1250. m.Post("/rerun", reqRepoActionsWriter, actions.Rerun)
  1251. })
  1252. m.Group("/workflows/{workflow_name}", func() {
  1253. m.Get("/badge.svg", actions.GetWorkflowBadge)
  1254. })
  1255. }, ignSignIn, context.RepoAssignment, reqRepoActionsReader, actions.MustEnableActions)
  1256. // end "/{username}/{reponame}/actions"
  1257. m.Group("/{username}/{reponame}/wiki", func() {
  1258. m.Combo("").
  1259. Get(repo.Wiki).
  1260. Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1261. m.Combo("/*").
  1262. Get(repo.Wiki).
  1263. Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, web.Bind(forms.NewWikiForm{}), repo.WikiPost)
  1264. m.Get("/commit/{sha:[a-f0-9]{7,64}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1265. m.Get("/commit/{sha:[a-f0-9]{7,64}}.{ext:patch|diff}", repo.RawDiff)
  1266. m.Get("/raw/*", repo.WikiRaw)
  1267. }, ignSignIn, context.RepoAssignment, repo.MustEnableWiki, reqRepoWikiReader, func(ctx *context.Context) {
  1268. ctx.Data["PageIsWiki"] = true
  1269. ctx.Data["CloneButtonOriginLink"] = ctx.Repo.Repository.WikiCloneLink()
  1270. })
  1271. // end "/{username}/{reponame}/wiki"
  1272. m.Group("/{username}/{reponame}/activity", func() {
  1273. m.Get("", repo.Activity)
  1274. m.Get("/{period}", repo.Activity)
  1275. m.Group("/contributors", func() {
  1276. m.Get("", repo.Contributors)
  1277. m.Get("/data", repo.ContributorsData)
  1278. })
  1279. m.Group("/code-frequency", func() {
  1280. m.Get("", repo.CodeFrequency)
  1281. m.Get("/data", repo.CodeFrequencyData)
  1282. })
  1283. m.Group("/recent-commits", func() {
  1284. m.Get("", repo.RecentCommits)
  1285. m.Get("/data", repo.RecentCommitsData)
  1286. })
  1287. },
  1288. ignSignIn, context.RepoAssignment, context.RequireRepoReaderOr(unit.TypePullRequests, unit.TypeIssues, unit.TypeReleases),
  1289. context.RepoRef(), repo.MustBeNotEmpty,
  1290. )
  1291. // end "/{username}/{reponame}/activity"
  1292. m.Group("/{username}/{reponame}", func() {
  1293. m.Group("/activity_author_data", func() {
  1294. m.Get("", repo.ActivityAuthors)
  1295. m.Get("/{period}", repo.ActivityAuthors)
  1296. }, context.RepoRef(), repo.MustBeNotEmpty)
  1297. m.Group("/archive", func() {
  1298. m.Get("/*", repo.Download)
  1299. m.Post("/*", repo.InitiateDownload)
  1300. }, repo.MustBeNotEmpty, dlSourceEnabled)
  1301. m.Group("/branches", func() {
  1302. m.Get("/list", repo.GetBranchesList)
  1303. m.Get("", repo.Branches)
  1304. }, repo.MustBeNotEmpty, context.RepoRef())
  1305. m.Group("/blob_excerpt", func() {
  1306. m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1307. }, func(ctx *context.Context) gocontext.CancelFunc {
  1308. // FIXME: refactor this function, use separate routes for wiki/code
  1309. if ctx.FormBool("wiki") {
  1310. ctx.Data["PageIsWiki"] = true
  1311. repo.MustEnableWiki(ctx)
  1312. return nil
  1313. }
  1314. if ctx.Written() {
  1315. return nil
  1316. }
  1317. cancel := context.RepoRef()(ctx)
  1318. if ctx.Written() {
  1319. return cancel
  1320. }
  1321. repo.MustBeNotEmpty(ctx)
  1322. return cancel
  1323. })
  1324. m.Group("/pulls/{index}", func() {
  1325. m.Get("", repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewIssue)
  1326. m.Get(".diff", repo.DownloadPullDiff)
  1327. m.Get(".patch", repo.DownloadPullPatch)
  1328. m.Group("/commits", func() {
  1329. m.Get("", context.RepoRef(), repo.SetWhitespaceBehavior, repo.GetPullDiffStats, repo.ViewPullCommits)
  1330. m.Get("/list", context.RepoRef(), repo.GetPullCommits)
  1331. m.Get("/{sha:[a-f0-9]{7,40}}", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForSingleCommit)
  1332. })
  1333. m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
  1334. m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest)
  1335. m.Post("/update", repo.UpdatePullRequest)
  1336. m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits)
  1337. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  1338. m.Group("/files", func() {
  1339. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesForAllCommitsOfPr)
  1340. m.Get("/{sha:[a-f0-9]{7,40}}", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.SetShowOutdatedComments, repo.ViewPullFilesStartingFromCommit)
  1341. 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)
  1342. m.Group("/reviews", func() {
  1343. m.Get("/new_comment", repo.RenderNewCodeCommentForm)
  1344. m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.SetShowOutdatedComments, repo.CreateCodeComment)
  1345. m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview)
  1346. }, context.RepoMustNotBeArchived())
  1347. })
  1348. }, repo.MustAllowPulls)
  1349. m.Group("/media", func() {
  1350. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  1351. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  1352. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  1353. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  1354. // "/*" route is deprecated, and kept for backward compatibility
  1355. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  1356. }, repo.MustBeNotEmpty)
  1357. m.Group("/raw", func() {
  1358. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  1359. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  1360. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  1361. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  1362. // "/*" route is deprecated, and kept for backward compatibility
  1363. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  1364. }, repo.MustBeNotEmpty)
  1365. m.Group("/render", func() {
  1366. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RenderFile)
  1367. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RenderFile)
  1368. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RenderFile)
  1369. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.RenderFile)
  1370. }, repo.MustBeNotEmpty)
  1371. m.Group("/commits", func() {
  1372. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  1373. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  1374. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  1375. // "/*" route is deprecated, and kept for backward compatibility
  1376. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  1377. }, repo.MustBeNotEmpty)
  1378. m.Group("/blame", func() {
  1379. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  1380. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  1381. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  1382. }, repo.MustBeNotEmpty)
  1383. m.Group("", func() {
  1384. m.Get("/graph", repo.Graph)
  1385. m.Get("/commit/{sha:([a-f0-9]{7,64})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1386. m.Get("/commit/{sha:([a-f0-9]{7,64})$}/load-branches-and-tags", repo.LoadBranchesAndTags)
  1387. m.Get("/cherry-pick/{sha:([a-f0-9]{7,64})$}", repo.SetEditorconfigIfExists, repo.CherryPick)
  1388. }, repo.MustBeNotEmpty, context.RepoRef())
  1389. m.Get("/rss/branch/*", context.RepoRefByType(context.RepoRefBranch), feedEnabled, feed.RenderBranchFeed)
  1390. m.Get("/atom/branch/*", context.RepoRefByType(context.RepoRefBranch), feedEnabled, feed.RenderBranchFeed)
  1391. m.Group("/src", func() {
  1392. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  1393. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  1394. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  1395. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home) // "/*" route is deprecated, and kept for backward compatibility
  1396. }, repo.SetEditorconfigIfExists)
  1397. m.Get("/forks", context.RepoRef(), repo.Forks)
  1398. m.Get("/commit/{sha:([a-f0-9]{7,64})}.{ext:patch|diff}", repo.MustBeNotEmpty, repo.RawDiff)
  1399. m.Post("/lastcommit/*", context.RepoRefByType(context.RepoRefCommit), repo.LastCommit)
  1400. }, ignSignIn, context.RepoAssignment, reqRepoCodeReader)
  1401. // end "/{username}/{reponame}": repo code
  1402. m.Group("/{username}/{reponame}", func() {
  1403. m.Get("/stars", repo.Stars)
  1404. m.Get("/watchers", repo.Watchers)
  1405. m.Get("/search", reqRepoCodeReader, repo.Search)
  1406. m.Post("/action/{action}", reqSignIn, repo.Action)
  1407. }, ignSignIn, context.RepoAssignment, context.RepoRef())
  1408. m.Group("/{username}/{reponame}", func() {
  1409. m.Group("/info/lfs", func() {
  1410. m.Post("/objects/batch", lfs.CheckAcceptMediaType, lfs.BatchHandler)
  1411. m.Put("/objects/{oid}/{size}", lfs.UploadHandler)
  1412. m.Get("/objects/{oid}/{filename}", lfs.DownloadHandler)
  1413. m.Get("/objects/{oid}", lfs.DownloadHandler)
  1414. m.Post("/verify", lfs.CheckAcceptMediaType, lfs.VerifyHandler)
  1415. m.Group("/locks", func() {
  1416. m.Get("/", lfs.GetListLockHandler)
  1417. m.Post("/", lfs.PostLockHandler)
  1418. m.Post("/verify", lfs.VerifyLockHandler)
  1419. m.Post("/{lid}/unlock", lfs.UnLockHandler)
  1420. }, lfs.CheckAcceptMediaType)
  1421. m.Any("/*", func(ctx *context.Context) {
  1422. ctx.NotFound("", nil)
  1423. })
  1424. }, ignSignInAndCsrf, lfsServerEnabled)
  1425. gitHTTPRouters(m)
  1426. })
  1427. // end "/{username}/{reponame}.git": git support
  1428. m.Group("/notifications", func() {
  1429. m.Get("", user.Notifications)
  1430. m.Get("/subscriptions", user.NotificationSubscriptions)
  1431. m.Get("/watching", user.NotificationWatching)
  1432. m.Post("/status", user.NotificationStatusPost)
  1433. m.Post("/purge", user.NotificationPurgePost)
  1434. m.Get("/new", user.NewAvailable)
  1435. }, reqSignIn)
  1436. if setting.API.EnableSwagger {
  1437. m.Get("/swagger.v1.json", SwaggerV1Json)
  1438. }
  1439. if !setting.IsProd {
  1440. m.Any("/devtest", devtest.List)
  1441. m.Any("/devtest/fetch-action-test", devtest.FetchActionTest)
  1442. m.Any("/devtest/{sub}", devtest.Tmpl)
  1443. }
  1444. m.NotFound(func(w http.ResponseWriter, req *http.Request) {
  1445. ctx := context.GetWebContext(req)
  1446. routing.UpdateFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))
  1447. ctx.NotFound("", nil)
  1448. })
  1449. }