web.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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/gogits/gogs/modules/auth"
  20. "github.com/gogits/gogs/modules/auth/apiv1"
  21. "github.com/gogits/gogs/modules/avatar"
  22. "github.com/gogits/gogs/modules/base"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/middleware"
  25. "github.com/gogits/gogs/modules/middleware/binding"
  26. "github.com/gogits/gogs/modules/setting"
  27. "github.com/gogits/gogs/routers"
  28. "github.com/gogits/gogs/routers/admin"
  29. "github.com/gogits/gogs/routers/api/v1"
  30. "github.com/gogits/gogs/routers/dev"
  31. "github.com/gogits/gogs/routers/org"
  32. "github.com/gogits/gogs/routers/repo"
  33. "github.com/gogits/gogs/routers/user"
  34. )
  35. var CmdWeb = cli.Command{
  36. Name: "web",
  37. Usage: "Start Gogs web server",
  38. Description: `Gogs web server is the only thing you need to run,
  39. and it takes care of all the other things for you`,
  40. Action: runWeb,
  41. Flags: []cli.Flag{},
  42. }
  43. // checkVersion checks if binary matches the version of temolate files.
  44. func checkVersion() {
  45. data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION"))
  46. if err != nil {
  47. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  48. }
  49. if string(data) != setting.AppVer {
  50. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  51. }
  52. }
  53. // newMacaron initializes Macaron instance.
  54. func newMacaron() *macaron.Macaron {
  55. m := macaron.New()
  56. m.Use(macaron.Logger())
  57. m.Use(macaron.Recovery())
  58. if setting.EnableGzip {
  59. m.Use(macaron.Gzip())
  60. }
  61. m.Use(macaron.Static("public",
  62. macaron.StaticOptions{
  63. SkipLogging: !setting.DisableRouterLog,
  64. },
  65. ))
  66. m.Use(macaron.Renderer(macaron.RenderOptions{
  67. Directory: path.Join(setting.StaticRootPath, "templates"),
  68. Funcs: []template.FuncMap{base.TemplateFuncs},
  69. IndentJSON: macaron.Env != macaron.PROD,
  70. }))
  71. m.Use(i18n.I18n(i18n.LocaleOptions{
  72. Langs: setting.Langs,
  73. Names: setting.Names,
  74. Redirect: true,
  75. }))
  76. m.Use(cache.Cacher(cache.Options{
  77. Adapter: setting.CacheAdapter,
  78. Interval: setting.CacheInternal,
  79. Conn: setting.CacheConn,
  80. }))
  81. m.Use(captcha.Captchaer())
  82. m.Use(session.Sessioner(session.Options{
  83. Provider: setting.SessionProvider,
  84. Config: *setting.SessionConfig,
  85. }))
  86. m.Use(csrf.Generate(csrf.Options{
  87. Secret: setting.SecretKey,
  88. SetCookie: true,
  89. }))
  90. m.Use(middleware.Contexter())
  91. return m
  92. }
  93. func runWeb(*cli.Context) {
  94. routers.GlobalInit()
  95. checkVersion()
  96. m := newMacaron()
  97. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  98. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  99. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  100. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  101. bindIgnErr := binding.BindIgnErr
  102. // Routers.
  103. m.Get("/", ignSignIn, routers.Home)
  104. m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
  105. m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  106. m.Group("", func(r *macaron.Router) {
  107. r.Get("/pulls", user.Pulls)
  108. r.Get("/issues", user.Issues)
  109. }, reqSignIn)
  110. // API routers.
  111. m.Group("/api", func(_ *macaron.Router) {
  112. m.Group("/v1", func(r *macaron.Router) {
  113. // Miscellaneous.
  114. r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  115. r.Post("/markdown/raw", v1.MarkdownRaw)
  116. // Users.
  117. r.Get("/users/search", v1.SearchUsers)
  118. // Repositories.
  119. r.Get("/orgs/:org/repos/search", v1.SearchOrgRepositoreis)
  120. r.Any("/*", func(ctx *middleware.Context) {
  121. ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
  122. })
  123. })
  124. })
  125. // User routers.
  126. m.Group("/user", func(r *macaron.Router) {
  127. r.Get("/login", user.SignIn)
  128. r.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  129. r.Get("/login/:name", user.SocialSignIn)
  130. r.Get("/sign_up", user.SignUp)
  131. r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  132. r.Get("/reset_password", user.ResetPasswd)
  133. r.Post("/reset_password", user.ResetPasswdPost)
  134. }, reqSignOut)
  135. m.Group("/user", func(r *macaron.Router) {
  136. r.Get("/settings", user.Settings)
  137. r.Post("/settings", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  138. m.Group("/settings", func(r *macaron.Router) {
  139. r.Get("/password", user.SettingsPassword)
  140. r.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  141. r.Get("/ssh", user.SettingsSSHKeys)
  142. r.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  143. r.Get("/social", user.SettingsSocial)
  144. r.Get("/orgs", user.SettingsOrgs)
  145. r.Route("/delete", "GET,POST", user.SettingsDelete)
  146. })
  147. }, reqSignIn)
  148. m.Group("/user", func(r *macaron.Router) {
  149. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  150. r.Any("/activate", user.Activate)
  151. r.Get("/email2user", user.Email2User)
  152. r.Get("/forget_password", user.ForgotPasswd)
  153. r.Post("/forget_password", user.ForgotPasswdPost)
  154. r.Get("/logout", user.SignOut)
  155. })
  156. m.Get("/user/:username", ignSignIn, user.Profile) // TODO: Legacy
  157. // Gravatar service.
  158. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  159. os.MkdirAll("public/img/avatar/", os.ModePerm)
  160. m.Get("/avatar/:hash", avt.ServeHTTP)
  161. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  162. m.Get("/admin", adminReq, admin.Dashboard)
  163. m.Group("/admin", func(r *macaron.Router) {
  164. r.Get("/users", admin.Users)
  165. r.Get("/repos", admin.Repositories)
  166. r.Get("/auths", admin.Auths)
  167. r.Get("/config", admin.Config)
  168. r.Get("/monitor", admin.Monitor)
  169. }, adminReq)
  170. m.Group("/admin/users", func(r *macaron.Router) {
  171. r.Get("/new", admin.NewUser)
  172. r.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  173. r.Get("/:userid", admin.EditUser)
  174. r.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  175. r.Get("/:userid/delete", admin.DeleteUser)
  176. }, adminReq)
  177. m.Group("/admin/auths", func(r *macaron.Router) {
  178. r.Get("/new", admin.NewAuthSource)
  179. r.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  180. r.Get("/:authid", admin.EditAuthSource)
  181. r.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  182. r.Get("/:authid/delete", admin.DeleteAuthSource)
  183. }, adminReq)
  184. m.Get("/:username", ignSignIn, user.Profile)
  185. if macaron.Env == macaron.DEV {
  186. m.Get("/template/*", dev.TemplatePreview)
  187. dev.RegisterDebugRoutes(m)
  188. }
  189. reqTrueOwner := middleware.RequireTrueOwner()
  190. // Organization routers.
  191. m.Group("/org", func(r *macaron.Router) {
  192. r.Get("/create", org.Create)
  193. r.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  194. r.Get("/:org", org.Home)
  195. r.Get("/:org/dashboard", user.Dashboard)
  196. r.Get("/:org/members", org.Members)
  197. r.Get("/:org/teams", org.Teams)
  198. r.Get("/:org/teams/new", org.NewTeam)
  199. r.Post("/:org/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  200. r.Get("/:org/teams/:team/edit", org.EditTeam)
  201. r.Get("/:org/team/:team", org.SingleTeam)
  202. r.Get("/:org/settings", org.Settings)
  203. r.Post("/:org/settings", bindIgnErr(auth.OrgSettingForm{}), org.SettingsPost)
  204. r.Post("/:org/settings/delete", org.DeletePost)
  205. }, reqSignIn)
  206. // Repository routers.
  207. m.Group("/repo", func(r *macaron.Router) {
  208. r.Get("/create", repo.Create)
  209. r.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  210. r.Get("/migrate", repo.Migrate)
  211. r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  212. }, reqSignIn)
  213. m.Group("/:username/:reponame", func(r *macaron.Router) {
  214. r.Get("/settings", repo.Settings)
  215. r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  216. m.Group("/settings", func(r *macaron.Router) {
  217. r.Get("/collaboration", repo.Collaboration)
  218. r.Post("/collaboration", repo.CollaborationPost)
  219. r.Get("/hooks", repo.WebHooks)
  220. r.Get("/hooks/add", repo.WebHooksAdd)
  221. r.Post("/hooks/add", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksAddPost)
  222. r.Get("/hooks/:id", repo.WebHooksEdit)
  223. r.Post("/hooks/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  224. })
  225. }, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
  226. m.Group("/:username/:reponame", func(r *macaron.Router) {
  227. // r.Get("/action/:action", repo.Action)
  228. m.Group("/issues", func(r *macaron.Router) {
  229. r.Get("/new", repo.CreateIssue)
  230. r.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  231. r.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  232. r.Post("/:index/label", repo.UpdateIssueLabel)
  233. r.Post("/:index/milestone", repo.UpdateIssueMilestone)
  234. r.Post("/:index/assignee", repo.UpdateAssignee)
  235. r.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  236. r.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  237. r.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  238. r.Post("/labels/delete", repo.DeleteLabel)
  239. r.Get("/milestones", repo.Milestones)
  240. r.Get("/milestones/new", repo.NewMilestone)
  241. r.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  242. r.Get("/milestones/:index/edit", repo.UpdateMilestone)
  243. r.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  244. r.Get("/milestones/:index/:action", repo.UpdateMilestone)
  245. })
  246. r.Post("/comment/:action", repo.Comment)
  247. r.Get("/releases/new", repo.NewRelease)
  248. r.Get("/releases/edit/:tagname", repo.EditRelease)
  249. }, reqSignIn, middleware.RepoAssignment(true))
  250. m.Group("/:username/:reponame", func(r *macaron.Router) {
  251. r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  252. r.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  253. }, reqSignIn, middleware.RepoAssignment(true, true))
  254. m.Group("/:username/:reponame", func(r *macaron.Router) {
  255. r.Get("/issues", repo.Issues)
  256. r.Get("/issues/:index", repo.ViewIssue)
  257. r.Get("/pulls", repo.Pulls)
  258. r.Get("/branches", repo.Branches)
  259. }, ignSignIn, middleware.RepoAssignment(true))
  260. m.Group("/:username/:reponame", func(r *macaron.Router) {
  261. r.Get("/src/:branchname", repo.Home)
  262. r.Get("/src/:branchname/*", repo.Home)
  263. r.Get("/raw/:branchname/*", repo.SingleDownload)
  264. r.Get("/commits/:branchname", repo.Commits)
  265. r.Get("/commits/:branchname/search", repo.SearchCommits)
  266. r.Get("/commits/:branchname/*", repo.FileHistory)
  267. r.Get("/commit/:branchname", repo.Diff)
  268. r.Get("/commit/:branchname/*", repo.Diff)
  269. r.Get("/releases", repo.Releases)
  270. r.Get("/archive/*.*", repo.Download)
  271. }, ignSignIn, middleware.RepoAssignment(true, true))
  272. m.Group("/:username", func(r *macaron.Router) {
  273. r.Get("/:reponame", middleware.RepoAssignment(true, true, true), repo.Home)
  274. m.Group("/:reponame", func(r *macaron.Router) {
  275. r.Any("/*", repo.Http)
  276. })
  277. }, ignSignInAndCsrf)
  278. // Not found handler.
  279. m.NotFound(routers.NotFound)
  280. var err error
  281. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  282. log.Info("Listen: %v://%s", setting.Protocol, listenAddr)
  283. switch setting.Protocol {
  284. case setting.HTTP:
  285. err = http.ListenAndServe(listenAddr, m)
  286. case setting.HTTPS:
  287. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  288. default:
  289. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  290. }
  291. if err != nil {
  292. log.Fatal(4, "Fail to start server: %v", err)
  293. }
  294. }