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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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. "os"
  8. "path"
  9. "code.gitea.io/gitea/models/perm"
  10. "code.gitea.io/gitea/models/unit"
  11. "code.gitea.io/gitea/modules/cache"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/httpcache"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/metrics"
  17. "code.gitea.io/gitea/modules/public"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/storage"
  20. "code.gitea.io/gitea/modules/structs"
  21. "code.gitea.io/gitea/modules/templates"
  22. "code.gitea.io/gitea/modules/validation"
  23. "code.gitea.io/gitea/modules/web"
  24. "code.gitea.io/gitea/modules/web/routing"
  25. "code.gitea.io/gitea/routers/web/admin"
  26. "code.gitea.io/gitea/routers/web/auth"
  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. "code.gitea.io/gitea/routers/web/repo"
  34. "code.gitea.io/gitea/routers/web/user"
  35. user_setting "code.gitea.io/gitea/routers/web/user/setting"
  36. "code.gitea.io/gitea/routers/web/user/setting/security"
  37. auth_service "code.gitea.io/gitea/services/auth"
  38. context_service "code.gitea.io/gitea/services/context"
  39. "code.gitea.io/gitea/services/forms"
  40. "code.gitea.io/gitea/services/lfs"
  41. _ "code.gitea.io/gitea/modules/session" // to registers all internal adapters
  42. "gitea.com/go-chi/captcha"
  43. "gitea.com/go-chi/session"
  44. "github.com/NYTimes/gziphandler"
  45. "github.com/go-chi/chi/v5/middleware"
  46. "github.com/go-chi/cors"
  47. "github.com/prometheus/client_golang/prometheus"
  48. )
  49. const (
  50. // GzipMinSize represents min size to compress for the body size of response
  51. GzipMinSize = 1400
  52. )
  53. // CorsHandler return a http handler who set CORS options if enabled by config
  54. func CorsHandler() func(next http.Handler) http.Handler {
  55. if setting.CORSConfig.Enabled {
  56. return cors.Handler(cors.Options{
  57. // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option
  58. AllowedOrigins: setting.CORSConfig.AllowDomain,
  59. // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option
  60. AllowedMethods: setting.CORSConfig.Methods,
  61. AllowCredentials: setting.CORSConfig.AllowCredentials,
  62. AllowedHeaders: setting.CORSConfig.Headers,
  63. MaxAge: int(setting.CORSConfig.MaxAge.Seconds()),
  64. })
  65. }
  66. return func(next http.Handler) http.Handler {
  67. return next
  68. }
  69. }
  70. // The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
  71. // in the session (if there is a user id stored in session other plugins might return the user
  72. // object for that id).
  73. //
  74. // The Session plugin is expected to be executed second, in order to skip authentication
  75. // for users that have already signed in.
  76. func buildAuthGroup() *auth_service.Group {
  77. group := auth_service.NewGroup(
  78. &auth_service.OAuth2{}, // FIXME: this should be removed and only applied in download and oauth related routers
  79. &auth_service.Basic{}, // FIXME: this should be removed and only applied in download and git/lfs routers
  80. &auth_service.Session{},
  81. )
  82. if setting.Service.EnableReverseProxyAuth {
  83. group.Add(&auth_service.ReverseProxy{})
  84. }
  85. specialAdd(group)
  86. return group
  87. }
  88. // Routes returns all web routes
  89. func Routes(ctx gocontext.Context) *web.Route {
  90. routes := web.NewRoute()
  91. routes.Use(web.WrapWithPrefix(public.AssetsURLPathPrefix, public.AssetsHandlerFunc(&public.Options{
  92. Directory: path.Join(setting.StaticRootPath, "public"),
  93. Prefix: public.AssetsURLPathPrefix,
  94. CorsHandler: CorsHandler(),
  95. }), "AssetsHandler"))
  96. sessioner := session.Sessioner(session.Options{
  97. Provider: setting.SessionConfig.Provider,
  98. ProviderConfig: setting.SessionConfig.ProviderConfig,
  99. CookieName: setting.SessionConfig.CookieName,
  100. CookiePath: setting.SessionConfig.CookiePath,
  101. Gclifetime: setting.SessionConfig.Gclifetime,
  102. Maxlifetime: setting.SessionConfig.Maxlifetime,
  103. Secure: setting.SessionConfig.Secure,
  104. SameSite: setting.SessionConfig.SameSite,
  105. Domain: setting.SessionConfig.Domain,
  106. })
  107. routes.Use(sessioner)
  108. ctx, _ = templates.HTMLRenderer(ctx)
  109. routes.Use(Recovery(ctx))
  110. // We use r.Route here over r.Use because this prevents requests that are not for avatars having to go through this additional handler
  111. routes.Route("/avatars/*", "GET, HEAD", storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
  112. routes.Route("/repo-avatars/*", "GET, HEAD", storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
  113. // for health check - doesn't need to be passed through gzip handler
  114. routes.Head("/", func(w http.ResponseWriter, req *http.Request) {
  115. w.WriteHeader(http.StatusOK)
  116. })
  117. // this png is very likely to always be below the limit for gzip so it doesn't need to pass through gzip
  118. routes.Get("/apple-touch-icon.png", func(w http.ResponseWriter, req *http.Request) {
  119. http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "/assets/img/apple-touch-icon.png"), http.StatusPermanentRedirect)
  120. })
  121. // redirect default favicon to the path of the custom favicon with a default as a fallback
  122. routes.Get("/favicon.ico", func(w http.ResponseWriter, req *http.Request) {
  123. http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "/assets/img/favicon.png"), http.StatusMovedPermanently)
  124. })
  125. common := []interface{}{}
  126. if setting.EnableGzip {
  127. h, err := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(GzipMinSize))
  128. if err != nil {
  129. log.Fatal("GzipHandlerWithOpts failed: %v", err)
  130. }
  131. common = append(common, h)
  132. }
  133. if setting.Service.EnableCaptcha {
  134. // The captcha http.Handler should only fire on /captcha/* so we can just mount this on that url
  135. routes.Route("/captcha/*", "GET,HEAD", append(common, captcha.Captchaer(context.GetImageCaptcha()))...)
  136. }
  137. if setting.HasRobotsTxt {
  138. routes.Get("/robots.txt", append(common, func(w http.ResponseWriter, req *http.Request) {
  139. filePath := path.Join(setting.CustomPath, "robots.txt")
  140. fi, err := os.Stat(filePath)
  141. if err == nil && httpcache.HandleTimeCache(req, w, fi) {
  142. return
  143. }
  144. http.ServeFile(w, req, filePath)
  145. })...)
  146. }
  147. // prometheus metrics endpoint - do not need to go through contexter
  148. if setting.Metrics.Enabled {
  149. c := metrics.NewCollector()
  150. prometheus.MustRegister(c)
  151. routes.Get("/metrics", append(common, Metrics)...)
  152. }
  153. routes.Get("/ssh_info", func(rw http.ResponseWriter, req *http.Request) {
  154. if !git.SupportProcReceive {
  155. rw.WriteHeader(http.StatusNotFound)
  156. return
  157. }
  158. rw.Header().Set("content-type", "text/json;charset=UTF-8")
  159. _, err := rw.Write([]byte(`{"type":"gitea","version":1}`))
  160. if err != nil {
  161. log.Error("fail to write result: err: %v", err)
  162. rw.WriteHeader(http.StatusInternalServerError)
  163. return
  164. }
  165. rw.WriteHeader(http.StatusOK)
  166. })
  167. routes.Get("/api/healthz", healthcheck.Check)
  168. // Removed: toolbox.Toolboxer middleware will provide debug information which seems unnecessary
  169. common = append(common, context.Contexter(ctx))
  170. group := buildAuthGroup()
  171. if err := group.Init(ctx); err != nil {
  172. log.Error("Could not initialize '%s' auth method, error: %s", group.Name(), err)
  173. }
  174. // Get user from session if logged in.
  175. common = append(common, context.Auth(group))
  176. // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route
  177. common = append(common, middleware.GetHead)
  178. if setting.API.EnableSwagger {
  179. // Note: The route moved from apiroutes because it's in fact want to render a web page
  180. routes.Get("/api/swagger", append(common, misc.Swagger)...) // Render V1 by default
  181. }
  182. // TODO: These really seem like things that could be folded into Contexter or as helper functions
  183. common = append(common, user.GetNotificationCount)
  184. common = append(common, repo.GetActiveStopwatch)
  185. common = append(common, goGet)
  186. others := web.NewRoute()
  187. for _, middle := range common {
  188. others.Use(middle)
  189. }
  190. RegisterRoutes(others)
  191. routes.Mount("", others)
  192. return routes
  193. }
  194. // RegisterRoutes register routes
  195. func RegisterRoutes(m *web.Route) {
  196. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  197. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  198. ignExploreSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView})
  199. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  200. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  201. validation.AddBindingRules()
  202. linkAccountEnabled := func(ctx *context.Context) {
  203. if !setting.Service.EnableOpenIDSignIn && !setting.Service.EnableOpenIDSignUp && !setting.OAuth2.Enable {
  204. ctx.Error(http.StatusForbidden)
  205. return
  206. }
  207. }
  208. openIDSignInEnabled := func(ctx *context.Context) {
  209. if !setting.Service.EnableOpenIDSignIn {
  210. ctx.Error(http.StatusForbidden)
  211. return
  212. }
  213. }
  214. openIDSignUpEnabled := func(ctx *context.Context) {
  215. if !setting.Service.EnableOpenIDSignUp {
  216. ctx.Error(http.StatusForbidden)
  217. return
  218. }
  219. }
  220. reqMilestonesDashboardPageEnabled := func(ctx *context.Context) {
  221. if !setting.Service.ShowMilestonesDashboardPage {
  222. ctx.Error(http.StatusForbidden)
  223. return
  224. }
  225. }
  226. // webhooksEnabled requires webhooks to be enabled by admin.
  227. webhooksEnabled := func(ctx *context.Context) {
  228. if setting.DisableWebhooks {
  229. ctx.Error(http.StatusForbidden)
  230. return
  231. }
  232. }
  233. lfsServerEnabled := func(ctx *context.Context) {
  234. if !setting.LFS.StartServer {
  235. ctx.Error(http.StatusNotFound)
  236. return
  237. }
  238. }
  239. federationEnabled := func(ctx *context.Context) {
  240. if !setting.Federation.Enabled {
  241. ctx.Error(http.StatusNotFound)
  242. return
  243. }
  244. }
  245. dlSourceEnabled := func(ctx *context.Context) {
  246. if setting.Repository.DisableDownloadSourceArchives {
  247. ctx.Error(http.StatusNotFound)
  248. return
  249. }
  250. }
  251. sitemapEnabled := func(ctx *context.Context) {
  252. if !setting.EnableSitemap {
  253. ctx.Error(http.StatusNotFound)
  254. return
  255. }
  256. }
  257. packagesEnabled := func(ctx *context.Context) {
  258. if !setting.Packages.Enabled {
  259. ctx.Error(http.StatusForbidden)
  260. return
  261. }
  262. }
  263. feedEnabled := func(ctx *context.Context) {
  264. if !setting.EnableFeed {
  265. ctx.Error(http.StatusNotFound)
  266. return
  267. }
  268. }
  269. // FIXME: not all routes need go through same middleware.
  270. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  271. // Routers.
  272. // for health check
  273. m.Get("/", Home)
  274. m.Get("/sitemap.xml", sitemapEnabled, ignExploreSignIn, HomeSitemap)
  275. m.Group("/.well-known", func() {
  276. m.Get("/openid-configuration", auth.OIDCWellKnown)
  277. m.Group("", func() {
  278. m.Get("/nodeinfo", NodeInfoLinks)
  279. m.Get("/webfinger", WebfingerQuery)
  280. }, federationEnabled)
  281. m.Get("/change-password", func(w http.ResponseWriter, req *http.Request) {
  282. http.Redirect(w, req, "/user/settings/account", http.StatusTemporaryRedirect)
  283. })
  284. })
  285. m.Group("/explore", func() {
  286. m.Get("", func(ctx *context.Context) {
  287. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  288. })
  289. m.Get("/repos", explore.Repos)
  290. m.Get("/repos/sitemap-{idx}.xml", sitemapEnabled, explore.Repos)
  291. m.Get("/users", explore.Users)
  292. m.Get("/users/sitemap-{idx}.xml", sitemapEnabled, explore.Users)
  293. m.Get("/organizations", explore.Organizations)
  294. m.Get("/code", explore.Code)
  295. m.Get("/topics/search", explore.TopicSearch)
  296. }, ignExploreSignIn)
  297. m.Group("/issues", func() {
  298. m.Get("", user.Issues)
  299. m.Get("/search", repo.SearchIssues)
  300. }, reqSignIn)
  301. m.Get("/pulls", reqSignIn, user.Pulls)
  302. m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
  303. // ***** START: User *****
  304. m.Group("/user", func() {
  305. m.Get("/login", auth.SignIn)
  306. m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost)
  307. m.Group("", func() {
  308. m.Combo("/login/openid").
  309. Get(auth.SignInOpenID).
  310. Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost)
  311. }, openIDSignInEnabled)
  312. m.Group("/openid", func() {
  313. m.Combo("/connect").
  314. Get(auth.ConnectOpenID).
  315. Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost)
  316. m.Group("/register", func() {
  317. m.Combo("").
  318. Get(auth.RegisterOpenID, openIDSignUpEnabled).
  319. Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost)
  320. }, openIDSignUpEnabled)
  321. }, openIDSignInEnabled)
  322. m.Get("/sign_up", auth.SignUp)
  323. m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost)
  324. m.Get("/link_account", linkAccountEnabled, auth.LinkAccount)
  325. m.Post("/link_account_signin", linkAccountEnabled, web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn)
  326. m.Post("/link_account_signup", linkAccountEnabled, web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister)
  327. m.Group("/two_factor", func() {
  328. m.Get("", auth.TwoFactor)
  329. m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost)
  330. m.Get("/scratch", auth.TwoFactorScratch)
  331. m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost)
  332. })
  333. m.Group("/webauthn", func() {
  334. m.Get("", auth.WebAuthn)
  335. m.Get("/assertion", auth.WebAuthnLoginAssertion)
  336. m.Post("/assertion", auth.WebAuthnLoginAssertionPost)
  337. })
  338. }, reqSignOut)
  339. m.Any("/user/events", routing.MarkLongPolling, events.Events)
  340. m.Group("/login/oauth", func() {
  341. m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  342. m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth)
  343. // TODO manage redirection
  344. m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth)
  345. }, ignSignInAndCsrf, reqSignIn)
  346. m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth)
  347. m.Post("/login/oauth/access_token", CorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth)
  348. m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys)
  349. m.Post("/login/oauth/introspect", CorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth)
  350. m.Group("/user/settings", func() {
  351. m.Get("", user_setting.Profile)
  352. m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost)
  353. m.Get("/change_password", auth.MustChangePassword)
  354. m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost)
  355. m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost)
  356. m.Post("/avatar/delete", user_setting.DeleteAvatar)
  357. m.Group("/account", func() {
  358. m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost)
  359. m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost)
  360. m.Post("/email/delete", user_setting.DeleteEmail)
  361. m.Post("/delete", user_setting.DeleteAccount)
  362. })
  363. m.Group("/appearance", func() {
  364. m.Get("", user_setting.Appearance)
  365. m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang)
  366. m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments)
  367. m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost)
  368. })
  369. m.Group("/security", func() {
  370. m.Get("", security.Security)
  371. m.Group("/two_factor", func() {
  372. m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor)
  373. m.Post("/disable", security.DisableTwoFactor)
  374. m.Get("/enroll", security.EnrollTwoFactor)
  375. m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost)
  376. })
  377. m.Group("/webauthn", func() {
  378. m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister)
  379. m.Post("/register", security.WebauthnRegisterPost)
  380. m.Post("/delete", web.Bind(forms.WebauthnDeleteForm{}), security.WebauthnDelete)
  381. })
  382. m.Group("/openid", func() {
  383. m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost)
  384. m.Post("/delete", security.DeleteOpenID)
  385. m.Post("/toggle_visibility", security.ToggleOpenIDVisibility)
  386. }, openIDSignInEnabled)
  387. m.Post("/account_link", linkAccountEnabled, security.DeleteAccountLink)
  388. })
  389. m.Group("/applications/oauth2", func() {
  390. m.Get("/{id}", user_setting.OAuth2ApplicationShow)
  391. m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit)
  392. m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret)
  393. m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost)
  394. m.Post("/{id}/delete", user_setting.DeleteOAuth2Application)
  395. m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant)
  396. })
  397. m.Combo("/applications").Get(user_setting.Applications).
  398. Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost)
  399. m.Post("/applications/delete", user_setting.DeleteApplication)
  400. m.Combo("/keys").Get(user_setting.Keys).
  401. Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost)
  402. m.Post("/keys/delete", user_setting.DeleteKey)
  403. m.Group("/packages", func() {
  404. m.Get("", user_setting.Packages)
  405. m.Group("/rules", func() {
  406. m.Group("/add", func() {
  407. m.Get("", user_setting.PackagesRuleAdd)
  408. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost)
  409. })
  410. m.Group("/{id}", func() {
  411. m.Get("", user_setting.PackagesRuleEdit)
  412. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost)
  413. m.Get("/preview", user_setting.PackagesRulePreview)
  414. })
  415. })
  416. }, packagesEnabled)
  417. m.Get("/organization", user_setting.Organization)
  418. m.Get("/repos", user_setting.Repos)
  419. m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository)
  420. }, reqSignIn, func(ctx *context.Context) {
  421. ctx.Data["PageIsUserSettings"] = true
  422. ctx.Data["AllThemes"] = setting.UI.Themes
  423. ctx.Data["EnablePackages"] = setting.Packages.Enabled
  424. })
  425. m.Group("/user", func() {
  426. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  427. m.Get("/activate", auth.Activate)
  428. m.Post("/activate", auth.ActivatePost)
  429. m.Any("/activate_email", auth.ActivateEmail)
  430. m.Get("/avatar/{username}/{size}", user.AvatarByUserName)
  431. m.Get("/recover_account", auth.ResetPasswd)
  432. m.Post("/recover_account", auth.ResetPasswdPost)
  433. m.Get("/forgot_password", auth.ForgotPasswd)
  434. m.Post("/forgot_password", auth.ForgotPasswdPost)
  435. m.Post("/logout", auth.SignOut)
  436. m.Get("/task/{task}", reqSignIn, user.TaskStatus)
  437. m.Get("/stopwatches", reqSignIn, user.GetStopwatches)
  438. m.Get("/search", ignExploreSignIn, user.Search)
  439. m.Group("/oauth2", func() {
  440. m.Get("/{provider}", auth.SignInOAuth)
  441. m.Get("/{provider}/callback", auth.SignInOAuthCallback)
  442. })
  443. })
  444. // ***** END: User *****
  445. m.Get("/avatar/{hash}", user.AvatarByEmailHash)
  446. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  447. // ***** START: Admin *****
  448. m.Group("/admin", func() {
  449. m.Get("", adminReq, admin.Dashboard)
  450. m.Post("", adminReq, web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost)
  451. m.Group("/config", func() {
  452. m.Get("", admin.Config)
  453. m.Post("", admin.ChangeConfig)
  454. m.Post("/test_mail", admin.SendTestMail)
  455. })
  456. m.Group("/monitor", func() {
  457. m.Get("", admin.Monitor)
  458. m.Get("/stacktrace", admin.GoroutineStacktrace)
  459. m.Post("/cancel/{pid}", admin.MonitorCancel)
  460. m.Group("/queue/{qid}", func() {
  461. m.Get("", admin.Queue)
  462. m.Post("/set", admin.SetQueueSettings)
  463. m.Post("/add", admin.AddWorkers)
  464. m.Post("/cancel/{pid}", admin.WorkerCancel)
  465. m.Post("/flush", admin.Flush)
  466. m.Post("/pause", admin.Pause)
  467. m.Post("/resume", admin.Resume)
  468. })
  469. })
  470. m.Group("/users", func() {
  471. m.Get("", admin.Users)
  472. m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost)
  473. m.Combo("/{userid}").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost)
  474. m.Post("/{userid}/delete", admin.DeleteUser)
  475. m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost)
  476. m.Post("/{userid}/avatar/delete", admin.DeleteAvatar)
  477. })
  478. m.Group("/emails", func() {
  479. m.Get("", admin.Emails)
  480. m.Post("/activate", admin.ActivateEmail)
  481. })
  482. m.Group("/orgs", func() {
  483. m.Get("", admin.Organizations)
  484. })
  485. m.Group("/repos", func() {
  486. m.Get("", admin.Repos)
  487. m.Combo("/unadopted").Get(admin.UnadoptedRepos).Post(admin.AdoptOrDeleteRepository)
  488. m.Post("/delete", admin.DeleteRepo)
  489. })
  490. m.Group("/packages", func() {
  491. m.Get("", admin.Packages)
  492. m.Post("/delete", admin.DeletePackageVersion)
  493. }, packagesEnabled)
  494. m.Group("/hooks", func() {
  495. m.Get("", admin.DefaultOrSystemWebhooks)
  496. m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
  497. m.Group("/{id}", func() {
  498. m.Get("", repo.WebHooksEdit)
  499. m.Post("/replay/{uuid}", repo.ReplayWebhook)
  500. })
  501. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost)
  502. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost)
  503. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost)
  504. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  505. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  506. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  507. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
  508. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  509. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  510. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost)
  511. m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost)
  512. }, webhooksEnabled)
  513. m.Group("/{configType:default-hooks|system-hooks}", func() {
  514. m.Get("/{type}/new", repo.WebhooksNew)
  515. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost)
  516. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost)
  517. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost)
  518. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  519. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  520. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  521. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
  522. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  523. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  524. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost)
  525. m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost)
  526. })
  527. m.Group("/auths", func() {
  528. m.Get("", admin.Authentications)
  529. m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost)
  530. m.Combo("/{authid}").Get(admin.EditAuthSource).
  531. Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost)
  532. m.Post("/{authid}/delete", admin.DeleteAuthSource)
  533. })
  534. m.Group("/notices", func() {
  535. m.Get("", admin.Notices)
  536. m.Post("/delete", admin.DeleteNotices)
  537. m.Post("/empty", admin.EmptyNotices)
  538. })
  539. m.Group("/applications", func() {
  540. m.Get("", admin.Applications)
  541. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost)
  542. m.Group("/oauth2/{id}", func() {
  543. m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost)
  544. m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret)
  545. m.Post("/delete", admin.DeleteApplication)
  546. })
  547. }, func(ctx *context.Context) {
  548. if !setting.OAuth2.Enable {
  549. ctx.Error(http.StatusForbidden)
  550. return
  551. }
  552. })
  553. }, func(ctx *context.Context) {
  554. ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable
  555. ctx.Data["EnablePackages"] = setting.Packages.Enabled
  556. }, adminReq)
  557. // ***** END: Admin *****
  558. m.Group("", func() {
  559. m.Get("/favicon.ico", func(ctx *context.Context) {
  560. ctx.SetServeHeaders(&context.ServeHeaderOptions{
  561. Filename: "favicon.png",
  562. })
  563. http.ServeFile(ctx.Resp, ctx.Req, path.Join(setting.StaticRootPath, "public/img/favicon.png"))
  564. })
  565. m.Group("/{username}", func() {
  566. m.Get(".png", user.AvatarByUserName)
  567. m.Get(".keys", user.ShowSSHKeys)
  568. m.Get(".gpg", user.ShowGPGKeys)
  569. m.Get(".rss", feedEnabled, feed.ShowUserFeedRSS)
  570. m.Get(".atom", feedEnabled, feed.ShowUserFeedAtom)
  571. m.Get("", user.Profile)
  572. }, func(ctx *context.Context) {
  573. ctx.Data["EnableFeed"] = setting.EnableFeed
  574. }, context_service.UserAssignmentWeb())
  575. m.Get("/attachments/{uuid}", repo.GetAttachment)
  576. }, ignSignIn)
  577. m.Post("/{username}", reqSignIn, context_service.UserAssignmentWeb(), user.Action)
  578. reqRepoAdmin := context.RequireRepoAdmin()
  579. reqRepoCodeWriter := context.RequireRepoWriter(unit.TypeCode)
  580. canEnableEditor := context.CanEnableEditor()
  581. reqRepoCodeReader := context.RequireRepoReader(unit.TypeCode)
  582. reqRepoReleaseWriter := context.RequireRepoWriter(unit.TypeReleases)
  583. reqRepoReleaseReader := context.RequireRepoReader(unit.TypeReleases)
  584. reqRepoWikiWriter := context.RequireRepoWriter(unit.TypeWiki)
  585. reqRepoIssueReader := context.RequireRepoReader(unit.TypeIssues)
  586. reqRepoPullsReader := context.RequireRepoReader(unit.TypePullRequests)
  587. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(unit.TypeIssues, unit.TypePullRequests)
  588. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(unit.TypeIssues, unit.TypePullRequests)
  589. reqRepoProjectsReader := context.RequireRepoReader(unit.TypeProjects)
  590. reqRepoProjectsWriter := context.RequireRepoWriter(unit.TypeProjects)
  591. reqPackageAccess := func(accessMode perm.AccessMode) func(ctx *context.Context) {
  592. return func(ctx *context.Context) {
  593. if ctx.Package.AccessMode < accessMode && !ctx.IsUserSiteAdmin() {
  594. ctx.NotFound("", nil)
  595. }
  596. }
  597. }
  598. // ***** START: Organization *****
  599. m.Group("/org", func() {
  600. m.Group("/{org}", func() {
  601. m.Get("/members", org.Members)
  602. }, context.OrgAssignment())
  603. }, ignSignIn)
  604. m.Group("/org", func() {
  605. m.Group("", func() {
  606. m.Get("/create", org.Create)
  607. m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost)
  608. })
  609. m.Group("/invite/{token}", func() {
  610. m.Get("", org.TeamInvite)
  611. m.Post("", org.TeamInvitePost)
  612. })
  613. m.Group("/{org}", func() {
  614. m.Get("/dashboard", user.Dashboard)
  615. m.Get("/dashboard/{team}", user.Dashboard)
  616. m.Get("/issues", user.Issues)
  617. m.Get("/issues/{team}", user.Issues)
  618. m.Get("/pulls", user.Pulls)
  619. m.Get("/pulls/{team}", user.Pulls)
  620. m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
  621. m.Get("/milestones/{team}", reqMilestonesDashboardPageEnabled, user.Milestones)
  622. m.Post("/members/action/{action}", org.MembersAction)
  623. m.Get("/teams", org.Teams)
  624. }, context.OrgAssignment(true, false, true))
  625. m.Group("/{org}", func() {
  626. m.Get("/teams/{team}", org.TeamMembers)
  627. m.Get("/teams/{team}/repositories", org.TeamRepositories)
  628. m.Post("/teams/{team}/action/{action}", org.TeamsAction)
  629. m.Post("/teams/{team}/action/repo/{action}", org.TeamsRepoAction)
  630. }, context.OrgAssignment(true, false, true))
  631. m.Group("/{org}", func() {
  632. m.Get("/teams/new", org.NewTeam)
  633. m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost)
  634. m.Get("/teams/-/search", org.SearchTeam)
  635. m.Get("/teams/{team}/edit", org.EditTeam)
  636. m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost)
  637. m.Post("/teams/{team}/delete", org.DeleteTeam)
  638. m.Group("/settings", func() {
  639. m.Combo("").Get(org.Settings).
  640. Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost)
  641. m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar)
  642. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  643. m.Group("/applications", func() {
  644. m.Get("", org.Applications)
  645. m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost)
  646. m.Group("/oauth2/{id}", func() {
  647. m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit)
  648. m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret)
  649. m.Post("/delete", org.DeleteOAuth2Application)
  650. })
  651. }, func(ctx *context.Context) {
  652. if !setting.OAuth2.Enable {
  653. ctx.Error(http.StatusForbidden)
  654. return
  655. }
  656. })
  657. m.Group("/hooks", func() {
  658. m.Get("", org.Webhooks)
  659. m.Post("/delete", org.DeleteWebhook)
  660. m.Get("/{type}/new", repo.WebhooksNew)
  661. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost)
  662. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost)
  663. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost)
  664. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  665. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  666. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  667. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
  668. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  669. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  670. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost)
  671. m.Group("/{id}", func() {
  672. m.Get("", repo.WebHooksEdit)
  673. m.Post("/replay/{uuid}", repo.ReplayWebhook)
  674. })
  675. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost)
  676. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost)
  677. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost)
  678. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  679. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  680. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  681. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
  682. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  683. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  684. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost)
  685. }, webhooksEnabled)
  686. m.Group("/labels", func() {
  687. m.Get("", org.RetrieveLabels, org.Labels)
  688. m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel)
  689. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel)
  690. m.Post("/delete", org.DeleteLabel)
  691. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels)
  692. })
  693. m.Group("/secrets", func() {
  694. m.Get("", org.Secrets)
  695. m.Post("", web.Bind(forms.AddSecretForm{}), org.SecretsPost)
  696. m.Post("/delete", org.SecretsDelete)
  697. })
  698. m.Route("/delete", "GET,POST", org.SettingsDelete)
  699. m.Group("/packages", func() {
  700. m.Get("", org.Packages)
  701. m.Group("/rules", func() {
  702. m.Group("/add", func() {
  703. m.Get("", org.PackagesRuleAdd)
  704. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost)
  705. })
  706. m.Group("/{id}", func() {
  707. m.Get("", org.PackagesRuleEdit)
  708. m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost)
  709. m.Get("/preview", org.PackagesRulePreview)
  710. })
  711. })
  712. }, packagesEnabled)
  713. }, func(ctx *context.Context) {
  714. ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable
  715. ctx.Data["EnablePackages"] = setting.Packages.Enabled
  716. })
  717. }, context.OrgAssignment(true, true))
  718. }, reqSignIn)
  719. // ***** END: Organization *****
  720. // ***** START: Repository *****
  721. m.Group("/repo", func() {
  722. m.Get("/create", repo.Create)
  723. m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost)
  724. m.Get("/migrate", repo.Migrate)
  725. m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost)
  726. m.Group("/fork", func() {
  727. m.Combo("/{repoid}").Get(repo.Fork).
  728. Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost)
  729. }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
  730. m.Get("/search", repo.SearchRepo)
  731. }, reqSignIn)
  732. m.Group("/{username}/-", func() {
  733. if setting.Packages.Enabled {
  734. m.Group("/packages", func() {
  735. m.Get("", user.ListPackages)
  736. m.Group("/{type}/{name}", func() {
  737. m.Get("", user.RedirectToLastVersion)
  738. m.Get("/versions", user.ListPackageVersions)
  739. m.Group("/{version}", func() {
  740. m.Get("", user.ViewPackageVersion)
  741. m.Get("/files/{fileid}", user.DownloadPackageFile)
  742. m.Group("/settings", func() {
  743. m.Get("", user.PackageSettings)
  744. m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost)
  745. }, reqPackageAccess(perm.AccessModeWrite))
  746. })
  747. })
  748. }, ignSignIn, context.PackageAssignment(), reqPackageAccess(perm.AccessModeRead))
  749. }
  750. m.Get("/code", user.CodeSearch)
  751. }, context_service.UserAssignmentWeb())
  752. // ***** Release Attachment Download without Signin
  753. m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment, repo.MustBeNotEmpty, repo.RedirectDownload)
  754. m.Group("/{username}/{reponame}", func() {
  755. m.Group("/settings", func() {
  756. m.Group("", func() {
  757. m.Combo("").Get(repo.Settings).
  758. Post(web.Bind(forms.RepoSettingForm{}), repo.SettingsPost)
  759. }, repo.SettingsCtxData)
  760. m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo.SettingsAvatar)
  761. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  762. m.Group("/collaboration", func() {
  763. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  764. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  765. m.Post("/delete", repo.DeleteCollaboration)
  766. m.Group("/team", func() {
  767. m.Post("", repo.AddTeamPost)
  768. m.Post("/delete", repo.DeleteTeam)
  769. })
  770. })
  771. m.Group("/branches", func() {
  772. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  773. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  774. Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
  775. }, repo.MustBeNotEmpty)
  776. m.Post("/rename_branch", web.Bind(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo.RenameBranchPost)
  777. m.Group("/tags", func() {
  778. m.Get("", repo.Tags)
  779. m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.NewProtectedTagPost)
  780. m.Post("/delete", context.RepoMustNotBeArchived(), repo.DeleteProtectedTagPost)
  781. m.Get("/{id}", repo.EditProtectedTag)
  782. m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.EditProtectedTagPost)
  783. })
  784. m.Group("/hooks/git", func() {
  785. m.Get("", repo.GitHooks)
  786. m.Combo("/{name}").Get(repo.GitHooksEdit).
  787. Post(repo.GitHooksEditPost)
  788. }, context.GitHookService())
  789. m.Group("/hooks", func() {
  790. m.Get("", repo.Webhooks)
  791. m.Post("/delete", repo.DeleteWebhook)
  792. m.Get("/{type}/new", repo.WebhooksNew)
  793. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost)
  794. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost)
  795. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost)
  796. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  797. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  798. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  799. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
  800. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  801. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  802. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost)
  803. m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost)
  804. m.Group("/{id}", func() {
  805. m.Get("", repo.WebHooksEdit)
  806. m.Post("/test", repo.TestWebhook)
  807. m.Post("/replay/{uuid}", repo.ReplayWebhook)
  808. })
  809. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost)
  810. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost)
  811. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost)
  812. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  813. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  814. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  815. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
  816. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  817. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  818. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost)
  819. m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost)
  820. }, webhooksEnabled)
  821. m.Group("/keys", func() {
  822. m.Combo("").Get(repo.DeployKeys).
  823. Post(web.Bind(forms.AddKeyForm{}), repo.DeployKeysPost)
  824. m.Post("/delete", repo.DeleteDeployKey)
  825. m.Group("/secrets", func() {
  826. m.Post("", web.Bind(forms.AddSecretForm{}), repo.SecretsPost)
  827. m.Post("/delete", repo.DeleteSecret)
  828. })
  829. })
  830. m.Group("/lfs", func() {
  831. m.Get("/", repo.LFSFiles)
  832. m.Get("/show/{oid}", repo.LFSFileGet)
  833. m.Post("/delete/{oid}", repo.LFSDelete)
  834. m.Get("/pointers", repo.LFSPointerFiles)
  835. m.Post("/pointers/associate", repo.LFSAutoAssociate)
  836. m.Get("/find", repo.LFSFileFind)
  837. m.Group("/locks", func() {
  838. m.Get("/", repo.LFSLocks)
  839. m.Post("/", repo.LFSLockFile)
  840. m.Post("/{lid}/unlock", repo.LFSUnlock)
  841. })
  842. })
  843. }, func(ctx *context.Context) {
  844. ctx.Data["PageIsSettings"] = true
  845. ctx.Data["LFSStartServer"] = setting.LFS.StartServer
  846. })
  847. }, reqSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  848. m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment, context.UnitTypes(), repo.Action)
  849. // Grouping for those endpoints not requiring authentication
  850. m.Group("/{username}/{reponame}", func() {
  851. m.Group("/milestone", func() {
  852. m.Get("/{id}", repo.MilestoneIssuesAndPulls)
  853. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  854. m.Get("/find/*", repo.FindFiles)
  855. m.Group("/tree-list", func() {
  856. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.TreeList)
  857. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.TreeList)
  858. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.TreeList)
  859. })
  860. m.Get("/compare", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists, ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
  861. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  862. Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
  863. Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
  864. m.Group("/{type:issues|pulls}", func() {
  865. m.Group("/{index}", func() {
  866. m.Get("/info", repo.GetIssueInfo)
  867. })
  868. })
  869. }, context.RepoAssignment, context.UnitTypes())
  870. // Grouping for those endpoints that do require authentication
  871. m.Group("/{username}/{reponame}", func() {
  872. m.Group("/issues", func() {
  873. m.Group("/new", func() {
  874. m.Combo("").Get(context.RepoRef(), repo.NewIssue).
  875. Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost)
  876. m.Get("/choose", context.RepoRef(), repo.NewIssueChooseTemplate)
  877. })
  878. m.Get("/search", repo.ListIssues)
  879. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  880. // FIXME: should use different URLs but mostly same logic for comments of issue and pull request.
  881. // So they can apply their own enable/disable logic on routers.
  882. m.Group("/{type:issues|pulls}", func() {
  883. m.Group("/{index}", func() {
  884. m.Post("/title", repo.UpdateIssueTitle)
  885. m.Post("/content", repo.UpdateIssueContent)
  886. m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  887. m.Post("/watch", repo.IssueWatch)
  888. m.Post("/ref", repo.UpdateIssueRef)
  889. m.Post("/viewed-files", repo.UpdateViewedFiles)
  890. m.Group("/dependency", func() {
  891. m.Post("/add", repo.AddDependency)
  892. m.Post("/delete", repo.RemoveDependency)
  893. })
  894. m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment)
  895. m.Group("/times", func() {
  896. m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually)
  897. m.Post("/{timeid}/delete", repo.DeleteTime)
  898. m.Group("/stopwatch", func() {
  899. m.Post("/toggle", repo.IssueStopwatch)
  900. m.Post("/cancel", repo.CancelStopwatch)
  901. })
  902. })
  903. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction)
  904. m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue)
  905. m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue)
  906. m.Post("/delete", reqRepoAdmin, repo.DeleteIssue)
  907. }, context.RepoMustNotBeArchived())
  908. m.Group("/{index}", func() {
  909. m.Get("/attachments", repo.GetIssueAttachments)
  910. m.Get("/attachments/{uuid}", repo.GetAttachment)
  911. })
  912. m.Group("/{index}", func() {
  913. m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory)
  914. })
  915. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  916. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  917. m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject)
  918. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  919. m.Post("/request_review", reqRepoIssuesOrPullsReader, repo.UpdatePullReviewRequest)
  920. m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview)
  921. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  922. m.Post("/resolve_conversation", reqRepoIssuesOrPullsReader, repo.UpdateResolveConversation)
  923. m.Post("/attachments", repo.UploadIssueAttachment)
  924. m.Post("/attachments/remove", repo.DeleteAttachment)
  925. }, context.RepoMustNotBeArchived())
  926. m.Group("/comments/{id}", func() {
  927. m.Post("", repo.UpdateCommentContent)
  928. m.Post("/delete", repo.DeleteComment)
  929. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction)
  930. }, context.RepoMustNotBeArchived())
  931. m.Group("/comments/{id}", func() {
  932. m.Get("/attachments", repo.GetCommentAttachments)
  933. })
  934. m.Post("/markdown", web.Bind(structs.MarkdownOption{}), misc.Markdown)
  935. m.Group("/labels", func() {
  936. m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel)
  937. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel)
  938. m.Post("/delete", repo.DeleteLabel)
  939. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels)
  940. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  941. m.Group("/milestones", func() {
  942. m.Combo("/new").Get(repo.NewMilestone).
  943. Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost)
  944. m.Get("/{id}/edit", repo.EditMilestone)
  945. m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost)
  946. m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
  947. m.Post("/delete", repo.DeleteMilestone)
  948. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  949. m.Group("/pull", func() {
  950. m.Post("/{index}/target_branch", repo.UpdatePullRequestTarget)
  951. }, context.RepoMustNotBeArchived())
  952. m.Group("", func() {
  953. m.Group("", func() {
  954. m.Combo("/_edit/*").Get(repo.EditFile).
  955. Post(web.Bind(forms.EditRepoFileForm{}), repo.EditFilePost)
  956. m.Combo("/_new/*").Get(repo.NewFile).
  957. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewFilePost)
  958. m.Post("/_preview/*", web.Bind(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  959. m.Combo("/_delete/*").Get(repo.DeleteFile).
  960. Post(web.Bind(forms.DeleteRepoFileForm{}), repo.DeleteFilePost)
  961. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  962. Get(repo.UploadFile).
  963. Post(web.Bind(forms.UploadRepoFileForm{}), repo.UploadFilePost)
  964. m.Combo("/_diffpatch/*").Get(repo.NewDiffPatch).
  965. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewDiffPatchPost)
  966. m.Combo("/_cherrypick/{sha:([a-f0-9]{7,40})}/*").Get(repo.CherryPick).
  967. Post(web.Bind(forms.CherryPickForm{}), repo.CherryPickPost)
  968. }, repo.MustBeEditable)
  969. m.Group("", func() {
  970. m.Post("/upload-file", repo.UploadFileToServer)
  971. m.Post("/upload-remove", web.Bind(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  972. }, repo.MustBeEditable, repo.MustBeAbleToUpload)
  973. }, context.RepoRef(), canEnableEditor, context.RepoMustNotBeArchived(), repo.MustBeNotEmpty)
  974. m.Group("/branches", func() {
  975. m.Group("/_new", func() {
  976. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  977. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  978. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  979. }, web.Bind(forms.NewBranchForm{}))
  980. m.Post("/delete", repo.DeleteBranchPost)
  981. m.Post("/restore", repo.RestoreBranchPost)
  982. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  983. }, reqSignIn, context.RepoAssignment, context.UnitTypes())
  984. // Releases
  985. m.Group("/{username}/{reponame}", func() {
  986. m.Group("/tags", func() {
  987. m.Get("", repo.TagsList)
  988. m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
  989. m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
  990. }, func(ctx *context.Context) {
  991. ctx.Data["EnableFeed"] = setting.EnableFeed
  992. }, repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
  993. m.Group("/releases", func() {
  994. m.Get("/", repo.Releases)
  995. m.Get("/tag/*", repo.SingleRelease)
  996. m.Get("/latest", repo.LatestRelease)
  997. m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
  998. m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
  999. }, func(ctx *context.Context) {
  1000. ctx.Data["EnableFeed"] = setting.EnableFeed
  1001. }, repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag, true))
  1002. m.Get("/releases/attachments/{uuid}", repo.GetAttachment, repo.MustBeNotEmpty, reqRepoReleaseReader)
  1003. m.Group("/releases", func() {
  1004. m.Get("/new", repo.NewRelease)
  1005. m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost)
  1006. m.Post("/delete", repo.DeleteRelease)
  1007. m.Post("/attachments", repo.UploadReleaseAttachment)
  1008. m.Post("/attachments/remove", repo.DeleteAttachment)
  1009. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  1010. m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
  1011. repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
  1012. m.Group("/releases", func() {
  1013. m.Get("/edit/*", repo.EditRelease)
  1014. m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
  1015. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
  1016. var err error
  1017. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  1018. if err != nil {
  1019. ctx.ServerError("GetBranchCommit", err)
  1020. return
  1021. }
  1022. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  1023. if err != nil {
  1024. ctx.ServerError("GetCommitsCount", err)
  1025. return
  1026. }
  1027. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  1028. ctx.Repo.GitRepo.LastCommitCache = git.NewLastCommitCache(ctx.Repo.CommitsCount, ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, cache.GetCache())
  1029. })
  1030. }, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
  1031. // to maintain compatibility with old attachments
  1032. m.Group("/{username}/{reponame}", func() {
  1033. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1034. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1035. m.Group("/{username}/{reponame}", func() {
  1036. m.Post("/topics", repo.TopicsPost)
  1037. }, context.RepoAssignment, context.RepoMustNotBeArchived(), reqRepoAdmin)
  1038. m.Group("/{username}/{reponame}", func() {
  1039. m.Group("", func() {
  1040. m.Get("/{type:issues|pulls}", repo.Issues)
  1041. m.Get("/{type:issues|pulls}/{index}", repo.ViewIssue)
  1042. m.Group("/{type:issues|pulls}/{index}/content-history", func() {
  1043. m.Get("/overview", repo.GetContentHistoryOverview)
  1044. m.Get("/list", repo.GetContentHistoryList)
  1045. m.Get("/detail", repo.GetContentHistoryDetail)
  1046. })
  1047. m.Get("/labels", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  1048. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  1049. }, context.RepoRef())
  1050. if setting.Packages.Enabled {
  1051. m.Get("/packages", repo.Packages)
  1052. }
  1053. m.Group("/projects", func() {
  1054. m.Get("", repo.Projects)
  1055. m.Get("/{id}", repo.ViewProject)
  1056. m.Group("", func() {
  1057. m.Get("/new", repo.NewProject)
  1058. m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
  1059. m.Group("/{id}", func() {
  1060. m.Post("", web.Bind(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost)
  1061. m.Post("/delete", repo.DeleteProject)
  1062. m.Get("/edit", repo.EditProject)
  1063. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost)
  1064. m.Post("/{action:open|close}", repo.ChangeProjectStatus)
  1065. m.Group("/{boardID}", func() {
  1066. m.Put("", web.Bind(forms.EditProjectBoardForm{}), repo.EditProjectBoard)
  1067. m.Delete("", repo.DeleteProjectBoard)
  1068. m.Post("/default", repo.SetDefaultProjectBoard)
  1069. m.Post("/move", repo.MoveIssues)
  1070. })
  1071. })
  1072. }, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
  1073. }, reqRepoProjectsReader, repo.MustEnableProjects)
  1074. m.Group("/wiki", func() {
  1075. m.Combo("/").
  1076. Get(repo.Wiki).
  1077. Post(context.RepoMustNotBeArchived(),
  1078. reqSignIn,
  1079. reqRepoWikiWriter,
  1080. web.Bind(forms.NewWikiForm{}),
  1081. repo.WikiPost)
  1082. m.Combo("/*").
  1083. Get(repo.Wiki).
  1084. Post(context.RepoMustNotBeArchived(),
  1085. reqSignIn,
  1086. reqRepoWikiWriter,
  1087. web.Bind(forms.NewWikiForm{}),
  1088. repo.WikiPost)
  1089. m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1090. m.Get("/commit/{sha:[a-f0-9]{7,40}}.{ext:patch|diff}", repo.RawDiff)
  1091. }, repo.MustEnableWiki, func(ctx *context.Context) {
  1092. ctx.Data["PageIsWiki"] = true
  1093. ctx.Data["CloneButtonOriginLink"] = ctx.Repo.Repository.WikiCloneLink()
  1094. })
  1095. m.Group("/wiki", func() {
  1096. m.Get("/raw/*", repo.WikiRaw)
  1097. }, repo.MustEnableWiki)
  1098. m.Group("/activity", func() {
  1099. m.Get("", repo.Activity)
  1100. m.Get("/{period}", repo.Activity)
  1101. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypePullRequests, unit.TypeIssues, unit.TypeReleases))
  1102. m.Group("/activity_author_data", func() {
  1103. m.Get("", repo.ActivityAuthors)
  1104. m.Get("/{period}", repo.ActivityAuthors)
  1105. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypeCode))
  1106. m.Group("/archive", func() {
  1107. m.Get("/*", repo.Download)
  1108. m.Post("/*", repo.InitiateDownload)
  1109. }, repo.MustBeNotEmpty, dlSourceEnabled, reqRepoCodeReader)
  1110. m.Group("/branches", func() {
  1111. m.Get("", repo.Branches)
  1112. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1113. m.Group("/blob_excerpt", func() {
  1114. m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1115. }, func(ctx *context.Context) (cancel gocontext.CancelFunc) {
  1116. if ctx.FormBool("wiki") {
  1117. ctx.Data["PageIsWiki"] = true
  1118. repo.MustEnableWiki(ctx)
  1119. return
  1120. }
  1121. reqRepoCodeReader(ctx)
  1122. if ctx.Written() {
  1123. return
  1124. }
  1125. cancel = context.RepoRef()(ctx)
  1126. if ctx.Written() {
  1127. return
  1128. }
  1129. repo.MustBeNotEmpty(ctx)
  1130. return cancel
  1131. })
  1132. m.Group("/pulls/{index}", func() {
  1133. m.Get(".diff", repo.DownloadPullDiff)
  1134. m.Get(".patch", repo.DownloadPullPatch)
  1135. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  1136. m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
  1137. m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest)
  1138. m.Post("/update", repo.UpdatePullRequest)
  1139. m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits)
  1140. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  1141. m.Group("/files", func() {
  1142. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
  1143. m.Group("/reviews", func() {
  1144. m.Get("/new_comment", repo.RenderNewCodeCommentForm)
  1145. m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.CreateCodeComment)
  1146. m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview)
  1147. }, context.RepoMustNotBeArchived())
  1148. })
  1149. }, repo.MustAllowPulls)
  1150. m.Group("/media", func() {
  1151. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  1152. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  1153. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  1154. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  1155. // "/*" route is deprecated, and kept for backward compatibility
  1156. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  1157. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1158. m.Group("/raw", func() {
  1159. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  1160. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  1161. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  1162. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  1163. // "/*" route is deprecated, and kept for backward compatibility
  1164. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  1165. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1166. m.Group("/render", func() {
  1167. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RenderFile)
  1168. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RenderFile)
  1169. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RenderFile)
  1170. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.RenderFile)
  1171. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1172. m.Group("/commits", func() {
  1173. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  1174. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  1175. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  1176. // "/*" route is deprecated, and kept for backward compatibility
  1177. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  1178. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1179. m.Group("/blame", func() {
  1180. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  1181. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  1182. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  1183. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1184. m.Group("", func() {
  1185. m.Get("/graph", repo.Graph)
  1186. m.Get("/commit/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1187. m.Get("/cherry-pick/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.CherryPick)
  1188. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1189. m.Group("/src", func() {
  1190. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  1191. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  1192. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  1193. // "/*" route is deprecated, and kept for backward compatibility
  1194. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  1195. }, repo.SetEditorconfigIfExists)
  1196. m.Group("", func() {
  1197. m.Get("/forks", repo.Forks)
  1198. }, context.RepoRef(), reqRepoCodeReader)
  1199. m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}",
  1200. repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  1201. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1202. m.Post("/{username}/{reponame}/lastcommit/*", ignSignInAndCsrf, context.RepoAssignment, context.UnitTypes(), context.RepoRefByType(context.RepoRefCommit), reqRepoCodeReader, repo.LastCommit)
  1203. m.Group("/{username}/{reponame}", func() {
  1204. m.Get("/stars", repo.Stars)
  1205. m.Get("/watchers", repo.Watchers)
  1206. m.Get("/search", reqRepoCodeReader, repo.Search)
  1207. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1208. m.Group("/{username}", func() {
  1209. m.Group("/{reponame}", func() {
  1210. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  1211. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1212. m.Group("/{reponame}", func() {
  1213. m.Group("/info/lfs", func() {
  1214. m.Post("/objects/batch", lfs.CheckAcceptMediaType, lfs.BatchHandler)
  1215. m.Put("/objects/{oid}/{size}", lfs.UploadHandler)
  1216. m.Get("/objects/{oid}/{filename}", lfs.DownloadHandler)
  1217. m.Get("/objects/{oid}", lfs.DownloadHandler)
  1218. m.Post("/verify", lfs.CheckAcceptMediaType, lfs.VerifyHandler)
  1219. m.Group("/locks", func() {
  1220. m.Get("/", lfs.GetListLockHandler)
  1221. m.Post("/", lfs.PostLockHandler)
  1222. m.Post("/verify", lfs.VerifyLockHandler)
  1223. m.Post("/{lid}/unlock", lfs.UnLockHandler)
  1224. }, lfs.CheckAcceptMediaType)
  1225. m.Any("/*", func(ctx *context.Context) {
  1226. ctx.NotFound("", nil)
  1227. })
  1228. }, ignSignInAndCsrf, lfsServerEnabled)
  1229. m.Group("", func() {
  1230. m.PostOptions("/git-upload-pack", repo.ServiceUploadPack)
  1231. m.PostOptions("/git-receive-pack", repo.ServiceReceivePack)
  1232. m.GetOptions("/info/refs", repo.GetInfoRefs)
  1233. m.GetOptions("/HEAD", repo.GetTextFile("HEAD"))
  1234. m.GetOptions("/objects/info/alternates", repo.GetTextFile("objects/info/alternates"))
  1235. m.GetOptions("/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates"))
  1236. m.GetOptions("/objects/info/packs", repo.GetInfoPacks)
  1237. m.GetOptions("/objects/info/{file:[^/]*}", repo.GetTextFile(""))
  1238. m.GetOptions("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject)
  1239. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile)
  1240. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile)
  1241. }, ignSignInAndCsrf, context_service.UserAssignmentWeb())
  1242. })
  1243. })
  1244. // ***** END: Repository *****
  1245. m.Group("/notifications", func() {
  1246. m.Get("", user.Notifications)
  1247. m.Get("/subscriptions", user.NotificationSubscriptions)
  1248. m.Get("/watching", user.NotificationWatching)
  1249. m.Post("/status", user.NotificationStatusPost)
  1250. m.Post("/purge", user.NotificationPurgePost)
  1251. m.Get("/new", user.NewAvailable)
  1252. }, reqSignIn)
  1253. if setting.API.EnableSwagger {
  1254. m.Get("/swagger.v1.json", SwaggerV1Json)
  1255. }
  1256. m.NotFound(func(w http.ResponseWriter, req *http.Request) {
  1257. ctx := context.GetContext(req)
  1258. ctx.NotFound("", nil)
  1259. })
  1260. }