web.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. "io/ioutil"
  9. "net/http"
  10. "net/http/fcgi"
  11. "os"
  12. "path"
  13. "strings"
  14. "github.com/codegangsta/cli"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "gopkg.in/ini.v1"
  26. "gopkg.in/macaron.v1"
  27. "github.com/gogits/git-module"
  28. "github.com/gogits/go-gogs-client"
  29. "github.com/gogits/gogs/models"
  30. "github.com/gogits/gogs/modules/auth"
  31. "github.com/gogits/gogs/modules/bindata"
  32. "github.com/gogits/gogs/modules/context"
  33. "github.com/gogits/gogs/modules/log"
  34. "github.com/gogits/gogs/modules/setting"
  35. "github.com/gogits/gogs/modules/template"
  36. "github.com/gogits/gogs/routers"
  37. "github.com/gogits/gogs/routers/admin"
  38. apiv1 "github.com/gogits/gogs/routers/api/v1"
  39. "github.com/gogits/gogs/routers/dev"
  40. "github.com/gogits/gogs/routers/org"
  41. "github.com/gogits/gogs/routers/repo"
  42. "github.com/gogits/gogs/routers/user"
  43. )
  44. var CmdWeb = cli.Command{
  45. Name: "web",
  46. Usage: "Start Gogs web server",
  47. Description: `Gogs web server is the only thing you need to run,
  48. and it takes care of all the other things for you`,
  49. Action: runWeb,
  50. Flags: []cli.Flag{
  51. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  52. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  53. },
  54. }
  55. type VerChecker struct {
  56. ImportPath string
  57. Version func() string
  58. Expected string
  59. }
  60. // checkVersion checks if binary matches the version of templates files.
  61. func checkVersion() {
  62. // Templates.
  63. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  64. if err != nil {
  65. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  66. }
  67. if strings.TrimSpace(string(data)) != setting.AppVer {
  68. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  69. }
  70. // Check dependency version.
  71. checkers := []VerChecker{
  72. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.5.5"},
  73. {"github.com/go-macaron/binding", binding.Version, "0.3.2"},
  74. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  75. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  76. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  77. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  78. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  79. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  80. {"gopkg.in/macaron.v1", macaron.Version, "1.1.4"},
  81. {"github.com/gogits/git-module", git.Version, "0.3.3"},
  82. {"github.com/gogits/go-gogs-client", gogs.Version, "0.7.4"},
  83. }
  84. for _, c := range checkers {
  85. if !version.Compare(c.Version(), c.Expected, ">=") {
  86. log.Fatal(4, `Dependency outdated!
  87. Package '%s' current version (%s) is below requirement (%s),
  88. please use following command to update this package and recompile Gogs:
  89. go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
  90. }
  91. }
  92. }
  93. // newMacaron initializes Macaron instance.
  94. func newMacaron() *macaron.Macaron {
  95. m := macaron.New()
  96. if !setting.DisableRouterLog {
  97. m.Use(macaron.Logger())
  98. }
  99. m.Use(macaron.Recovery())
  100. if setting.EnableGzip {
  101. m.Use(gzip.Gziper())
  102. }
  103. if setting.Protocol == setting.FCGI {
  104. m.SetURLPrefix(setting.AppSubUrl)
  105. }
  106. m.Use(macaron.Static(
  107. path.Join(setting.StaticRootPath, "public"),
  108. macaron.StaticOptions{
  109. SkipLogging: setting.DisableRouterLog,
  110. },
  111. ))
  112. m.Use(macaron.Static(
  113. setting.AvatarUploadPath,
  114. macaron.StaticOptions{
  115. Prefix: "avatars",
  116. SkipLogging: setting.DisableRouterLog,
  117. },
  118. ))
  119. funcMap := template.NewFuncMap()
  120. m.Use(macaron.Renderer(macaron.RenderOptions{
  121. Directory: path.Join(setting.StaticRootPath, "templates"),
  122. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  123. Funcs: funcMap,
  124. IndentJSON: macaron.Env != macaron.PROD,
  125. }))
  126. models.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  127. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  128. localeNames, err := bindata.AssetDir("conf/locale")
  129. if err != nil {
  130. log.Fatal(4, "Fail to list locale files: %v", err)
  131. }
  132. localFiles := make(map[string][]byte)
  133. for _, name := range localeNames {
  134. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  135. }
  136. m.Use(i18n.I18n(i18n.Options{
  137. SubURL: setting.AppSubUrl,
  138. Files: localFiles,
  139. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  140. Langs: setting.Langs,
  141. Names: setting.Names,
  142. DefaultLang: "en-US",
  143. Redirect: true,
  144. }))
  145. m.Use(cache.Cacher(cache.Options{
  146. Adapter: setting.CacheAdapter,
  147. AdapterConfig: setting.CacheConn,
  148. Interval: setting.CacheInternal,
  149. }))
  150. m.Use(captcha.Captchaer(captcha.Options{
  151. SubURL: setting.AppSubUrl,
  152. }))
  153. m.Use(session.Sessioner(setting.SessionConfig))
  154. m.Use(csrf.Csrfer(csrf.Options{
  155. Secret: setting.SecretKey,
  156. Cookie: setting.CSRFCookieName,
  157. SetCookie: true,
  158. Header: "X-Csrf-Token",
  159. CookiePath: setting.AppSubUrl,
  160. }))
  161. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  162. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  163. &toolbox.HealthCheckFuncDesc{
  164. Desc: "Database connection",
  165. Func: models.Ping,
  166. },
  167. },
  168. }))
  169. m.Use(context.Contexter())
  170. return m
  171. }
  172. func runWeb(ctx *cli.Context) error {
  173. if ctx.IsSet("config") {
  174. setting.CustomConf = ctx.String("config")
  175. }
  176. routers.GlobalInit()
  177. checkVersion()
  178. m := newMacaron()
  179. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  180. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  181. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  182. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  183. bindIgnErr := binding.BindIgnErr
  184. // FIXME: not all routes need go through same middlewares.
  185. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  186. // Routers.
  187. m.Get("/", ignSignIn, routers.Home)
  188. <<<<<<< HEAD
  189. m.Get("/explore", ignSignIn, routers.Explore)
  190. m.Get("/help", ignSignIn, routers.Help)
  191. m.Get("/about", ignSignIn, routers.About)
  192. m.Get("/tos", ignSignIn, routers.Tos)
  193. m.Get("/outages", ignSignIn, routers.Outages)
  194. m.Combo("/install", routers.InstallInit).
  195. Get(routers.Install).
  196. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  197. m.Group("", func() {
  198. m.Get("/pulls", user.Pulls)
  199. m.Get("/issues", user.Issues)
  200. }, reqSignIn)
  201. // API.
  202. // FIXME: custom form error response.
  203. m.Group("/api", func() {
  204. m.Group("/v1", func() {
  205. // Miscellaneous.
  206. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  207. m.Post("/markdown/raw", v1.MarkdownRaw)
  208. // Users.
  209. m.Group("/users", func() {
  210. m.Get("/search", v1.SearchUsers)
  211. m.Group("/:username", func() {
  212. m.Get("", v1.GetUserInfo)
  213. m.Group("/tokens", func() {
  214. m.Combo("").Get(v1.ListAccessTokens).Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
  215. }, middleware.ApiReqBasicAuth())
  216. })
  217. })
  218. // Repositories.
  219. m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
  220. m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
  221. m.Group("/repos", func() {
  222. m.Get("/search", v1.SearchRepos)
  223. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
  224. m.Group("/:username/:reponame", func() {
  225. m.Combo("/hooks").Get(v1.ListRepoHooks).Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
  226. m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
  227. m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
  228. }, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
  229. })
  230. m.Any("/*", func(ctx *middleware.Context) {
  231. ctx.HandleAPI(404, "Page not found")
  232. })
  233. =======
  234. m.Group("/explore", func() {
  235. m.Get("", func(ctx *context.Context) {
  236. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  237. >>>>>>> upstream/master
  238. })
  239. m.Get("/repos", routers.ExploreRepos)
  240. m.Get("/users", routers.ExploreUsers)
  241. }, ignSignIn)
  242. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  243. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  244. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  245. // ***** START: User *****
  246. m.Group("/user", func() {
  247. m.Get("/login", user.SignIn)
  248. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  249. m.Get("/sign_up", user.SignUp)
  250. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  251. m.Get("/reset_password", user.ResetPasswd)
  252. m.Post("/reset_password", user.ResetPasswdPost)
  253. }, reqSignOut)
  254. m.Group("/user/settings", func() {
  255. m.Get("", user.Settings)
  256. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  257. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  258. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  259. m.Combo("/email").Get(user.SettingsEmails).
  260. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  261. m.Post("/email/delete", user.DeleteEmail)
  262. m.Get("/password", user.SettingsPassword)
  263. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  264. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  265. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  266. m.Post("/ssh/delete", user.DeleteSSHKey)
  267. m.Combo("/applications").Get(user.SettingsApplications).
  268. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  269. m.Post("/applications/delete", user.SettingsDeleteApplication)
  270. m.Route("/delete", "GET,POST", user.SettingsDelete)
  271. }, reqSignIn, func(ctx *context.Context) {
  272. ctx.Data["PageIsUserSettings"] = true
  273. })
  274. m.Group("/user", func() {
  275. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  276. m.Any("/activate", user.Activate)
  277. m.Any("/activate_email", user.ActivateEmail)
  278. m.Get("/email2user", user.Email2User)
  279. m.Get("/forget_password", user.ForgotPasswd)
  280. m.Post("/forget_password", user.ForgotPasswdPost)
  281. m.Get("/logout", user.SignOut)
  282. })
  283. // ***** END: User *****
  284. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  285. // ***** START: Admin *****
  286. m.Group("/admin", func() {
  287. m.Get("", adminReq, admin.Dashboard)
  288. m.Get("/config", admin.Config)
  289. m.Post("/config/test_mail", admin.SendTestMail)
  290. m.Get("/monitor", admin.Monitor)
  291. m.Group("/users", func() {
  292. m.Get("", admin.Users)
  293. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  294. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  295. m.Post("/:userid/delete", admin.DeleteUser)
  296. })
  297. m.Group("/orgs", func() {
  298. m.Get("", admin.Organizations)
  299. })
  300. m.Group("/repos", func() {
  301. m.Get("", admin.Repos)
  302. m.Post("/delete", admin.DeleteRepo)
  303. })
  304. m.Group("/auths", func() {
  305. m.Get("", admin.Authentications)
  306. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  307. m.Combo("/:authid").Get(admin.EditAuthSource).
  308. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  309. m.Post("/:authid/delete", admin.DeleteAuthSource)
  310. })
  311. m.Group("/notices", func() {
  312. m.Get("", admin.Notices)
  313. m.Post("/delete", admin.DeleteNotices)
  314. m.Get("/empty", admin.EmptyNotices)
  315. })
  316. }, adminReq)
  317. // ***** END: Admin *****
  318. m.Group("", func() {
  319. m.Group("/:username", func() {
  320. m.Get("", user.Profile)
  321. m.Get("/followers", user.Followers)
  322. m.Get("/following", user.Following)
  323. m.Get("/stars", user.Stars)
  324. })
  325. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  326. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  327. if err != nil {
  328. if models.IsErrAttachmentNotExist(err) {
  329. ctx.Error(404)
  330. } else {
  331. ctx.Handle(500, "GetAttachmentByUUID", err)
  332. }
  333. return
  334. }
  335. fr, err := os.Open(attach.LocalPath())
  336. if err != nil {
  337. ctx.Handle(500, "Open", err)
  338. return
  339. }
  340. defer fr.Close()
  341. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  342. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  343. // We must put the name in " manually.
  344. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  345. ctx.Handle(500, "ServeData", err)
  346. return
  347. }
  348. })
  349. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  350. }, ignSignIn)
  351. m.Group("/:username", func() {
  352. m.Get("/action/:action", user.Action)
  353. }, reqSignIn)
  354. if macaron.Env == macaron.DEV {
  355. m.Get("/template/*", dev.TemplatePreview)
  356. }
  357. reqRepoAdmin := context.RequireRepoAdmin()
  358. reqRepoWriter := context.RequireRepoWriter()
  359. // ***** START: Organization *****
  360. m.Group("/org", func() {
  361. m.Get("/create", org.Create)
  362. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  363. m.Group("/:org", func() {
  364. m.Get("/dashboard", user.Dashboard)
  365. m.Get("/^:type(issues|pulls)$", user.Issues)
  366. m.Get("/members", org.Members)
  367. m.Get("/members/action/:action", org.MembersAction)
  368. m.Get("/teams", org.Teams)
  369. }, context.OrgAssignment(true))
  370. m.Group("/:org", func() {
  371. m.Get("/teams/:team", org.TeamMembers)
  372. m.Get("/teams/:team/repositories", org.TeamRepositories)
  373. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  374. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  375. }, context.OrgAssignment(true, false, true))
  376. m.Group("/:org", func() {
  377. m.Get("/teams/new", org.NewTeam)
  378. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  379. m.Get("/teams/:team/edit", org.EditTeam)
  380. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  381. m.Post("/teams/:team/delete", org.DeleteTeam)
  382. m.Group("/settings", func() {
  383. m.Combo("").Get(org.Settings).
  384. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  385. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  386. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  387. m.Group("/hooks", func() {
  388. m.Get("", org.Webhooks)
  389. m.Post("/delete", org.DeleteWebhook)
  390. m.Get("/:type/new", repo.WebhooksNew)
  391. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  392. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  393. m.Get("/:id", repo.WebHooksEdit)
  394. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  395. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  396. })
  397. m.Route("/delete", "GET,POST", org.SettingsDelete)
  398. })
  399. m.Route("/invitations/new", "GET,POST", org.Invitation)
  400. }, context.OrgAssignment(true, true))
  401. }, reqSignIn)
  402. // ***** END: Organization *****
  403. // ***** START: Repository *****
  404. m.Group("/repo", func() {
  405. m.Get("/create", repo.Create)
  406. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  407. m.Get("/migrate", repo.Migrate)
  408. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  409. m.Combo("/fork/:repoid").Get(repo.Fork).
  410. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  411. }, reqSignIn)
  412. m.Group("/:username/:reponame", func() {
  413. m.Group("/settings", func() {
  414. m.Combo("").Get(repo.Settings).
  415. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  416. m.Group("/collaboration", func() {
  417. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  418. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  419. m.Post("/delete", repo.DeleteCollaboration)
  420. })
  421. m.Group("/hooks", func() {
  422. m.Get("", repo.Webhooks)
  423. m.Post("/delete", repo.DeleteWebhook)
  424. m.Get("/:type/new", repo.WebhooksNew)
  425. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  426. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  427. m.Get("/:id", repo.WebHooksEdit)
  428. m.Post("/:id/test", repo.TestWebhook)
  429. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  430. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  431. m.Group("/git", func() {
  432. m.Get("", repo.GitHooks)
  433. m.Combo("/:name").Get(repo.GitHooksEdit).
  434. Post(repo.GitHooksEditPost)
  435. }, context.GitHookService())
  436. })
  437. m.Group("/keys", func() {
  438. m.Combo("").Get(repo.DeployKeys).
  439. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  440. m.Post("/delete", repo.DeleteDeployKey)
  441. })
  442. }, func(ctx *context.Context) {
  443. ctx.Data["PageIsSettings"] = true
  444. })
  445. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  446. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  447. m.Group("/:username/:reponame", func() {
  448. m.Group("/issues", func() {
  449. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  450. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  451. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  452. m.Group("/:index", func() {
  453. m.Post("/label", repo.UpdateIssueLabel)
  454. m.Post("/milestone", repo.UpdateIssueMilestone)
  455. m.Post("/assignee", repo.UpdateIssueAssignee)
  456. }, reqRepoWriter)
  457. m.Group("/:index", func() {
  458. m.Post("/title", repo.UpdateIssueTitle)
  459. m.Post("/content", repo.UpdateIssueContent)
  460. })
  461. })
  462. m.Post("/comments/:id", repo.UpdateCommentContent)
  463. m.Group("/labels", func() {
  464. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  465. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  466. m.Post("/delete", repo.DeleteLabel)
  467. }, reqRepoWriter, context.RepoRef())
  468. m.Group("/milestones", func() {
  469. m.Combo("/new").Get(repo.NewMilestone).
  470. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  471. m.Get("/:id/edit", repo.EditMilestone)
  472. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  473. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  474. m.Post("/delete", repo.DeleteMilestone)
  475. }, reqRepoWriter, context.RepoRef())
  476. m.Group("/releases", func() {
  477. m.Get("/new", repo.NewRelease)
  478. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  479. m.Get("/edit/:tagname", repo.EditRelease)
  480. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  481. m.Post("/delete", repo.DeleteRelease)
  482. }, reqRepoWriter, context.RepoRef())
  483. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  484. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  485. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  486. m.Group("/:username/:reponame", func() {
  487. m.Group("", func() {
  488. m.Get("/releases", repo.Releases)
  489. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  490. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  491. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  492. m.Get("/milestones", repo.Milestones)
  493. }, context.RepoRef())
  494. // m.Get("/branches", repo.Branches)
  495. m.Group("/wiki", func() {
  496. m.Get("/?:page", repo.Wiki)
  497. m.Get("/_pages", repo.WikiPages)
  498. m.Group("", func() {
  499. m.Combo("/_new").Get(repo.NewWiki).
  500. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  501. m.Combo("/:page/_edit").Get(repo.EditWiki).
  502. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  503. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  504. }, reqSignIn, reqRepoWriter)
  505. }, repo.MustEnableWiki, context.RepoRef())
  506. m.Get("/archive/*", repo.Download)
  507. m.Group("/pulls/:index", func() {
  508. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  509. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  510. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  511. }, repo.MustAllowPulls)
  512. m.Group("", func() {
  513. m.Get("/src/*", repo.Home)
  514. m.Get("/raw/*", repo.SingleDownload)
  515. m.Get("/commits/*", repo.RefCommits)
  516. m.Get("/commit/:sha([a-z0-9]{40})$", repo.Diff)
  517. m.Get("/forks", repo.Forks)
  518. }, context.RepoRef())
  519. m.Get("/commit/:sha([a-z0-9]{40})\\.:ext(patch|diff)", repo.RawDiff)
  520. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  521. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  522. m.Group("/:username/:reponame", func() {
  523. m.Get("/stars", repo.Stars)
  524. m.Get("/watchers", repo.Watchers)
  525. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  526. m.Group("/:username", func() {
  527. m.Group("/:reponame", func() {
  528. m.Get("", repo.Home)
  529. m.Get("\\.git$", repo.Home)
  530. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  531. m.Group("/:reponame", func() {
  532. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  533. m.Head("/tasks/trigger", repo.TriggerTask)
  534. })
  535. })
  536. // ***** END: Repository *****
  537. m.Group("/api", func() {
  538. apiv1.RegisterRoutes(m)
  539. }, ignSignIn)
  540. // robots.txt
  541. m.Get("/robots.txt", func(ctx *context.Context) {
  542. if setting.HasRobotsTxt {
  543. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  544. } else {
  545. ctx.Error(404)
  546. }
  547. })
  548. // Not found handler.
  549. m.NotFound(routers.NotFound)
  550. // Flag for port number in case first time run conflict.
  551. if ctx.IsSet("port") {
  552. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  553. setting.HttpPort = ctx.String("port")
  554. }
  555. var err error
  556. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  557. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  558. switch setting.Protocol {
  559. case setting.HTTP:
  560. err = http.ListenAndServe(listenAddr, m)
  561. case setting.HTTPS:
  562. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  563. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  564. case setting.FCGI:
  565. err = fcgi.Serve(nil, m)
  566. default:
  567. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  568. }
  569. if err != nil {
  570. log.Fatal(4, "Fail to start server: %v", err)
  571. }
  572. return nil
  573. }