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.

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