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

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