web.go 15 KB

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