You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.4.2")) {
  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. if setting.Protocol == setting.FCGI {
  81. m.SetURLPrefix(setting.AppSubUrl)
  82. }
  83. m.Use(macaron.Static(
  84. path.Join(setting.StaticRootPath, "public"),
  85. macaron.StaticOptions{
  86. SkipLogging: !setting.DisableRouterLog,
  87. },
  88. ))
  89. m.Use(macaron.Renderer(macaron.RenderOptions{
  90. Directory: path.Join(setting.StaticRootPath, "templates"),
  91. Funcs: []template.FuncMap{base.TemplateFuncs},
  92. IndentJSON: macaron.Env != macaron.PROD,
  93. }))
  94. m.Use(i18n.I18n(i18n.Options{
  95. SubURL: setting.AppSubUrl,
  96. Directory: path.Join(setting.ConfRootPath, "locale"),
  97. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  98. Langs: setting.Langs,
  99. Names: setting.Names,
  100. Redirect: true,
  101. }))
  102. m.Use(cache.Cacher(cache.Options{
  103. Adapter: setting.CacheAdapter,
  104. Interval: setting.CacheInternal,
  105. Conn: setting.CacheConn,
  106. }))
  107. m.Use(captcha.Captchaer(captcha.Options{
  108. SubURL: setting.AppSubUrl,
  109. }))
  110. m.Use(session.Sessioner(session.Options{
  111. Provider: setting.SessionProvider,
  112. Config: *setting.SessionConfig,
  113. }))
  114. m.Use(csrf.Generate(csrf.Options{
  115. Secret: setting.SecretKey,
  116. SetCookie: true,
  117. Header: "X-Csrf-Token",
  118. CookiePath: setting.AppSubUrl,
  119. }))
  120. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  121. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  122. &toolbox.HealthCheckFuncDesc{
  123. Desc: "Database connection",
  124. Func: models.Ping,
  125. },
  126. },
  127. }))
  128. m.Use(middleware.Contexter())
  129. return m
  130. }
  131. func runWeb(*cli.Context) {
  132. routers.GlobalInit()
  133. checkVersion()
  134. m := newMacaron()
  135. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  136. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  137. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  138. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  139. bind := binding.Bind
  140. bindIgnErr := binding.BindIgnErr
  141. // Routers.
  142. m.Get("/", ignSignIn, routers.Home)
  143. m.Get("/explore", ignSignIn, routers.Explore)
  144. m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
  145. m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  146. m.Group("", func() {
  147. m.Get("/pulls", user.Pulls)
  148. m.Get("/issues", user.Issues)
  149. }, reqSignIn)
  150. // API.
  151. // FIXME: custom form error response.
  152. m.Group("/api", func() {
  153. m.Group("/v1", func() {
  154. // Miscellaneous.
  155. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  156. m.Post("/markdown/raw", v1.MarkdownRaw)
  157. // Users.
  158. m.Group("/users", func() {
  159. m.Get("/search", v1.SearchUsers)
  160. })
  161. // Repositories.
  162. m.Get("/user/repos", middleware.ApiReqToken(), v1.ListMyRepos)
  163. m.Group("/repos", func() {
  164. m.Get("/search", v1.SearchRepos)
  165. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.Migrate)
  166. m.Group("/:username/:reponame", func() {
  167. m.Combo("/hooks").Get(v1.ListRepoHooks).Post(bind(v1.CreateRepoHookForm{}), v1.CreateRepoHook)
  168. m.Patch("/hooks/:id:int", bind(v1.EditRepoHookForm{}), v1.EditRepoHook)
  169. }, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
  170. })
  171. m.Any("/*", func(ctx *middleware.Context) {
  172. ctx.JSON(404, &base.ApiJsonErr{"Not Found", base.DOC_URL})
  173. })
  174. })
  175. })
  176. // User.
  177. m.Group("/user", func() {
  178. m.Get("/login", user.SignIn)
  179. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  180. m.Get("/login/:name", user.SocialSignIn)
  181. m.Get("/sign_up", user.SignUp)
  182. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  183. m.Get("/reset_password", user.ResetPasswd)
  184. m.Post("/reset_password", user.ResetPasswdPost)
  185. }, reqSignOut)
  186. m.Group("/user/settings", func() {
  187. m.Get("", user.Settings)
  188. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  189. m.Get("/password", user.SettingsPassword)
  190. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  191. m.Get("/ssh", user.SettingsSSHKeys)
  192. m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  193. m.Get("/social", user.SettingsSocial)
  194. m.Combo("/applications").Get(user.SettingsApplications).Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  195. m.Route("/delete", "GET,POST", user.SettingsDelete)
  196. }, reqSignIn)
  197. m.Group("/user", func() {
  198. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  199. m.Any("/activate", user.Activate)
  200. m.Get("/email2user", user.Email2User)
  201. m.Get("/forget_password", user.ForgotPasswd)
  202. m.Post("/forget_password", user.ForgotPasswdPost)
  203. m.Get("/logout", user.SignOut)
  204. })
  205. // Gravatar service.
  206. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  207. os.MkdirAll("public/img/avatar/", os.ModePerm)
  208. m.Get("/avatar/:hash", avt.ServeHTTP)
  209. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  210. m.Group("/admin", func() {
  211. m.Get("", adminReq, admin.Dashboard)
  212. m.Get("/config", admin.Config)
  213. m.Get("/monitor", admin.Monitor)
  214. m.Group("/users", func() {
  215. m.Get("", admin.Users)
  216. m.Get("/new", admin.NewUser)
  217. m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  218. m.Get("/:userid", admin.EditUser)
  219. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  220. m.Post("/:userid/delete", admin.DeleteUser)
  221. })
  222. m.Group("/orgs", func() {
  223. m.Get("", admin.Organizations)
  224. })
  225. m.Group("/repos", func() {
  226. m.Get("", admin.Repositories)
  227. })
  228. m.Group("/auths", func() {
  229. m.Get("", admin.Authentications)
  230. m.Get("/new", admin.NewAuthSource)
  231. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  232. m.Get("/:authid", admin.EditAuthSource)
  233. m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  234. m.Post("/:authid/delete", admin.DeleteAuthSource)
  235. })
  236. m.Group("/notices", func() {
  237. m.Get("", admin.Notices)
  238. m.Get("/:id:int/delete", admin.DeleteNotice)
  239. })
  240. }, adminReq)
  241. m.Get("/:username", ignSignIn, user.Profile)
  242. if macaron.Env == macaron.DEV {
  243. m.Get("/template/*", dev.TemplatePreview)
  244. }
  245. reqTrueOwner := middleware.RequireTrueOwner()
  246. // Organization.
  247. m.Group("/org", func() {
  248. m.Get("/create", org.Create)
  249. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  250. m.Group("/:org", func() {
  251. m.Get("/dashboard", user.Dashboard)
  252. m.Get("/members", org.Members)
  253. m.Get("/members/action/:action", org.MembersAction)
  254. m.Get("/teams", org.Teams)
  255. m.Get("/teams/:team", org.TeamMembers)
  256. m.Get("/teams/:team/repositories", org.TeamRepositories)
  257. m.Get("/teams/:team/action/:action", org.TeamsAction)
  258. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  259. }, middleware.OrgAssignment(true, true))
  260. m.Group("/:org", func() {
  261. m.Get("/teams/new", org.NewTeam)
  262. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  263. m.Get("/teams/:team/edit", org.EditTeam)
  264. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  265. m.Post("/teams/:team/delete", org.DeleteTeam)
  266. m.Group("/settings", func() {
  267. m.Get("", org.Settings)
  268. m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  269. m.Get("/hooks", org.SettingsHooks)
  270. m.Get("/hooks/new", repo.WebHooksNew)
  271. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  272. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  273. m.Get("/hooks/:id", repo.WebHooksEdit)
  274. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  275. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  276. m.Route("/delete", "GET,POST", org.SettingsDelete)
  277. })
  278. m.Route("/invitations/new", "GET,POST", org.Invitation)
  279. }, middleware.OrgAssignment(true, true, true))
  280. }, reqSignIn)
  281. m.Group("/org", func() {
  282. m.Get("/:org", org.Home)
  283. }, middleware.OrgAssignment(true))
  284. // Repository.
  285. m.Group("/repo", func() {
  286. m.Get("/create", repo.Create)
  287. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  288. m.Get("/migrate", repo.Migrate)
  289. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  290. m.Get("/fork", repo.Fork)
  291. m.Post("/fork", bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  292. }, reqSignIn)
  293. m.Group("/:username/:reponame", func() {
  294. m.Get("/settings", repo.Settings)
  295. m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  296. m.Group("/settings", func() {
  297. m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  298. m.Get("/hooks", repo.Webhooks)
  299. m.Get("/hooks/new", repo.WebHooksNew)
  300. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  301. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  302. m.Get("/hooks/:id", repo.WebHooksEdit)
  303. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  304. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  305. m.Group("/hooks/git", func() {
  306. m.Get("", repo.GitHooks)
  307. m.Get("/:name", repo.GitHooksEdit)
  308. m.Post("/:name", repo.GitHooksEditPost)
  309. }, middleware.GitHookService())
  310. })
  311. }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
  312. m.Group("/:username/:reponame", func() {
  313. m.Get("/action/:action", repo.Action)
  314. m.Group("/issues", func() {
  315. m.Get("/new", repo.CreateIssue)
  316. m.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  317. m.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  318. m.Post("/:index/label", repo.UpdateIssueLabel)
  319. m.Post("/:index/milestone", repo.UpdateIssueMilestone)
  320. m.Post("/:index/assignee", repo.UpdateAssignee)
  321. m.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  322. m.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  323. m.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  324. m.Post("/labels/delete", repo.DeleteLabel)
  325. m.Get("/milestones/new", repo.NewMilestone)
  326. m.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  327. m.Get("/milestones/:index/edit", repo.UpdateMilestone)
  328. m.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  329. m.Get("/milestones/:index/:action", repo.UpdateMilestone)
  330. })
  331. m.Post("/comment/:action", repo.Comment)
  332. m.Get("/releases/new", repo.NewRelease)
  333. m.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  334. m.Get("/releases/edit/:tagname", repo.EditRelease)
  335. m.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  336. }, reqSignIn, middleware.RepoAssignment(true))
  337. m.Group("/:username/:reponame", func() {
  338. m.Get("/releases", repo.Releases)
  339. m.Get("/issues", repo.Issues)
  340. m.Get("/issues/:index", repo.ViewIssue)
  341. m.Get("/issues/milestones", repo.Milestones)
  342. m.Get("/pulls", repo.Pulls)
  343. m.Get("/branches", repo.Branches)
  344. m.Get("/archive/*", repo.Download)
  345. m.Get("/issues2/", repo.Issues2)
  346. m.Group("", func() {
  347. m.Get("/src/*", repo.Home)
  348. m.Get("/raw/*", repo.SingleDownload)
  349. m.Get("/commits/*", repo.RefCommits)
  350. m.Get("/commit/*", repo.Diff)
  351. }, middleware.RepoRef())
  352. m.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
  353. }, ignSignIn, middleware.RepoAssignment(true))
  354. m.Group("/:username", func() {
  355. m.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef(), repo.Home)
  356. m.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
  357. })
  358. // robots.txt
  359. m.Get("/robots.txt", func(ctx *middleware.Context) {
  360. if setting.HasRobotsTxt {
  361. ctx.ServeFile(path.Join(setting.CustomPath, "robots.txt"))
  362. } else {
  363. ctx.Error(404)
  364. }
  365. })
  366. // Not found handler.
  367. m.NotFound(routers.NotFound)
  368. var err error
  369. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  370. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  371. switch setting.Protocol {
  372. case setting.HTTP:
  373. err = http.ListenAndServe(listenAddr, m)
  374. case setting.HTTPS:
  375. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  376. case setting.FCGI:
  377. err = fcgi.Serve(nil, m)
  378. default:
  379. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  380. }
  381. if err != nil {
  382. log.Fatal(4, "Fail to start server: %v", err)
  383. }
  384. }