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.
 
 
 
 
 

935 line
24 KiB

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