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.
 
 
 
 
 

631 rivejä
16 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. "database/sql"
  13. "fmt"
  14. "html/template"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "os/signal"
  19. "path/filepath"
  20. "regexp"
  21. "strings"
  22. "syscall"
  23. "time"
  24. "github.com/gorilla/mux"
  25. "github.com/gorilla/schema"
  26. "github.com/gorilla/sessions"
  27. "github.com/manifoldco/promptui"
  28. "github.com/writeas/go-strip-markdown"
  29. "github.com/writeas/impart"
  30. "github.com/writeas/web-core/auth"
  31. "github.com/writeas/web-core/converter"
  32. "github.com/writeas/web-core/log"
  33. "github.com/writeas/writefreely/author"
  34. "github.com/writeas/writefreely/config"
  35. "github.com/writeas/writefreely/key"
  36. "github.com/writeas/writefreely/migrations"
  37. "github.com/writeas/writefreely/page"
  38. )
  39. const (
  40. staticDir = "static"
  41. assumedTitleLen = 80
  42. postsPerPage = 10
  43. serverSoftware = "WriteFreely"
  44. softwareURL = "https://writefreely.org"
  45. )
  46. var (
  47. debugging bool
  48. // Software version can be set from git env using -ldflags
  49. softwareVer = "0.9.0"
  50. // DEPRECATED VARS
  51. // TODO: pass app.cfg into GetCollection* calls so we can get these values
  52. // from Collection methods and we no longer need these.
  53. hostName string
  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. func (app *App) SetKeys(k *key.Keychain) {
  69. app.keys = k
  70. }
  71. // handleViewHome shows page at root path. Will be the Pad if logged in and the
  72. // catch-all landing page otherwise.
  73. func handleViewHome(app *App, w http.ResponseWriter, r *http.Request) error {
  74. if app.cfg.App.SingleUser {
  75. // Render blog index
  76. return handleViewCollection(app, w, r)
  77. }
  78. // Multi-user instance
  79. u := getUserSession(app, r)
  80. if u != nil {
  81. // User is logged in, so show the Pad
  82. return handleViewPad(app, w, r)
  83. }
  84. if land := app.cfg.App.LandingPath(); land != "/" {
  85. return impart.HTTPError{http.StatusFound, land}
  86. }
  87. p := struct {
  88. page.StaticPage
  89. Flashes []template.HTML
  90. }{
  91. StaticPage: pageForReq(app, r),
  92. }
  93. // Get error messages
  94. session, err := app.sessionStore.Get(r, cookieName)
  95. if err != nil {
  96. // Ignore this
  97. log.Error("Unable to get session in handleViewHome; ignoring: %v", err)
  98. }
  99. flashes, _ := getSessionFlashes(app, w, r, session)
  100. for _, flash := range flashes {
  101. p.Flashes = append(p.Flashes, template.HTML(flash))
  102. }
  103. // Show landing page
  104. return renderPage(w, "landing.tmpl", p)
  105. }
  106. func handleTemplatedPage(app *App, w http.ResponseWriter, r *http.Request, t *template.Template) error {
  107. p := struct {
  108. page.StaticPage
  109. ContentTitle string
  110. Content template.HTML
  111. PlainContent string
  112. Updated string
  113. AboutStats *InstanceStats
  114. }{
  115. StaticPage: pageForReq(app, r),
  116. }
  117. if r.URL.Path == "/about" || r.URL.Path == "/privacy" {
  118. var c *instanceContent
  119. var err error
  120. if r.URL.Path == "/about" {
  121. c, err = getAboutPage(app)
  122. // Fetch stats
  123. p.AboutStats = &InstanceStats{}
  124. p.AboutStats.NumPosts, _ = app.db.GetTotalPosts()
  125. p.AboutStats.NumBlogs, _ = app.db.GetTotalCollections()
  126. } else {
  127. c, err = getPrivacyPage(app)
  128. }
  129. if err != nil {
  130. return err
  131. }
  132. p.ContentTitle = c.Title.String
  133. p.Content = template.HTML(applyMarkdown([]byte(c.Content), ""))
  134. p.PlainContent = shortPostDescription(stripmd.Strip(c.Content))
  135. if !c.Updated.IsZero() {
  136. p.Updated = c.Updated.Format("January 2, 2006")
  137. }
  138. }
  139. // Serve templated page
  140. err := t.ExecuteTemplate(w, "base", p)
  141. if err != nil {
  142. log.Error("Unable to render page: %v", err)
  143. }
  144. return nil
  145. }
  146. func pageForReq(app *App, r *http.Request) page.StaticPage {
  147. p := page.StaticPage{
  148. AppCfg: app.cfg.App,
  149. Path: r.URL.Path,
  150. Version: "v" + softwareVer,
  151. }
  152. // Add user information, if given
  153. var u *User
  154. accessToken := r.FormValue("t")
  155. if accessToken != "" {
  156. userID := app.db.GetUserID(accessToken)
  157. if userID != -1 {
  158. var err error
  159. u, err = app.db.GetUserByID(userID)
  160. if err == nil {
  161. p.Username = u.Username
  162. }
  163. }
  164. } else {
  165. u = getUserSession(app, r)
  166. if u != nil {
  167. p.Username = u.Username
  168. }
  169. }
  170. return p
  171. }
  172. var fileRegex = regexp.MustCompile("/([^/]*\\.[^/]*)$")
  173. func Serve(app *App, debug bool) {
  174. debugging = debug
  175. log.Info("Initializing...")
  176. loadConfig(app)
  177. hostName = app.cfg.App.Host
  178. isSingleUser = app.cfg.App.SingleUser
  179. app.cfg.Server.Dev = debugging
  180. err := initTemplates(app.cfg)
  181. if err != nil {
  182. log.Error("load templates: %s", err)
  183. os.Exit(1)
  184. }
  185. // Load keys
  186. log.Info("Loading encryption keys...")
  187. initKeyPaths(app)
  188. err = initKeys(app)
  189. if err != nil {
  190. log.Error("\n%s\n", err)
  191. }
  192. // Initialize modules
  193. app.sessionStore = initSession(app)
  194. app.formDecoder = schema.NewDecoder()
  195. app.formDecoder.RegisterConverter(converter.NullJSONString{}, converter.ConvertJSONNullString)
  196. app.formDecoder.RegisterConverter(converter.NullJSONBool{}, converter.ConvertJSONNullBool)
  197. app.formDecoder.RegisterConverter(sql.NullString{}, converter.ConvertSQLNullString)
  198. app.formDecoder.RegisterConverter(sql.NullBool{}, converter.ConvertSQLNullBool)
  199. app.formDecoder.RegisterConverter(sql.NullInt64{}, converter.ConvertSQLNullInt64)
  200. app.formDecoder.RegisterConverter(sql.NullFloat64{}, converter.ConvertSQLNullFloat64)
  201. // Check database configuration
  202. if app.cfg.Database.Type == driverMySQL && (app.cfg.Database.User == "" || app.cfg.Database.Password == "") {
  203. log.Error("Database user or password not set.")
  204. os.Exit(1)
  205. }
  206. if app.cfg.Database.Host == "" {
  207. app.cfg.Database.Host = "localhost"
  208. }
  209. if app.cfg.Database.Database == "" {
  210. app.cfg.Database.Database = "writefreely"
  211. }
  212. connectToDatabase(app)
  213. defer shutdown(app)
  214. // Test database connection
  215. err = app.db.Ping()
  216. if err != nil {
  217. log.Error("Database ping failed: %s", err)
  218. }
  219. r := mux.NewRouter()
  220. handler := NewHandler(app)
  221. handler.SetErrorPages(&ErrorPages{
  222. NotFound: pages["404-general.tmpl"],
  223. Gone: pages["410.tmpl"],
  224. InternalServerError: pages["500.tmpl"],
  225. Blank: pages["blank.tmpl"],
  226. })
  227. // Handle app routes
  228. initRoutes(handler, r, app.cfg, app.db)
  229. // Handle local timeline, if enabled
  230. if app.cfg.App.LocalTimeline {
  231. log.Info("Initializing local timeline...")
  232. initLocalTimeline(app)
  233. }
  234. // Handle shutdown
  235. c := make(chan os.Signal, 2)
  236. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  237. go func() {
  238. <-c
  239. log.Info("Shutting down...")
  240. shutdown(app)
  241. log.Info("Done.")
  242. os.Exit(0)
  243. }()
  244. http.Handle("/", r)
  245. // Start web application server
  246. var bindAddress = app.cfg.Server.Bind
  247. if bindAddress == "" {
  248. bindAddress = "localhost"
  249. }
  250. if app.cfg.IsSecureStandalone() {
  251. log.Info("Serving redirects on http://%s:80", bindAddress)
  252. go func() {
  253. err = http.ListenAndServe(
  254. fmt.Sprintf("%s:80", bindAddress), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  255. http.Redirect(w, r, app.cfg.App.Host, http.StatusMovedPermanently)
  256. }))
  257. log.Error("Unable to start redirect server: %v", err)
  258. }()
  259. log.Info("Serving on https://%s:443", bindAddress)
  260. log.Info("---")
  261. err = http.ListenAndServeTLS(
  262. fmt.Sprintf("%s:443", bindAddress), app.cfg.Server.TLSCertPath, app.cfg.Server.TLSKeyPath, nil)
  263. } else {
  264. log.Info("Serving on http://%s:%d\n", bindAddress, app.cfg.Server.Port)
  265. log.Info("---")
  266. err = http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddress, app.cfg.Server.Port), nil)
  267. }
  268. if err != nil {
  269. log.Error("Unable to start: %v", err)
  270. os.Exit(1)
  271. }
  272. }
  273. // OutputVersion prints out the version of the application.
  274. func OutputVersion() {
  275. fmt.Println(serverSoftware + " " + softwareVer)
  276. }
  277. // NewApp creates a new app instance.
  278. func NewApp(cfgFile string) *App {
  279. return &App{
  280. cfgFile: cfgFile,
  281. }
  282. }
  283. // CreateConfig creates a default configuration and saves it to the app's cfgFile.
  284. func CreateConfig(app *App) error {
  285. log.Info("Creating configuration...")
  286. c := config.New()
  287. log.Info("Saving configuration %s...", app.cfgFile)
  288. err := config.Save(c, app.cfgFile)
  289. if err != nil {
  290. return fmt.Errorf("Unable to save configuration: %v", err)
  291. }
  292. return nil
  293. }
  294. // DoConfig runs the interactive configuration process.
  295. func DoConfig(app *App) {
  296. d, err := config.Configure(app.cfgFile)
  297. if err != nil {
  298. log.Error("Unable to configure: %v", err)
  299. os.Exit(1)
  300. }
  301. if d.User != nil {
  302. app.cfg = d.Config
  303. connectToDatabase(app)
  304. defer shutdown(app)
  305. if !app.db.DatabaseInitialized() {
  306. err = adminInitDatabase(app)
  307. if err != nil {
  308. log.Error(err.Error())
  309. os.Exit(1)
  310. }
  311. }
  312. u := &User{
  313. Username: d.User.Username,
  314. HashedPass: d.User.HashedPass,
  315. Created: time.Now().Truncate(time.Second).UTC(),
  316. }
  317. // Create blog
  318. log.Info("Creating user %s...\n", u.Username)
  319. err = app.db.CreateUser(u, app.cfg.App.SiteName)
  320. if err != nil {
  321. log.Error("Unable to create user: %s", err)
  322. os.Exit(1)
  323. }
  324. log.Info("Done!")
  325. }
  326. os.Exit(0)
  327. }
  328. // GenerateKeys creates app encryption keys and saves them into the configured KeysParentDir.
  329. func GenerateKeys(app *App) error {
  330. // Read keys path from config
  331. loadConfig(app)
  332. // Create keys dir if it doesn't exist yet
  333. fullKeysDir := filepath.Join(app.cfg.Server.KeysParentDir, keysDir)
  334. if _, err := os.Stat(fullKeysDir); os.IsNotExist(err) {
  335. err = os.Mkdir(fullKeysDir, 0700)
  336. if err != nil {
  337. return err
  338. }
  339. }
  340. // Generate keys
  341. initKeyPaths(app)
  342. var keyErrs error
  343. err := generateKey(emailKeyPath)
  344. if err != nil {
  345. keyErrs = err
  346. }
  347. err = generateKey(cookieAuthKeyPath)
  348. if err != nil {
  349. keyErrs = err
  350. }
  351. err = generateKey(cookieKeyPath)
  352. if err != nil {
  353. keyErrs = err
  354. }
  355. return keyErrs
  356. }
  357. // CreateSchema creates all database tables needed for the application.
  358. func CreateSchema(app *App) error {
  359. loadConfig(app)
  360. connectToDatabase(app)
  361. defer shutdown(app)
  362. err := adminInitDatabase(app)
  363. if err != nil {
  364. return err
  365. }
  366. return nil
  367. }
  368. // Migrate runs all necessary database migrations.
  369. func Migrate(app *App) error {
  370. loadConfig(app)
  371. connectToDatabase(app)
  372. defer shutdown(app)
  373. err := migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  374. if err != nil {
  375. return fmt.Errorf("migrate: %s", err)
  376. }
  377. return nil
  378. }
  379. // ResetPassword runs the interactive password reset process.
  380. func ResetPassword(app *App, username string) error {
  381. // Connect to the database
  382. loadConfig(app)
  383. connectToDatabase(app)
  384. defer shutdown(app)
  385. // Fetch user
  386. u, err := app.db.GetUserForAuth(username)
  387. if err != nil {
  388. log.Error("Get user: %s", err)
  389. os.Exit(1)
  390. }
  391. // Prompt for new password
  392. prompt := promptui.Prompt{
  393. Templates: &promptui.PromptTemplates{
  394. Success: "{{ . | bold | faint }}: ",
  395. },
  396. Label: "New password",
  397. Mask: '*',
  398. }
  399. newPass, err := prompt.Run()
  400. if err != nil {
  401. log.Error("%s", err)
  402. os.Exit(1)
  403. }
  404. // Do the update
  405. log.Info("Updating...")
  406. err = adminResetPassword(app, u, newPass)
  407. if err != nil {
  408. log.Error("%s", err)
  409. os.Exit(1)
  410. }
  411. log.Info("Success.")
  412. return nil
  413. }
  414. func loadConfig(app *App) {
  415. log.Info("Loading %s configuration...", app.cfgFile)
  416. cfg, err := config.Load(app.cfgFile)
  417. if err != nil {
  418. log.Error("Unable to load configuration: %v", err)
  419. os.Exit(1)
  420. }
  421. app.cfg = cfg
  422. }
  423. func connectToDatabase(app *App) {
  424. log.Info("Connecting to %s database...", app.cfg.Database.Type)
  425. var db *sql.DB
  426. var err error
  427. if app.cfg.Database.Type == driverMySQL {
  428. 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())))
  429. db.SetMaxOpenConns(50)
  430. } else if app.cfg.Database.Type == driverSQLite {
  431. if !SQLiteEnabled {
  432. log.Error("Invalid database type '%s'. Binary wasn't compiled with SQLite3 support.", app.cfg.Database.Type)
  433. os.Exit(1)
  434. }
  435. if app.cfg.Database.FileName == "" {
  436. log.Error("SQLite database filename value in config.ini is empty.")
  437. os.Exit(1)
  438. }
  439. db, err = sql.Open("sqlite3_with_regex", app.cfg.Database.FileName+"?parseTime=true&cached=shared")
  440. db.SetMaxOpenConns(1)
  441. } else {
  442. log.Error("Invalid database type '%s'. Only 'mysql' and 'sqlite3' are supported right now.", app.cfg.Database.Type)
  443. os.Exit(1)
  444. }
  445. if err != nil {
  446. log.Error("%s", err)
  447. os.Exit(1)
  448. }
  449. app.db = &datastore{db, app.cfg.Database.Type}
  450. }
  451. func shutdown(app *App) {
  452. log.Info("Closing database connection...")
  453. app.db.Close()
  454. }
  455. // CreateUser creates a new admin or normal user from the given credentials.
  456. func CreateUser(app *App, username, password string, isAdmin bool) error {
  457. // Create an admin user with --create-admin
  458. loadConfig(app)
  459. connectToDatabase(app)
  460. defer shutdown(app)
  461. // Ensure an admin / first user doesn't already exist
  462. firstUser, _ := app.db.GetUserByID(1)
  463. if isAdmin {
  464. // Abort if trying to create admin user, but one already exists
  465. if firstUser != nil {
  466. return fmt.Errorf("Admin user already exists (%s). Create a regular user with: writefreely --create-user", firstUser.Username)
  467. }
  468. } else {
  469. // Abort if trying to create regular user, but no admin exists yet
  470. if firstUser == nil {
  471. return fmt.Errorf("No admin user exists yet. Create an admin first with: writefreely --create-admin")
  472. }
  473. }
  474. // Create the user
  475. // Normalize and validate username
  476. desiredUsername := username
  477. username = getSlug(username, "")
  478. usernameDesc := username
  479. if username != desiredUsername {
  480. usernameDesc += " (originally: " + desiredUsername + ")"
  481. }
  482. if !author.IsValidUsername(app.cfg, username) {
  483. return fmt.Errorf("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, app.cfg.App.MinUsernameLen)
  484. }
  485. // Hash the password
  486. hashedPass, err := auth.HashPass([]byte(password))
  487. if err != nil {
  488. return fmt.Errorf("Unable to hash password: %v", err)
  489. }
  490. u := &User{
  491. Username: username,
  492. HashedPass: hashedPass,
  493. Created: time.Now().Truncate(time.Second).UTC(),
  494. }
  495. userType := "user"
  496. if isAdmin {
  497. userType = "admin"
  498. }
  499. log.Info("Creating %s %s...", userType, usernameDesc)
  500. err = app.db.CreateUser(u, desiredUsername)
  501. if err != nil {
  502. return fmt.Errorf("Unable to create user: %s", err)
  503. }
  504. log.Info("Done!")
  505. return nil
  506. }
  507. func adminInitDatabase(app *App) error {
  508. schemaFileName := "schema.sql"
  509. if app.cfg.Database.Type == driverSQLite {
  510. schemaFileName = "sqlite.sql"
  511. }
  512. schema, err := Asset(schemaFileName)
  513. if err != nil {
  514. return fmt.Errorf("Unable to load schema file: %v", err)
  515. }
  516. tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`")
  517. queries := strings.Split(string(schema), ";\n")
  518. for _, q := range queries {
  519. if strings.TrimSpace(q) == "" {
  520. continue
  521. }
  522. parts := tblReg.FindStringSubmatch(q)
  523. if len(parts) >= 3 {
  524. log.Info("Creating table %s...", parts[2])
  525. } else {
  526. log.Info("Creating table ??? (Weird query) No match in: %v", parts)
  527. }
  528. _, err = app.db.Exec(q)
  529. if err != nil {
  530. log.Error("%s", err)
  531. } else {
  532. log.Info("Created.")
  533. }
  534. }
  535. // Set up migrations table
  536. log.Info("Initializing appmigrations table...")
  537. err = migrations.SetInitialMigrations(migrations.NewDatastore(app.db.DB, app.db.driverName))
  538. if err != nil {
  539. return fmt.Errorf("Unable to set initial migrations: %v", err)
  540. }
  541. log.Info("Running migrations...")
  542. err = migrations.Migrate(migrations.NewDatastore(app.db.DB, app.db.driverName))
  543. if err != nil {
  544. return fmt.Errorf("migrate: %s", err)
  545. }
  546. log.Info("Done.")
  547. return nil
  548. }