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.
 
 
 
 
 

916 lines
24 KiB

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