web.go 16 KB

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