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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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.Group("/projects", func() {
  751. m.Get("", org.Projects)
  752. m.Get("/{id}", org.ViewProject)
  753. m.Group("", func() { //nolint:dupl
  754. m.Get("/new", org.NewProject)
  755. m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost)
  756. m.Group("/{id}", func() {
  757. m.Post("", web.Bind(forms.EditProjectBoardForm{}), org.AddBoardToProjectPost)
  758. m.Post("/delete", org.DeleteProject)
  759. m.Get("/edit", org.EditProject)
  760. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), org.EditProjectPost)
  761. m.Post("/{action:open|close}", org.ChangeProjectStatus)
  762. m.Group("/{boardID}", func() {
  763. m.Put("", web.Bind(forms.EditProjectBoardForm{}), org.EditProjectBoard)
  764. m.Delete("", org.DeleteProjectBoard)
  765. m.Post("/default", org.SetDefaultProjectBoard)
  766. m.Post("/move", org.MoveIssues)
  767. })
  768. })
  769. }, reqSignIn, func(ctx *context.Context) {
  770. if ctx.ContextUser == nil {
  771. ctx.NotFound("NewProject", nil)
  772. return
  773. }
  774. if ctx.ContextUser.IsOrganization() {
  775. if !ctx.Org.CanWriteUnit(ctx, unit.TypeProjects) {
  776. ctx.NotFound("NewProject", nil)
  777. return
  778. }
  779. } else if ctx.ContextUser.ID != ctx.Doer.ID {
  780. ctx.NotFound("NewProject", nil)
  781. return
  782. }
  783. })
  784. }, repo.MustEnableProjects)
  785. m.Get("/code", user.CodeSearch)
  786. }, context_service.UserAssignmentWeb())
  787. // ***** Release Attachment Download without Signin
  788. m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment, repo.MustBeNotEmpty, repo.RedirectDownload)
  789. m.Group("/{username}/{reponame}", func() {
  790. m.Group("/settings", func() {
  791. m.Group("", func() {
  792. m.Combo("").Get(repo.Settings).
  793. Post(web.Bind(forms.RepoSettingForm{}), repo.SettingsPost)
  794. }, repo.SettingsCtxData)
  795. m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo.SettingsAvatar)
  796. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  797. m.Group("/collaboration", func() {
  798. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  799. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  800. m.Post("/delete", repo.DeleteCollaboration)
  801. m.Group("/team", func() {
  802. m.Post("", repo.AddTeamPost)
  803. m.Post("/delete", repo.DeleteTeam)
  804. })
  805. })
  806. m.Group("/branches", func() {
  807. m.Post("/", repo.SetDefaultBranchPost)
  808. }, repo.MustBeNotEmpty)
  809. m.Group("/branches", func() {
  810. m.Get("/", repo.ProtectedBranchRules)
  811. m.Combo("/edit").Get(repo.SettingsProtectedBranch).
  812. Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
  813. m.Post("/{id}/delete", repo.DeleteProtectedBranchRulePost)
  814. }, repo.MustBeNotEmpty)
  815. m.Post("/rename_branch", web.Bind(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo.RenameBranchPost)
  816. m.Group("/tags", func() {
  817. m.Get("", repo.Tags)
  818. m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.NewProtectedTagPost)
  819. m.Post("/delete", context.RepoMustNotBeArchived(), repo.DeleteProtectedTagPost)
  820. m.Get("/{id}", repo.EditProtectedTag)
  821. m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.EditProtectedTagPost)
  822. })
  823. m.Group("/hooks/git", func() {
  824. m.Get("", repo.GitHooks)
  825. m.Combo("/{name}").Get(repo.GitHooksEdit).
  826. Post(repo.GitHooksEditPost)
  827. }, context.GitHookService())
  828. m.Group("/hooks", func() {
  829. m.Get("", repo.Webhooks)
  830. m.Post("/delete", repo.DeleteWebhook)
  831. m.Get("/{type}/new", repo.WebhooksNew)
  832. m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost)
  833. m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost)
  834. m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost)
  835. m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  836. m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  837. m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  838. m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
  839. m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  840. m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  841. m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost)
  842. m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost)
  843. m.Group("/{id}", func() {
  844. m.Get("", repo.WebHooksEdit)
  845. m.Post("/test", repo.TestWebhook)
  846. m.Post("/replay/{uuid}", repo.ReplayWebhook)
  847. })
  848. m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost)
  849. m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost)
  850. m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost)
  851. m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  852. m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  853. m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  854. m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
  855. m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  856. m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  857. m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost)
  858. m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost)
  859. }, webhooksEnabled)
  860. m.Group("/keys", func() {
  861. m.Combo("").Get(repo.DeployKeys).
  862. Post(web.Bind(forms.AddKeyForm{}), repo.DeployKeysPost)
  863. m.Post("/delete", repo.DeleteDeployKey)
  864. m.Group("/secrets", func() {
  865. m.Post("", web.Bind(forms.AddSecretForm{}), repo.SecretsPost)
  866. m.Post("/delete", repo.DeleteSecret)
  867. })
  868. })
  869. m.Group("/lfs", func() {
  870. m.Get("/", repo.LFSFiles)
  871. m.Get("/show/{oid}", repo.LFSFileGet)
  872. m.Post("/delete/{oid}", repo.LFSDelete)
  873. m.Get("/pointers", repo.LFSPointerFiles)
  874. m.Post("/pointers/associate", repo.LFSAutoAssociate)
  875. m.Get("/find", repo.LFSFileFind)
  876. m.Group("/locks", func() {
  877. m.Get("/", repo.LFSLocks)
  878. m.Post("/", repo.LFSLockFile)
  879. m.Post("/{lid}/unlock", repo.LFSUnlock)
  880. })
  881. })
  882. }, func(ctx *context.Context) {
  883. ctx.Data["PageIsSettings"] = true
  884. ctx.Data["LFSStartServer"] = setting.LFS.StartServer
  885. })
  886. }, reqSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  887. m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment, context.UnitTypes(), repo.Action)
  888. // Grouping for those endpoints not requiring authentication
  889. m.Group("/{username}/{reponame}", func() {
  890. m.Group("/milestone", func() {
  891. m.Get("/{id}", repo.MilestoneIssuesAndPulls)
  892. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  893. m.Get("/find/*", repo.FindFiles)
  894. m.Group("/tree-list", func() {
  895. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.TreeList)
  896. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.TreeList)
  897. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.TreeList)
  898. })
  899. m.Get("/compare", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists, ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
  900. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  901. Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
  902. Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
  903. m.Group("/{type:issues|pulls}", func() {
  904. m.Group("/{index}", func() {
  905. m.Get("/info", repo.GetIssueInfo)
  906. })
  907. })
  908. }, context.RepoAssignment, context.UnitTypes())
  909. // Grouping for those endpoints that do require authentication
  910. m.Group("/{username}/{reponame}", func() {
  911. m.Group("/issues", func() {
  912. m.Group("/new", func() {
  913. m.Combo("").Get(context.RepoRef(), repo.NewIssue).
  914. Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost)
  915. m.Get("/choose", context.RepoRef(), repo.NewIssueChooseTemplate)
  916. })
  917. m.Get("/search", repo.ListIssues)
  918. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  919. // FIXME: should use different URLs but mostly same logic for comments of issue and pull request.
  920. // So they can apply their own enable/disable logic on routers.
  921. m.Group("/{type:issues|pulls}", func() {
  922. m.Group("/{index}", func() {
  923. m.Post("/title", repo.UpdateIssueTitle)
  924. m.Post("/content", repo.UpdateIssueContent)
  925. m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline)
  926. m.Post("/watch", repo.IssueWatch)
  927. m.Post("/ref", repo.UpdateIssueRef)
  928. m.Post("/viewed-files", repo.UpdateViewedFiles)
  929. m.Group("/dependency", func() {
  930. m.Post("/add", repo.AddDependency)
  931. m.Post("/delete", repo.RemoveDependency)
  932. })
  933. m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment)
  934. m.Group("/times", func() {
  935. m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually)
  936. m.Post("/{timeid}/delete", repo.DeleteTime)
  937. m.Group("/stopwatch", func() {
  938. m.Post("/toggle", repo.IssueStopwatch)
  939. m.Post("/cancel", repo.CancelStopwatch)
  940. })
  941. })
  942. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction)
  943. m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue)
  944. m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue)
  945. m.Post("/delete", reqRepoAdmin, repo.DeleteIssue)
  946. }, context.RepoMustNotBeArchived())
  947. m.Group("/{index}", func() {
  948. m.Get("/attachments", repo.GetIssueAttachments)
  949. m.Get("/attachments/{uuid}", repo.GetAttachment)
  950. })
  951. m.Group("/{index}", func() {
  952. m.Post("/content-history/soft-delete", repo.SoftDeleteContentHistory)
  953. })
  954. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  955. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  956. m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject)
  957. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  958. m.Post("/request_review", reqRepoIssuesOrPullsReader, repo.UpdatePullReviewRequest)
  959. m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview)
  960. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  961. m.Post("/resolve_conversation", reqRepoIssuesOrPullsReader, repo.UpdateResolveConversation)
  962. m.Post("/attachments", repo.UploadIssueAttachment)
  963. m.Post("/attachments/remove", repo.DeleteAttachment)
  964. }, context.RepoMustNotBeArchived())
  965. m.Group("/comments/{id}", func() {
  966. m.Post("", repo.UpdateCommentContent)
  967. m.Post("/delete", repo.DeleteComment)
  968. m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction)
  969. }, context.RepoMustNotBeArchived())
  970. m.Group("/comments/{id}", func() {
  971. m.Get("/attachments", repo.GetCommentAttachments)
  972. })
  973. m.Post("/markdown", web.Bind(structs.MarkdownOption{}), misc.Markdown)
  974. m.Group("/labels", func() {
  975. m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel)
  976. m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel)
  977. m.Post("/delete", repo.DeleteLabel)
  978. m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels)
  979. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  980. m.Group("/milestones", func() {
  981. m.Combo("/new").Get(repo.NewMilestone).
  982. Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost)
  983. m.Get("/{id}/edit", repo.EditMilestone)
  984. m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost)
  985. m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
  986. m.Post("/delete", repo.DeleteMilestone)
  987. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  988. m.Group("/pull", func() {
  989. m.Post("/{index}/target_branch", repo.UpdatePullRequestTarget)
  990. }, context.RepoMustNotBeArchived())
  991. m.Group("", func() {
  992. m.Group("", func() {
  993. m.Combo("/_edit/*").Get(repo.EditFile).
  994. Post(web.Bind(forms.EditRepoFileForm{}), repo.EditFilePost)
  995. m.Combo("/_new/*").Get(repo.NewFile).
  996. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewFilePost)
  997. m.Post("/_preview/*", web.Bind(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  998. m.Combo("/_delete/*").Get(repo.DeleteFile).
  999. Post(web.Bind(forms.DeleteRepoFileForm{}), repo.DeleteFilePost)
  1000. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  1001. Get(repo.UploadFile).
  1002. Post(web.Bind(forms.UploadRepoFileForm{}), repo.UploadFilePost)
  1003. m.Combo("/_diffpatch/*").Get(repo.NewDiffPatch).
  1004. Post(web.Bind(forms.EditRepoFileForm{}), repo.NewDiffPatchPost)
  1005. m.Combo("/_cherrypick/{sha:([a-f0-9]{7,40})}/*").Get(repo.CherryPick).
  1006. Post(web.Bind(forms.CherryPickForm{}), repo.CherryPickPost)
  1007. }, repo.MustBeEditable)
  1008. m.Group("", func() {
  1009. m.Post("/upload-file", repo.UploadFileToServer)
  1010. m.Post("/upload-remove", web.Bind(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  1011. }, repo.MustBeEditable, repo.MustBeAbleToUpload)
  1012. }, context.RepoRef(), canEnableEditor, context.RepoMustNotBeArchived(), repo.MustBeNotEmpty)
  1013. m.Group("/branches", func() {
  1014. m.Group("/_new", func() {
  1015. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  1016. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  1017. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  1018. }, web.Bind(forms.NewBranchForm{}))
  1019. m.Post("/delete", repo.DeleteBranchPost)
  1020. m.Post("/restore", repo.RestoreBranchPost)
  1021. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  1022. }, reqSignIn, context.RepoAssignment, context.UnitTypes())
  1023. // Releases
  1024. m.Group("/{username}/{reponame}", func() {
  1025. m.Group("/tags", func() {
  1026. m.Get("", repo.TagsList)
  1027. m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
  1028. m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
  1029. }, func(ctx *context.Context) {
  1030. ctx.Data["EnableFeed"] = setting.EnableFeed
  1031. }, repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
  1032. m.Group("/releases", func() {
  1033. m.Get("/", repo.Releases)
  1034. m.Get("/tag/*", repo.SingleRelease)
  1035. m.Get("/latest", repo.LatestRelease)
  1036. m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
  1037. m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
  1038. }, func(ctx *context.Context) {
  1039. ctx.Data["EnableFeed"] = setting.EnableFeed
  1040. }, repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag, true))
  1041. m.Get("/releases/attachments/{uuid}", repo.GetAttachment, repo.MustBeNotEmpty, reqRepoReleaseReader)
  1042. m.Group("/releases", func() {
  1043. m.Get("/new", repo.NewRelease)
  1044. m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost)
  1045. m.Post("/delete", repo.DeleteRelease)
  1046. m.Post("/attachments", repo.UploadReleaseAttachment)
  1047. m.Post("/attachments/remove", repo.DeleteAttachment)
  1048. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  1049. m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
  1050. repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
  1051. m.Group("/releases", func() {
  1052. m.Get("/edit/*", repo.EditRelease)
  1053. m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost)
  1054. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
  1055. var err error
  1056. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  1057. if err != nil {
  1058. ctx.ServerError("GetBranchCommit", err)
  1059. return
  1060. }
  1061. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  1062. if err != nil {
  1063. ctx.ServerError("GetCommitsCount", err)
  1064. return
  1065. }
  1066. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  1067. ctx.Repo.GitRepo.LastCommitCache = git.NewLastCommitCache(ctx.Repo.CommitsCount, ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, cache.GetCache())
  1068. })
  1069. }, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
  1070. // to maintain compatibility with old attachments
  1071. m.Group("/{username}/{reponame}", func() {
  1072. m.Get("/attachments/{uuid}", repo.GetAttachment)
  1073. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1074. m.Group("/{username}/{reponame}", func() {
  1075. m.Post("/topics", repo.TopicsPost)
  1076. }, context.RepoAssignment, context.RepoMustNotBeArchived(), reqRepoAdmin)
  1077. m.Group("/{username}/{reponame}", func() {
  1078. m.Group("", func() {
  1079. m.Get("/{type:issues|pulls}", repo.Issues)
  1080. m.Get("/{type:issues|pulls}/{index}", repo.ViewIssue)
  1081. m.Group("/{type:issues|pulls}/{index}/content-history", func() {
  1082. m.Get("/overview", repo.GetContentHistoryOverview)
  1083. m.Get("/list", repo.GetContentHistoryList)
  1084. m.Get("/detail", repo.GetContentHistoryDetail)
  1085. })
  1086. m.Get("/labels", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  1087. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  1088. }, context.RepoRef())
  1089. if setting.Packages.Enabled {
  1090. m.Get("/packages", repo.Packages)
  1091. }
  1092. m.Group("/projects", func() {
  1093. m.Get("", repo.Projects)
  1094. m.Get("/{id}", repo.ViewProject)
  1095. m.Group("", func() { //nolint:dupl
  1096. m.Get("/new", repo.NewProject)
  1097. m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
  1098. m.Group("/{id}", func() {
  1099. m.Post("", web.Bind(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost)
  1100. m.Post("/delete", repo.DeleteProject)
  1101. m.Get("/edit", repo.EditProject)
  1102. m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost)
  1103. m.Post("/{action:open|close}", repo.ChangeProjectStatus)
  1104. m.Group("/{boardID}", func() {
  1105. m.Put("", web.Bind(forms.EditProjectBoardForm{}), repo.EditProjectBoard)
  1106. m.Delete("", repo.DeleteProjectBoard)
  1107. m.Post("/default", repo.SetDefaultProjectBoard)
  1108. m.Post("/move", repo.MoveIssues)
  1109. })
  1110. })
  1111. }, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
  1112. }, reqRepoProjectsReader, repo.MustEnableProjects)
  1113. m.Group("/wiki", func() {
  1114. m.Combo("/").
  1115. Get(repo.Wiki).
  1116. Post(context.RepoMustNotBeArchived(),
  1117. reqSignIn,
  1118. reqRepoWikiWriter,
  1119. web.Bind(forms.NewWikiForm{}),
  1120. repo.WikiPost)
  1121. m.Combo("/*").
  1122. Get(repo.Wiki).
  1123. Post(context.RepoMustNotBeArchived(),
  1124. reqSignIn,
  1125. reqRepoWikiWriter,
  1126. web.Bind(forms.NewWikiForm{}),
  1127. repo.WikiPost)
  1128. m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1129. m.Get("/commit/{sha:[a-f0-9]{7,40}}.{ext:patch|diff}", repo.RawDiff)
  1130. }, repo.MustEnableWiki, func(ctx *context.Context) {
  1131. ctx.Data["PageIsWiki"] = true
  1132. ctx.Data["CloneButtonOriginLink"] = ctx.Repo.Repository.WikiCloneLink()
  1133. })
  1134. m.Group("/wiki", func() {
  1135. m.Get("/raw/*", repo.WikiRaw)
  1136. }, repo.MustEnableWiki)
  1137. m.Group("/activity", func() {
  1138. m.Get("", repo.Activity)
  1139. m.Get("/{period}", repo.Activity)
  1140. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypePullRequests, unit.TypeIssues, unit.TypeReleases))
  1141. m.Group("/activity_author_data", func() {
  1142. m.Get("", repo.ActivityAuthors)
  1143. m.Get("/{period}", repo.ActivityAuthors)
  1144. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(unit.TypeCode))
  1145. m.Group("/archive", func() {
  1146. m.Get("/*", repo.Download)
  1147. m.Post("/*", repo.InitiateDownload)
  1148. }, repo.MustBeNotEmpty, dlSourceEnabled, reqRepoCodeReader)
  1149. m.Group("/branches", func() {
  1150. m.Get("", repo.Branches)
  1151. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1152. m.Group("/blob_excerpt", func() {
  1153. m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  1154. }, func(ctx *context.Context) (cancel gocontext.CancelFunc) {
  1155. if ctx.FormBool("wiki") {
  1156. ctx.Data["PageIsWiki"] = true
  1157. repo.MustEnableWiki(ctx)
  1158. return
  1159. }
  1160. reqRepoCodeReader(ctx)
  1161. if ctx.Written() {
  1162. return
  1163. }
  1164. cancel = context.RepoRef()(ctx)
  1165. if ctx.Written() {
  1166. return
  1167. }
  1168. repo.MustBeNotEmpty(ctx)
  1169. return cancel
  1170. })
  1171. m.Group("/pulls/{index}", func() {
  1172. m.Get(".diff", repo.DownloadPullDiff)
  1173. m.Get(".patch", repo.DownloadPullPatch)
  1174. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  1175. m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest)
  1176. m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest)
  1177. m.Post("/update", repo.UpdatePullRequest)
  1178. m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits)
  1179. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  1180. m.Group("/files", func() {
  1181. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
  1182. m.Group("/reviews", func() {
  1183. m.Get("/new_comment", repo.RenderNewCodeCommentForm)
  1184. m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.CreateCodeComment)
  1185. m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview)
  1186. }, context.RepoMustNotBeArchived())
  1187. })
  1188. }, repo.MustAllowPulls)
  1189. m.Group("/media", func() {
  1190. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  1191. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  1192. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  1193. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  1194. // "/*" route is deprecated, and kept for backward compatibility
  1195. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  1196. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1197. m.Group("/raw", func() {
  1198. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  1199. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  1200. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  1201. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  1202. // "/*" route is deprecated, and kept for backward compatibility
  1203. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  1204. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1205. m.Group("/render", func() {
  1206. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RenderFile)
  1207. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RenderFile)
  1208. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RenderFile)
  1209. m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.RenderFile)
  1210. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1211. m.Group("/commits", func() {
  1212. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  1213. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  1214. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  1215. // "/*" route is deprecated, and kept for backward compatibility
  1216. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  1217. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1218. m.Group("/blame", func() {
  1219. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  1220. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  1221. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  1222. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  1223. m.Group("", func() {
  1224. m.Get("/graph", repo.Graph)
  1225. m.Get("/commit/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff)
  1226. m.Get("/cherry-pick/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.CherryPick)
  1227. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  1228. m.Group("/src", func() {
  1229. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  1230. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  1231. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  1232. // "/*" route is deprecated, and kept for backward compatibility
  1233. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  1234. }, repo.SetEditorconfigIfExists)
  1235. m.Group("", func() {
  1236. m.Get("/forks", repo.Forks)
  1237. }, context.RepoRef(), reqRepoCodeReader)
  1238. m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}",
  1239. repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  1240. }, ignSignIn, context.RepoAssignment, context.UnitTypes())
  1241. m.Post("/{username}/{reponame}/lastcommit/*", ignSignInAndCsrf, context.RepoAssignment, context.UnitTypes(), context.RepoRefByType(context.RepoRefCommit), reqRepoCodeReader, repo.LastCommit)
  1242. m.Group("/{username}/{reponame}", func() {
  1243. m.Get("/stars", repo.Stars)
  1244. m.Get("/watchers", repo.Watchers)
  1245. m.Get("/search", reqRepoCodeReader, repo.Search)
  1246. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1247. m.Group("/{username}", func() {
  1248. m.Group("/{reponame}", func() {
  1249. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  1250. }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
  1251. m.Group("/{reponame}", func() {
  1252. m.Group("/info/lfs", func() {
  1253. m.Post("/objects/batch", lfs.CheckAcceptMediaType, lfs.BatchHandler)
  1254. m.Put("/objects/{oid}/{size}", lfs.UploadHandler)
  1255. m.Get("/objects/{oid}/{filename}", lfs.DownloadHandler)
  1256. m.Get("/objects/{oid}", lfs.DownloadHandler)
  1257. m.Post("/verify", lfs.CheckAcceptMediaType, lfs.VerifyHandler)
  1258. m.Group("/locks", func() {
  1259. m.Get("/", lfs.GetListLockHandler)
  1260. m.Post("/", lfs.PostLockHandler)
  1261. m.Post("/verify", lfs.VerifyLockHandler)
  1262. m.Post("/{lid}/unlock", lfs.UnLockHandler)
  1263. }, lfs.CheckAcceptMediaType)
  1264. m.Any("/*", func(ctx *context.Context) {
  1265. ctx.NotFound("", nil)
  1266. })
  1267. }, ignSignInAndCsrf, lfsServerEnabled)
  1268. m.Group("", func() {
  1269. m.PostOptions("/git-upload-pack", repo.ServiceUploadPack)
  1270. m.PostOptions("/git-receive-pack", repo.ServiceReceivePack)
  1271. m.GetOptions("/info/refs", repo.GetInfoRefs)
  1272. m.GetOptions("/HEAD", repo.GetTextFile("HEAD"))
  1273. m.GetOptions("/objects/info/alternates", repo.GetTextFile("objects/info/alternates"))
  1274. m.GetOptions("/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates"))
  1275. m.GetOptions("/objects/info/packs", repo.GetInfoPacks)
  1276. m.GetOptions("/objects/info/{file:[^/]*}", repo.GetTextFile(""))
  1277. m.GetOptions("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject)
  1278. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile)
  1279. m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile)
  1280. }, ignSignInAndCsrf, context_service.UserAssignmentWeb())
  1281. })
  1282. })
  1283. // ***** END: Repository *****
  1284. m.Group("/notifications", func() {
  1285. m.Get("", user.Notifications)
  1286. m.Get("/subscriptions", user.NotificationSubscriptions)
  1287. m.Get("/watching", user.NotificationWatching)
  1288. m.Post("/status", user.NotificationStatusPost)
  1289. m.Post("/purge", user.NotificationPurgePost)
  1290. m.Get("/new", user.NewAvailable)
  1291. }, reqSignIn)
  1292. if setting.API.EnableSwagger {
  1293. m.Get("/swagger.v1.json", SwaggerV1Json)
  1294. }
  1295. m.NotFound(func(w http.ResponseWriter, req *http.Request) {
  1296. ctx := context.GetContext(req)
  1297. ctx.NotFound("", nil)
  1298. })
  1299. }