本站源代码
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1028 lignes
40KB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package routes
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "net/http"
  9. "os"
  10. "path"
  11. "text/template"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/auth"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/gzip"
  17. "code.gitea.io/gitea/modules/lfs"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/metrics"
  20. "code.gitea.io/gitea/modules/options"
  21. "code.gitea.io/gitea/modules/public"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/templates"
  24. "code.gitea.io/gitea/modules/validation"
  25. "code.gitea.io/gitea/routers"
  26. "code.gitea.io/gitea/routers/admin"
  27. apiv1 "code.gitea.io/gitea/routers/api/v1"
  28. "code.gitea.io/gitea/routers/dev"
  29. "code.gitea.io/gitea/routers/org"
  30. "code.gitea.io/gitea/routers/private"
  31. "code.gitea.io/gitea/routers/repo"
  32. "code.gitea.io/gitea/routers/user"
  33. userSetting "code.gitea.io/gitea/routers/user/setting"
  34. "code.gitea.io/gitea/services/mailer"
  35. // to registers all internal adapters
  36. _ "code.gitea.io/gitea/modules/session"
  37. "gitea.com/macaron/binding"
  38. "gitea.com/macaron/cache"
  39. "gitea.com/macaron/captcha"
  40. "gitea.com/macaron/cors"
  41. "gitea.com/macaron/csrf"
  42. "gitea.com/macaron/i18n"
  43. "gitea.com/macaron/macaron"
  44. "gitea.com/macaron/session"
  45. "gitea.com/macaron/toolbox"
  46. "github.com/prometheus/client_golang/prometheus"
  47. "github.com/tstranex/u2f"
  48. )
  49. type routerLoggerOptions struct {
  50. Ctx *macaron.Context
  51. Identity *string
  52. Start *time.Time
  53. ResponseWriter *macaron.ResponseWriter
  54. }
  55. func setupAccessLogger(m *macaron.Macaron) {
  56. logger := log.GetLogger("access")
  57. logTemplate, _ := template.New("log").Parse(setting.AccessLogTemplate)
  58. m.Use(func(ctx *macaron.Context) {
  59. start := time.Now()
  60. ctx.Next()
  61. identity := "-"
  62. if val, ok := ctx.Data["SignedUserName"]; ok {
  63. if stringVal, ok := val.(string); ok && stringVal != "" {
  64. identity = stringVal
  65. }
  66. }
  67. rw := ctx.Resp.(macaron.ResponseWriter)
  68. buf := bytes.NewBuffer([]byte{})
  69. err := logTemplate.Execute(buf, routerLoggerOptions{
  70. Ctx: ctx,
  71. Identity: &identity,
  72. Start: &start,
  73. ResponseWriter: &rw,
  74. })
  75. if err != nil {
  76. log.Error("Could not set up macaron access logger: %v", err.Error())
  77. }
  78. err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "")
  79. if err != nil {
  80. log.Error("Could not set up macaron access logger: %v", err.Error())
  81. }
  82. })
  83. }
  84. // RouterHandler is a macaron handler that will log the routing to the default gitea log
  85. func RouterHandler(level log.Level) func(ctx *macaron.Context) {
  86. return func(ctx *macaron.Context) {
  87. start := time.Now()
  88. _ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, ctx.RemoteAddr())
  89. rw := ctx.Resp.(macaron.ResponseWriter)
  90. ctx.Next()
  91. status := rw.Status()
  92. _ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(rw.Status())), log.ColoredTime(time.Since(start)))
  93. }
  94. }
  95. // NewMacaron initializes Macaron instance.
  96. func NewMacaron() *macaron.Macaron {
  97. gob.Register(&u2f.Challenge{})
  98. var m *macaron.Macaron
  99. if setting.RedirectMacaronLog {
  100. loggerAsWriter := log.NewLoggerAsWriter("INFO", log.GetLogger("macaron"))
  101. m = macaron.NewWithLogger(loggerAsWriter)
  102. if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
  103. if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
  104. m.Use(RouterHandler(setting.RouterLogLevel))
  105. }
  106. }
  107. } else {
  108. m = macaron.New()
  109. if !setting.DisableRouterLog {
  110. m.Use(macaron.Logger())
  111. }
  112. }
  113. // Access Logger is similar to Router Log but more configurable and by default is more like the NCSA Common Log format
  114. if setting.EnableAccessLog {
  115. setupAccessLogger(m)
  116. }
  117. m.Use(macaron.Recovery())
  118. if setting.EnableGzip {
  119. m.Use(gzip.Middleware())
  120. }
  121. if setting.Protocol == setting.FCGI {
  122. m.SetURLPrefix(setting.AppSubURL)
  123. }
  124. m.Use(public.Custom(
  125. &public.Options{
  126. SkipLogging: setting.DisableRouterLog,
  127. ExpiresAfter: setting.StaticCacheTime,
  128. },
  129. ))
  130. m.Use(public.Static(
  131. &public.Options{
  132. Directory: path.Join(setting.StaticRootPath, "public"),
  133. SkipLogging: setting.DisableRouterLog,
  134. ExpiresAfter: setting.StaticCacheTime,
  135. },
  136. ))
  137. m.Use(public.StaticHandler(
  138. setting.AvatarUploadPath,
  139. &public.Options{
  140. Prefix: "avatars",
  141. SkipLogging: setting.DisableRouterLog,
  142. ExpiresAfter: setting.StaticCacheTime,
  143. },
  144. ))
  145. m.Use(public.StaticHandler(
  146. setting.RepositoryAvatarUploadPath,
  147. &public.Options{
  148. Prefix: "repo-avatars",
  149. SkipLogging: setting.DisableRouterLog,
  150. ExpiresAfter: setting.StaticCacheTime,
  151. },
  152. ))
  153. m.Use(templates.HTMLRenderer())
  154. mailer.InitMailRender(templates.Mailer())
  155. localeNames, err := options.Dir("locale")
  156. if err != nil {
  157. log.Fatal("Failed to list locale files: %v", err)
  158. }
  159. localFiles := make(map[string][]byte)
  160. for _, name := range localeNames {
  161. localFiles[name], err = options.Locale(name)
  162. if err != nil {
  163. log.Fatal("Failed to load %s locale file. %v", name, err)
  164. }
  165. }
  166. m.Use(i18n.I18n(i18n.Options{
  167. SubURL: setting.AppSubURL,
  168. Files: localFiles,
  169. Langs: setting.Langs,
  170. Names: setting.Names,
  171. DefaultLang: "en-US",
  172. Redirect: false,
  173. CookieDomain: setting.SessionConfig.Domain,
  174. }))
  175. m.Use(cache.Cacher(cache.Options{
  176. Adapter: setting.CacheService.Adapter,
  177. AdapterConfig: setting.CacheService.Conn,
  178. Interval: setting.CacheService.Interval,
  179. }))
  180. m.Use(captcha.Captchaer(captcha.Options{
  181. SubURL: setting.AppSubURL,
  182. }))
  183. m.Use(session.Sessioner(setting.SessionConfig))
  184. m.Use(csrf.Csrfer(csrf.Options{
  185. Secret: setting.SecretKey,
  186. Cookie: setting.CSRFCookieName,
  187. SetCookie: true,
  188. Secure: setting.SessionConfig.Secure,
  189. CookieHttpOnly: setting.CSRFCookieHTTPOnly,
  190. Header: "X-Csrf-Token",
  191. CookieDomain: setting.SessionConfig.Domain,
  192. CookiePath: setting.AppSubURL,
  193. }))
  194. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  195. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  196. {
  197. Desc: "Database connection",
  198. Func: models.Ping,
  199. },
  200. },
  201. DisableDebug: !setting.EnablePprof,
  202. }))
  203. m.Use(context.Contexter())
  204. // OK we are now set-up enough to allow us to create a nicer recovery than
  205. // the default macaron recovery
  206. m.Use(context.Recovery())
  207. m.SetAutoHead(true)
  208. return m
  209. }
  210. // RegisterRoutes routes routes to Macaron
  211. func RegisterRoutes(m *macaron.Macaron) {
  212. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  213. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  214. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  215. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  216. bindIgnErr := binding.BindIgnErr
  217. validation.AddBindingRules()
  218. openIDSignInEnabled := func(ctx *context.Context) {
  219. if !setting.Service.EnableOpenIDSignIn {
  220. ctx.Error(403)
  221. return
  222. }
  223. }
  224. openIDSignUpEnabled := func(ctx *context.Context) {
  225. if !setting.Service.EnableOpenIDSignUp {
  226. ctx.Error(403)
  227. return
  228. }
  229. }
  230. m.Use(user.GetNotificationCount)
  231. // FIXME: not all routes need go through same middlewares.
  232. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  233. // Routers.
  234. // for health check
  235. m.Head("/", func() string {
  236. return ""
  237. })
  238. m.Get("/", routers.Home)
  239. m.Group("/explore", func() {
  240. m.Get("", func(ctx *context.Context) {
  241. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  242. })
  243. m.Get("/trans",bindIgnErr(auth.SearchRecords{}), routers.ExploreTrans)
  244. m.Get("/repos", routers.ExploreRepos)
  245. m.Get("/users", routers.ExploreUsers)
  246. m.Get("/organizations", routers.ExploreOrganizations)
  247. m.Get("/code", routers.ExploreCode)
  248. }, ignSignIn)
  249. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  250. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  251. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  252. // ***** START: User *****
  253. m.Group("/user", func() {
  254. m.Get("/login", user.SignIn)
  255. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  256. m.Group("", func() {
  257. m.Combo("/login/openid").
  258. Get(user.SignInOpenID).
  259. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  260. }, openIDSignInEnabled)
  261. m.Group("/openid", func() {
  262. m.Combo("/connect").
  263. Get(user.ConnectOpenID).
  264. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  265. m.Group("/register", func() {
  266. m.Combo("").
  267. Get(user.RegisterOpenID, openIDSignUpEnabled).
  268. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  269. }, openIDSignUpEnabled)
  270. }, openIDSignInEnabled)
  271. m.Get("/sign_up", user.SignUp)
  272. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  273. m.Group("/oauth2", func() {
  274. m.Get("/:provider", user.SignInOAuth)
  275. m.Get("/:provider/callback", user.SignInOAuthCallback)
  276. })
  277. m.Get("/link_account", user.LinkAccount)
  278. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  279. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  280. m.Group("/two_factor", func() {
  281. m.Get("", user.TwoFactor)
  282. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  283. m.Get("/scratch", user.TwoFactorScratch)
  284. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  285. })
  286. m.Group("/u2f", func() {
  287. m.Get("", user.U2F)
  288. m.Get("/challenge", user.U2FChallenge)
  289. m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign)
  290. })
  291. }, reqSignOut)
  292. m.Group("/login/oauth", func() {
  293. m.Get("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  294. m.Post("/grant", bindIgnErr(auth.GrantApplicationForm{}), user.GrantApplicationOAuth)
  295. // TODO manage redirection
  296. m.Post("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  297. }, ignSignInAndCsrf, reqSignIn)
  298. m.Post("/login/oauth/access_token", bindIgnErr(auth.AccessTokenForm{}), ignSignInAndCsrf, user.AccessTokenOAuth)
  299. m.Group("/user/settings", func() {
  300. m.Get("", userSetting.Profile)
  301. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
  302. m.Get("/change_password", user.MustChangePassword)
  303. m.Post("/change_password", bindIgnErr(auth.MustChangePasswordForm{}), user.MustChangePasswordPost)
  304. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), userSetting.AvatarPost)
  305. m.Post("/avatar/delete", userSetting.DeleteAvatar)
  306. m.Group("/account", func() {
  307. m.Combo("").Get(userSetting.Account).Post(bindIgnErr(auth.ChangePasswordForm{}), userSetting.AccountPost)
  308. m.Post("/email", bindIgnErr(auth.AddEmailForm{}), userSetting.EmailPost)
  309. m.Post("/email/delete", userSetting.DeleteEmail)
  310. m.Post("/delete", userSetting.DeleteAccount)
  311. m.Post("/theme", bindIgnErr(auth.UpdateThemeForm{}), userSetting.UpdateUIThemePost)
  312. })
  313. m.Group("/security", func() {
  314. m.Get("", userSetting.Security)
  315. m.Group("/two_factor", func() {
  316. m.Post("/regenerate_scratch", userSetting.RegenerateScratchTwoFactor)
  317. m.Post("/disable", userSetting.DisableTwoFactor)
  318. m.Get("/enroll", userSetting.EnrollTwoFactor)
  319. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), userSetting.EnrollTwoFactorPost)
  320. })
  321. m.Group("/u2f", func() {
  322. m.Post("/request_register", bindIgnErr(auth.U2FRegistrationForm{}), userSetting.U2FRegister)
  323. m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), userSetting.U2FRegisterPost)
  324. m.Post("/delete", bindIgnErr(auth.U2FDeleteForm{}), userSetting.U2FDelete)
  325. })
  326. m.Group("/openid", func() {
  327. m.Post("", bindIgnErr(auth.AddOpenIDForm{}), userSetting.OpenIDPost)
  328. m.Post("/delete", userSetting.DeleteOpenID)
  329. m.Post("/toggle_visibility", userSetting.ToggleOpenIDVisibility)
  330. }, openIDSignInEnabled)
  331. m.Post("/account_link", userSetting.DeleteAccountLink)
  332. })
  333. m.Group("/applications/oauth2", func() {
  334. m.Get("/:id", userSetting.OAuth2ApplicationShow)
  335. m.Post("/:id", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
  336. m.Post("/:id/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
  337. m.Post("", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost)
  338. m.Post("/delete", userSetting.DeleteOAuth2Application)
  339. m.Post("/revoke", userSetting.RevokeOAuth2Grant)
  340. })
  341. m.Combo("/applications").Get(userSetting.Applications).
  342. Post(bindIgnErr(auth.NewAccessTokenForm{}), userSetting.ApplicationsPost)
  343. m.Post("/applications/delete", userSetting.DeleteApplication)
  344. m.Combo("/keys").Get(userSetting.Keys).
  345. Post(bindIgnErr(auth.AddKeyForm{}), userSetting.KeysPost)
  346. m.Post("/keys/delete", userSetting.DeleteKey)
  347. m.Get("/organization", userSetting.Organization)
  348. m.Get("/repos", userSetting.Repos)
  349. // redirects from old settings urls to new ones
  350. // TODO: can be removed on next major version
  351. m.Get("/avatar", func(ctx *context.Context) {
  352. ctx.Redirect(setting.AppSubURL+"/user/settings", http.StatusMovedPermanently)
  353. })
  354. m.Get("/email", func(ctx *context.Context) {
  355. ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
  356. })
  357. m.Get("/delete", func(ctx *context.Context) {
  358. ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
  359. })
  360. m.Get("/openid", func(ctx *context.Context) {
  361. ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
  362. })
  363. m.Get("/account_link", func(ctx *context.Context) {
  364. ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
  365. })
  366. }, reqSignIn, func(ctx *context.Context) {
  367. ctx.Data["PageIsUserSettings"] = true
  368. ctx.Data["AllThemes"] = setting.UI.Themes
  369. })
  370. m.Group("/user", func() {
  371. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  372. m.Any("/activate", user.Activate, reqSignIn)
  373. m.Any("/activate_email", user.ActivateEmail)
  374. m.Get("/avatar/:username/:size", user.Avatar)
  375. m.Get("/email2user", user.Email2User)
  376. m.Get("/recover_account", user.ResetPasswd)
  377. m.Post("/recover_account", user.ResetPasswdPost)
  378. m.Get("/forgot_password", user.ForgotPasswd)
  379. m.Post("/forgot_password", user.ForgotPasswdPost)
  380. m.Get("/logout", user.SignOut)
  381. })
  382. // ***** END: User *****
  383. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  384. // ***** START: Admin *****
  385. m.Group("/admin", func() {
  386. m.Get("", adminReq, admin.Dashboard)
  387. m.Get("/config", admin.Config)
  388. m.Post("/config/test_mail", admin.SendTestMail)
  389. m.Get("/monitor", admin.Monitor)
  390. m.Group("/users", func() {
  391. m.Get("", admin.Users)
  392. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  393. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  394. m.Post("/:userid/delete", admin.DeleteUser)
  395. })
  396. m.Group("/orgs", func() {
  397. m.Get("", admin.Organizations)
  398. })
  399. m.Group("/repos", func() {
  400. m.Get("", admin.Repos)
  401. m.Post("/delete", admin.DeleteRepo)
  402. })
  403. m.Group("/hooks", func() {
  404. m.Get("", admin.DefaultWebhooks)
  405. m.Post("/delete", admin.DeleteDefaultWebhook)
  406. m.Get("/:type/new", repo.WebhooksNew)
  407. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  408. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  409. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  410. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  411. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  412. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  413. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  414. m.Get("/:id", repo.WebHooksEdit)
  415. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  416. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  417. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  418. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  419. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  420. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  421. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  422. })
  423. m.Group("/auths", func() {
  424. m.Get("", admin.Authentications)
  425. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  426. m.Combo("/:authid").Get(admin.EditAuthSource).
  427. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  428. m.Post("/:authid/delete", admin.DeleteAuthSource)
  429. })
  430. m.Group("/notices", func() {
  431. m.Get("", admin.Notices)
  432. m.Post("/delete", admin.DeleteNotices)
  433. m.Get("/empty", admin.EmptyNotices)
  434. })
  435. }, adminReq)
  436. // ***** END: Admin *****
  437. m.Group("", func() {
  438. m.Group("/:username", func() {
  439. m.Get("", user.Profile)
  440. m.Get("/followers", user.Followers)
  441. m.Get("/following", user.Following)
  442. })
  443. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  444. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  445. if err != nil {
  446. if models.IsErrAttachmentNotExist(err) {
  447. ctx.Error(404)
  448. } else {
  449. ctx.ServerError("GetAttachmentByUUID", err)
  450. }
  451. return
  452. }
  453. fr, err := os.Open(attach.LocalPath())
  454. if err != nil {
  455. ctx.ServerError("Open", err)
  456. return
  457. }
  458. defer fr.Close()
  459. if err := attach.IncreaseDownloadCount(); err != nil {
  460. ctx.ServerError("Update", err)
  461. return
  462. }
  463. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  464. ctx.ServerError("ServeData", err)
  465. return
  466. }
  467. })
  468. }, ignSignIn)
  469. m.Group("/attachments", func() {
  470. m.Post("", repo.UploadAttachment)
  471. m.Post("/delete", repo.DeleteAttachment)
  472. }, reqSignIn)
  473. m.Group("/:username", func() {
  474. m.Get("/action/:action", user.Action)
  475. m.Post("/action/transfer_point", user.TransferP)
  476. }, reqSignIn)
  477. if macaron.Env == macaron.DEV {
  478. m.Get("/template/*", dev.TemplatePreview)
  479. }
  480. reqRepoAdmin := context.RequireRepoAdmin()
  481. reqRepoCodeWriter := context.RequireRepoWriter(models.UnitTypeCode)
  482. reqRepoCodeReader := context.RequireRepoReader(models.UnitTypeCode)
  483. reqRepoReleaseWriter := context.RequireRepoWriter(models.UnitTypeReleases)
  484. reqRepoReleaseReader := context.RequireRepoReader(models.UnitTypeReleases)
  485. reqRepoWikiWriter := context.RequireRepoWriter(models.UnitTypeWiki)
  486. reqRepoIssueReader := context.RequireRepoReader(models.UnitTypeIssues)
  487. reqRepoPullsWriter := context.RequireRepoWriter(models.UnitTypePullRequests)
  488. reqRepoPullsReader := context.RequireRepoReader(models.UnitTypePullRequests)
  489. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  490. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  491. reqRepoIssueWriter := func(ctx *context.Context) {
  492. if !ctx.Repo.CanWrite(models.UnitTypeIssues) {
  493. ctx.Error(403)
  494. return
  495. }
  496. }
  497. // ***** START: Organization *****
  498. m.Group("/org", func() {
  499. m.Group("", func() {
  500. m.Get("/create", org.Create)
  501. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  502. })
  503. m.Group("/:org", func() {
  504. m.Get("/dashboard", user.Dashboard)
  505. m.Get("/^:type(issues|pulls)$", user.Issues)
  506. m.Get("/members", org.Members)
  507. m.Get("/members/action/:action", org.MembersAction)
  508. m.Get("/teams", org.Teams)
  509. }, context.OrgAssignment(true))
  510. m.Group("/:org", func() {
  511. m.Get("/teams/:team", org.TeamMembers)
  512. m.Get("/teams/:team/repositories", org.TeamRepositories)
  513. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  514. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  515. }, context.OrgAssignment(true, false, true))
  516. m.Group("/:org", func() {
  517. m.Get("/teams/new", org.NewTeam)
  518. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  519. m.Get("/teams/:team/edit", org.EditTeam)
  520. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  521. m.Post("/teams/:team/delete", org.DeleteTeam)
  522. m.Group("/settings", func() {
  523. m.Combo("").Get(org.Settings).
  524. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  525. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  526. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  527. m.Group("/hooks", func() {
  528. m.Get("", org.Webhooks)
  529. m.Post("/delete", org.DeleteWebhook)
  530. m.Get("/:type/new", repo.WebhooksNew)
  531. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  532. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  533. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  534. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  535. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  536. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  537. m.Get("/:id", repo.WebHooksEdit)
  538. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  539. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  540. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  541. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  542. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  543. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  544. })
  545. m.Route("/delete", "GET,POST", org.SettingsDelete)
  546. })
  547. }, context.OrgAssignment(true, true))
  548. }, reqSignIn)
  549. // ***** END: Organization *****
  550. // ***** START: Repository *****
  551. m.Group("/repo", func() {
  552. m.Get("/create", repo.Create)
  553. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  554. m.Get("/migrate", repo.Migrate)
  555. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  556. m.Group("/fork", func() {
  557. m.Combo("/:repoid").Get(repo.Fork).
  558. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  559. }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
  560. }, reqSignIn)
  561. // ***** Release Attachment Download without Signin
  562. m.Get("/:username/:reponame/releases/download/:vTag/:fileName", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
  563. m.Group("/:username/:reponame", func() {
  564. m.Group("/settings", func() {
  565. m.Combo("").Get(repo.Settings).
  566. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  567. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), repo.SettingsAvatar)
  568. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  569. m.Group("/collaboration", func() {
  570. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  571. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  572. m.Post("/delete", repo.DeleteCollaboration)
  573. m.Group("/team", func() {
  574. m.Post("", repo.AddTeamPost)
  575. m.Post("/delete", repo.DeleteTeam)
  576. })
  577. })
  578. m.Group("/branches", func() {
  579. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  580. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  581. Post(bindIgnErr(auth.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
  582. }, repo.MustBeNotEmpty)
  583. m.Group("/hooks", func() {
  584. m.Get("", repo.Webhooks)
  585. m.Post("/delete", repo.DeleteWebhook)
  586. m.Get("/:type/new", repo.WebhooksNew)
  587. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  588. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  589. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  590. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  591. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  592. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  593. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  594. m.Get("/:id", repo.WebHooksEdit)
  595. m.Post("/:id/test", repo.TestWebhook)
  596. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  597. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  598. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  599. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  600. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  601. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  602. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  603. m.Group("/git", func() {
  604. m.Get("", repo.GitHooks)
  605. m.Combo("/:name").Get(repo.GitHooksEdit).
  606. Post(repo.GitHooksEditPost)
  607. }, context.GitHookService())
  608. })
  609. m.Group("/keys", func() {
  610. m.Combo("").Get(repo.DeployKeys).
  611. Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
  612. m.Post("/delete", repo.DeleteDeployKey)
  613. })
  614. m.Group("/lfs", func() {
  615. m.Get("", repo.LFSFiles)
  616. m.Get("/show/:oid", repo.LFSFileGet)
  617. m.Post("/delete/:oid", repo.LFSDelete)
  618. m.Get("/pointers", repo.LFSPointerFiles)
  619. m.Post("/pointers/associate", repo.LFSAutoAssociate)
  620. m.Get("/find", repo.LFSFileFind)
  621. })
  622. }, func(ctx *context.Context) {
  623. ctx.Data["PageIsSettings"] = true
  624. ctx.Data["LFSStartServer"] = setting.LFS.StartServer
  625. })
  626. }, reqSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  627. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action)
  628. m.Group("/:username/:reponame", func() {
  629. m.Group("/issues", func() {
  630. m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
  631. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  632. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  633. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  634. // So they can apply their own enable/disable logic on routers.
  635. m.Group("/issues", func() {
  636. m.Group("/:index", func() {
  637. m.Post("/title", repo.UpdateIssueTitle)
  638. m.Post("/content", repo.UpdateIssueContent)
  639. m.Post("/watch", repo.IssueWatch)
  640. m.Group("/dependency", func() {
  641. m.Post("/add", repo.AddDependency)
  642. m.Post("/delete", repo.RemoveDependency)
  643. })
  644. m.Combo("/comments").Post(repo.MustAllowUserComment, bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  645. m.Group("/times", func() {
  646. m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
  647. m.Group("/stopwatch", func() {
  648. m.Post("/toggle", repo.IssueStopwatch)
  649. m.Post("/cancel", repo.CancelStopwatch)
  650. })
  651. })
  652. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
  653. m.Post("/lock", reqRepoIssueWriter, bindIgnErr(auth.IssueLockForm{}), repo.LockIssue)
  654. m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue)
  655. m.Get("/attachments", repo.GetIssueAttachments)
  656. }, context.RepoMustNotBeArchived())
  657. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  658. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  659. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  660. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  661. }, context.RepoMustNotBeArchived())
  662. m.Group("/comments/:id", func() {
  663. m.Post("", repo.UpdateCommentContent)
  664. m.Post("/delete", repo.DeleteComment)
  665. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
  666. m.Get("/attachments", repo.GetCommentAttachments)
  667. }, context.RepoMustNotBeArchived())
  668. m.Group("/labels", func() {
  669. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  670. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  671. m.Post("/delete", repo.DeleteLabel)
  672. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  673. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  674. m.Group("/milestones", func() {
  675. m.Combo("/new").Get(repo.NewMilestone).
  676. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  677. m.Get("/:id/edit", repo.EditMilestone)
  678. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  679. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  680. m.Post("/delete", repo.DeleteMilestone)
  681. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  682. m.Group("/milestone", func() {
  683. m.Get("/:id", repo.MilestoneIssuesAndPulls)
  684. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  685. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  686. Get(repo.SetDiffViewStyle, repo.CompareDiff).
  687. Post(context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  688. m.Group("", func() {
  689. m.Group("", func() {
  690. m.Combo("/_edit/*").Get(repo.EditFile).
  691. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  692. m.Combo("/_new/*").Get(repo.NewFile).
  693. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  694. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  695. m.Combo("/_delete/*").Get(repo.DeleteFile).
  696. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  697. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  698. Get(repo.UploadFile).
  699. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  700. }, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
  701. m.Group("", func() {
  702. m.Post("/upload-file", repo.UploadFileToServer)
  703. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  704. }, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
  705. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  706. m.Group("/branches", func() {
  707. m.Group("/_new/", func() {
  708. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  709. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  710. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  711. }, bindIgnErr(auth.NewBranchForm{}))
  712. m.Post("/delete", repo.DeleteBranchPost)
  713. m.Post("/restore", repo.RestoreBranchPost)
  714. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  715. }, reqSignIn, context.RepoAssignment(), context.UnitTypes())
  716. // Releases
  717. m.Group("/:username/:reponame", func() {
  718. m.Group("/releases", func() {
  719. m.Get("/", repo.MustBeNotEmpty, repo.Releases)
  720. }, repo.MustBeNotEmpty, context.RepoRef())
  721. m.Group("/releases", func() {
  722. m.Get("/new", repo.NewRelease)
  723. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  724. m.Post("/delete", repo.DeleteRelease)
  725. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  726. m.Group("/releases", func() {
  727. m.Get("/edit/*", repo.EditRelease)
  728. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  729. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
  730. var err error
  731. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  732. if err != nil {
  733. ctx.ServerError("GetBranchCommit", err)
  734. return
  735. }
  736. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  737. if err != nil {
  738. ctx.ServerError("GetCommitsCount", err)
  739. return
  740. }
  741. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  742. })
  743. }, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader)
  744. m.Group("/:username/:reponame", func() {
  745. m.Post("/topics", repo.TopicsPost)
  746. }, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin)
  747. m.Group("/:username/:reponame", func() {
  748. m.Group("", func() {
  749. m.Get("/^:type(issues|pulls)$", repo.Issues)
  750. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  751. m.Get("/labels/", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  752. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  753. }, context.RepoRef())
  754. m.Group("/wiki", func() {
  755. m.Get("/?:page", repo.Wiki)
  756. m.Get("/_pages", repo.WikiPages)
  757. m.Get("/:page/_revision", repo.WikiRevision)
  758. m.Group("", func() {
  759. m.Combo("/_new").Get(repo.NewWiki).
  760. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  761. m.Combo("/:page/_edit").Get(repo.EditWiki).
  762. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  763. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  764. }, context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter)
  765. }, repo.MustEnableWiki, context.RepoRef())
  766. m.Group("/wiki", func() {
  767. m.Get("/raw/*", repo.WikiRaw)
  768. }, repo.MustEnableWiki)
  769. m.Group("/funds", func(){
  770. m.Get("", repo.Funds)
  771. m.Post("/action/funding",repo.Funding)
  772. },context.RepoRef())
  773. m.Group("/activity", func() {
  774. m.Get("", repo.Activity)
  775. m.Get("/:period", repo.Activity)
  776. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
  777. m.Group("/activity_author_data", func() {
  778. m.Get("", repo.ActivityAuthors)
  779. m.Get("/:period", repo.ActivityAuthors)
  780. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypeCode))
  781. m.Get("/archive/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.Download)
  782. m.Get("/status", reqRepoCodeReader, repo.Status)
  783. m.Group("/branches", func() {
  784. m.Get("", repo.Branches)
  785. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  786. m.Group("/pulls/:index", func() {
  787. m.Get(".diff", repo.DownloadPullDiff)
  788. m.Get(".patch", repo.DownloadPullPatch)
  789. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  790. m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
  791. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  792. m.Group("/files", func() {
  793. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
  794. m.Group("/reviews", func() {
  795. m.Post("/comments", bindIgnErr(auth.CodeCommentForm{}), repo.CreateCodeComment)
  796. m.Post("/submit", bindIgnErr(auth.SubmitReviewForm{}), repo.SubmitReview)
  797. }, context.RepoMustNotBeArchived())
  798. })
  799. }, repo.MustAllowPulls)
  800. m.Group("/media", func() {
  801. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  802. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  803. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  804. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  805. // "/*" route is deprecated, and kept for backward compatibility
  806. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  807. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  808. m.Group("/raw", func() {
  809. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  810. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  811. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  812. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  813. // "/*" route is deprecated, and kept for backward compatibility
  814. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  815. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  816. m.Group("/commits", func() {
  817. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  818. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  819. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  820. // "/*" route is deprecated, and kept for backward compatibility
  821. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  822. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  823. m.Group("/blame", func() {
  824. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  825. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  826. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  827. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  828. m.Group("", func() {
  829. m.Get("/graph", repo.Graph)
  830. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  831. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  832. m.Group("/src", func() {
  833. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  834. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  835. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  836. // "/*" route is deprecated, and kept for backward compatibility
  837. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  838. }, repo.SetEditorconfigIfExists)
  839. m.Group("", func() {
  840. m.Get("/forks", repo.Forks)
  841. }, context.RepoRef(), reqRepoCodeReader)
  842. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
  843. repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  844. }, ignSignIn, context.RepoAssignment(), context.UnitTypes())
  845. m.Group("/:username/:reponame", func() {
  846. m.Get("/stars", repo.Stars)
  847. m.Get("/watchers", repo.Watchers)
  848. m.Get("/search", reqRepoCodeReader, repo.Search)
  849. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  850. m.Group("/:username", func() {
  851. m.Group("/:reponame", func() {
  852. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  853. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  854. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  855. m.Group("/:reponame", func() {
  856. m.Group("\\.git/info/lfs", func() {
  857. m.Post("/objects/batch", lfs.BatchHandler)
  858. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  859. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  860. m.Post("/objects", lfs.PostHandler)
  861. m.Post("/verify", lfs.VerifyHandler)
  862. m.Group("/locks", func() {
  863. m.Get("/", lfs.GetListLockHandler)
  864. m.Post("/", lfs.PostLockHandler)
  865. m.Post("/verify", lfs.VerifyLockHandler)
  866. m.Post("/:lid/unlock", lfs.UnLockHandler)
  867. })
  868. m.Any("/*", func(ctx *context.Context) {
  869. ctx.NotFound("", nil)
  870. })
  871. }, ignSignInAndCsrf)
  872. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  873. m.Head("/tasks/trigger", repo.TriggerTask)
  874. })
  875. })
  876. // ***** END: Repository *****
  877. m.Group("/notifications", func() {
  878. m.Get("", user.Notifications)
  879. m.Post("/status", user.NotificationStatusPost)
  880. m.Post("/purge", user.NotificationPurgePost)
  881. }, reqSignIn)
  882. if setting.API.EnableSwagger {
  883. m.Get("/swagger.v1.json", templates.JSONRenderer(), routers.SwaggerV1Json)
  884. }
  885. var handlers []macaron.Handler
  886. if setting.EnableCORS {
  887. handlers = append(handlers, cors.CORS(setting.CORSConfig))
  888. }
  889. handlers = append(handlers, ignSignIn)
  890. m.Group("/api", func() {
  891. apiv1.RegisterRoutes(m)
  892. }, handlers...)
  893. m.Group("/api/internal", func() {
  894. // package name internal is ideal but Golang is not allowed, so we use private as package name.
  895. private.RegisterRoutes(m)
  896. })
  897. // robots.txt
  898. m.Get("/robots.txt", func(ctx *context.Context) {
  899. if setting.HasRobotsTxt {
  900. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  901. } else {
  902. ctx.NotFound("", nil)
  903. }
  904. })
  905. // Progressive Web App
  906. m.Get("/manifest.json", templates.JSONRenderer(), func(ctx *context.Context) {
  907. ctx.HTML(200, "pwa/manifest_json")
  908. })
  909. m.Get("/serviceworker.js", templates.JSRenderer(), func(ctx *context.Context) {
  910. ctx.HTML(200, "pwa/serviceworker_js")
  911. })
  912. // prometheus metrics endpoint
  913. if setting.Metrics.Enabled {
  914. c := metrics.NewCollector()
  915. prometheus.MustRegister(c)
  916. m.Get("/metrics", routers.Metrics)
  917. }
  918. // Not found handler.
  919. m.NotFound(routers.NotFound)
  920. }
上海开阖软件有限公司 沪ICP备12045867号-1