A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

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