web.go 16 KB

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