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

web.go 65KB

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