web.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. }))
  92. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  93. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  94. &toolbox.HealthCheckFuncDesc{
  95. Desc: "Database connection",
  96. Func: models.Ping,
  97. },
  98. },
  99. }))
  100. m.Use(middleware.Contexter())
  101. return m
  102. }
  103. func runWeb(*cli.Context) {
  104. routers.GlobalInit()
  105. checkVersion()
  106. m := newMacaron()
  107. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  108. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  109. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  110. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  111. bindIgnErr := binding.BindIgnErr
  112. // Routers.
  113. m.Get("/", ignSignIn, routers.Home)
  114. m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
  115. m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  116. m.Group("", func(r *macaron.Router) {
  117. r.Get("/pulls", user.Pulls)
  118. r.Get("/issues", user.Issues)
  119. }, reqSignIn)
  120. // API routers.
  121. m.Group("/api", func(_ *macaron.Router) {
  122. m.Group("/v1", func(r *macaron.Router) {
  123. // Miscellaneous.
  124. r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  125. r.Post("/markdown/raw", v1.MarkdownRaw)
  126. // Users.
  127. m.Group("/users", func(r *macaron.Router) {
  128. r.Get("/search", v1.SearchUsers)
  129. })
  130. // Repositories.
  131. m.Group("/repos", func(r *macaron.Router) {
  132. r.Get("/search", v1.SearchRepos)
  133. r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.Migrate)
  134. })
  135. r.Any("/*", func(ctx *middleware.Context) {
  136. ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
  137. })
  138. })
  139. })
  140. // User routers.
  141. m.Group("/user", func(r *macaron.Router) {
  142. r.Get("/login", user.SignIn)
  143. r.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  144. r.Get("/login/:name", user.SocialSignIn)
  145. r.Get("/sign_up", user.SignUp)
  146. r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  147. r.Get("/reset_password", user.ResetPasswd)
  148. r.Post("/reset_password", user.ResetPasswdPost)
  149. }, reqSignOut)
  150. m.Group("/user/settings", func(r *macaron.Router) {
  151. r.Get("", user.Settings)
  152. r.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  153. r.Get("/password", user.SettingsPassword)
  154. r.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  155. r.Get("/ssh", user.SettingsSSHKeys)
  156. r.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  157. r.Get("/social", user.SettingsSocial)
  158. r.Route("/delete", "GET,POST", user.SettingsDelete)
  159. }, reqSignIn)
  160. m.Group("/user", func(r *macaron.Router) {
  161. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  162. r.Any("/activate", user.Activate)
  163. r.Get("/email2user", user.Email2User)
  164. r.Get("/forget_password", user.ForgotPasswd)
  165. r.Post("/forget_password", user.ForgotPasswdPost)
  166. r.Get("/logout", user.SignOut)
  167. })
  168. m.Get("/user/:username", ignSignIn, user.Profile) // TODO: Legacy
  169. // Gravatar service.
  170. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  171. os.MkdirAll("public/img/avatar/", os.ModePerm)
  172. m.Get("/avatar/:hash", avt.ServeHTTP)
  173. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  174. m.Group("/admin", func(r *macaron.Router) {
  175. m.Get("", adminReq, admin.Dashboard)
  176. r.Get("/config", admin.Config)
  177. r.Get("/monitor", admin.Monitor)
  178. m.Group("/users", func(r *macaron.Router) {
  179. r.Get("", admin.Users)
  180. r.Get("/new", admin.NewUser)
  181. r.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  182. r.Get("/:userid", admin.EditUser)
  183. r.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  184. r.Post("/:userid/delete", admin.DeleteUser)
  185. })
  186. m.Group("/orgs", func(r *macaron.Router) {
  187. r.Get("", admin.Organizations)
  188. })
  189. m.Group("/repos", func(r *macaron.Router) {
  190. r.Get("", admin.Repositories)
  191. })
  192. m.Group("/auths", func(r *macaron.Router) {
  193. r.Get("", admin.Authentications)
  194. r.Get("/new", admin.NewAuthSource)
  195. r.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  196. r.Get("/:authid", admin.EditAuthSource)
  197. r.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  198. r.Post("/:authid/delete", admin.DeleteAuthSource)
  199. })
  200. }, adminReq)
  201. m.Get("/:username", ignSignIn, user.Profile)
  202. if macaron.Env == macaron.DEV {
  203. m.Get("/template/*", dev.TemplatePreview)
  204. }
  205. reqTrueOwner := middleware.RequireTrueOwner()
  206. // Organization routers.
  207. m.Group("/org", func(r *macaron.Router) {
  208. r.Get("/create", org.Create)
  209. r.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  210. m.Group("/:org", func(r *macaron.Router) {
  211. r.Get("/dashboard", user.Dashboard)
  212. r.Get("/members", org.Members)
  213. r.Get("/members/action/:action", org.MembersAction)
  214. r.Get("/teams", org.Teams)
  215. r.Get("/teams/:team", org.TeamMembers)
  216. r.Get("/teams/:team/repositories", org.TeamRepositories)
  217. r.Get("/teams/:team/action/:action", org.TeamsAction)
  218. r.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  219. }, middleware.OrgAssignment(true, true))
  220. m.Group("/:org", func(r *macaron.Router) {
  221. r.Get("/teams/new", org.NewTeam)
  222. r.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  223. r.Get("/teams/:team/edit", org.EditTeam)
  224. r.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  225. r.Post("/teams/:team/delete", org.DeleteTeam)
  226. m.Group("/settings", func(r *macaron.Router) {
  227. r.Get("", org.Settings)
  228. r.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  229. r.Route("/delete", "GET,POST", org.SettingsDelete)
  230. })
  231. r.Route("/invitations/new", "GET,POST", org.Invitation)
  232. }, middleware.OrgAssignment(true, true, true))
  233. }, reqSignIn)
  234. m.Group("/org", func(r *macaron.Router) {
  235. r.Get("/:org", org.Home)
  236. }, middleware.OrgAssignment(true))
  237. // Repository routers.
  238. m.Group("/repo", func(r *macaron.Router) {
  239. r.Get("/create", repo.Create)
  240. r.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  241. r.Get("/migrate", repo.Migrate)
  242. r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  243. }, reqSignIn)
  244. m.Group("/:username/:reponame", func(r *macaron.Router) {
  245. r.Get("/settings", repo.Settings)
  246. r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  247. m.Group("/settings", func(r *macaron.Router) {
  248. r.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  249. r.Get("/hooks", repo.Webhooks)
  250. r.Get("/hooks/new", repo.WebHooksNew)
  251. r.Post("/hooks/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  252. r.Get("/hooks/:id", repo.WebHooksEdit)
  253. r.Post("/hooks/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  254. })
  255. }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
  256. m.Group("/:username/:reponame", func(r *macaron.Router) {
  257. r.Get("/action/:action", repo.Action)
  258. m.Group("/issues", func(r *macaron.Router) {
  259. r.Get("/new", repo.CreateIssue)
  260. r.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  261. r.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  262. r.Post("/:index/label", repo.UpdateIssueLabel)
  263. r.Post("/:index/milestone", repo.UpdateIssueMilestone)
  264. r.Post("/:index/assignee", repo.UpdateAssignee)
  265. r.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  266. r.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  267. r.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  268. r.Post("/labels/delete", repo.DeleteLabel)
  269. r.Get("/milestones", repo.Milestones)
  270. r.Get("/milestones/new", repo.NewMilestone)
  271. r.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  272. r.Get("/milestones/:index/edit", repo.UpdateMilestone)
  273. r.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  274. r.Get("/milestones/:index/:action", repo.UpdateMilestone)
  275. })
  276. r.Post("/comment/:action", repo.Comment)
  277. r.Get("/releases/new", repo.NewRelease)
  278. r.Get("/releases/edit/:tagname", repo.EditRelease)
  279. }, reqSignIn, middleware.RepoAssignment(true))
  280. m.Group("/:username/:reponame", func(r *macaron.Router) {
  281. r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  282. r.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  283. }, reqSignIn, middleware.RepoAssignment(true, true))
  284. m.Group("/:username/:reponame", func(r *macaron.Router) {
  285. r.Get("/issues", repo.Issues)
  286. r.Get("/issues/:index", repo.ViewIssue)
  287. r.Get("/pulls", repo.Pulls)
  288. r.Get("/branches", repo.Branches)
  289. }, ignSignIn, middleware.RepoAssignment(true))
  290. m.Group("/:username/:reponame", func(r *macaron.Router) {
  291. r.Get("/src/:branchname", repo.Home)
  292. r.Get("/src/:branchname/*", repo.Home)
  293. r.Get("/raw/:branchname/*", repo.SingleDownload)
  294. r.Get("/commits/:branchname", repo.Commits)
  295. r.Get("/commits/:branchname/search", repo.SearchCommits)
  296. r.Get("/commits/:branchname/*", repo.FileHistory)
  297. r.Get("/commit/:branchname", repo.Diff)
  298. r.Get("/commit/:branchname/*", repo.Diff)
  299. r.Get("/releases", repo.Releases)
  300. r.Get("/archive/*.*", repo.Download)
  301. }, ignSignIn, middleware.RepoAssignment(true, true))
  302. m.Group("/:username", func(r *macaron.Router) {
  303. r.Get("/:reponame", middleware.RepoAssignment(true, true, true), repo.Home)
  304. m.Group("/:reponame", func(r *macaron.Router) {
  305. r.Any("/*", repo.Http)
  306. })
  307. }, ignSignInAndCsrf)
  308. // Not found handler.
  309. m.NotFound(routers.NotFound)
  310. var err error
  311. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  312. log.Info("Listen: %v://%s", setting.Protocol, listenAddr)
  313. switch setting.Protocol {
  314. case setting.HTTP:
  315. err = http.ListenAndServe(listenAddr, m)
  316. case setting.HTTPS:
  317. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  318. default:
  319. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  320. }
  321. if err != nil {
  322. log.Fatal(4, "Fail to start server: %v", err)
  323. }
  324. }