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.
 
 
 
 
 

531 lines
15 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. "net/http"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/gorilla/mux"
  20. "github.com/writeas/impart"
  21. "github.com/writeas/web-core/auth"
  22. "github.com/writeas/web-core/log"
  23. "github.com/writeas/web-core/passgen"
  24. "github.com/writeas/writefreely/appstats"
  25. "github.com/writeas/writefreely/config"
  26. )
  27. var (
  28. appStartTime = time.Now()
  29. sysStatus systemStatus
  30. )
  31. const adminUsersPerPage = 30
  32. type systemStatus struct {
  33. Uptime string
  34. NumGoroutine int
  35. // General statistics.
  36. MemAllocated string // bytes allocated and still in use
  37. MemTotal string // bytes allocated (even if freed)
  38. MemSys string // bytes obtained from system (sum of XxxSys below)
  39. Lookups uint64 // number of pointer lookups
  40. MemMallocs uint64 // number of mallocs
  41. MemFrees uint64 // number of frees
  42. // Main allocation heap statistics.
  43. HeapAlloc string // bytes allocated and still in use
  44. HeapSys string // bytes obtained from system
  45. HeapIdle string // bytes in idle spans
  46. HeapInuse string // bytes in non-idle span
  47. HeapReleased string // bytes released to the OS
  48. HeapObjects uint64 // total number of allocated objects
  49. // Low-level fixed-size structure allocator statistics.
  50. // Inuse is bytes used now.
  51. // Sys is bytes obtained from system.
  52. StackInuse string // bootstrap stacks
  53. StackSys string
  54. MSpanInuse string // mspan structures
  55. MSpanSys string
  56. MCacheInuse string // mcache structures
  57. MCacheSys string
  58. BuckHashSys string // profiling bucket hash table
  59. GCSys string // GC metadata
  60. OtherSys string // other system allocations
  61. // Garbage collector statistics.
  62. NextGC string // next run in HeapAlloc time (bytes)
  63. LastGC string // last run in absolute time (ns)
  64. PauseTotalNs string
  65. PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
  66. NumGC uint32
  67. }
  68. type inspectedCollection struct {
  69. CollectionObj
  70. Followers int
  71. LastPost string
  72. }
  73. type instanceContent struct {
  74. ID string
  75. Type string
  76. Title sql.NullString
  77. Content string
  78. Updated time.Time
  79. }
  80. func (c instanceContent) UpdatedFriendly() string {
  81. /*
  82. // TODO: accept a locale in this method and use that for the format
  83. var loc monday.Locale = monday.LocaleEnUS
  84. return monday.Format(u.Created, monday.DateTimeFormatsByLocale[loc], loc)
  85. */
  86. return c.Updated.Format("January 2, 2006, 3:04 PM")
  87. }
  88. func handleViewAdminDash(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  89. updateAppStats()
  90. p := struct {
  91. *UserPage
  92. SysStatus systemStatus
  93. Config config.AppCfg
  94. Message, ConfigMessage string
  95. }{
  96. UserPage: NewUserPage(app, r, u, "Admin", nil),
  97. SysStatus: sysStatus,
  98. Config: app.cfg.App,
  99. Message: r.FormValue("m"),
  100. ConfigMessage: r.FormValue("cm"),
  101. }
  102. showUserPage(w, "admin", p)
  103. return nil
  104. }
  105. func handleViewAdminUsers(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  106. p := struct {
  107. *UserPage
  108. Config config.AppCfg
  109. Message string
  110. Users *[]User
  111. CurPage int
  112. TotalUsers int64
  113. TotalPages []int
  114. }{
  115. UserPage: NewUserPage(app, r, u, "Users", nil),
  116. Config: app.cfg.App,
  117. Message: r.FormValue("m"),
  118. }
  119. p.TotalUsers = app.db.GetAllUsersCount()
  120. ttlPages := p.TotalUsers / adminUsersPerPage
  121. p.TotalPages = []int{}
  122. for i := 1; i <= int(ttlPages); i++ {
  123. p.TotalPages = append(p.TotalPages, i)
  124. }
  125. var err error
  126. p.CurPage, err = strconv.Atoi(r.FormValue("p"))
  127. if err != nil || p.CurPage < 1 {
  128. p.CurPage = 1
  129. } else if p.CurPage > int(ttlPages) {
  130. p.CurPage = int(ttlPages)
  131. }
  132. p.Users, err = app.db.GetAllUsers(uint(p.CurPage))
  133. if err != nil {
  134. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get users: %v", err)}
  135. }
  136. showUserPage(w, "users", p)
  137. return nil
  138. }
  139. func handleViewAdminUser(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  140. vars := mux.Vars(r)
  141. username := vars["username"]
  142. if username == "" {
  143. return impart.HTTPError{http.StatusFound, "/admin/users"}
  144. }
  145. p := struct {
  146. *UserPage
  147. Config config.AppCfg
  148. Message string
  149. User *User
  150. Colls []inspectedCollection
  151. LastPost string
  152. NewPassword string
  153. TotalPosts int64
  154. ClearEmail string
  155. }{
  156. Config: app.cfg.App,
  157. Message: r.FormValue("m"),
  158. Colls: []inspectedCollection{},
  159. }
  160. var err error
  161. p.User, err = app.db.GetUserForAuth(username)
  162. if err != nil {
  163. if err == ErrUserNotFound {
  164. return err
  165. }
  166. log.Error("Could not get user: %v", err)
  167. return impart.HTTPError{http.StatusInternalServerError, err.Error()}
  168. }
  169. flashes, _ := getSessionFlashes(app, w, r, nil)
  170. for _, flash := range flashes {
  171. if strings.HasPrefix(flash, "SUCCESS: ") {
  172. p.NewPassword = strings.TrimPrefix(flash, "SUCCESS: ")
  173. p.ClearEmail = p.User.EmailClear(app.keys)
  174. }
  175. }
  176. p.UserPage = NewUserPage(app, r, u, p.User.Username, nil)
  177. p.TotalPosts = app.db.GetUserPostsCount(p.User.ID)
  178. lp, err := app.db.GetUserLastPostTime(p.User.ID)
  179. if err != nil {
  180. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user's last post time: %v", err)}
  181. }
  182. if lp != nil {
  183. p.LastPost = lp.Format("January 2, 2006, 3:04 PM")
  184. }
  185. colls, err := app.db.GetCollections(p.User, app.cfg.App.Host)
  186. if err != nil {
  187. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user's collections: %v", err)}
  188. }
  189. for _, c := range *colls {
  190. ic := inspectedCollection{
  191. CollectionObj: CollectionObj{Collection: c},
  192. }
  193. if app.cfg.App.Federation {
  194. folls, err := app.db.GetAPFollowers(&c)
  195. if err == nil {
  196. // TODO: handle error here (at least log it)
  197. ic.Followers = len(*folls)
  198. }
  199. }
  200. app.db.GetPostsCount(&ic.CollectionObj, true)
  201. lp, err := app.db.GetCollectionLastPostTime(c.ID)
  202. if err != nil {
  203. log.Error("Didn't get last post time for collection %d: %v", c.ID, err)
  204. }
  205. if lp != nil {
  206. ic.LastPost = lp.Format("January 2, 2006, 3:04 PM")
  207. }
  208. p.Colls = append(p.Colls, ic)
  209. }
  210. showUserPage(w, "view-user", p)
  211. return nil
  212. }
  213. func handleAdminToggleUserStatus(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  214. vars := mux.Vars(r)
  215. username := vars["username"]
  216. if username == "" {
  217. return impart.HTTPError{http.StatusFound, "/admin/users"}
  218. }
  219. user, err := app.db.GetUserForAuth(username)
  220. if err != nil {
  221. log.Error("failed to get user: %v", err)
  222. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user from username: %v", err)}
  223. }
  224. if user.IsSilenced() {
  225. err = app.db.SetUserStatus(user.ID, UserActive)
  226. } else {
  227. err = app.db.SetUserStatus(user.ID, UserSilenced)
  228. }
  229. if err != nil {
  230. log.Error("toggle user silenced: %v", err)
  231. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not toggle user status: %v", err)}
  232. }
  233. return impart.HTTPError{http.StatusFound, fmt.Sprintf("/admin/user/%s#status", username)}
  234. }
  235. func handleAdminResetUserPass(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  236. vars := mux.Vars(r)
  237. username := vars["username"]
  238. if username == "" {
  239. return impart.HTTPError{http.StatusFound, "/admin/users"}
  240. }
  241. // Generate new random password since none supplied
  242. pass := passgen.NewWordish()
  243. hashedPass, err := auth.HashPass([]byte(pass))
  244. if err != nil {
  245. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not create password hash: %v", err)}
  246. }
  247. userIDVal := r.FormValue("user")
  248. log.Info("ADMIN: Changing user %s password", userIDVal)
  249. id, err := strconv.Atoi(userIDVal)
  250. if err != nil {
  251. return impart.HTTPError{http.StatusBadRequest, fmt.Sprintf("Invalid user ID: %v", err)}
  252. }
  253. err = app.db.ChangePassphrase(int64(id), true, "", hashedPass)
  254. if err != nil {
  255. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not update passphrase: %v", err)}
  256. }
  257. log.Info("ADMIN: Successfully changed.")
  258. addSessionFlash(app, w, r, fmt.Sprintf("SUCCESS: %s", pass), nil)
  259. return impart.HTTPError{http.StatusFound, fmt.Sprintf("/admin/user/%s", username)}
  260. }
  261. func handleViewAdminPages(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  262. p := struct {
  263. *UserPage
  264. Config config.AppCfg
  265. Message string
  266. Pages []*instanceContent
  267. }{
  268. UserPage: NewUserPage(app, r, u, "Pages", nil),
  269. Config: app.cfg.App,
  270. Message: r.FormValue("m"),
  271. }
  272. var err error
  273. p.Pages, err = app.db.GetInstancePages()
  274. if err != nil {
  275. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get pages: %v", err)}
  276. }
  277. // Add in default pages
  278. var hasAbout, hasPrivacy bool
  279. for i, c := range p.Pages {
  280. if hasAbout && hasPrivacy {
  281. break
  282. }
  283. if c.ID == "about" {
  284. hasAbout = true
  285. if !c.Title.Valid {
  286. p.Pages[i].Title = defaultAboutTitle(app.cfg)
  287. }
  288. } else if c.ID == "privacy" {
  289. hasPrivacy = true
  290. if !c.Title.Valid {
  291. p.Pages[i].Title = defaultPrivacyTitle()
  292. }
  293. }
  294. }
  295. if !hasAbout {
  296. p.Pages = append(p.Pages, &instanceContent{
  297. ID: "about",
  298. Title: defaultAboutTitle(app.cfg),
  299. Content: defaultAboutPage(app.cfg),
  300. Updated: defaultPageUpdatedTime,
  301. })
  302. }
  303. if !hasPrivacy {
  304. p.Pages = append(p.Pages, &instanceContent{
  305. ID: "privacy",
  306. Title: defaultPrivacyTitle(),
  307. Content: defaultPrivacyPolicy(app.cfg),
  308. Updated: defaultPageUpdatedTime,
  309. })
  310. }
  311. showUserPage(w, "pages", p)
  312. return nil
  313. }
  314. func handleViewAdminPage(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  315. vars := mux.Vars(r)
  316. slug := vars["slug"]
  317. if slug == "" {
  318. return impart.HTTPError{http.StatusFound, "/admin/pages"}
  319. }
  320. p := struct {
  321. *UserPage
  322. Config config.AppCfg
  323. Message string
  324. Banner *instanceContent
  325. Content *instanceContent
  326. }{
  327. Config: app.cfg.App,
  328. Message: r.FormValue("m"),
  329. }
  330. var err error
  331. // Get pre-defined pages, or select slug
  332. if slug == "about" {
  333. p.Content, err = getAboutPage(app)
  334. } else if slug == "privacy" {
  335. p.Content, err = getPrivacyPage(app)
  336. } else if slug == "landing" {
  337. p.Banner, err = getLandingBanner(app)
  338. if err != nil {
  339. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get banner: %v", err)}
  340. }
  341. p.Content, err = getLandingBody(app)
  342. p.Content.ID = "landing"
  343. } else if slug == "reader" {
  344. p.Content, err = getReaderSection(app)
  345. } else {
  346. p.Content, err = app.db.GetDynamicContent(slug)
  347. }
  348. if err != nil {
  349. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get page: %v", err)}
  350. }
  351. title := "New page"
  352. if p.Content != nil {
  353. title = "Edit " + p.Content.ID
  354. } else {
  355. p.Content = &instanceContent{}
  356. }
  357. p.UserPage = NewUserPage(app, r, u, title, nil)
  358. showUserPage(w, "view-page", p)
  359. return nil
  360. }
  361. func handleAdminUpdateSite(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
  362. vars := mux.Vars(r)
  363. id := vars["page"]
  364. // Validate
  365. if id != "about" && id != "privacy" && id != "landing" && id != "reader" {
  366. return impart.HTTPError{http.StatusNotFound, "No such page."}
  367. }
  368. var err error
  369. m := ""
  370. if id == "landing" {
  371. // Handle special landing page
  372. err = app.db.UpdateDynamicContent("landing-banner", "", r.FormValue("banner"), "section")
  373. if err != nil {
  374. m = "?m=" + err.Error()
  375. return impart.HTTPError{http.StatusFound, "/admin/page/" + id + m}
  376. }
  377. err = app.db.UpdateDynamicContent("landing-body", "", r.FormValue("content"), "section")
  378. } else if id == "reader" {
  379. // Update sections with titles
  380. err = app.db.UpdateDynamicContent(id, r.FormValue("title"), r.FormValue("content"), "section")
  381. } else {
  382. // Update page
  383. err = app.db.UpdateDynamicContent(id, r.FormValue("title"), r.FormValue("content"), "page")
  384. }
  385. if err != nil {
  386. m = "?m=" + err.Error()
  387. }
  388. return impart.HTTPError{http.StatusFound, "/admin/page/" + id + m}
  389. }
  390. func handleAdminUpdateConfig(apper Apper, u *User, w http.ResponseWriter, r *http.Request) error {
  391. apper.App().cfg.App.SiteName = r.FormValue("site_name")
  392. apper.App().cfg.App.SiteDesc = r.FormValue("site_desc")
  393. apper.App().cfg.App.Landing = r.FormValue("landing")
  394. apper.App().cfg.App.OpenRegistration = r.FormValue("open_registration") == "on"
  395. mul, err := strconv.Atoi(r.FormValue("min_username_len"))
  396. if err == nil {
  397. apper.App().cfg.App.MinUsernameLen = mul
  398. }
  399. mb, err := strconv.Atoi(r.FormValue("max_blogs"))
  400. if err == nil {
  401. apper.App().cfg.App.MaxBlogs = mb
  402. }
  403. apper.App().cfg.App.Federation = r.FormValue("federation") == "on"
  404. apper.App().cfg.App.PublicStats = r.FormValue("public_stats") == "on"
  405. apper.App().cfg.App.Private = r.FormValue("private") == "on"
  406. apper.App().cfg.App.LocalTimeline = r.FormValue("local_timeline") == "on"
  407. if apper.App().cfg.App.LocalTimeline && apper.App().timeline == nil {
  408. log.Info("Initializing local timeline...")
  409. initLocalTimeline(apper.App())
  410. }
  411. apper.App().cfg.App.UserInvites = r.FormValue("user_invites")
  412. if apper.App().cfg.App.UserInvites == "none" {
  413. apper.App().cfg.App.UserInvites = ""
  414. }
  415. apper.App().cfg.App.DefaultVisibility = r.FormValue("default_visibility")
  416. m := "?cm=Configuration+saved."
  417. err = apper.SaveConfig(apper.App().cfg)
  418. if err != nil {
  419. m = "?cm=" + err.Error()
  420. }
  421. return impart.HTTPError{http.StatusFound, "/admin" + m + "#config"}
  422. }
  423. func updateAppStats() {
  424. sysStatus.Uptime = appstats.TimeSincePro(appStartTime)
  425. m := new(runtime.MemStats)
  426. runtime.ReadMemStats(m)
  427. sysStatus.NumGoroutine = runtime.NumGoroutine()
  428. sysStatus.MemAllocated = appstats.FileSize(int64(m.Alloc))
  429. sysStatus.MemTotal = appstats.FileSize(int64(m.TotalAlloc))
  430. sysStatus.MemSys = appstats.FileSize(int64(m.Sys))
  431. sysStatus.Lookups = m.Lookups
  432. sysStatus.MemMallocs = m.Mallocs
  433. sysStatus.MemFrees = m.Frees
  434. sysStatus.HeapAlloc = appstats.FileSize(int64(m.HeapAlloc))
  435. sysStatus.HeapSys = appstats.FileSize(int64(m.HeapSys))
  436. sysStatus.HeapIdle = appstats.FileSize(int64(m.HeapIdle))
  437. sysStatus.HeapInuse = appstats.FileSize(int64(m.HeapInuse))
  438. sysStatus.HeapReleased = appstats.FileSize(int64(m.HeapReleased))
  439. sysStatus.HeapObjects = m.HeapObjects
  440. sysStatus.StackInuse = appstats.FileSize(int64(m.StackInuse))
  441. sysStatus.StackSys = appstats.FileSize(int64(m.StackSys))
  442. sysStatus.MSpanInuse = appstats.FileSize(int64(m.MSpanInuse))
  443. sysStatus.MSpanSys = appstats.FileSize(int64(m.MSpanSys))
  444. sysStatus.MCacheInuse = appstats.FileSize(int64(m.MCacheInuse))
  445. sysStatus.MCacheSys = appstats.FileSize(int64(m.MCacheSys))
  446. sysStatus.BuckHashSys = appstats.FileSize(int64(m.BuckHashSys))
  447. sysStatus.GCSys = appstats.FileSize(int64(m.GCSys))
  448. sysStatus.OtherSys = appstats.FileSize(int64(m.OtherSys))
  449. sysStatus.NextGC = appstats.FileSize(int64(m.NextGC))
  450. sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000)
  451. sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
  452. sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
  453. sysStatus.NumGC = m.NumGC
  454. }
  455. func adminResetPassword(app *App, u *User, newPass string) error {
  456. hashedPass, err := auth.HashPass([]byte(newPass))
  457. if err != nil {
  458. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not create password hash: %v", err)}
  459. }
  460. err = app.db.ChangePassphrase(u.ID, true, "", hashedPass)
  461. if err != nil {
  462. return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not update passphrase: %v", err)}
  463. }
  464. return nil
  465. }