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

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