You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

install.go 14KB

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