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 12KB

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