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.
 
 
 
 
 

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