web.go 11 KB

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