A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
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.
 
 
 
 
 

889 lines
23 KiB

  1. /*
  2. * Copyright © 2018-2019 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "crypto/tls"
  13. "database/sql"
  14. "fmt"
  15. "html/template"
  16. "io/ioutil"
  17. "net/http"
  18. "net/url"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "regexp"
  23. "strings"
  24. "syscall"
  25. "time"
  26. "github.com/gorilla/mux"
  27. "github.com/gorilla/schema"
  28. "github.com/gorilla/sessions"
  29. "github.com/manifoldco/promptui"
  30. stripmd "github.com/writeas/go-strip-markdown"
  31. "github.com/writeas/impart"
  32. "github.com/writeas/web-core/auth"
  33. "github.com/writeas/web-core/converter"
  34. "github.com/writeas/web-core/log"
  35. "github.com/writeas/writefreely/author"
  36. "github.com/writeas/writefreely/config"
  37. "github.com/writeas/writefreely/key"
  38. "github.com/writeas/writefreely/migrations"
  39. "github.com/writeas/writefreely/page"
  40. "golang.org/x/crypto/acme/autocert"
  41. )
  42. const (
  43. staticDir = "static"
  44. assumedTitleLen = 80
  45. postsPerPage = 10
  46. serverSoftware = "WriteFreely"
  47. softwareURL = "https://writefreely.org"
  48. )
  49. var (
  50. debugging bool
  51. // Software version can be set from git env using -ldflags
  52. softwareVer = "0.11.2"
  53. // DEPRECATED VARS
  54. isSingleUser bool
  55. )
  56. // App holds data and configuration for an individual WriteFreely instance.
  57. type App struct {
  58. router *mux.Router
  59. shttp *http.ServeMux
  60. db *datastore
  61. cfg *config.Config
  62. cfgFile string
  63. keys *key.Keychain
  64. sessionStore sessions.Store
  65. formDecoder *schema.Decoder
  66. updates *updatesCache
  67. timeline *localTimeline
  68. }
  69. // DB returns the App's datastore
  70. func (app *App) DB() *datastore {
  71. return app.db
  72. }
  73. // Router returns the App's router
  74. func (app *App) Router() *mux.Router {
  75. return app.router
  76. }
  77. // Config returns the App's current configuration.
  78. func (app *App) Config() *config.Config {
  79. return app.cfg
  80. }
  81. // SetConfig updates the App's Config to the given value.
  82. func (app *App) SetConfig(cfg *config.Config) {
  83. app.cfg = cfg
  84. }
  85. // SetKeys updates the App's Keychain to the given value.
  86. func (app *App) SetKeys(k *key.Keychain) {
  87. app.keys = k
  88. }
  89. func (app *App) SessionStore() sessions.Store {
  90. return app.sessionStore
  91. }
  92. func (app *App) SetSessionStore(s sessions.Store) {
  93. app.sessionStore = s
  94. }
  95. // Apper is the interface for getting data into and out of a WriteFreely
  96. // instance (or "App").
  97. //
  98. // App returns the App for the current instance.
  99. //
  100. // LoadConfig reads an app configuration into the App, returning any error
  101. // encountered.
  102. //
  103. // SaveConfig persists the current App configuration.
  104. //
  105. // LoadKeys reads the App's encryption keys and loads them into its
  106. // key.Keychain.
  107. type Apper interface {
  108. App() *App
  109. LoadConfig() error
  110. SaveConfig(*config.Config) error
  111. LoadKeys() error
  112. ReqLog(r *http.Request, status int, timeSince time.Duration) string
  113. }
  114. // App returns the App
  115. func (app *App) App() *App {
  116. return app
  117. }
  118. // LoadConfig loads and parses a config file.
  119. func (app *App) LoadConfig() error {
  120. log.Info("Loading %s configuration...", app.cfgFile)
  121. cfg, err := config.Load(app.cfgFile)
  122. if err != nil {
  123. log.Error("Unable to load configuration: %v", err)
  124. os.Exit(1)
  125. return err
  126. }
  127. app.cfg = cfg
  128. return nil
  129. }
  130. // SaveConfig saves the given Config to disk -- namely, to the App's cfgFile.
  131. func (app *App) SaveConfig(c *config.Config) error {
  132. return config.Save(c, app.cfgFile)
  133. }
  134. // LoadKeys reads all needed keys from disk into the App. In order to use the
  135. // configured `Server.KeysParentDir`, you must call initKeyPaths(App) before
  136. // this.
  137. func (app *App) LoadKeys() error {
  138. var err error
  139. app.keys = &key.Keychain{}
  140. if debugging {
  141. log.Info(" %s", emailKeyPath)
  142. }
  143. app.keys.EmailKey, err = ioutil.ReadFile(emailKeyPath)
  144. if err != nil {
  145. return err
  146. }
  147. if debugging {
  148. log.Info(" %s", cookieAuthKeyPath)
  149. }
  150. app.keys.CookieAuthKey, err = ioutil.ReadFile(cookieAuthKeyPath)
  151. if err != nil {
  152. return err
  153. }
  154. if debugging {
  155. log.Info(" %s", cookieKeyPath)
  156. }
  157. app.keys.CookieKey, err = ioutil.ReadFile(cookieKeyPath)
  158. if err != nil {
  159. return err
  160. }
  161. return nil
  162. }
  163. func (app *App) ReqLog(r *http.Request, status int, timeSince time.Duration) string {
  164. return fmt.Sprintf("\"%s %s\" %d %s \"%s\"", r.Method, r.RequestURI, status, timeSince, r.UserAgent())
  165. }
  166. // handleViewHome shows page at root path. It checks the configuration and
  167. // authentication state to show the correct page.
  168. func handleViewHome(app *App, w http.ResponseWriter, r *http.Request) error {
  169. if app.cfg.App.SingleUser {
  170. // Render blog index
  171. return handleViewCollection(app, w, r)
  172. }
  173. // Multi-user instance
  174. forceLanding := r.FormValue("landing") == "1"
  175. if !forceLanding {
  176. // Show correct page based on user auth status and configured landing path
  177. u := getUserSession(app, r)
  178. if app.cfg.App.Chorus {
  179. // This instance is focused on reading, so show Reader on home route if not
  180. // private or a private-instance user is logged in.
  181. if !app.cfg.App.Private || u != nil {
  182. return viewLocalTimeline(app, w, r)
  183. }
  184. }
  185. if u != nil {
  186. // User is logged in, so show the Pad
  187. return handleViewPad(app, w, r)
  188. }
  189. if land := app.cfg.App.LandingPath(); land != "/" {
  190. return impart.HTTPError{http.StatusFound, land}
  191. }
  192. }
  193. return handleViewLanding(app, w, r)
  194. }
  195. func handleViewLanding(app *App, w http.ResponseWriter, r *http.Request) error {
  196. forceLanding := r.FormValue("landing") == "1"
  197. p := struct {
  198. page.StaticPage
  199. Flashes []template.HTML
  200. Banner template.HTML
  201. Content template.HTML
  202. ForcedLanding bool
  203. }{
  204. StaticPage: pageForReq(app, r),
  205. ForcedLanding: forceLanding,
  206. }
  207. banner, err := getLandingBanner(app)
  208. if err != nil {
  209. log.Error("unable to get landing banner: %v", err)
  210. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get banner: %v", err)}
  211. }
  212. p.Banner = template.HTML(applyMarkdown([]byte(banner.Content), "", app.cfg))
  213. content, err := getLandingBody(app)
  214. if err != nil {
  215. log.Error("unable to get landing content: %v", err)
  216. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get content: %v", err)}
  217. }
  218. p.Content = template.HTML(applyMarkdown([]byte(content.Content), "", app.cfg))
  219. // Get error messages
  220. session, err := app.sessionStore.Get(r, cookieName)
  221. if err != nil {
  222. // Ignore this
  223. log.Error("Unable to get session in handleViewHome; ignoring: %v", err)
  224. }
  225. flashes, _ := getSessionFlashes(app, w, r, session)
  226. for _, flash := range flashes {
  227. p.Flashes = append(p.Flashes, template.HTML(flash))
  228. }
  229. // Show landing page
  230. return renderPage(w, "landing.tmpl", p)
  231. }
  232. func handleTemplatedPage(app *App, w http.ResponseWriter, r *http.Request, t *template.Template) error {
  233. p := struct {
  234. page.StaticPage
  235. ContentTitle string
  236. Content template.HTML
  237. PlainContent string
  238. Updated string
  239. AboutStats *InstanceStats
  240. }{
  241. StaticPage: pageForReq(app, r),
  242. }
  243. if r.URL.Path == "/about" || r.URL.Path == "/privacy" {
  244. var c *instanceContent
  245. var err error
  246. if r.URL.Path == "/about" {
  247. c, err = getAboutPage(app)
  248. // Fetch stats
  249. p.AboutStats = &InstanceStats{}
  250. p.AboutStats.NumPosts, _ = app.db.GetTotalPosts()
  251. p.AboutStats.NumBlogs, _ = app.db.GetTotalCollections()
  252. } else {
  253. c, err = getPrivacyPage(app)
  254. }
  255. if err != nil {
  256. return err
  257. }
  258. p.ContentTitle = c.Title.String
  259. p.Content = template.HTML(applyMarkdown([]byte(c.Content), "", app.cfg))
  260. p.PlainContent = shortPostDescription(stripmd.Strip(c.Content))
  261. if !c.Updated.IsZero() {
  262. p.Updated = c.Updated.Format("January 2, 2006")
  263. }
  264. }
  265. // Serve templated page
  266. err := t.ExecuteTemplate(w, "base", p)
  267. if err != nil {
  268. log.Error("Unable to render page: %v", err)
  269. }
  270. return nil
  271. }
  272. func pageForReq(app *App, r *http.Request) page.StaticPage {
  273. p := page.StaticPage{
  274. AppCfg: app.cfg.App,
  275. Path: r.URL.Path,
  276. Version: "v" + softwareVer,
  277. }
  278. // Add user information, if given
  279. var u *User
  280. accessToken := r.FormValue("t")
  281. if accessToken != "" {
  282. userID := app.db.GetUserID(accessToken)
  283. if userID != -1 {
  284. var err error
  285. u, err = app.db.GetUserByID(userID)
  286. if err == nil {
  287. p.Username = u.Username
  288. }
  289. }
  290. } else {
  291. u = getUserSession(app, r)
  292. if u != nil {
  293. p.Username = u.Username
  294. p.IsAdmin = u != nil && u.IsAdmin()
  295. p.CanInvite = canUserInvite(app.cfg, p.IsAdmin)
  296. }
  297. }
  298. p.CanViewReader = !app.cfg.App.Private || u != nil
  299. return p
  300. }
  301. var fileRegex = regexp.MustCompile("/([^/]*\\.[^/]*)$")
  302. // Initialize loads the app configuration and initializes templates, keys,
  303. // session, route handlers, and the database connection.
  304. func Initialize(apper Apper, debug bool) (*App, error) {
  305. debugging = debug
  306. apper.LoadConfig()
  307. // Load templates
  308. err := InitTemplates(apper.App().Config())
  309. if err != nil {
  310. return nil, fmt.Errorf("load templates: %s", err)
  311. }
  312. // Load keys and set up session
  313. initKeyPaths(apper.App()) // TODO: find a better way to do this, since it's unneeded in all Apper implementations
  314. err = InitKeys(apper)
  315. if err != nil {
  316. return nil, fmt.Errorf("init keys: %s", err)
  317. }
  318. apper.App().InitUpdates()
  319. apper.App().InitSession()
  320. apper.App().InitDecoder()
  321. err = ConnectToDatabase(apper.App())
  322. if err != nil {
  323. return nil, fmt.Errorf("connect to DB: %s", err)
  324. }
  325. // Handle local timeline, if enabled
  326. if apper.App().cfg.App.LocalTimeline {
  327. log.Info("Initializing local timeline...")
  328. initLocalTimeline(apper.App())
  329. }
  330. return apper.App(), nil
  331. }
  332. func Serve(app *App, r *mux.Router) {
  333. log.Info("Going to serve...")
  334. isSingleUser = app.cfg.App.SingleUser
  335. app.cfg.Server.Dev = debugging
  336. // Handle shutdown
  337. c := make(chan os.Signal, 2)
  338. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  339. go func() {
  340. <-c
  341. log.Info("Shutting down...")
  342. shutdown(app)
  343. log.Info("Done.")
  344. os.Exit(0)
  345. }()
  346. // Start gopher server
  347. if app.cfg.Server.GopherPort > 0 {
  348. go initGopher(app)
  349. }
  350. // Start web application server
  351. var bindAddress = app.cfg.Server.Bind
  352. if bindAddress == "" {
  353. bindAddress = "localhost"
  354. }
  355. var err error
  356. if app.cfg.IsSecureStandalone() {
  357. if app.cfg.Server.Autocert {
  358. m := &autocert.Manager{
  359. Prompt: autocert.AcceptTOS,
  360. Cache: autocert.DirCache(app.cfg.Server.TLSCertPath),
  361. }
  362. host, err := url.Parse(app.cfg.App.Host)
  363. if err != nil {
  364. log.Error("[WARNING] Unable to parse configured host! %s", err)
  365. log.Error(`[WARNING] ALL hosts are allowed, which can open you to an attack where
  366. clients connect to a server by IP address and pretend to be asking for an
  367. incorrect host name, and cause you to reach the CA's rate limit for certificate
  368. requests. We recommend supplying a valid host name.`)
  369. log.Info("Using autocert on ANY host")
  370. } else {
  371. log.Info("Using autocert on host %s", host.Host)
  372. m.HostPolicy = autocert.HostWhitelist(host.Host)
  373. }
  374. s := &http.Server{
  375. Addr: ":https",
  376. Handler: r,
  377. TLSConfig: &tls.Config{
  378. GetCertificate: m.GetCertificate,
  379. },
  380. }
  381. s.SetKeepAlivesEnabled(false)
  382. go func() {
  383. log.Info("Serving redirects on http://%s:80", bindAddress)
  384. err = http.ListenAndServe(":80", m.HTTPHandler(nil))
  385. log.Error("Unable to start redirect server: %v", err)
  386. }()
  387. log.Info("Serving on https://%s:443", bindAddress)
  388. log.Info("---")
  389. err = s.ListenAndServeTLS("", "")
  390. } else {
  391. go func() {
  392. log.Info("Serving redirects on http://%s:80", bindAddress)
  393. err = http.ListenAndServe(fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  394. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  395. }))
  396. log.Error("Unable to start redirect server: %v", err)
  397. }()
  398. log.Info("Serving on https://%s:443", bindAddress)
  399. log.Info("Using manual certificates")
  400. log.Info("---")
  401. err = http.ListenAndServeTLS(fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, r)
  402. }
  403. } else {
  404. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  405. log.Info("---")
  406. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), r)
  407. }
  408. if err != nil {
  409. log.Error("Unable to start: %v", err)
  410. os.Exit(1)
  411. }
  412. }
  413. func (app *App) InitDecoder() {
  414. // TODO: do this at the package level, instead of the App level
  415. // Initialize modules
  416. app.formDecoder = schema.NewDecoder()
  417. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  418. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  419. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  420. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  421. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  422. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  423. }
  424. // ConnectToDatabase validates and connects to the configured database, then
  425. // tests the connection.
  426. func ConnectToDatabase(app *App) error {
  427. // Check database configuration
  428. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  429. return fmt.Errorf("Database user or password not set.")
  430. }
  431. if app.cfg.Database.Host == "" {
  432. app.cfg.Database.Host = "localhost"
  433. }
  434. if app.cfg.Database.Database == "" {
  435. app.cfg.Database.Database = "writefreely"
  436. }
  437. // TODO: check err
  438. connectToDatabase(app)
  439. // Test database connection
  440. err := app.db.Ping()
  441. if err != nil {
  442. return fmt.Errorf("Database ping failed: %s", err)
  443. }
  444. return nil
  445. }
  446. // FormatVersion constructs the version string for the application
  447. func FormatVersion() string {
  448. return serverSoftware + " " + softwareVer
  449. }
  450. // OutputVersion prints out the version of the application.
  451. func OutputVersion() {
  452. fmt.Println(FormatVersion())
  453. }
  454. // NewApp creates a new app instance.
  455. func NewApp(cfgFile string) *App {
  456. return &App{
  457. cfgFile: cfgFile,
  458. }
  459. }
  460. // CreateConfig creates a default configuration and saves it to the app's cfgFile.
  461. func CreateConfig(app *App) error {
  462. log.Info("Creating configuration...")
  463. c := config.New()
  464. log.Info("Saving configuration %s...", app.cfgFile)
  465. err := config.Save(c, app.cfgFile)
  466. if err != nil {
  467. return fmt.Errorf("Unable to save configuration: %v", err)
  468. }
  469. return nil
  470. }
  471. // DoConfig runs the interactive configuration process.
  472. func DoConfig(app *App, configSections string) {
  473. if configSections == "" {
  474. configSections = "server db app"
  475. }
  476. // let's check there aren't any garbage in the list
  477. configSectionsArray := strings.Split(configSections, " ")
  478. for _, element := range configSectionsArray {
  479. if element != "server" && element != "db" && element != "app" {
  480. log.Error("Invalid argument to --sections. Valid arguments are only \"server\", \"db\" and \"app\"")
  481. os.Exit(1)
  482. }
  483. }
  484. d, err := config.Configure(app.cfgFile, configSections)
  485. if err != nil {
  486. log.Error("Unable to configure: %v", err)
  487. os.Exit(1)
  488. }
  489. app.cfg = d.Config
  490. connectToDatabase(app)
  491. defer shutdown(app)
  492. if !app.db.DatabaseInitialized() {
  493. err = adminInitDatabase(app)
  494. if err != nil {
  495. log.Error(err.Error())
  496. os.Exit(1)
  497. }
  498. } else {
  499. log.Info("Database already initialized.")
  500. }
  501. if d.User != nil {
  502. u := &User{
  503. Username: d.User.Username,
  504. HashedPass: d.User.HashedPass,
  505. Created: time.Now().Truncate(time.Second).UTC(),
  506. }
  507. // Create blog
  508. log.Info("Creating user %s...\n", u.Username)
  509. err = app.db.CreateUser(app.cfg, u, app.cfg.App.SiteName)
  510. if err != nil {
  511. log.Error("Unable to create user: %s", err)
  512. os.Exit(1)
  513. }
  514. log.Info("Done!")
  515. }
  516. os.Exit(0)
  517. }
  518. // GenerateKeyFiles creates app encryption keys and saves them into the configured KeysParentDir.
  519. func GenerateKeyFiles(app *App) error {
  520. // Read keys path from config
  521. app.LoadConfig()
  522. // Create keys dir if it doesn't exist yet
  523. fullKeysDir := filepath.Join(app.cfg.Server.KeysParentDir, keysDir)
  524. if _, err := os.Stat(fullKeysDir); os.IsNotExist(err) {
  525. err = os.Mkdir(fullKeysDir, 0700)
  526. if err != nil {
  527. return err
  528. }
  529. }
  530. // Generate keys
  531. initKeyPaths(app)
  532. // TODO: use something like https://github.com/hashicorp/go-multierror to return errors
  533. var keyErrs error
  534. err := generateKey(emailKeyPath)
  535. if err != nil {
  536. keyErrs = err
  537. }
  538. err = generateKey(cookieAuthKeyPath)
  539. if err != nil {
  540. keyErrs = err
  541. }
  542. err = generateKey(cookieKeyPath)
  543. if err != nil {
  544. keyErrs = err
  545. }
  546. return keyErrs
  547. }
  548. // CreateSchema creates all database tables needed for the application.
  549. func CreateSchema(apper Apper) error {
  550. apper.LoadConfig()
  551. connectToDatabase(apper.App())
  552. defer shutdown(apper.App())
  553. err := adminInitDatabase(apper.App())
  554. if err != nil {
  555. return err
  556. }
  557. return nil
  558. }
  559. // Migrate runs all necessary database migrations.
  560. func Migrate(apper Apper) error {
  561. apper.LoadConfig()
  562. connectToDatabase(apper.App())
  563. defer shutdown(apper.App())
  564. err := migrations.Migrate(migrations.NewDatastore(apper.App().db.DB, apper.App().db.driverName))
  565. if err != nil {
  566. return fmt.Errorf("migrate: %s", err)
  567. }
  568. return nil
  569. }
  570. // ResetPassword runs the interactive password reset process.
  571. func ResetPassword(apper Apper, username string) error {
  572. // Connect to the database
  573. apper.LoadConfig()
  574. connectToDatabase(apper.App())
  575. defer shutdown(apper.App())
  576. // Fetch user
  577. u, err := apper.App().db.GetUserForAuth(username)
  578. if err != nil {
  579. log.Error("Get user: %s", err)
  580. os.Exit(1)
  581. }
  582. // Prompt for new password
  583. prompt := promptui.Prompt{
  584. Templates: &promptui.PromptTemplates{
  585. Success: "{{ . | bold | faint }}: ",
  586. },
  587. Label: "New password",
  588. Mask: '*',
  589. }
  590. newPass, err := prompt.Run()
  591. if err != nil {
  592. log.Error("%s", err)
  593. os.Exit(1)
  594. }
  595. // Do the update
  596. log.Info("Updating...")
  597. err = adminResetPassword(apper.App(), u, newPass)
  598. if err != nil {
  599. log.Error("%s", err)
  600. os.Exit(1)
  601. }
  602. log.Info("Success.")
  603. return nil
  604. }
  605. // DoDeleteAccount runs the confirmation and account delete process.
  606. func DoDeleteAccount(apper Apper, username string) error {
  607. // Connect to the database
  608. apper.LoadConfig()
  609. connectToDatabase(apper.App())
  610. defer shutdown(apper.App())
  611. // check user exists
  612. u, err := apper.App().db.GetUserForAuth(username)
  613. if err != nil {
  614. log.Error("%s", err)
  615. os.Exit(1)
  616. }
  617. userID := u.ID
  618. // do not delete the admin account
  619. // TODO: check for other admins and skip?
  620. if u.IsAdmin() {
  621. log.Error("Can not delete admin account")
  622. os.Exit(1)
  623. }
  624. // confirm deletion, w/ w/out posts
  625. prompt := promptui.Prompt{
  626. Templates: &promptui.PromptTemplates{
  627. Success: "{{ . | bold | faint }}: ",
  628. },
  629. Label: fmt.Sprintf("Really delete user : %s", username),
  630. IsConfirm: true,
  631. }
  632. _, err = prompt.Run()
  633. if err != nil {
  634. log.Info("Aborted...")
  635. os.Exit(0)
  636. }
  637. log.Info("Deleting...")
  638. err = apper.App().db.DeleteAccount(userID)
  639. if err != nil {
  640. log.Error("%s", err)
  641. os.Exit(1)
  642. }
  643. log.Info("Success.")
  644. return nil
  645. }
  646. func connectToDatabase(app *App) {
  647. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  648. var db *sql.DB
  649. var err error
  650. if app.cfg.Database.Type == driverMySQL {
  651. db, err = sql.Open(app.cfg.Database.Type, fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=%s", app.cfg.Database.User, app.cfg.Database.Password, app.cfg.Database.Host, app.cfg.Database.Port, app.cfg.Database.Database, url.QueryEscape(time.Local.String())))
  652. db.SetMaxOpenConns(50)
  653. } else if app.cfg.Database.Type == driverSQLite {
  654. if !SQLiteEnabled {
  655. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  656. os.Exit(1)
  657. }
  658. if app.cfg.Database.FileName == "" {
  659. log.Error("SQLite database filename value in config.ini is empty.")
  660. os.Exit(1)
  661. }
  662. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  663. db.SetMaxOpenConns(1)
  664. } else {
  665. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  666. os.Exit(1)
  667. }
  668. if err != nil {
  669. log.Error("%s", err)
  670. os.Exit(1)
  671. }
  672. app.db = &datastore{db, app.cfg.Database.Type}
  673. }
  674. func shutdown(app *App) {
  675. log.Info("Closing database connection...")
  676. app.db.Close()
  677. }
  678. // CreateUser creates a new admin or normal user from the given credentials.
  679. func CreateUser(apper Apper, username, password string, isAdmin bool) error {
  680. // Create an admin user with --create-admin
  681. apper.LoadConfig()
  682. connectToDatabase(apper.App())
  683. defer shutdown(apper.App())
  684. // Ensure an admin / first user doesn't already exist
  685. firstUser, _ := apper.App().db.GetUserByID(1)
  686. if isAdmin {
  687. // Abort if trying to create admin user, but one already exists
  688. if firstUser != nil {
  689. return fmt.Errorf("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  690. }
  691. } else {
  692. // Abort if trying to create regular user, but no admin exists yet
  693. if firstUser == nil {
  694. return fmt.Errorf("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  695. }
  696. }
  697. // Create the user
  698. // Normalize and validate username
  699. desiredUsername := username
  700. username = getSlug(username, "")
  701. usernameDesc := username
  702. if username != desiredUsername {
  703. usernameDesc += " (originally: " + desiredUsername + ")"
  704. }
  705. if !author.IsValidUsername(apper.App().cfg, username) {
  706. return fmt.Errorf("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, apper.App().cfg.App.MinUsernameLen)
  707. }
  708. // Hash the password
  709. hashedPass, err := auth.HashPass([]byte(password))
  710. if err != nil {
  711. return fmt.Errorf("Unable to hash password: %v", err)
  712. }
  713. u := &User{
  714. Username: username,
  715. HashedPass: hashedPass,
  716. Created: time.Now().Truncate(time.Second).UTC(),
  717. }
  718. userType := "user"
  719. if isAdmin {
  720. userType = "admin"
  721. }
  722. log.Info("Creating %s %s...", userType, usernameDesc)
  723. err = apper.App().db.CreateUser(apper.App().Config(), u, desiredUsername)
  724. if err != nil {
  725. return fmt.Errorf("Unable to create user: %s", err)
  726. }
  727. log.Info("Done!")
  728. return nil
  729. }
  730. func adminInitDatabase(app *App) error {
  731. schemaFileName := "schema.sql"
  732. if app.cfg.Database.Type == driverSQLite {
  733. schemaFileName = "sqlite.sql"
  734. }
  735. schema, err := Asset(schemaFileName)
  736. if err != nil {
  737. return fmt.Errorf("Unable to load schema file: %v", err)
  738. }
  739. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  740. queries := strings.Split(string(schema), ";\n")
  741. for _, q := range queries {
  742. if strings.TrimSpace(q) == "" {
  743. continue
  744. }
  745. parts := tblReg.FindStringSubmatch(q)
  746. if len(parts) >= 3 {
  747. log.Info("Creating table %s...", parts[2])
  748. } else {
  749. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  750. }
  751. _, err = app.db.Exec(q)
  752. if err != nil {
  753. log.Error("%s", err)
  754. } else {
  755. log.Info("Created.")
  756. }
  757. }
  758. // Set up migrations table
  759. log.Info("Initializing appmigrations table...")
  760. err = migrations.SetInitialMigrations(migrations.NewDatastore(app.db.DB, app.db.driverName))
  761. if err != nil {
  762. return fmt.Errorf("Unable to set initial migrations: %v", err)
  763. }
  764. log.Info("Running migrations...")
  765. err = migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  766. if err != nil {
  767. return fmt.Errorf("migrate: %s", err)
  768. }
  769. log.Info("Done.")
  770. return nil
  771. }