web.go 16 KB

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