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 66KB

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