web.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package cmd
  7. import (
  8. "crypto/tls"
  9. "fmt"
  10. "gitote/gitote/models"
  11. "gitote/gitote/pkg/bindata"
  12. "gitote/gitote/pkg/context"
  13. "gitote/gitote/pkg/form"
  14. "gitote/gitote/pkg/mailer"
  15. "gitote/gitote/pkg/setting"
  16. "gitote/gitote/pkg/template"
  17. "gitote/gitote/routes"
  18. "gitote/gitote/routes/admin"
  19. apiv1 "gitote/gitote/routes/api/v1"
  20. "gitote/gitote/routes/dev"
  21. "gitote/gitote/routes/org"
  22. "gitote/gitote/routes/pages"
  23. "gitote/gitote/routes/repo"
  24. "gitote/gitote/routes/user"
  25. "net"
  26. "net/http"
  27. "net/http/fcgi"
  28. "os"
  29. "path"
  30. "strings"
  31. "gitlab.com/gitote/com"
  32. raven "github.com/getsentry/raven-go"
  33. "github.com/go-macaron/binding"
  34. "github.com/go-macaron/cache"
  35. "github.com/go-macaron/captcha"
  36. "github.com/go-macaron/csrf"
  37. "github.com/go-macaron/gzip"
  38. "github.com/go-macaron/i18n"
  39. "github.com/go-macaron/session"
  40. "github.com/go-macaron/toolbox"
  41. "github.com/prometheus/client_golang/prometheus/promhttp"
  42. "github.com/urfave/cli"
  43. log "gopkg.in/clog.v1"
  44. "gopkg.in/macaron.v1"
  45. )
  46. // Web Initialize web CLI
  47. var Web = cli.Command{
  48. Name: "web",
  49. Usage: "Start web server",
  50. Description: `Gitote web server is the only thing you need to run,
  51. and it takes care of all the other things for you`,
  52. Action: runWeb,
  53. Flags: []cli.Flag{
  54. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  55. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  56. },
  57. }
  58. // newMacaron initializes Macaron instance.
  59. func newMacaron() *macaron.Macaron {
  60. m := macaron.New()
  61. if !setting.DisableRouterLog {
  62. m.Use(macaron.Logger())
  63. }
  64. m.Use(macaron.Recovery())
  65. if setting.EnableGzip {
  66. m.Use(gzip.Gziper())
  67. }
  68. if setting.Protocol == setting.SchemeFCGI {
  69. m.SetURLPrefix(setting.AppSubURL)
  70. }
  71. m.Use(macaron.Static(
  72. path.Join(setting.StaticRootPath, "public"),
  73. macaron.StaticOptions{
  74. SkipLogging: setting.DisableRouterLog,
  75. },
  76. ))
  77. m.Use(macaron.Static(
  78. setting.AvatarUploadPath,
  79. macaron.StaticOptions{
  80. Prefix: models.UserAvatarURLPrefix,
  81. SkipLogging: setting.DisableRouterLog,
  82. },
  83. ))
  84. m.Use(macaron.Static(
  85. setting.RepositoryAvatarUploadPath,
  86. macaron.StaticOptions{
  87. Prefix: models.RepoAvatarURLPrefix,
  88. SkipLogging: setting.DisableRouterLog,
  89. },
  90. ))
  91. funcMap := template.NewFuncMap()
  92. m.Use(macaron.Renderer(macaron.RenderOptions{
  93. Directory: path.Join(setting.StaticRootPath, "templates"),
  94. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  95. Funcs: funcMap,
  96. IndentJSON: macaron.Env != macaron.PROD,
  97. }))
  98. mailer.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  99. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  100. localeNames, err := bindata.AssetDir("conf/locale")
  101. if err != nil {
  102. raven.CaptureErrorAndWait(err, nil)
  103. log.Fatal(4, "Fail to list locale files: %v", err)
  104. }
  105. localFiles := make(map[string][]byte)
  106. for _, name := range localeNames {
  107. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  108. }
  109. m.Use(i18n.I18n(i18n.Options{
  110. SubURL: setting.AppSubURL,
  111. Files: localFiles,
  112. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  113. Langs: []string{"en-US", "en-GB"},
  114. Names: []string{"English US", "English UK"},
  115. DefaultLang: "en-US",
  116. Redirect: true,
  117. }))
  118. m.Use(cache.Cacher(cache.Options{
  119. Adapter: setting.CacheAdapter,
  120. AdapterConfig: setting.CacheConn,
  121. Interval: setting.CacheInterval,
  122. }))
  123. m.Use(captcha.Captchaer(captcha.Options{
  124. SubURL: setting.AppSubURL,
  125. }))
  126. m.Use(session.Sessioner(setting.SessionConfig))
  127. m.Use(csrf.Csrfer(csrf.Options{
  128. Secret: setting.SecretKey,
  129. Cookie: setting.CSRFCookieName,
  130. SetCookie: true,
  131. Header: "X-Csrf-Token",
  132. CookiePath: setting.AppSubURL,
  133. }))
  134. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  135. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  136. &toolbox.HealthCheckFuncDesc{
  137. Desc: "Database connection",
  138. Func: models.Ping,
  139. },
  140. },
  141. }))
  142. m.Use(context.Contexter())
  143. return m
  144. }
  145. func runWeb(c *cli.Context) error {
  146. if c.IsSet("config") {
  147. setting.CustomConf = c.String("config")
  148. }
  149. routes.GlobalInit()
  150. m := newMacaron()
  151. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  152. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  153. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  154. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  155. bindIgnErr := binding.BindIgnErr
  156. m.SetAutoHead(true)
  157. // FIXME: not all routes need go through same middlewares.
  158. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  159. // Routers.
  160. m.Get("/", ignSignIn, routes.Home)
  161. m.Get("/trending", routes.ExploreTrending)
  162. m.Group("/explore", func() {
  163. m.Get("/", routes.Explore)
  164. m.Get("/repos", routes.ExploreRepos)
  165. m.Get("/users", routes.ExploreUsers)
  166. m.Get("/organizations", routes.ExploreOrganizations)
  167. }, ignSignIn)
  168. m.Combo("/install", routes.InstallInit).Get(routes.Install).
  169. Post(bindIgnErr(form.Install{}), routes.InstallPost)
  170. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  171. // ***** START: Auth *****
  172. m.Group("", func() {
  173. m.Group("/login", func() {
  174. m.Combo("").Get(user.Login).
  175. Post(bindIgnErr(form.SignIn{}), user.LoginPost)
  176. m.Combo("/two_factor").Get(user.LoginTwoFactor).Post(user.LoginTwoFactorPost)
  177. m.Combo("/two_factor_recovery_code").Get(user.LoginTwoFactorRecoveryCode).Post(user.LoginTwoFactorRecoveryCodePost)
  178. })
  179. m.Get("/join", user.SignUp)
  180. m.Post("/join", bindIgnErr(form.Register{}), user.SignUpPost)
  181. m.Get("/reset_password", user.ResetPasswd)
  182. m.Post("/reset_password", user.ResetPasswdPost)
  183. }, reqSignOut)
  184. // ***** END: Auth *****
  185. // ***** START: User *****
  186. m.Group("/user/settings", func() {
  187. m.Get("", user.Settings)
  188. m.Post("", bindIgnErr(form.UpdateProfile{}), user.SettingsPost)
  189. m.Get("/social", user.SettingsSocial)
  190. m.Post("/social", bindIgnErr(form.UpdateSocial{}), user.SettingsSocialPost)
  191. m.Combo("/avatar").Get(user.SettingsAvatar).
  192. Post(binding.MultipartForm(form.Avatar{}), user.SettingsAvatarPost)
  193. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  194. m.Combo("/email").Get(user.SettingsEmails).
  195. Post(bindIgnErr(form.AddEmail{}), user.SettingsEmailPost)
  196. m.Post("/email/delete", user.DeleteEmail)
  197. m.Get("/password", user.SettingsPassword)
  198. m.Post("/password", bindIgnErr(form.ChangePassword{}), user.SettingsPasswordPost)
  199. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  200. Post(bindIgnErr(form.AddSSHKey{}), user.SettingsSSHKeysPost)
  201. m.Post("/ssh/delete", user.DeleteSSHKey)
  202. m.Group("/security", func() {
  203. m.Get("", user.SettingsSecurity)
  204. m.Combo("/two_factor_enable").Get(user.SettingsTwoFactorEnable).
  205. Post(user.SettingsTwoFactorEnablePost)
  206. m.Combo("/two_factor_recovery_codes").Get(user.SettingsTwoFactorRecoveryCodes).
  207. Post(user.SettingsTwoFactorRecoveryCodesPost)
  208. m.Post("/two_factor_disable", user.SettingsTwoFactorDisable)
  209. })
  210. m.Group("/repositories", func() {
  211. m.Get("", user.SettingsRepos)
  212. m.Post("/leave", user.SettingsLeaveRepo)
  213. })
  214. m.Group("/organizations", func() {
  215. m.Get("", user.SettingsOrganizations)
  216. m.Post("/leave", user.SettingsLeaveOrganization)
  217. })
  218. m.Combo("/applications").Get(user.SettingsApplications).
  219. Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost)
  220. m.Post("/applications/delete", user.SettingsDeleteApplication)
  221. m.Get("/embeds", user.SettingsEmbeds)
  222. m.Route("/delete", "GET,POST", user.SettingsDelete)
  223. }, reqSignIn, func(c *context.Context) {
  224. c.Data["PageIsUserSettings"] = true
  225. })
  226. m.Group("/user", func() {
  227. m.Any("/activate", user.Activate)
  228. m.Any("/activate_email", user.ActivateEmail)
  229. m.Get("/email2user", user.Email2User)
  230. m.Get("/forget_password", user.ForgotPasswd)
  231. m.Post("/forget_password", user.ForgotPasswdPost)
  232. m.Post("/logout", user.SignOut)
  233. })
  234. // ***** END: User *****
  235. reqAdmin := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  236. // ***** START: Admin *****
  237. m.Group("/admin", func() {
  238. m.Get("", admin.Dashboard)
  239. m.Get("/analytics", admin.Analytics)
  240. m.Get("/config", admin.Config)
  241. m.Post("/config/test_mail", admin.SendTestMail)
  242. m.Get("/monitor", admin.Monitor)
  243. m.Get("/allusers", admin.AllUsers)
  244. m.Group("/news", func() {
  245. m.Get("", admin.News)
  246. m.Get("/new", admin.NewsNew)
  247. m.Get("/edit", admin.NewsEdit)
  248. })
  249. m.Group("/users", func() {
  250. m.Get("", admin.Users)
  251. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(form.AdminCreateUser{}), admin.NewUserPost)
  252. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(form.AdminEditUser{}), admin.EditUserPost)
  253. m.Post("/:userid/delete", admin.DeleteUser)
  254. })
  255. m.Group("/orgs", func() {
  256. m.Get("", admin.Organizations)
  257. })
  258. m.Group("/repos", func() {
  259. m.Get("", admin.Repos)
  260. m.Post("/delete", admin.DeleteRepo)
  261. })
  262. m.Group("/auths", func() {
  263. m.Get("", admin.Authentications)
  264. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(form.Authentication{}), admin.NewAuthSourcePost)
  265. m.Combo("/:authid").Get(admin.EditAuthSource).
  266. Post(bindIgnErr(form.Authentication{}), admin.EditAuthSourcePost)
  267. m.Post("/:authid/delete", admin.DeleteAuthSource)
  268. })
  269. m.Group("/notices", func() {
  270. m.Get("", admin.Notices)
  271. m.Post("/delete", admin.DeleteNotices)
  272. m.Get("/empty", admin.EmptyNotices)
  273. })
  274. }, reqAdmin)
  275. // ***** END: Admin *****
  276. // ***** START: Pages *****
  277. m.Get("/about", ignSignIn, pages.About)
  278. m.Get("/faq", ignSignIn, pages.Faq)
  279. m.Get("/privacy", ignSignIn, pages.Privacy)
  280. m.Get("/tos", ignSignIn, pages.Tos)
  281. m.Get("/brand", ignSignIn, pages.Brand)
  282. m.Get("/contribute", ignSignIn, pages.Contribute)
  283. m.Get("/security", ignSignIn, pages.Security)
  284. m.Get("/verified", ignSignIn, pages.Verified)
  285. m.Get("/makers", ignSignIn, pages.Makers)
  286. m.Get("/help", ignSignIn, pages.Help)
  287. m.Get("/contact", ignSignIn, pages.Contact)
  288. m.Get("/features", ignSignIn, pages.Features)
  289. m.Get("/request", ignSignIn, pages.FeatureRequest)
  290. m.Get("/sponsorship", ignSignIn, pages.Sponsorship)
  291. m.Get("/sponsors", ignSignIn, pages.Sponsors)
  292. // ***** END: Pages *****
  293. m.Group("/sitemap", func() {
  294. m.Get("", ignSignIn, admin.Sitemap)
  295. m.Get("/users", ignSignIn, admin.UserSitemap)
  296. m.Get("/orgs", ignSignIn, admin.OrgSitemap)
  297. m.Get("/repos", ignSignIn, admin.RepoSitemap)
  298. })
  299. // ***** START: Misc *****
  300. m.Get("/certificate/:username", ignSignIn, user.InternCertificate)
  301. // ***** END: Misc *****
  302. // ***** START: Embed *****
  303. m.Get("/embed/user/:username", ignSignIn, user.Embed)
  304. // ***** END: Embed *****
  305. m.Group("", func() {
  306. m.Group("/:username", func() {
  307. m.Get("", user.Profile)
  308. m.Get("/followers", user.Followers)
  309. m.Get("/following", user.Following)
  310. m.Get("/stars", user.Stars)
  311. }, context.InjectParamsUser())
  312. m.Get("/attachments/:uuid", func(c *context.Context) {
  313. attach, err := models.GetAttachmentByUUID(c.Params(":uuid"))
  314. if err != nil {
  315. c.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err)
  316. return
  317. } else if !com.IsFile(attach.LocalPath()) {
  318. c.NotFound()
  319. return
  320. }
  321. fr, err := os.Open(attach.LocalPath())
  322. if err != nil {
  323. c.Handle(500, "Open", err)
  324. return
  325. }
  326. defer fr.Close()
  327. c.Header().Set("Cache-Control", "public,max-age=86400")
  328. fmt.Println("attach.Name:", attach.Name)
  329. c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  330. if err = repo.ServeData(c, attach.Name, fr); err != nil {
  331. c.Handle(500, "ServeData", err)
  332. return
  333. }
  334. })
  335. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  336. m.Post("/releases/attachments", repo.UploadReleaseAttachment)
  337. }, ignSignIn)
  338. m.Group("/:username", func() {
  339. m.Post("/action/:action", user.Action)
  340. }, reqSignIn, context.InjectParamsUser())
  341. if macaron.Env == macaron.DEV {
  342. m.Get("/template/*", dev.TemplatePreview)
  343. }
  344. reqRepoAdmin := context.RequireRepoAdmin()
  345. reqRepoWriter := context.RequireRepoWriter()
  346. // ***** START: Organization *****
  347. m.Group("/org", func() {
  348. m.Group("", func() {
  349. m.Get("/create", org.Create)
  350. m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
  351. }, func(c *context.Context) {
  352. if !c.User.CanCreateOrganization() {
  353. c.NotFound()
  354. }
  355. })
  356. m.Group("/:org", func() {
  357. m.Get("/dashboard", user.Dashboard)
  358. m.Get("/^:type(issues|pulls)$", user.Issues)
  359. m.Get("/members", org.Members)
  360. m.Get("/members/action/:action", org.MembersAction)
  361. m.Get("/teams", org.Teams)
  362. }, context.OrgAssignment(true))
  363. m.Group("/:org", func() {
  364. m.Get("/teams/:team", org.TeamMembers)
  365. m.Get("/teams/:team/repositories", org.TeamRepositories)
  366. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  367. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  368. }, context.OrgAssignment(true, false, true))
  369. m.Group("/:org", func() {
  370. m.Get("/teams/new", org.NewTeam)
  371. m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
  372. m.Get("/teams/:team/edit", org.EditTeam)
  373. m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
  374. m.Post("/teams/:team/delete", org.DeleteTeam)
  375. m.Group("/settings", func() {
  376. m.Combo("").Get(org.Settings).
  377. Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
  378. m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
  379. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  380. m.Group("/hooks", func() {
  381. m.Get("", org.Webhooks)
  382. m.Post("/delete", org.DeleteWebhook)
  383. m.Get("/:type/new", repo.WebhooksNew)
  384. m.Post("/gitote/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
  385. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
  386. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
  387. m.Get("/:id", repo.WebHooksEdit)
  388. m.Post("/gitote/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
  389. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
  390. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
  391. })
  392. m.Route("/delete", "GET,POST", org.SettingsDelete)
  393. })
  394. m.Route("/invitations/new", "GET,POST", org.Invitation)
  395. }, context.OrgAssignment(true, true))
  396. }, reqSignIn)
  397. // ***** END: Organization *****
  398. // ***** START: Repository *****
  399. m.Group("/repo", func() {
  400. m.Get("/create", repo.Create)
  401. m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
  402. m.Get("/migrate", repo.Migrate)
  403. m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
  404. m.Combo("/fork/:repoid").Get(repo.Fork).
  405. Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
  406. }, reqSignIn)
  407. m.Group("/:username/:reponame", func() {
  408. m.Group("/settings", func() {
  409. m.Combo("").Get(repo.Settings).
  410. Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
  411. m.Combo("/avatar").Get(repo.SettingsAvatar).
  412. Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
  413. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  414. m.Group("/collaboration", func() {
  415. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  416. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  417. m.Post("/delete", repo.DeleteCollaboration)
  418. })
  419. m.Group("/branches", func() {
  420. m.Get("", repo.SettingsBranches)
  421. m.Post("/default_branch", repo.UpdateDefaultBranch)
  422. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  423. Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  424. }, func(c *context.Context) {
  425. if c.Repo.Repository.IsMirror {
  426. c.NotFound()
  427. return
  428. }
  429. })
  430. m.Group("/hooks", func() {
  431. m.Get("", repo.Webhooks)
  432. m.Post("/delete", repo.DeleteWebhook)
  433. m.Get("/:type/new", repo.WebhooksNew)
  434. m.Post("/gitote/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
  435. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
  436. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
  437. m.Post("/gitote/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
  438. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
  439. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
  440. m.Group("/:id", func() {
  441. m.Get("", repo.WebHooksEdit)
  442. m.Post("/test", repo.TestWebhook)
  443. m.Post("/redelivery", repo.RedeliveryWebhook)
  444. })
  445. m.Group("/git", func() {
  446. m.Get("", repo.SettingsGitHooks)
  447. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  448. Post(repo.SettingsGitHooksEditPost)
  449. }, context.GitHookService())
  450. })
  451. m.Group("/keys", func() {
  452. m.Combo("").Get(repo.SettingsDeployKeys).
  453. Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  454. m.Post("/delete", repo.DeleteDeployKey)
  455. })
  456. }, func(c *context.Context) {
  457. c.Data["PageIsSettings"] = true
  458. })
  459. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  460. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  461. m.Group("/:username/:reponame", func() {
  462. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  463. m.Get("/issues/:index", repo.ViewIssue)
  464. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  465. m.Get("/milestones", repo.Milestones)
  466. }, ignSignIn, context.RepoAssignment(true))
  467. m.Group("/:username/:reponame", func() {
  468. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  469. // So they can apply their own enable/disable logic on routers.
  470. m.Group("/issues", func() {
  471. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  472. Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
  473. m.Group("/:index", func() {
  474. m.Post("/title", repo.UpdateIssueTitle)
  475. m.Post("/content", repo.UpdateIssueContent)
  476. m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
  477. })
  478. })
  479. m.Group("/comments/:id", func() {
  480. m.Post("", repo.UpdateCommentContent)
  481. m.Post("/delete", repo.DeleteComment)
  482. })
  483. }, reqSignIn, context.RepoAssignment(true))
  484. m.Group("/:username/:reponame", func() {
  485. m.Group("/wiki", func() {
  486. m.Get("/?:page", repo.Wiki)
  487. m.Get("/_pages", repo.WikiPages)
  488. }, repo.MustEnableWiki, context.RepoRef())
  489. }, ignSignIn, context.RepoAssignment(false, true))
  490. m.Group("/:username/:reponame", func() {
  491. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  492. // So they can apply their own enable/disable logic on routers.
  493. m.Group("/issues", func() {
  494. m.Group("/:index", func() {
  495. m.Post("/label", repo.UpdateIssueLabel)
  496. m.Post("/milestone", repo.UpdateIssueMilestone)
  497. m.Post("/assignee", repo.UpdateIssueAssignee)
  498. }, reqRepoWriter)
  499. })
  500. m.Group("/labels", func() {
  501. m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
  502. m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
  503. m.Post("/delete", repo.DeleteLabel)
  504. m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
  505. }, reqRepoWriter, context.RepoRef())
  506. m.Group("/milestones", func() {
  507. m.Combo("/new").Get(repo.NewMilestone).
  508. Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
  509. m.Get("/:id/edit", repo.EditMilestone)
  510. m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
  511. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  512. m.Post("/delete", repo.DeleteMilestone)
  513. }, reqRepoWriter, context.RepoRef())
  514. m.Group("/releases", func() {
  515. m.Get("/new", repo.NewRelease)
  516. m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
  517. m.Post("/delete", repo.DeleteRelease)
  518. m.Get("/edit/*", repo.EditRelease)
  519. m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
  520. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  521. c.Data["PageIsViewFiles"] = true
  522. })
  523. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  524. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  525. // e.g. /org1/test-repo/compare/master...org1:develop
  526. // which should be /org1/test-repo/compare/master...develop
  527. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  528. Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
  529. m.Group("", func() {
  530. m.Combo("/_edit/*").Get(repo.EditFile).
  531. Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
  532. m.Combo("/_new/*").Get(repo.NewFile).
  533. Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
  534. m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  535. m.Combo("/_delete/*").Get(repo.DeleteFile).
  536. Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
  537. m.Group("", func() {
  538. m.Combo("/_upload/*").Get(repo.UploadFile).
  539. Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
  540. m.Post("/upload-file", repo.UploadFileToServer)
  541. m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  542. }, func(c *context.Context) {
  543. if !setting.Repository.Upload.Enabled {
  544. c.NotFound()
  545. return
  546. }
  547. })
  548. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  549. if !c.Repo.CanEnableEditor() {
  550. c.NotFound()
  551. return
  552. }
  553. c.Data["PageIsViewFiles"] = true
  554. })
  555. }, reqSignIn, context.RepoAssignment())
  556. m.Group("/:username/:reponame", func() {
  557. m.Group("", func() {
  558. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  559. m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  560. m.Get("/pulls/:index", repo.ViewPull)
  561. }, context.RepoRef())
  562. m.Group("/branches", func() {
  563. m.Get("", repo.Branches)
  564. m.Get("/all", repo.AllBranches)
  565. m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  566. }, repo.MustBeNotBare, func(c *context.Context) {
  567. c.Data["PageIsViewFiles"] = true
  568. })
  569. m.Group("/wiki", func() {
  570. m.Group("", func() {
  571. m.Combo("/_new").Get(repo.NewWiki).
  572. Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
  573. m.Combo("/:page/_edit").Get(repo.EditWiki).
  574. Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
  575. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  576. }, reqSignIn, reqRepoWriter)
  577. }, repo.MustEnableWiki, context.RepoRef())
  578. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  579. m.Group("/pulls/:index", func() {
  580. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  581. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  582. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  583. }, repo.MustAllowPulls)
  584. m.Group("", func() {
  585. m.Get("/src/*", repo.Home)
  586. m.Get("/raw/*", repo.SingleDownload)
  587. m.Get("/commits/*", repo.RefCommits)
  588. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  589. m.Get("/forks", repo.Forks)
  590. }, repo.MustBeNotBare, context.RepoRef())
  591. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  592. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  593. }, ignSignIn, context.RepoAssignment())
  594. m.Group("/:username/:reponame", func() {
  595. m.Get("/stars", repo.Stars)
  596. m.Get("/watchers", repo.Watchers)
  597. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  598. m.Group("/:username", func() {
  599. m.Get("/:reponame", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  600. m.Group("/:reponame", func() {
  601. m.Head("/tasks/trigger", repo.TriggerTask)
  602. })
  603. // Use the regexp to match the repository name
  604. // Duplicated routes to enable different ways of accessing same set of URLs,
  605. // e.g. with or without ".git" suffix.
  606. m.Group("/:reponame([\\d\\w-_\\.]+\\.git$)", func() {
  607. m.Get("", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  608. m.Options("/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  609. m.Route("/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  610. })
  611. m.Options("/:reponame/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  612. m.Route("/:reponame/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  613. })
  614. // ***** END: Repository *****
  615. m.Group("/api", func() {
  616. apiv1.RegisterRoutes(m)
  617. }, ignSignIn)
  618. m.Group("/-", func() {
  619. if setting.Prometheus.Enabled {
  620. m.Get("/metrics", func(c *context.Context) {
  621. if !setting.Prometheus.EnableBasicAuth {
  622. return
  623. }
  624. c.RequireBasicAuth(setting.Prometheus.BasicAuthUsername, setting.Prometheus.BasicAuthPassword)
  625. }, promhttp.Handler())
  626. }
  627. })
  628. // Not found handler.
  629. m.NotFound(routes.NotFound)
  630. // Flag for port number in case first time run conflict.
  631. if c.IsSet("port") {
  632. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, c.String("port"), 1)
  633. setting.HTTPPort = c.String("port")
  634. }
  635. var listenAddr string
  636. if setting.Protocol == setting.SchemeUnixSocket {
  637. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  638. } else {
  639. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  640. }
  641. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  642. var err error
  643. switch setting.Protocol {
  644. case setting.SchemeHTTP:
  645. err = http.ListenAndServe(listenAddr, m)
  646. case setting.SchemeHTTPS:
  647. var tlsMinVersion uint16
  648. switch setting.TLSMinVersion {
  649. case "SSL30":
  650. tlsMinVersion = tls.VersionSSL30
  651. case "TLS12":
  652. tlsMinVersion = tls.VersionTLS12
  653. case "TLS11":
  654. tlsMinVersion = tls.VersionTLS11
  655. case "TLS10":
  656. fallthrough
  657. default:
  658. tlsMinVersion = tls.VersionTLS10
  659. }
  660. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{
  661. MinVersion: tlsMinVersion,
  662. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  663. PreferServerCipherSuites: true,
  664. CipherSuites: []uint16{
  665. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  666. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Required for HTTP/2 support.
  667. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  668. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  669. },
  670. }, Handler: m}
  671. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  672. case setting.SchemeFCGI:
  673. err = fcgi.Serve(nil, m)
  674. case setting.SchemeUnixSocket:
  675. os.Remove(listenAddr)
  676. var listener *net.UnixListener
  677. listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
  678. if err != nil {
  679. break // Handle error after switch
  680. }
  681. // FIXME: add proper implementation of signal capture on all protocols
  682. // execute this on SIGTERM or SIGINT: listener.Close()
  683. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  684. raven.CaptureErrorAndWait(err, nil)
  685. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  686. }
  687. err = http.Serve(listener, m)
  688. default:
  689. raven.CaptureErrorAndWait(err, nil)
  690. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  691. }
  692. if err != nil {
  693. raven.CaptureErrorAndWait(err, nil)
  694. log.Fatal(4, "Failed to start server: %v", err)
  695. }
  696. return nil
  697. }