web.go 16 KB

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