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.
 
 
 
 
 

956 lines
24 KiB

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