web.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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("/repos", routes.ExploreRepos)
  164. m.Get("/users", routes.ExploreUsers)
  165. m.Get("/organizations", routes.ExploreOrganizations)
  166. }, ignSignIn)
  167. m.Combo("/install", routes.InstallInit).Get(routes.Install).
  168. Post(bindIgnErr(form.Install{}), routes.InstallPost)
  169. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  170. // ***** START: Auth *****
  171. m.Group("", func() {
  172. m.Group("/login", func() {
  173. m.Combo("").Get(user.Login).
  174. Post(bindIgnErr(form.SignIn{}), user.LoginPost)
  175. m.Combo("/two_factor").Get(user.LoginTwoFactor).Post(user.LoginTwoFactorPost)
  176. m.Combo("/two_factor_recovery_code").Get(user.LoginTwoFactorRecoveryCode).Post(user.LoginTwoFactorRecoveryCodePost)
  177. })
  178. m.Get("/join", user.SignUp)
  179. m.Post("/join", bindIgnErr(form.Register{}), user.SignUpPost)
  180. m.Get("/reset_password", user.ResetPasswd)
  181. m.Post("/reset_password", user.ResetPasswdPost)
  182. }, reqSignOut)
  183. // ***** END: Auth *****
  184. // ***** START: User *****
  185. m.Group("/user/settings", func() {
  186. m.Get("", user.Settings)
  187. m.Post("", bindIgnErr(form.UpdateProfile{}), user.SettingsPost)
  188. m.Get("/social", user.SettingsSocial)
  189. m.Post("/social", bindIgnErr(form.UpdateSocial{}), user.SettingsSocialPost)
  190. m.Combo("/avatar").Get(user.SettingsAvatar).
  191. Post(binding.MultipartForm(form.Avatar{}), user.SettingsAvatarPost)
  192. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  193. m.Combo("/email").Get(user.SettingsEmails).
  194. Post(bindIgnErr(form.AddEmail{}), user.SettingsEmailPost)
  195. m.Post("/email/delete", user.DeleteEmail)
  196. m.Get("/password", user.SettingsPassword)
  197. m.Post("/password", bindIgnErr(form.ChangePassword{}), user.SettingsPasswordPost)
  198. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  199. Post(bindIgnErr(form.AddSSHKey{}), user.SettingsSSHKeysPost)
  200. m.Post("/ssh/delete", user.DeleteSSHKey)
  201. m.Group("/security", func() {
  202. m.Get("", user.SettingsSecurity)
  203. m.Combo("/two_factor_enable").Get(user.SettingsTwoFactorEnable).
  204. Post(user.SettingsTwoFactorEnablePost)
  205. m.Combo("/two_factor_recovery_codes").Get(user.SettingsTwoFactorRecoveryCodes).
  206. Post(user.SettingsTwoFactorRecoveryCodesPost)
  207. m.Post("/two_factor_disable", user.SettingsTwoFactorDisable)
  208. })
  209. m.Group("/repositories", func() {
  210. m.Get("", user.SettingsRepos)
  211. m.Post("/leave", user.SettingsLeaveRepo)
  212. })
  213. m.Group("/organizations", func() {
  214. m.Get("", user.SettingsOrganizations)
  215. m.Post("/leave", user.SettingsLeaveOrganization)
  216. })
  217. m.Combo("/applications").Get(user.SettingsApplications).
  218. Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost)
  219. m.Post("/applications/delete", user.SettingsDeleteApplication)
  220. m.Get("/embeds", user.SettingsEmbeds)
  221. m.Route("/delete", "GET,POST", user.SettingsDelete)
  222. }, reqSignIn, func(c *context.Context) {
  223. c.Data["PageIsUserSettings"] = true
  224. })
  225. m.Group("/user", func() {
  226. m.Any("/activate", user.Activate)
  227. m.Any("/activate_email", user.ActivateEmail)
  228. m.Get("/email2user", user.Email2User)
  229. m.Get("/forget_password", user.ForgotPasswd)
  230. m.Post("/forget_password", user.ForgotPasswdPost)
  231. m.Post("/logout", user.SignOut)
  232. })
  233. // ***** END: User *****
  234. reqAdmin := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  235. // ***** START: Admin *****
  236. m.Group("/admin", func() {
  237. m.Get("", admin.Dashboard)
  238. m.Get("/config", admin.Config)
  239. m.Post("/config/test_mail", admin.SendTestMail)
  240. m.Get("/monitor", admin.Monitor)
  241. m.Get("/allusers", admin.AllUsers)
  242. m.Group("/users", func() {
  243. m.Get("", admin.Users)
  244. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(form.AdminCreateUser{}), admin.NewUserPost)
  245. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(form.AdminEditUser{}), admin.EditUserPost)
  246. m.Post("/:userid/delete", admin.DeleteUser)
  247. })
  248. m.Group("/orgs", func() {
  249. m.Get("", admin.Organizations)
  250. })
  251. m.Group("/repos", func() {
  252. m.Get("", admin.Repos)
  253. m.Post("/delete", admin.DeleteRepo)
  254. })
  255. m.Group("/auths", func() {
  256. m.Get("", admin.Authentications)
  257. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(form.Authentication{}), admin.NewAuthSourcePost)
  258. m.Combo("/:authid").Get(admin.EditAuthSource).
  259. Post(bindIgnErr(form.Authentication{}), admin.EditAuthSourcePost)
  260. m.Post("/:authid/delete", admin.DeleteAuthSource)
  261. })
  262. m.Group("/notices", func() {
  263. m.Get("", admin.Notices)
  264. m.Post("/delete", admin.DeleteNotices)
  265. m.Get("/empty", admin.EmptyNotices)
  266. })
  267. }, reqAdmin)
  268. // ***** END: Admin *****
  269. // ***** START: Pages *****
  270. m.Get("/about", ignSignIn, pages.About)
  271. m.Get("/faq", ignSignIn, pages.Faq)
  272. m.Get("/privacy", ignSignIn, pages.Privacy)
  273. m.Get("/tos", ignSignIn, pages.Tos)
  274. m.Get("/brand", ignSignIn, pages.Brand)
  275. m.Get("/contribute", ignSignIn, pages.Contribute)
  276. m.Get("/security", ignSignIn, pages.Security)
  277. m.Get("/verified", ignSignIn, pages.Verified)
  278. m.Get("/makers", ignSignIn, pages.Makers)
  279. m.Get("/help", ignSignIn, pages.Help)
  280. m.Get("/contact", ignSignIn, pages.Contact)
  281. m.Get("/features", ignSignIn, pages.Features)
  282. m.Get("/request", ignSignIn, pages.FeatureRequest)
  283. m.Get("/sponsorship", ignSignIn, pages.Sponsorship)
  284. m.Get("/sponsors", ignSignIn, pages.Sponsors)
  285. // ***** END: Pages *****
  286. m.Group("/sitemap", func() {
  287. m.Get("", ignSignIn, admin.Sitemap)
  288. m.Get("/users", ignSignIn, admin.UserSitemap)
  289. m.Get("/orgs", ignSignIn, admin.OrgSitemap)
  290. m.Get("/repos", ignSignIn, admin.RepoSitemap)
  291. })
  292. // ***** START: Embed *****
  293. m.Get("/embed/user/:username", ignSignIn, user.Embed)
  294. // ***** END: Embed *****
  295. m.Group("", func() {
  296. m.Group("/:username", func() {
  297. m.Get("", user.Profile)
  298. m.Get("/followers", user.Followers)
  299. m.Get("/following", user.Following)
  300. m.Get("/stars", user.Stars)
  301. }, context.InjectParamsUser())
  302. m.Get("/attachments/:uuid", func(c *context.Context) {
  303. attach, err := models.GetAttachmentByUUID(c.Params(":uuid"))
  304. if err != nil {
  305. c.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err)
  306. return
  307. } else if !com.IsFile(attach.LocalPath()) {
  308. c.NotFound()
  309. return
  310. }
  311. fr, err := os.Open(attach.LocalPath())
  312. if err != nil {
  313. c.Handle(500, "Open", err)
  314. return
  315. }
  316. defer fr.Close()
  317. c.Header().Set("Cache-Control", "public,max-age=86400")
  318. fmt.Println("attach.Name:", attach.Name)
  319. c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
  320. if err = repo.ServeData(c, attach.Name, fr); err != nil {
  321. c.Handle(500, "ServeData", err)
  322. return
  323. }
  324. })
  325. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  326. m.Post("/releases/attachments", repo.UploadReleaseAttachment)
  327. }, ignSignIn)
  328. m.Group("/:username", func() {
  329. m.Post("/action/:action", user.Action)
  330. }, reqSignIn, context.InjectParamsUser())
  331. if macaron.Env == macaron.DEV {
  332. m.Get("/template/*", dev.TemplatePreview)
  333. }
  334. reqRepoAdmin := context.RequireRepoAdmin()
  335. reqRepoWriter := context.RequireRepoWriter()
  336. // ***** START: Organization *****
  337. m.Group("/org", func() {
  338. m.Group("", func() {
  339. m.Get("/create", org.Create)
  340. m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
  341. }, func(c *context.Context) {
  342. if !c.User.CanCreateOrganization() {
  343. c.NotFound()
  344. }
  345. })
  346. m.Group("/:org", func() {
  347. m.Get("/dashboard", user.Dashboard)
  348. m.Get("/^:type(issues|pulls)$", user.Issues)
  349. m.Get("/members", org.Members)
  350. m.Get("/members/action/:action", org.MembersAction)
  351. m.Get("/teams", org.Teams)
  352. }, context.OrgAssignment(true))
  353. m.Group("/:org", func() {
  354. m.Get("/teams/:team", org.TeamMembers)
  355. m.Get("/teams/:team/repositories", org.TeamRepositories)
  356. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  357. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  358. }, context.OrgAssignment(true, false, true))
  359. m.Group("/:org", func() {
  360. m.Get("/teams/new", org.NewTeam)
  361. m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
  362. m.Get("/teams/:team/edit", org.EditTeam)
  363. m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
  364. m.Post("/teams/:team/delete", org.DeleteTeam)
  365. m.Group("/settings", func() {
  366. m.Combo("").Get(org.Settings).
  367. Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
  368. m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
  369. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  370. m.Group("/hooks", func() {
  371. m.Get("", org.Webhooks)
  372. m.Post("/delete", org.DeleteWebhook)
  373. m.Get("/:type/new", repo.WebhooksNew)
  374. m.Post("/gitote/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
  375. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
  376. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
  377. m.Get("/:id", repo.WebHooksEdit)
  378. m.Post("/gitote/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
  379. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
  380. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
  381. })
  382. m.Route("/delete", "GET,POST", org.SettingsDelete)
  383. })
  384. m.Route("/invitations/new", "GET,POST", org.Invitation)
  385. }, context.OrgAssignment(true, true))
  386. }, reqSignIn)
  387. // ***** END: Organization *****
  388. // ***** START: Repository *****
  389. m.Group("/repo", func() {
  390. m.Get("/create", repo.Create)
  391. m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
  392. m.Get("/migrate", repo.Migrate)
  393. m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
  394. m.Combo("/fork/:repoid").Get(repo.Fork).
  395. Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
  396. }, reqSignIn)
  397. m.Group("/:username/:reponame", func() {
  398. m.Group("/settings", func() {
  399. m.Combo("").Get(repo.Settings).
  400. Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
  401. m.Combo("/avatar").Get(repo.SettingsAvatar).
  402. Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
  403. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  404. m.Group("/collaboration", func() {
  405. m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
  406. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  407. m.Post("/delete", repo.DeleteCollaboration)
  408. })
  409. m.Group("/branches", func() {
  410. m.Get("", repo.SettingsBranches)
  411. m.Post("/default_branch", repo.UpdateDefaultBranch)
  412. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  413. Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
  414. }, func(c *context.Context) {
  415. if c.Repo.Repository.IsMirror {
  416. c.NotFound()
  417. return
  418. }
  419. })
  420. m.Group("/hooks", func() {
  421. m.Get("", repo.Webhooks)
  422. m.Post("/delete", repo.DeleteWebhook)
  423. m.Get("/:type/new", repo.WebhooksNew)
  424. m.Post("/gitote/new", bindIgnErr(form.NewWebhook{}), repo.WebHooksNewPost)
  425. m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksNewPost)
  426. m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksNewPost)
  427. m.Post("/gitote/:id", bindIgnErr(form.NewWebhook{}), repo.WebHooksEditPost)
  428. m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.SlackHooksEditPost)
  429. m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.DiscordHooksEditPost)
  430. m.Group("/:id", func() {
  431. m.Get("", repo.WebHooksEdit)
  432. m.Post("/test", repo.TestWebhook)
  433. m.Post("/redelivery", repo.RedeliveryWebhook)
  434. })
  435. m.Group("/git", func() {
  436. m.Get("", repo.SettingsGitHooks)
  437. m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
  438. Post(repo.SettingsGitHooksEditPost)
  439. }, context.GitHookService())
  440. })
  441. m.Group("/keys", func() {
  442. m.Combo("").Get(repo.SettingsDeployKeys).
  443. Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
  444. m.Post("/delete", repo.DeleteDeployKey)
  445. })
  446. }, func(c *context.Context) {
  447. c.Data["PageIsSettings"] = true
  448. })
  449. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  450. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  451. m.Group("/:username/:reponame", func() {
  452. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  453. m.Get("/issues/:index", repo.ViewIssue)
  454. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  455. m.Get("/milestones", repo.Milestones)
  456. }, ignSignIn, context.RepoAssignment(true))
  457. m.Group("/:username/:reponame", func() {
  458. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  459. // So they can apply their own enable/disable logic on routers.
  460. m.Group("/issues", func() {
  461. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  462. Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
  463. m.Group("/:index", func() {
  464. m.Post("/title", repo.UpdateIssueTitle)
  465. m.Post("/content", repo.UpdateIssueContent)
  466. m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
  467. })
  468. })
  469. m.Group("/comments/:id", func() {
  470. m.Post("", repo.UpdateCommentContent)
  471. m.Post("/delete", repo.DeleteComment)
  472. })
  473. }, reqSignIn, context.RepoAssignment(true))
  474. m.Group("/:username/:reponame", func() {
  475. m.Group("/wiki", func() {
  476. m.Get("/?:page", repo.Wiki)
  477. m.Get("/_pages", repo.WikiPages)
  478. }, repo.MustEnableWiki, context.RepoRef())
  479. }, ignSignIn, context.RepoAssignment(false, true))
  480. m.Group("/:username/:reponame", func() {
  481. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  482. // So they can apply their own enable/disable logic on routers.
  483. m.Group("/issues", func() {
  484. m.Group("/:index", func() {
  485. m.Post("/label", repo.UpdateIssueLabel)
  486. m.Post("/milestone", repo.UpdateIssueMilestone)
  487. m.Post("/assignee", repo.UpdateIssueAssignee)
  488. }, reqRepoWriter)
  489. })
  490. m.Group("/labels", func() {
  491. m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
  492. m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
  493. m.Post("/delete", repo.DeleteLabel)
  494. m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
  495. }, reqRepoWriter, context.RepoRef())
  496. m.Group("/milestones", func() {
  497. m.Combo("/new").Get(repo.NewMilestone).
  498. Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
  499. m.Get("/:id/edit", repo.EditMilestone)
  500. m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
  501. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  502. m.Post("/delete", repo.DeleteMilestone)
  503. }, reqRepoWriter, context.RepoRef())
  504. m.Group("/releases", func() {
  505. m.Get("/new", repo.NewRelease)
  506. m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
  507. m.Post("/delete", repo.DeleteRelease)
  508. m.Get("/edit/*", repo.EditRelease)
  509. m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
  510. }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
  511. c.Data["PageIsViewFiles"] = true
  512. })
  513. // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
  514. // for PR in same repository. After select branch on the page, the URL contains redundant head user name.
  515. // e.g. /org1/test-repo/compare/master...org1:develop
  516. // which should be /org1/test-repo/compare/master...develop
  517. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  518. Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
  519. m.Group("", func() {
  520. m.Combo("/_edit/*").Get(repo.EditFile).
  521. Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
  522. m.Combo("/_new/*").Get(repo.NewFile).
  523. Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
  524. m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
  525. m.Combo("/_delete/*").Get(repo.DeleteFile).
  526. Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
  527. m.Group("", func() {
  528. m.Combo("/_upload/*").Get(repo.UploadFile).
  529. Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
  530. m.Post("/upload-file", repo.UploadFileToServer)
  531. m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
  532. }, func(c *context.Context) {
  533. if !setting.Repository.Upload.Enabled {
  534. c.NotFound()
  535. return
  536. }
  537. })
  538. }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
  539. if !c.Repo.CanEnableEditor() {
  540. c.NotFound()
  541. return
  542. }
  543. c.Data["PageIsViewFiles"] = true
  544. })
  545. }, reqSignIn, context.RepoAssignment())
  546. m.Group("/:username/:reponame", func() {
  547. m.Group("", func() {
  548. m.Get("/releases", repo.MustBeNotBare, repo.Releases)
  549. m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
  550. m.Get("/pulls/:index", repo.ViewPull)
  551. }, context.RepoRef())
  552. m.Group("/branches", func() {
  553. m.Get("", repo.Branches)
  554. m.Get("/all", repo.AllBranches)
  555. m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
  556. }, repo.MustBeNotBare, func(c *context.Context) {
  557. c.Data["PageIsViewFiles"] = true
  558. })
  559. m.Group("/wiki", func() {
  560. m.Group("", func() {
  561. m.Combo("/_new").Get(repo.NewWiki).
  562. Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
  563. m.Combo("/:page/_edit").Get(repo.EditWiki).
  564. Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
  565. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  566. }, reqSignIn, reqRepoWriter)
  567. }, repo.MustEnableWiki, context.RepoRef())
  568. m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
  569. m.Group("/pulls/:index", func() {
  570. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  571. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  572. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  573. }, repo.MustAllowPulls)
  574. m.Group("", func() {
  575. m.Get("/src/*", repo.Home)
  576. m.Get("/raw/*", repo.SingleDownload)
  577. m.Get("/commits/*", repo.RefCommits)
  578. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
  579. m.Get("/forks", repo.Forks)
  580. }, repo.MustBeNotBare, context.RepoRef())
  581. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
  582. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
  583. }, ignSignIn, context.RepoAssignment())
  584. m.Group("/:username/:reponame", func() {
  585. m.Get("/stars", repo.Stars)
  586. m.Get("/watchers", repo.Watchers)
  587. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  588. m.Group("/:username", func() {
  589. m.Get("/:reponame", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  590. m.Group("/:reponame", func() {
  591. m.Head("/tasks/trigger", repo.TriggerTask)
  592. })
  593. // Use the regexp to match the repository name
  594. // Duplicated routes to enable different ways of accessing same set of URLs,
  595. // e.g. with or without ".git" suffix.
  596. m.Group("/:reponame([\\d\\w-_\\.]+\\.git$)", func() {
  597. m.Get("", ignSignIn, context.RepoAssignment(), context.RepoRef(), repo.Home)
  598. m.Options("/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  599. m.Route("/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  600. })
  601. m.Options("/:reponame/*", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  602. m.Route("/:reponame/*", "GET,POST", ignSignInAndCsrf, repo.HTTPContexter(), repo.HTTP)
  603. })
  604. // ***** END: Repository *****
  605. m.Group("/api", func() {
  606. apiv1.RegisterRoutes(m)
  607. }, ignSignIn)
  608. m.Group("/-", func() {
  609. if setting.Prometheus.Enabled {
  610. m.Get("/metrics", func(c *context.Context) {
  611. if !setting.Prometheus.EnableBasicAuth {
  612. return
  613. }
  614. c.RequireBasicAuth(setting.Prometheus.BasicAuthUsername, setting.Prometheus.BasicAuthPassword)
  615. }, promhttp.Handler())
  616. }
  617. })
  618. // Not found handler.
  619. m.NotFound(routes.NotFound)
  620. // Flag for port number in case first time run conflict.
  621. if c.IsSet("port") {
  622. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, c.String("port"), 1)
  623. setting.HTTPPort = c.String("port")
  624. }
  625. var listenAddr string
  626. if setting.Protocol == setting.SchemeUnixSocket {
  627. listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
  628. } else {
  629. listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
  630. }
  631. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  632. var err error
  633. switch setting.Protocol {
  634. case setting.SchemeHTTP:
  635. err = http.ListenAndServe(listenAddr, m)
  636. case setting.SchemeHTTPS:
  637. var tlsMinVersion uint16
  638. switch setting.TLSMinVersion {
  639. case "SSL30":
  640. tlsMinVersion = tls.VersionSSL30
  641. case "TLS12":
  642. tlsMinVersion = tls.VersionTLS12
  643. case "TLS11":
  644. tlsMinVersion = tls.VersionTLS11
  645. case "TLS10":
  646. fallthrough
  647. default:
  648. tlsMinVersion = tls.VersionTLS10
  649. }
  650. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{
  651. MinVersion: tlsMinVersion,
  652. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  653. PreferServerCipherSuites: true,
  654. CipherSuites: []uint16{
  655. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  656. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Required for HTTP/2 support.
  657. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  658. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  659. },
  660. }, Handler: m}
  661. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  662. case setting.SchemeFCGI:
  663. err = fcgi.Serve(nil, m)
  664. case setting.SchemeUnixSocket:
  665. os.Remove(listenAddr)
  666. var listener *net.UnixListener
  667. listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
  668. if err != nil {
  669. break // Handle error after switch
  670. }
  671. // FIXME: add proper implementation of signal capture on all protocols
  672. // execute this on SIGTERM or SIGINT: listener.Close()
  673. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  674. raven.CaptureErrorAndWait(err, nil)
  675. log.Fatal(4, "Failed to set permission of unix socket: %v", err)
  676. }
  677. err = http.Serve(listener, m)
  678. default:
  679. raven.CaptureErrorAndWait(err, nil)
  680. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  681. }
  682. if err != nil {
  683. raven.CaptureErrorAndWait(err, nil)
  684. log.Fatal(4, "Failed to start server: %v", err)
  685. }
  686. return nil
  687. }