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

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