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.
 
 
 
 
 

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