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.
 
 
 
 
 

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