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.
 
 
 
 
 

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