Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

install.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 routers
  5. import (
  6. "errors"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "gopkg.in/ini.v1"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/auth"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/context"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/user"
  22. )
  23. const (
  24. // tplInstall template for installation page
  25. tplInstall base.TplName = "install"
  26. )
  27. // InstallInit prepare for rendering installation page
  28. func InstallInit(ctx *context.Context) {
  29. if setting.InstallLock {
  30. ctx.Handle(404, "Install", errors.New("Installation is prohibited"))
  31. return
  32. }
  33. ctx.Data["Title"] = ctx.Tr("install.install")
  34. ctx.Data["PageIsInstall"] = true
  35. dbOpts := []string{"MySQL", "PostgreSQL", "MSSQL"}
  36. if models.EnableSQLite3 {
  37. dbOpts = append(dbOpts, "SQLite3")
  38. }
  39. if models.EnableTiDB {
  40. dbOpts = append(dbOpts, "TiDB")
  41. }
  42. ctx.Data["DbOptions"] = dbOpts
  43. }
  44. // Install render installation page
  45. func Install(ctx *context.Context) {
  46. form := auth.InstallForm{}
  47. // Database settings
  48. form.DbHost = models.DbCfg.Host
  49. form.DbUser = models.DbCfg.User
  50. form.DbName = models.DbCfg.Name
  51. form.DbPath = models.DbCfg.Path
  52. ctx.Data["CurDbOption"] = "MySQL"
  53. switch models.DbCfg.Type {
  54. case "postgres":
  55. ctx.Data["CurDbOption"] = "PostgreSQL"
  56. case "mssql":
  57. ctx.Data["CurDbOption"] = "MSSQL"
  58. case "sqlite3":
  59. if models.EnableSQLite3 {
  60. ctx.Data["CurDbOption"] = "SQLite3"
  61. }
  62. case "tidb":
  63. if models.EnableTiDB {
  64. ctx.Data["CurDbOption"] = "TiDB"
  65. }
  66. }
  67. // Application general settings
  68. form.AppName = setting.AppName
  69. form.RepoRootPath = setting.RepoRootPath
  70. form.LFSRootPath = setting.LFS.ContentPath
  71. // Note(unknown): it's hard for Windows users change a running user,
  72. // so just use current one if config says default.
  73. if setting.IsWindows && setting.RunUser == "git" {
  74. form.RunUser = user.CurrentUsername()
  75. } else {
  76. form.RunUser = setting.RunUser
  77. }
  78. form.Domain = setting.Domain
  79. form.SSHPort = setting.SSH.Port
  80. form.HTTPPort = setting.HTTPPort
  81. form.AppURL = setting.AppURL
  82. form.LogRootPath = setting.LogRootPath
  83. // E-mail service settings
  84. if setting.MailService != nil {
  85. form.SMTPHost = setting.MailService.Host
  86. form.SMTPFrom = setting.MailService.From
  87. form.SMTPUser = setting.MailService.User
  88. }
  89. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  90. form.MailNotify = setting.Service.EnableNotifyMail
  91. // Server and other services settings
  92. form.OfflineMode = setting.OfflineMode
  93. form.DisableGravatar = setting.DisableGravatar
  94. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  95. form.EnableOpenIDSignIn = true
  96. form.EnableOpenIDSignUp = true
  97. form.DisableRegistration = setting.Service.DisableRegistration
  98. form.EnableCaptcha = setting.Service.EnableCaptcha
  99. form.RequireSignInView = setting.Service.RequireSignInView
  100. form.DefaultKeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  101. form.DefaultAllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  102. form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
  103. form.NoReplyAddress = setting.Service.NoReplyAddress
  104. auth.AssignForm(form, ctx.Data)
  105. ctx.HTML(200, tplInstall)
  106. }
  107. // InstallPost response for submit install items
  108. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  109. var err error
  110. ctx.Data["CurDbOption"] = form.DbType
  111. if ctx.HasError() {
  112. if ctx.HasValue("Err_SMTPUser") {
  113. ctx.Data["Err_SMTP"] = true
  114. }
  115. if ctx.HasValue("Err_AdminName") ||
  116. ctx.HasValue("Err_AdminPasswd") ||
  117. ctx.HasValue("Err_AdminEmail") {
  118. ctx.Data["Err_Admin"] = true
  119. }
  120. ctx.HTML(200, tplInstall)
  121. return
  122. }
  123. if _, err = exec.LookPath("git"); err != nil {
  124. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form)
  125. return
  126. }
  127. // Pass basic check, now test configuration.
  128. // Test database setting.
  129. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"}
  130. models.DbCfg.Type = dbTypes[form.DbType]
  131. models.DbCfg.Host = form.DbHost
  132. models.DbCfg.User = form.DbUser
  133. models.DbCfg.Passwd = form.DbPasswd
  134. models.DbCfg.Name = form.DbName
  135. models.DbCfg.SSLMode = form.SSLMode
  136. models.DbCfg.Path = form.DbPath
  137. if (models.DbCfg.Type == "sqlite3" || models.DbCfg.Type == "tidb") &&
  138. len(models.DbCfg.Path) == 0 {
  139. ctx.Data["Err_DbPath"] = true
  140. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form)
  141. return
  142. } else if models.DbCfg.Type == "tidb" &&
  143. strings.ContainsAny(path.Base(models.DbCfg.Path), ".-") {
  144. ctx.Data["Err_DbPath"] = true
  145. ctx.RenderWithErr(ctx.Tr("install.err_invalid_tidb_name"), tplInstall, &form)
  146. return
  147. }
  148. // Set test engine.
  149. var x *xorm.Engine
  150. if err = models.NewTestEngine(x); err != nil {
  151. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  152. ctx.Data["Err_DbType"] = true
  153. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/installation/install_from_binary.html"), tplInstall, &form)
  154. } else {
  155. ctx.Data["Err_DbSetting"] = true
  156. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form)
  157. }
  158. return
  159. }
  160. // Test repository root path.
  161. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  162. if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  163. ctx.Data["Err_RepoRootPath"] = true
  164. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
  165. return
  166. }
  167. // Test LFS root path if not empty, empty meaning disable LFS
  168. if form.LFSRootPath != "" {
  169. form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
  170. if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
  171. ctx.Data["Err_LFSRootPath"] = true
  172. ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
  173. return
  174. }
  175. }
  176. // Test log root path.
  177. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  178. if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  179. ctx.Data["Err_LogRootPath"] = true
  180. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
  181. return
  182. }
  183. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  184. if !match {
  185. ctx.Data["Err_RunUser"] = true
  186. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form)
  187. return
  188. }
  189. // Check logic loophole between disable self-registration and no admin account.
  190. if form.DisableRegistration && len(form.AdminName) == 0 {
  191. ctx.Data["Err_Services"] = true
  192. ctx.Data["Err_Admin"] = true
  193. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), tplInstall, form)
  194. return
  195. }
  196. // Check admin password.
  197. if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 {
  198. ctx.Data["Err_Admin"] = true
  199. ctx.Data["Err_AdminPasswd"] = true
  200. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), tplInstall, form)
  201. return
  202. }
  203. if form.AdminPasswd != form.AdminConfirmPasswd {
  204. ctx.Data["Err_Admin"] = true
  205. ctx.Data["Err_AdminPasswd"] = true
  206. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplInstall, form)
  207. return
  208. }
  209. if form.AppURL[len(form.AppURL)-1] != '/' {
  210. form.AppURL += "/"
  211. }
  212. // Save settings.
  213. cfg := ini.Empty()
  214. if com.IsFile(setting.CustomConf) {
  215. // Keeps custom settings if there is already something.
  216. if err = cfg.Append(setting.CustomConf); err != nil {
  217. log.Error(4, "Failed to load custom conf '%s': %v", setting.CustomConf, err)
  218. }
  219. }
  220. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  221. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  222. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  223. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  224. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  225. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  226. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  227. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  228. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  229. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  230. cfg.Section("server").Key("SSH_DOMAIN").SetValue(form.Domain)
  231. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  232. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  233. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL)
  234. if form.SSHPort == 0 {
  235. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  236. } else {
  237. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  238. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  239. }
  240. if form.LFSRootPath != "" {
  241. cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
  242. cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
  243. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(base.GetRandomBytesAsBase64(32))
  244. } else {
  245. cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
  246. }
  247. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  248. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  249. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  250. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  251. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  252. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  253. } else {
  254. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  255. }
  256. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  257. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  258. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  259. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  260. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  261. cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn))
  262. cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp))
  263. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  264. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  265. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  266. cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate))
  267. cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization))
  268. cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking))
  269. cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress))
  270. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  271. cfg.Section("session").Key("PROVIDER").SetValue("file")
  272. cfg.Section("log").Key("MODE").SetValue("file")
  273. cfg.Section("log").Key("LEVEL").SetValue("Info")
  274. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  275. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  276. var secretKey string
  277. if secretKey, err = base.GetRandomString(10); err != nil {
  278. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
  279. return
  280. }
  281. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  282. err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  283. if err != nil {
  284. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  285. return
  286. }
  287. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  288. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  289. return
  290. }
  291. GlobalInit()
  292. // Create admin account
  293. if len(form.AdminName) > 0 {
  294. u := &models.User{
  295. Name: form.AdminName,
  296. Email: form.AdminEmail,
  297. Passwd: form.AdminPasswd,
  298. IsAdmin: true,
  299. IsActive: true,
  300. }
  301. if err = models.CreateUser(u); err != nil {
  302. if !models.IsErrUserAlreadyExist(err) {
  303. setting.InstallLock = false
  304. ctx.Data["Err_AdminName"] = true
  305. ctx.Data["Err_AdminEmail"] = true
  306. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form)
  307. return
  308. }
  309. log.Info("Admin account already exist")
  310. u, _ = models.GetUserByName(u.Name)
  311. }
  312. // Auto-login for admin
  313. if err = ctx.Session.Set("uid", u.ID); err != nil {
  314. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  315. return
  316. }
  317. if err = ctx.Session.Set("uname", u.Name); err != nil {
  318. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  319. return
  320. }
  321. }
  322. log.Info("First-time run install finished!")
  323. ctx.Flash.Success(ctx.Tr("install.install_success"))
  324. ctx.Redirect(form.AppURL + "user/login")
  325. }