web.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. // Copyright 2014 The Gogs 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 cmd
  5. import (
  6. "fmt"
  7. "html/template"
  8. "io/ioutil"
  9. "net/http"
  10. "net/http/fcgi"
  11. "os"
  12. "path"
  13. "strings"
  14. "github.com/Unknwon/macaron"
  15. "github.com/codegangsta/cli"
  16. "github.com/macaron-contrib/binding"
  17. "github.com/macaron-contrib/cache"
  18. "github.com/macaron-contrib/captcha"
  19. "github.com/macaron-contrib/csrf"
  20. "github.com/macaron-contrib/i18n"
  21. "github.com/macaron-contrib/session"
  22. "github.com/macaron-contrib/toolbox"
  23. "github.com/gogits/gogs/models"
  24. "github.com/gogits/gogs/modules/auth"
  25. "github.com/gogits/gogs/modules/auth/apiv1"
  26. "github.com/gogits/gogs/modules/avatar"
  27. "github.com/gogits/gogs/modules/base"
  28. "github.com/gogits/gogs/modules/git"
  29. "github.com/gogits/gogs/modules/log"
  30. "github.com/gogits/gogs/modules/middleware"
  31. "github.com/gogits/gogs/modules/setting"
  32. "github.com/gogits/gogs/routers"
  33. "github.com/gogits/gogs/routers/admin"
  34. "github.com/gogits/gogs/routers/api/v1"
  35. "github.com/gogits/gogs/routers/dev"
  36. "github.com/gogits/gogs/routers/org"
  37. "github.com/gogits/gogs/routers/repo"
  38. "github.com/gogits/gogs/routers/user"
  39. )
  40. var CmdWeb = cli.Command{
  41. Name: "web",
  42. Usage: "Start Gogs web server",
  43. Description: `Gogs web server is the only thing you need to run,
  44. and it takes care of all the other things for you`,
  45. Action: runWeb,
  46. Flags: []cli.Flag{},
  47. }
  48. // checkVersion checks if binary matches the version of templates files.
  49. func checkVersion() {
  50. // Templates.
  51. data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION"))
  52. if err != nil {
  53. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  54. }
  55. if string(data) != setting.AppVer {
  56. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  57. }
  58. // Check dependency version.
  59. macaronVer := git.MustParseVersion(strings.Join(strings.Split(macaron.Version(), ".")[:3], "."))
  60. if macaronVer.LessThan(git.MustParseVersion("0.2.3")) {
  61. log.Fatal(4, "Package macaron version is too old, did you forget to update?(github.com/Unknwon/macaron)")
  62. }
  63. i18nVer := git.MustParseVersion(i18n.Version())
  64. if i18nVer.LessThan(git.MustParseVersion("0.0.2")) {
  65. log.Fatal(4, "Package i18n version is too old, did you forget to update?(github.com/macaron-contrib/i18n)")
  66. }
  67. sessionVer := git.MustParseVersion(session.Version())
  68. if sessionVer.LessThan(git.MustParseVersion("0.0.5")) {
  69. log.Fatal(4, "Package session version is too old, did you forget to update?(github.com/macaron-contrib/session)")
  70. }
  71. }
  72. // newMacaron initializes Macaron instance.
  73. func newMacaron() *macaron.Macaron {
  74. m := macaron.New()
  75. m.Use(macaron.Logger())
  76. m.Use(macaron.Recovery())
  77. if setting.EnableGzip {
  78. m.Use(macaron.Gziper())
  79. }
  80. m.Use(macaron.Static(
  81. path.Join(setting.StaticRootPath, "public"),
  82. macaron.StaticOptions{
  83. SkipLogging: !setting.DisableRouterLog,
  84. },
  85. ))
  86. m.Use(macaron.Renderer(macaron.RenderOptions{
  87. Directory: path.Join(setting.StaticRootPath, "templates"),
  88. Funcs: []template.FuncMap{base.TemplateFuncs},
  89. IndentJSON: macaron.Env != macaron.PROD,
  90. }))
  91. m.Use(i18n.I18n(i18n.Options{
  92. SubURL: setting.AppSubUrl,
  93. Directory: path.Join(setting.ConfRootPath, "locale"),
  94. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  95. Langs: setting.Langs,
  96. Names: setting.Names,
  97. Redirect: true,
  98. }))
  99. m.Use(cache.Cacher(cache.Options{
  100. Adapter: setting.CacheAdapter,
  101. Interval: setting.CacheInternal,
  102. Conn: setting.CacheConn,
  103. }))
  104. m.Use(captcha.Captchaer(captcha.Options{
  105. SubURL: setting.AppSubUrl,
  106. }))
  107. m.Use(session.Sessioner(session.Options{
  108. Provider: setting.SessionProvider,
  109. Config: *setting.SessionConfig,
  110. }))
  111. m.Use(csrf.Generate(csrf.Options{
  112. Secret: setting.SecretKey,
  113. SetCookie: true,
  114. Header: "X-Csrf-Token",
  115. CookiePath: setting.AppSubUrl,
  116. }))
  117. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  118. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  119. &toolbox.HealthCheckFuncDesc{
  120. Desc: "Database connection",
  121. Func: models.Ping,
  122. },
  123. },
  124. }))
  125. m.Use(middleware.Contexter())
  126. return m
  127. }
  128. func runWeb(*cli.Context) {
  129. routers.GlobalInit()
  130. checkVersion()
  131. m := newMacaron()
  132. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  133. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  134. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  135. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  136. bindIgnErr := binding.BindIgnErr
  137. // Routers.
  138. m.Get("/", ignSignIn, routers.Home)
  139. m.Get("/explore", ignSignIn, routers.Explore)
  140. m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
  141. m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  142. m.Group("", func() {
  143. m.Get("/pulls", user.Pulls)
  144. m.Get("/issues", user.Issues)
  145. }, reqSignIn)
  146. // API routers.
  147. m.Group("/api", func() {
  148. m.Group("/v1", func() {
  149. // Miscellaneous.
  150. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  151. m.Post("/markdown/raw", v1.MarkdownRaw)
  152. // Users.
  153. m.Group("/users", func() {
  154. m.Get("/search", v1.SearchUsers)
  155. })
  156. // Repositories.
  157. m.Group("/repos", func() {
  158. m.Get("/search", v1.SearchRepos)
  159. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.Migrate)
  160. })
  161. m.Any("/*", func(ctx *middleware.Context) {
  162. ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
  163. })
  164. })
  165. })
  166. // User routers.
  167. m.Group("/user", func() {
  168. m.Get("/login", user.SignIn)
  169. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  170. m.Get("/login/:name", user.SocialSignIn)
  171. m.Get("/sign_up", user.SignUp)
  172. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  173. m.Get("/reset_password", user.ResetPasswd)
  174. m.Post("/reset_password", user.ResetPasswdPost)
  175. }, reqSignOut)
  176. m.Group("/user/settings", func() {
  177. m.Get("", user.Settings)
  178. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  179. m.Get("/password", user.SettingsPassword)
  180. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  181. m.Get("/ssh", user.SettingsSSHKeys)
  182. m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  183. m.Get("/social", user.SettingsSocial)
  184. m.Route("/delete", "GET,POST", user.SettingsDelete)
  185. }, reqSignIn)
  186. m.Group("/user", func() {
  187. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  188. m.Any("/activate", user.Activate)
  189. m.Get("/email2user", user.Email2User)
  190. m.Get("/forget_password", user.ForgotPasswd)
  191. m.Post("/forget_password", user.ForgotPasswdPost)
  192. m.Get("/logout", user.SignOut)
  193. })
  194. // FIXME: Legacy
  195. m.Get("/user/:username", ignSignIn, user.Profile)
  196. // Gravatar service.
  197. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  198. os.MkdirAll("public/img/avatar/", os.ModePerm)
  199. m.Get("/avatar/:hash", avt.ServeHTTP)
  200. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  201. m.Group("/admin", func() {
  202. m.Get("", adminReq, admin.Dashboard)
  203. m.Get("/config", admin.Config)
  204. m.Get("/monitor", admin.Monitor)
  205. m.Group("/users", func() {
  206. m.Get("", admin.Users)
  207. m.Get("/new", admin.NewUser)
  208. m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  209. m.Get("/:userid", admin.EditUser)
  210. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  211. m.Post("/:userid/delete", admin.DeleteUser)
  212. })
  213. m.Group("/orgs", func() {
  214. m.Get("", admin.Organizations)
  215. })
  216. m.Group("/repos", func() {
  217. m.Get("", admin.Repositories)
  218. })
  219. m.Group("/auths", func() {
  220. m.Get("", admin.Authentications)
  221. m.Get("/new", admin.NewAuthSource)
  222. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  223. m.Get("/:authid", admin.EditAuthSource)
  224. m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  225. m.Post("/:authid/delete", admin.DeleteAuthSource)
  226. })
  227. m.Group("/notices", func() {
  228. m.Get("", admin.Notices)
  229. m.Get("/:id:int/delete", admin.DeleteNotice)
  230. })
  231. }, adminReq)
  232. m.Get("/:username", ignSignIn, user.Profile)
  233. if macaron.Env == macaron.DEV {
  234. m.Get("/template/*", dev.TemplatePreview)
  235. }
  236. reqTrueOwner := middleware.RequireTrueOwner()
  237. // Organization.
  238. m.Group("/org", func() {
  239. m.Get("/create", org.Create)
  240. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  241. m.Group("/:org", func() {
  242. m.Get("/dashboard", user.Dashboard)
  243. m.Get("/members", org.Members)
  244. m.Get("/members/action/:action", org.MembersAction)
  245. m.Get("/teams", org.Teams)
  246. m.Get("/teams/:team", org.TeamMembers)
  247. m.Get("/teams/:team/repositories", org.TeamRepositories)
  248. m.Get("/teams/:team/action/:action", org.TeamsAction)
  249. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  250. }, middleware.OrgAssignment(true, true))
  251. m.Group("/:org", func() {
  252. m.Get("/teams/new", org.NewTeam)
  253. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  254. m.Get("/teams/:team/edit", org.EditTeam)
  255. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  256. m.Post("/teams/:team/delete", org.DeleteTeam)
  257. m.Group("/settings", func() {
  258. m.Get("", org.Settings)
  259. m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  260. m.Get("/hooks", org.SettingsHooks)
  261. m.Get("/hooks/new", repo.WebHooksNew)
  262. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  263. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  264. m.Get("/hooks/:id", repo.WebHooksEdit)
  265. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  266. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  267. m.Route("/delete", "GET,POST", org.SettingsDelete)
  268. })
  269. m.Route("/invitations/new", "GET,POST", org.Invitation)
  270. }, middleware.OrgAssignment(true, true, true))
  271. }, reqSignIn)
  272. m.Group("/org", func() {
  273. m.Get("/:org", org.Home)
  274. }, middleware.OrgAssignment(true))
  275. // Repository.
  276. m.Group("/repo", func() {
  277. m.Get("/create", repo.Create)
  278. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  279. m.Get("/migrate", repo.Migrate)
  280. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  281. m.Get("/fork", repo.Fork)
  282. m.Post("/fork", bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  283. }, reqSignIn)
  284. m.Group("/:username/:reponame", func() {
  285. m.Get("/settings", repo.Settings)
  286. m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  287. m.Group("/settings", func() {
  288. m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  289. m.Get("/hooks", repo.Webhooks)
  290. m.Get("/hooks/new", repo.WebHooksNew)
  291. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  292. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  293. m.Get("/hooks/:id", repo.WebHooksEdit)
  294. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  295. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  296. m.Group("/hooks/git", func() {
  297. m.Get("", repo.GitHooks)
  298. m.Get("/:name", repo.GitHooksEdit)
  299. m.Post("/:name", repo.GitHooksEditPost)
  300. }, middleware.GitHookService())
  301. })
  302. }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
  303. m.Group("/:username/:reponame", func() {
  304. m.Get("/action/:action", repo.Action)
  305. m.Group("/issues", func() {
  306. m.Get("/new", repo.CreateIssue)
  307. m.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  308. m.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  309. m.Post("/:index/label", repo.UpdateIssueLabel)
  310. m.Post("/:index/milestone", repo.UpdateIssueMilestone)
  311. m.Post("/:index/assignee", repo.UpdateAssignee)
  312. m.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  313. m.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  314. m.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  315. m.Post("/labels/delete", repo.DeleteLabel)
  316. m.Get("/milestones", repo.Milestones)
  317. m.Get("/milestones/new", repo.NewMilestone)
  318. m.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  319. m.Get("/milestones/:index/edit", repo.UpdateMilestone)
  320. m.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  321. m.Get("/milestones/:index/:action", repo.UpdateMilestone)
  322. })
  323. m.Post("/comment/:action", repo.Comment)
  324. m.Get("/releases/new", repo.NewRelease)
  325. m.Get("/releases/edit/:tagname", repo.EditRelease)
  326. }, reqSignIn, middleware.RepoAssignment(true))
  327. m.Group("/:username/:reponame", func() {
  328. m.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  329. m.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  330. }, reqSignIn, middleware.RepoAssignment(true, true))
  331. m.Group("/:username/:reponame", func() {
  332. m.Get("/issues", repo.Issues)
  333. m.Get("/issues/:index", repo.ViewIssue)
  334. m.Get("/pulls", repo.Pulls)
  335. m.Get("/branches", repo.Branches)
  336. m.Get("/archive/*", repo.Download)
  337. m.Get("/issues2/", repo.Issues2)
  338. }, ignSignIn, middleware.RepoAssignment(true))
  339. m.Group("/:username/:reponame", func() {
  340. m.Get("/src/:branchname", repo.Home)
  341. m.Get("/src/:branchname/*", repo.Home)
  342. m.Get("/raw/:branchname/*", repo.SingleDownload)
  343. m.Get("/commits/:branchname", repo.Commits)
  344. m.Get("/commits/:branchname/search", repo.SearchCommits)
  345. m.Get("/commits/:branchname/*", repo.FileHistory)
  346. m.Get("/commit/:branchname", repo.Diff)
  347. m.Get("/commit/:branchname/*", repo.Diff)
  348. m.Get("/releases", repo.Releases)
  349. m.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
  350. }, ignSignIn, middleware.RepoAssignment(true, true))
  351. m.Group("/:username", func() {
  352. m.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true, true), repo.Home)
  353. m.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
  354. })
  355. // robots.txt
  356. m.Get("/robots.txt", func(ctx *middleware.Context) {
  357. if setting.HasRobotsTxt {
  358. ctx.ServeFile(path.Join(setting.CustomPath, "robots.txt"))
  359. } else {
  360. ctx.Error(404)
  361. }
  362. })
  363. // Not found handler.
  364. m.NotFound(routers.NotFound)
  365. var err error
  366. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  367. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  368. switch setting.Protocol {
  369. case setting.HTTP:
  370. err = http.ListenAndServe(listenAddr, m)
  371. case setting.HTTPS:
  372. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  373. case setting.FCGI:
  374. err = fcgi.Serve(nil, m)
  375. default:
  376. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  377. }
  378. if err != nil {
  379. log.Fatal(4, "Fail to start server: %v", err)
  380. }
  381. }