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.

381 lines
13 KiB

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