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.
 
 
 
 
 

888 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.12.0"
  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 app.cfg.App.Private {
  190. return viewLogin(app, w, r)
  191. }
  192. if land := app.cfg.App.LandingPath(); land != "/" {
  193. return impart.HTTPError{http.StatusFound, land}
  194. }
  195. }
  196. return handleViewLanding(app, w, r)
  197. }
  198. func handleViewLanding(app *App, w http.ResponseWriter, r *http.Request) error {
  199. forceLanding := r.FormValue("landing") == "1"
  200. p := struct {
  201. page.StaticPage
  202. Flashes []template.HTML
  203. Banner template.HTML
  204. Content template.HTML
  205. ForcedLanding bool
  206. }{
  207. StaticPage: pageForReq(app, r),
  208. ForcedLanding: forceLanding,
  209. }
  210. banner, err := getLandingBanner(app)
  211. if err != nil {
  212. log.Error("unable to get landing banner: %v", err)
  213. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get banner: %v", err)}
  214. }
  215. p.Banner = template.HTML(applyMarkdown([]byte(banner.Content), "", app.cfg))
  216. content, err := getLandingBody(app)
  217. if err != nil {
  218. log.Error("unable to get landing content: %v", err)
  219. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get content: %v", err)}
  220. }
  221. p.Content = template.HTML(applyMarkdown([]byte(content.Content), "", app.cfg))
  222. // Get error messages
  223. session, err := app.sessionStore.Get(r, cookieName)
  224. if err != nil {
  225. // Ignore this
  226. log.Error("Unable to get session in handleViewHome; ignoring: %v", err)
  227. }
  228. flashes, _ := getSessionFlashes(app, w, r, session)
  229. for _, flash := range flashes {
  230. p.Flashes = append(p.Flashes, template.HTML(flash))
  231. }
  232. // Show landing page
  233. return renderPage(w, "landing.tmpl", p)
  234. }
  235. func handleTemplatedPage(app *App, w http.ResponseWriter, r *http.Request, t *template.Template) error {
  236. p := struct {
  237. page.StaticPage
  238. ContentTitle string
  239. Content template.HTML
  240. PlainContent string
  241. Updated string
  242. AboutStats *InstanceStats
  243. }{
  244. StaticPage: pageForReq(app, r),
  245. }
  246. if r.URL.Path == "/about" || r.URL.Path == "/privacy" {
  247. var c *instanceContent
  248. var err error
  249. if r.URL.Path == "/about" {
  250. c, err = getAboutPage(app)
  251. // Fetch stats
  252. p.AboutStats = &InstanceStats{}
  253. p.AboutStats.NumPosts, _ = app.db.GetTotalPosts()
  254. p.AboutStats.NumBlogs, _ = app.db.GetTotalCollections()
  255. } else {
  256. c, err = getPrivacyPage(app)
  257. }
  258. if err != nil {
  259. return err
  260. }
  261. p.ContentTitle = c.Title.String
  262. p.Content = template.HTML(applyMarkdown([]byte(c.Content), "", app.cfg))
  263. p.PlainContent = shortPostDescription(stripmd.Strip(c.Content))
  264. if !c.Updated.IsZero() {
  265. p.Updated = c.Updated.Format("January 2, 2006")
  266. }
  267. }
  268. // Serve templated page
  269. err := t.ExecuteTemplate(w, "base", p)
  270. if err != nil {
  271. log.Error("Unable to render page: %v", err)
  272. }
  273. return nil
  274. }
  275. func pageForReq(app *App, r *http.Request) page.StaticPage {
  276. p := page.StaticPage{
  277. AppCfg: app.cfg.App,
  278. Path: r.URL.Path,
  279. Version: "v" + softwareVer,
  280. }
  281. // Add user information, if given
  282. var u *User
  283. accessToken := r.FormValue("t")
  284. if accessToken != "" {
  285. userID := app.db.GetUserID(accessToken)
  286. if userID != -1 {
  287. var err error
  288. u, err = app.db.GetUserByID(userID)
  289. if err == nil {
  290. p.Username = u.Username
  291. }
  292. }
  293. } else {
  294. u = getUserSession(app, r)
  295. if u != nil {
  296. p.Username = u.Username
  297. p.IsAdmin = u != nil && u.IsAdmin()
  298. p.CanInvite = canUserInvite(app.cfg, p.IsAdmin)
  299. }
  300. }
  301. p.CanViewReader = !app.cfg.App.Private || u != nil
  302. return p
  303. }
  304. var fileRegex = regexp.MustCompile("/([^/]*\\.[^/]*)$")
  305. // Initialize loads the app configuration and initializes templates, keys,
  306. // session, route handlers, and the database connection.
  307. func Initialize(apper Apper, debug bool) (*App, error) {
  308. debugging = debug
  309. apper.LoadConfig()
  310. // Load templates
  311. err := InitTemplates(apper.App().Config())
  312. if err != nil {
  313. return nil, fmt.Errorf("load templates: %s", err)
  314. }
  315. // Load keys and set up session
  316. initKeyPaths(apper.App()) // TODO: find a better way to do this, since it's unneeded in all Apper implementations
  317. err = InitKeys(apper)
  318. if err != nil {
  319. return nil, fmt.Errorf("init keys: %s", err)
  320. }
  321. apper.App().InitUpdates()
  322. apper.App().InitSession()
  323. apper.App().InitDecoder()
  324. err = ConnectToDatabase(apper.App())
  325. if err != nil {
  326. return nil, fmt.Errorf("connect to DB: %s", err)
  327. }
  328. // Handle local timeline, if enabled
  329. if apper.App().cfg.App.LocalTimeline {
  330. log.Info("Initializing local timeline...")
  331. initLocalTimeline(apper.App())
  332. }
  333. return apper.App(), nil
  334. }
  335. func Serve(app *App, r *mux.Router) {
  336. log.Info("Going to serve...")
  337. isSingleUser = app.cfg.App.SingleUser
  338. app.cfg.Server.Dev = debugging
  339. // Handle shutdown
  340. c := make(chan os.Signal, 2)
  341. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  342. go func() {
  343. <-c
  344. log.Info("Shutting down...")
  345. shutdown(app)
  346. log.Info("Done.")
  347. os.Exit(0)
  348. }()
  349. // Start web application server
  350. var bindAddress = app.cfg.Server.Bind
  351. if bindAddress == "" {
  352. bindAddress = "localhost"
  353. }
  354. var err error
  355. if app.cfg.IsSecureStandalone() {
  356. if app.cfg.Server.Autocert {
  357. m := &autocert.Manager{
  358. Prompt: autocert.AcceptTOS,
  359. Cache: autocert.DirCache(app.cfg.Server.TLSCertPath),
  360. }
  361. host, err := url.Parse(app.cfg.App.Host)
  362. if err != nil {
  363. log.Error("[WARNING] Unable to parse configured host! %s", err)
  364. log.Error(`[WARNING] ALL hosts are allowed, which can open you to an attack where
  365. clients connect to a server by IP address and pretend to be asking for an
  366. incorrect host name, and cause you to reach the CA's rate limit for certificate
  367. requests. We recommend supplying a valid host name.`)
  368. log.Info("Using autocert on ANY host")
  369. } else {
  370. log.Info("Using autocert on host %s", host.Host)
  371. m.HostPolicy = autocert.HostWhitelist(host.Host)
  372. }
  373. s := &http.Server{
  374. Addr: ":https",
  375. Handler: r,
  376. TLSConfig: &tls.Config{
  377. GetCertificate: m.GetCertificate,
  378. },
  379. }
  380. s.SetKeepAlivesEnabled(false)
  381. go func() {
  382. log.Info("Serving redirects on http://%s:80", bindAddress)
  383. err = http.ListenAndServe(":80", m.HTTPHandler(nil))
  384. log.Error("Unable to start redirect server: %v", err)
  385. }()
  386. log.Info("Serving on https://%s:443", bindAddress)
  387. log.Info("---")
  388. err = s.ListenAndServeTLS("", "")
  389. } else {
  390. go func() {
  391. log.Info("Serving redirects on http://%s:80", bindAddress)
  392. err = http.ListenAndServe(fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  393. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  394. }))
  395. log.Error("Unable to start redirect server: %v", err)
  396. }()
  397. log.Info("Serving on https://%s:443", bindAddress)
  398. log.Info("Using manual certificates")
  399. log.Info("---")
  400. err = http.ListenAndServeTLS(fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, r)
  401. }
  402. } else {
  403. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  404. log.Info("---")
  405. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), r)
  406. }
  407. if err != nil {
  408. log.Error("Unable to start: %v", err)
  409. os.Exit(1)
  410. }
  411. }
  412. func (app *App) InitDecoder() {
  413. // TODO: do this at the package level, instead of the App level
  414. // Initialize modules
  415. app.formDecoder = schema.NewDecoder()
  416. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  417. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  418. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  419. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  420. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  421. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  422. }
  423. // ConnectToDatabase validates and connects to the configured database, then
  424. // tests the connection.
  425. func ConnectToDatabase(app *App) error {
  426. // Check database configuration
  427. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  428. return fmt.Errorf("Database user or password not set.")
  429. }
  430. if app.cfg.Database.Host == "" {
  431. app.cfg.Database.Host = "localhost"
  432. }
  433. if app.cfg.Database.Database == "" {
  434. app.cfg.Database.Database = "writefreely"
  435. }
  436. // TODO: check err
  437. connectToDatabase(app)
  438. // Test database connection
  439. err := app.db.Ping()
  440. if err != nil {
  441. return fmt.Errorf("Database ping failed: %s", err)
  442. }
  443. return nil
  444. }
  445. // FormatVersion constructs the version string for the application
  446. func FormatVersion() string {
  447. return serverSoftware + " " + softwareVer
  448. }
  449. // OutputVersion prints out the version of the application.
  450. func OutputVersion() {
  451. fmt.Println(FormatVersion())
  452. }
  453. // NewApp creates a new app instance.
  454. func NewApp(cfgFile string) *App {
  455. return &App{
  456. cfgFile: cfgFile,
  457. }
  458. }
  459. // CreateConfig creates a default configuration and saves it to the app's cfgFile.
  460. func CreateConfig(app *App) error {
  461. log.Info("Creating configuration...")
  462. c := config.New()
  463. log.Info("Saving configuration %s...", app.cfgFile)
  464. err := config.Save(c, app.cfgFile)
  465. if err != nil {
  466. return fmt.Errorf("Unable to save configuration: %v", err)
  467. }
  468. return nil
  469. }
  470. // DoConfig runs the interactive configuration process.
  471. func DoConfig(app *App, configSections string) {
  472. if configSections == "" {
  473. configSections = "server db app"
  474. }
  475. // let's check there aren't any garbage in the list
  476. configSectionsArray := strings.Split(configSections, " ")
  477. for _, element := range configSectionsArray {
  478. if element != "server" && element != "db" && element != "app" {
  479. log.Error("Invalid argument to --sections. Valid arguments are only \"server\", \"db\" and \"app\"")
  480. os.Exit(1)
  481. }
  482. }
  483. d, err := config.Configure(app.cfgFile, configSections)
  484. if err != nil {
  485. log.Error("Unable to configure: %v", err)
  486. os.Exit(1)
  487. }
  488. app.cfg = d.Config
  489. connectToDatabase(app)
  490. defer shutdown(app)
  491. if !app.db.DatabaseInitialized() {
  492. err = adminInitDatabase(app)
  493. if err != nil {
  494. log.Error(err.Error())
  495. os.Exit(1)
  496. }
  497. } else {
  498. log.Info("Database already initialized.")
  499. }
  500. if d.User != nil {
  501. u := &User{
  502. Username: d.User.Username,
  503. HashedPass: d.User.HashedPass,
  504. Created: time.Now().Truncate(time.Second).UTC(),
  505. }
  506. // Create blog
  507. log.Info("Creating user %s...\n", u.Username)
  508. err = app.db.CreateUser(app.cfg, u, app.cfg.App.SiteName)
  509. if err != nil {
  510. log.Error("Unable to create user: %s", err)
  511. os.Exit(1)
  512. }
  513. log.Info("Done!")
  514. }
  515. os.Exit(0)
  516. }
  517. // GenerateKeyFiles creates app encryption keys and saves them into the configured KeysParentDir.
  518. func GenerateKeyFiles(app *App) error {
  519. // Read keys path from config
  520. app.LoadConfig()
  521. // Create keys dir if it doesn't exist yet
  522. fullKeysDir := filepath.Join(app.cfg.Server.KeysParentDir, keysDir)
  523. if _, err := os.Stat(fullKeysDir); os.IsNotExist(err) {
  524. err = os.Mkdir(fullKeysDir, 0700)
  525. if err != nil {
  526. return err
  527. }
  528. }
  529. // Generate keys
  530. initKeyPaths(app)
  531. // TODO: use something like https://github.com/hashicorp/go-multierror to return errors
  532. var keyErrs error
  533. err := generateKey(emailKeyPath)
  534. if err != nil {
  535. keyErrs = err
  536. }
  537. err = generateKey(cookieAuthKeyPath)
  538. if err != nil {
  539. keyErrs = err
  540. }
  541. err = generateKey(cookieKeyPath)
  542. if err != nil {
  543. keyErrs = err
  544. }
  545. return keyErrs
  546. }
  547. // CreateSchema creates all database tables needed for the application.
  548. func CreateSchema(apper Apper) error {
  549. apper.LoadConfig()
  550. connectToDatabase(apper.App())
  551. defer shutdown(apper.App())
  552. err := adminInitDatabase(apper.App())
  553. if err != nil {
  554. return err
  555. }
  556. return nil
  557. }
  558. // Migrate runs all necessary database migrations.
  559. func Migrate(apper Apper) error {
  560. apper.LoadConfig()
  561. connectToDatabase(apper.App())
  562. defer shutdown(apper.App())
  563. err := migrations.Migrate(migrations.NewDatastore(apper.App().db.DB, apper.App().db.driverName))
  564. if err != nil {
  565. return fmt.Errorf("migrate: %s", err)
  566. }
  567. return nil
  568. }
  569. // ResetPassword runs the interactive password reset process.
  570. func ResetPassword(apper Apper, username string) error {
  571. // Connect to the database
  572. apper.LoadConfig()
  573. connectToDatabase(apper.App())
  574. defer shutdown(apper.App())
  575. // Fetch user
  576. u, err := apper.App().db.GetUserForAuth(username)
  577. if err != nil {
  578. log.Error("Get user: %s", err)
  579. os.Exit(1)
  580. }
  581. // Prompt for new password
  582. prompt := promptui.Prompt{
  583. Templates: &promptui.PromptTemplates{
  584. Success: "{{ . | bold | faint }}: ",
  585. },
  586. Label: "New password",
  587. Mask: '*',
  588. }
  589. newPass, err := prompt.Run()
  590. if err != nil {
  591. log.Error("%s", err)
  592. os.Exit(1)
  593. }
  594. // Do the update
  595. log.Info("Updating...")
  596. err = adminResetPassword(apper.App(), u, newPass)
  597. if err != nil {
  598. log.Error("%s", err)
  599. os.Exit(1)
  600. }
  601. log.Info("Success.")
  602. return nil
  603. }
  604. // DoDeleteAccount runs the confirmation and account delete process.
  605. func DoDeleteAccount(apper Apper, username string) error {
  606. // Connect to the database
  607. apper.LoadConfig()
  608. connectToDatabase(apper.App())
  609. defer shutdown(apper.App())
  610. // check user exists
  611. u, err := apper.App().db.GetUserForAuth(username)
  612. if err != nil {
  613. log.Error("%s", err)
  614. os.Exit(1)
  615. }
  616. userID := u.ID
  617. // do not delete the admin account
  618. // TODO: check for other admins and skip?
  619. if u.IsAdmin() {
  620. log.Error("Can not delete admin account")
  621. os.Exit(1)
  622. }
  623. // confirm deletion, w/ w/out posts
  624. prompt := promptui.Prompt{
  625. Templates: &promptui.PromptTemplates{
  626. Success: "{{ . | bold | faint }}: ",
  627. },
  628. Label: fmt.Sprintf("Really delete user : %s", username),
  629. IsConfirm: true,
  630. }
  631. _, err = prompt.Run()
  632. if err != nil {
  633. log.Info("Aborted...")
  634. os.Exit(0)
  635. }
  636. log.Info("Deleting...")
  637. err = apper.App().db.DeleteAccount(userID)
  638. if err != nil {
  639. log.Error("%s", err)
  640. os.Exit(1)
  641. }
  642. log.Info("Success.")
  643. return nil
  644. }
  645. func connectToDatabase(app *App) {
  646. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  647. var db *sql.DB
  648. var err error
  649. if app.cfg.Database.Type == driverMySQL {
  650. 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())))
  651. db.SetMaxOpenConns(50)
  652. } else if app.cfg.Database.Type == driverSQLite {
  653. if !SQLiteEnabled {
  654. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  655. os.Exit(1)
  656. }
  657. if app.cfg.Database.FileName == "" {
  658. log.Error("SQLite database filename value in config.ini is empty.")
  659. os.Exit(1)
  660. }
  661. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  662. db.SetMaxOpenConns(1)
  663. } else {
  664. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  665. os.Exit(1)
  666. }
  667. if err != nil {
  668. log.Error("%s", err)
  669. os.Exit(1)
  670. }
  671. app.db = &datastore{db, app.cfg.Database.Type}
  672. }
  673. func shutdown(app *App) {
  674. log.Info("Closing database connection...")
  675. app.db.Close()
  676. }
  677. // CreateUser creates a new admin or normal user from the given credentials.
  678. func CreateUser(apper Apper, username, password string, isAdmin bool) error {
  679. // Create an admin user with --create-admin
  680. apper.LoadConfig()
  681. connectToDatabase(apper.App())
  682. defer shutdown(apper.App())
  683. // Ensure an admin / first user doesn't already exist
  684. firstUser, _ := apper.App().db.GetUserByID(1)
  685. if isAdmin {
  686. // Abort if trying to create admin user, but one already exists
  687. if firstUser != nil {
  688. return fmt.Errorf("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  689. }
  690. } else {
  691. // Abort if trying to create regular user, but no admin exists yet
  692. if firstUser == nil {
  693. return fmt.Errorf("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  694. }
  695. }
  696. // Create the user
  697. // Normalize and validate username
  698. desiredUsername := username
  699. username = getSlug(username, "")
  700. usernameDesc := username
  701. if username != desiredUsername {
  702. usernameDesc += " (originally: " + desiredUsername + ")"
  703. }
  704. if !author.IsValidUsername(apper.App().cfg, username) {
  705. return fmt.Errorf("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, apper.App().cfg.App.MinUsernameLen)
  706. }
  707. // Hash the password
  708. hashedPass, err := auth.HashPass([]byte(password))
  709. if err != nil {
  710. return fmt.Errorf("Unable to hash password: %v", err)
  711. }
  712. u := &User{
  713. Username: username,
  714. HashedPass: hashedPass,
  715. Created: time.Now().Truncate(time.Second).UTC(),
  716. }
  717. userType := "user"
  718. if isAdmin {
  719. userType = "admin"
  720. }
  721. log.Info("Creating %s %s...", userType, usernameDesc)
  722. err = apper.App().db.CreateUser(apper.App().Config(), u, desiredUsername)
  723. if err != nil {
  724. return fmt.Errorf("Unable to create user: %s", err)
  725. }
  726. log.Info("Done!")
  727. return nil
  728. }
  729. func adminInitDatabase(app *App) error {
  730. schemaFileName := "schema.sql"
  731. if app.cfg.Database.Type == driverSQLite {
  732. schemaFileName = "sqlite.sql"
  733. }
  734. schema, err := Asset(schemaFileName)
  735. if err != nil {
  736. return fmt.Errorf("Unable to load schema file: %v", err)
  737. }
  738. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  739. queries := strings.Split(string(schema), ";\n")
  740. for _, q := range queries {
  741. if strings.TrimSpace(q) == "" {
  742. continue
  743. }
  744. parts := tblReg.FindStringSubmatch(q)
  745. if len(parts) >= 3 {
  746. log.Info("Creating table %s...", parts[2])
  747. } else {
  748. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  749. }
  750. _, err = app.db.Exec(q)
  751. if err != nil {
  752. log.Error("%s", err)
  753. } else {
  754. log.Info("Created.")
  755. }
  756. }
  757. // Set up migrations table
  758. log.Info("Initializing appmigrations table...")
  759. err = migrations.SetInitialMigrations(migrations.NewDatastore(app.db.DB, app.db.driverName))
  760. if err != nil {
  761. return fmt.Errorf("Unable to set initial migrations: %v", err)
  762. }
  763. log.Info("Running migrations...")
  764. err = migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  765. if err != nil {
  766. return fmt.Errorf("migrate: %s", err)
  767. }
  768. log.Info("Done.")
  769. return nil
  770. }