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.
 
 
 
 
 

2647 lines
80 KiB

  1. /*
  2. * Copyright © 2018-2020 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. "context"
  13. "database/sql"
  14. "fmt"
  15. wf_db "github.com/writeas/writefreely/db"
  16. "net/http"
  17. "strings"
  18. "time"
  19. "github.com/guregu/null"
  20. "github.com/guregu/null/zero"
  21. uuid "github.com/nu7hatch/gouuid"
  22. "github.com/writeas/activityserve"
  23. "github.com/writeas/impart"
  24. "github.com/writeas/nerds/store"
  25. "github.com/writeas/web-core/activitypub"
  26. "github.com/writeas/web-core/auth"
  27. "github.com/writeas/web-core/data"
  28. "github.com/writeas/web-core/id"
  29. "github.com/writeas/web-core/log"
  30. "github.com/writeas/web-core/query"
  31. "github.com/writeas/writefreely/author"
  32. "github.com/writeas/writefreely/config"
  33. "github.com/writeas/writefreely/key"
  34. )
  35. const (
  36. mySQLErrDuplicateKey = 1062
  37. mySQLErrCollationMix = 1267
  38. mySQLErrTooManyConns = 1040
  39. mySQLErrMaxUserConns = 1203
  40. driverMySQL = "mysql"
  41. driverSQLite = "sqlite3"
  42. )
  43. var (
  44. SQLiteEnabled bool
  45. )
  46. type writestore interface {
  47. CreateUser(*config.Config, *User, string) error
  48. UpdateUserEmail(keys *key.Keychain, userID int64, email string) error
  49. UpdateEncryptedUserEmail(int64, []byte) error
  50. GetUserByID(int64) (*User, error)
  51. GetUserForAuth(string) (*User, error)
  52. GetUserForAuthByID(int64) (*User, error)
  53. GetUserNameFromToken(string) (string, error)
  54. GetUserDataFromToken(string) (int64, string, error)
  55. GetAPIUser(header string) (*User, error)
  56. GetUserID(accessToken string) int64
  57. GetUserIDPrivilege(accessToken string) (userID int64, sudo bool)
  58. DeleteToken(accessToken []byte) error
  59. FetchLastAccessToken(userID int64) string
  60. GetAccessToken(userID int64) (string, error)
  61. GetTemporaryAccessToken(userID int64, validSecs int) (string, error)
  62. GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error)
  63. DeleteAccount(userID int64) error
  64. ChangeSettings(app *App, u *User, s *userSettings) error
  65. ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error
  66. GetCollections(u *User, hostName string) (*[]Collection, error)
  67. GetPublishableCollections(u *User, hostName string) (*[]Collection, error)
  68. GetMeStats(u *User) userMeStats
  69. GetTotalCollections() (int64, error)
  70. GetTotalPosts() (int64, error)
  71. GetTopPosts(u *User, alias string) (*[]PublicPost, error)
  72. GetAnonymousPosts(u *User) (*[]PublicPost, error)
  73. GetUserPosts(u *User) (*[]PublicPost, error)
  74. CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error)
  75. CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error)
  76. UpdateOwnedPost(post *AuthenticatedPost, userID int64) error
  77. GetEditablePost(id, editToken string) (*PublicPost, error)
  78. PostIDExists(id string) bool
  79. GetPost(id string, collectionID int64) (*PublicPost, error)
  80. GetOwnedPost(id string, ownerID int64) (*PublicPost, error)
  81. GetPostProperty(id string, collectionID int64, property string) (interface{}, error)
  82. CreateCollectionFromToken(*config.Config, string, string, string) (*Collection, error)
  83. CreateCollection(*config.Config, string, string, int64) (*Collection, error)
  84. GetCollectionBy(condition string, value interface{}) (*Collection, error)
  85. GetCollection(alias string) (*Collection, error)
  86. GetCollectionForPad(alias string) (*Collection, error)
  87. GetCollectionByID(id int64) (*Collection, error)
  88. UpdateCollection(c *SubmittedCollection, alias string) error
  89. DeleteCollection(alias string, userID int64) error
  90. UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error
  91. GetLastPinnedPostPos(collID int64) int64
  92. GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error)
  93. RemoveCollectionRedirect(t *sql.Tx, alias string) error
  94. GetCollectionRedirect(alias string) (new string)
  95. IsCollectionAttributeOn(id int64, attr string) bool
  96. CollectionHasAttribute(id int64, attr string) bool
  97. CanCollect(cpr *ClaimPostRequest, userID int64) bool
  98. AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error)
  99. DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error)
  100. ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error)
  101. GetPostsCount(c *CollectionObj, includeFuture bool)
  102. GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error)
  103. GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error)
  104. GetAPFollowers(c *Collection) (*[]RemoteUser, error)
  105. GetAPActorKeys(collectionID int64) ([]byte, []byte)
  106. CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error
  107. GetUserInvites(userID int64) (*[]Invite, error)
  108. GetUserInvite(id string) (*Invite, error)
  109. GetUsersInvitedCount(id string) int64
  110. CreateInvitedUser(inviteID string, userID int64) error
  111. GetDynamicContent(id string) (*instanceContent, error)
  112. UpdateDynamicContent(id, title, content, contentType string) error
  113. GetAllUsers(page uint) (*[]User, error)
  114. GetAllUsersCount() int64
  115. GetUserLastPostTime(id int64) (*time.Time, error)
  116. GetCollectionLastPostTime(id int64) (*time.Time, error)
  117. GetIDForRemoteUser(context.Context, string, string, string) (int64, error)
  118. RecordRemoteUserID(context.Context, int64, string, string, string, string) error
  119. ValidateOAuthState(context.Context, string) (string, string, error)
  120. GenerateOAuthState(context.Context, string, string) (string, error)
  121. DatabaseInitialized() bool
  122. }
  123. type datastore struct {
  124. *sql.DB
  125. driverName string
  126. }
  127. var _ writestore = &datastore{}
  128. func (db *datastore) now() string {
  129. if db.driverName == driverSQLite {
  130. return "strftime('%Y-%m-%d %H:%M:%S','now')"
  131. }
  132. return "NOW()"
  133. }
  134. func (db *datastore) clip(field string, l int) string {
  135. if db.driverName == driverSQLite {
  136. return fmt.Sprintf("SUBSTR(%s, 0, %d)", field, l)
  137. }
  138. return fmt.Sprintf("LEFT(%s, %d)", field, l)
  139. }
  140. func (db *datastore) upsert(indexedCols ...string) string {
  141. if db.driverName == driverSQLite {
  142. // NOTE: SQLite UPSERT syntax only works in v3.24.0 (2018-06-04) or later
  143. // Leaving this for whenever we can upgrade and include it in our binary
  144. cc := strings.Join(indexedCols, ", ")
  145. return "ON CONFLICT(" + cc + ") DO UPDATE SET"
  146. }
  147. return "ON DUPLICATE KEY UPDATE"
  148. }
  149. func (db *datastore) dateSub(l int, unit string) string {
  150. if db.driverName == driverSQLite {
  151. return fmt.Sprintf("DATETIME('now', '-%d %s')", l, unit)
  152. }
  153. return fmt.Sprintf("DATE_SUB(NOW(), INTERVAL %d %s)", l, unit)
  154. }
  155. func (db *datastore) CreateUser(cfg *config.Config, u *User, collectionTitle string) error {
  156. if db.PostIDExists(u.Username) {
  157. return impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  158. }
  159. // New users get a `users` and `collections` row.
  160. t, err := db.Begin()
  161. if err != nil {
  162. return err
  163. }
  164. // 1. Add to `users` table
  165. // NOTE: Assumes User's Password is already hashed!
  166. res, err := t.Exec("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", u.Username, u.HashedPass, u.Email)
  167. if err != nil {
  168. t.Rollback()
  169. if db.isDuplicateKeyErr(err) {
  170. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  171. }
  172. log.Error("Rolling back users INSERT: %v\n", err)
  173. return err
  174. }
  175. u.ID, err = res.LastInsertId()
  176. if err != nil {
  177. t.Rollback()
  178. log.Error("Rolling back after LastInsertId: %v\n", err)
  179. return err
  180. }
  181. // 2. Create user's Collection
  182. if collectionTitle == "" {
  183. collectionTitle = u.Username
  184. }
  185. res, err = t.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", u.Username, collectionTitle, "", defaultVisibility(cfg), u.ID, 0)
  186. if err != nil {
  187. t.Rollback()
  188. if db.isDuplicateKeyErr(err) {
  189. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  190. }
  191. log.Error("Rolling back collections INSERT: %v\n", err)
  192. return err
  193. }
  194. db.RemoveCollectionRedirect(t, u.Username)
  195. err = t.Commit()
  196. if err != nil {
  197. t.Rollback()
  198. log.Error("Rolling back after Commit(): %v\n", err)
  199. return err
  200. }
  201. return nil
  202. }
  203. // FIXME: We're returning errors inconsistently in this file. Do we use Errorf
  204. // for returned value, or impart?
  205. func (db *datastore) UpdateUserEmail(keys *key.Keychain, userID int64, email string) error {
  206. encEmail, err := data.Encrypt(keys.EmailKey, email)
  207. if err != nil {
  208. return fmt.Errorf("Couldn't encrypt email %s: %s\n", email, err)
  209. }
  210. return db.UpdateEncryptedUserEmail(userID, encEmail)
  211. }
  212. func (db *datastore) UpdateEncryptedUserEmail(userID int64, encEmail []byte) error {
  213. _, err := db.Exec("UPDATE users SET email = ? WHERE id = ?", encEmail, userID)
  214. if err != nil {
  215. return fmt.Errorf("Unable to update user email: %s", err)
  216. }
  217. return nil
  218. }
  219. func (db *datastore) CreateCollectionFromToken(cfg *config.Config, alias, title, accessToken string) (*Collection, error) {
  220. userID := db.GetUserID(accessToken)
  221. if userID == -1 {
  222. return nil, ErrBadAccessToken
  223. }
  224. return db.CreateCollection(cfg, alias, title, userID)
  225. }
  226. func (db *datastore) GetUserCollectionCount(userID int64) (uint64, error) {
  227. var collCount uint64
  228. err := db.QueryRow("SELECT COUNT(*) FROM collections WHERE owner_id = ?", userID).Scan(&collCount)
  229. switch {
  230. case err == sql.ErrNoRows:
  231. return 0, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user from database."}
  232. case err != nil:
  233. log.Error("Couldn't get collections count for user %d: %v", userID, err)
  234. return 0, err
  235. }
  236. return collCount, nil
  237. }
  238. func (db *datastore) CreateCollection(cfg *config.Config, alias, title string, userID int64) (*Collection, error) {
  239. if db.PostIDExists(alias) {
  240. return nil, impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  241. }
  242. // All good, so create new collection
  243. res, err := db.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", alias, title, "", defaultVisibility(cfg), userID, 0)
  244. if err != nil {
  245. if db.isDuplicateKeyErr(err) {
  246. return nil, impart.HTTPError{http.StatusConflict, "Collection already exists."}
  247. }
  248. log.Error("Couldn't add to collections: %v\n", err)
  249. return nil, err
  250. }
  251. c := &Collection{
  252. Alias: alias,
  253. Title: title,
  254. OwnerID: userID,
  255. PublicOwner: false,
  256. Public: defaultVisibility(cfg) == CollPublic,
  257. }
  258. c.ID, err = res.LastInsertId()
  259. if err != nil {
  260. log.Error("Couldn't get collection LastInsertId: %v\n", err)
  261. }
  262. return c, nil
  263. }
  264. func (db *datastore) GetUserByID(id int64) (*User, error) {
  265. u := &User{ID: id}
  266. err := db.QueryRow("SELECT username, password, email, created, status FROM users WHERE id = ?", id).Scan(&u.Username, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  267. switch {
  268. case err == sql.ErrNoRows:
  269. return nil, ErrUserNotFound
  270. case err != nil:
  271. log.Error("Couldn't SELECT user password: %v", err)
  272. return nil, err
  273. }
  274. return u, nil
  275. }
  276. // IsUserSilenced returns true if the user account associated with id is
  277. // currently silenced.
  278. func (db *datastore) IsUserSilenced(id int64) (bool, error) {
  279. u := &User{ID: id}
  280. err := db.QueryRow("SELECT status FROM users WHERE id = ?", id).Scan(&u.Status)
  281. switch {
  282. case err == sql.ErrNoRows:
  283. return false, fmt.Errorf("is user silenced: %v", ErrUserNotFound)
  284. case err != nil:
  285. log.Error("Couldn't SELECT user status: %v", err)
  286. return false, fmt.Errorf("is user silenced: %v", err)
  287. }
  288. return u.IsSilenced(), nil
  289. }
  290. // DoesUserNeedAuth returns true if the user hasn't provided any methods for
  291. // authenticating with the account, such a passphrase or email address.
  292. // Any errors are reported to admin and silently quashed, returning false as the
  293. // result.
  294. func (db *datastore) DoesUserNeedAuth(id int64) bool {
  295. var pass, email []byte
  296. // Find out if user has an email set first
  297. err := db.QueryRow("SELECT password, email FROM users WHERE id = ?", id).Scan(&pass, &email)
  298. switch {
  299. case err == sql.ErrNoRows:
  300. // ERROR. Don't give false positives on needing auth methods
  301. return false
  302. case err != nil:
  303. // ERROR. Don't give false positives on needing auth methods
  304. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  305. return false
  306. }
  307. // User doesn't need auth if there's an email
  308. return len(email) == 0 && len(pass) == 0
  309. }
  310. func (db *datastore) IsUserPassSet(id int64) (bool, error) {
  311. var pass []byte
  312. err := db.QueryRow("SELECT password FROM users WHERE id = ?", id).Scan(&pass)
  313. switch {
  314. case err == sql.ErrNoRows:
  315. return false, nil
  316. case err != nil:
  317. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  318. return false, err
  319. }
  320. return len(pass) > 0, nil
  321. }
  322. func (db *datastore) GetUserForAuth(username string) (*User, error) {
  323. u := &User{Username: username}
  324. err := db.QueryRow("SELECT id, password, email, created, status FROM users WHERE username = ?", username).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  325. switch {
  326. case err == sql.ErrNoRows:
  327. // Check if they've entered the wrong, unnormalized username
  328. username = getSlug(username, "")
  329. if username != u.Username {
  330. err = db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", username).Scan(&u.ID)
  331. if err == nil {
  332. return db.GetUserForAuth(username)
  333. }
  334. }
  335. return nil, ErrUserNotFound
  336. case err != nil:
  337. log.Error("Couldn't SELECT user password: %v", err)
  338. return nil, err
  339. }
  340. return u, nil
  341. }
  342. func (db *datastore) GetUserForAuthByID(userID int64) (*User, error) {
  343. u := &User{ID: userID}
  344. err := db.QueryRow("SELECT id, password, email, created, status FROM users WHERE id = ?", u.ID).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  345. switch {
  346. case err == sql.ErrNoRows:
  347. return nil, ErrUserNotFound
  348. case err != nil:
  349. log.Error("Couldn't SELECT userForAuthByID: %v", err)
  350. return nil, err
  351. }
  352. return u, nil
  353. }
  354. func (db *datastore) GetUserNameFromToken(accessToken string) (string, error) {
  355. t := auth.GetToken(accessToken)
  356. if len(t) == 0 {
  357. return "", ErrNoAccessToken
  358. }
  359. var oneTime bool
  360. var username string
  361. err := db.QueryRow("SELECT username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&username, &oneTime)
  362. switch {
  363. case err == sql.ErrNoRows:
  364. return "", ErrBadAccessToken
  365. case err != nil:
  366. return "", ErrInternalGeneral
  367. }
  368. // Delete token if it was one-time
  369. if oneTime {
  370. db.DeleteToken(t[:])
  371. }
  372. return username, nil
  373. }
  374. func (db *datastore) GetUserDataFromToken(accessToken string) (int64, string, error) {
  375. t := auth.GetToken(accessToken)
  376. if len(t) == 0 {
  377. return 0, "", ErrNoAccessToken
  378. }
  379. var userID int64
  380. var oneTime bool
  381. var username string
  382. err := db.QueryRow("SELECT user_id, username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &username, &oneTime)
  383. switch {
  384. case err == sql.ErrNoRows:
  385. return 0, "", ErrBadAccessToken
  386. case err != nil:
  387. return 0, "", ErrInternalGeneral
  388. }
  389. // Delete token if it was one-time
  390. if oneTime {
  391. db.DeleteToken(t[:])
  392. }
  393. return userID, username, nil
  394. }
  395. func (db *datastore) GetAPIUser(header string) (*User, error) {
  396. uID := db.GetUserID(header)
  397. if uID == -1 {
  398. return nil, fmt.Errorf(ErrUserNotFound.Error())
  399. }
  400. return db.GetUserByID(uID)
  401. }
  402. // GetUserID takes a hexadecimal accessToken, parses it into its binary
  403. // representation, and gets any user ID associated with the token. If no user
  404. // is associated, -1 is returned.
  405. func (db *datastore) GetUserID(accessToken string) int64 {
  406. i, _ := db.GetUserIDPrivilege(accessToken)
  407. return i
  408. }
  409. func (db *datastore) GetUserIDPrivilege(accessToken string) (userID int64, sudo bool) {
  410. t := auth.GetToken(accessToken)
  411. if len(t) == 0 {
  412. return -1, false
  413. }
  414. var oneTime bool
  415. err := db.QueryRow("SELECT user_id, sudo, one_time FROM accesstokens WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &sudo, &oneTime)
  416. switch {
  417. case err == sql.ErrNoRows:
  418. return -1, false
  419. case err != nil:
  420. return -1, false
  421. }
  422. // Delete token if it was one-time
  423. if oneTime {
  424. db.DeleteToken(t[:])
  425. }
  426. return
  427. }
  428. func (db *datastore) DeleteToken(accessToken []byte) error {
  429. res, err := db.Exec("DELETE FROM accesstokens WHERE token LIKE ?", accessToken)
  430. if err != nil {
  431. return err
  432. }
  433. rowsAffected, _ := res.RowsAffected()
  434. if rowsAffected == 0 {
  435. return impart.HTTPError{http.StatusNotFound, "Token is invalid or doesn't exist"}
  436. }
  437. return nil
  438. }
  439. // FetchLastAccessToken creates a new non-expiring, valid access token for the given
  440. // userID.
  441. func (db *datastore) FetchLastAccessToken(userID int64) string {
  442. var t []byte
  443. err := db.QueryRow("SELECT token FROM accesstokens WHERE user_id = ? AND (expires IS NULL OR expires > "+db.now()+") ORDER BY created DESC LIMIT 1", userID).Scan(&t)
  444. switch {
  445. case err == sql.ErrNoRows:
  446. return ""
  447. case err != nil:
  448. log.Error("Failed selecting from accesstoken: %v", err)
  449. return ""
  450. }
  451. u, err := uuid.Parse(t)
  452. if err != nil {
  453. return ""
  454. }
  455. return u.String()
  456. }
  457. // GetAccessToken creates a new non-expiring, valid access token for the given
  458. // userID.
  459. func (db *datastore) GetAccessToken(userID int64) (string, error) {
  460. return db.GetTemporaryOneTimeAccessToken(userID, 0, false)
  461. }
  462. // GetTemporaryAccessToken creates a new valid access token for the given
  463. // userID that remains valid for the given time in seconds. If validSecs is 0,
  464. // the access token doesn't automatically expire.
  465. func (db *datastore) GetTemporaryAccessToken(userID int64, validSecs int) (string, error) {
  466. return db.GetTemporaryOneTimeAccessToken(userID, validSecs, false)
  467. }
  468. // GetTemporaryOneTimeAccessToken creates a new valid access token for the given
  469. // userID that remains valid for the given time in seconds and can only be used
  470. // once if oneTime is true. If validSecs is 0, the access token doesn't
  471. // automatically expire.
  472. func (db *datastore) GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error) {
  473. u, err := uuid.NewV4()
  474. if err != nil {
  475. log.Error("Unable to generate token: %v", err)
  476. return "", err
  477. }
  478. // Insert UUID to `accesstokens`
  479. binTok := u[:]
  480. expirationVal := "NULL"
  481. if validSecs > 0 {
  482. expirationVal = fmt.Sprintf("DATE_ADD("+db.now()+", INTERVAL %d SECOND)", validSecs)
  483. }
  484. _, err = db.Exec("INSERT INTO accesstokens (token, user_id, one_time, expires) VALUES (?, ?, ?, "+expirationVal+")", string(binTok), userID, oneTime)
  485. if err != nil {
  486. log.Error("Couldn't INSERT accesstoken: %v", err)
  487. return "", err
  488. }
  489. return u.String(), nil
  490. }
  491. func (db *datastore) CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error) {
  492. var userID, collID int64 = -1, -1
  493. var coll *Collection
  494. var err error
  495. if accessToken != "" {
  496. userID = db.GetUserID(accessToken)
  497. if userID == -1 {
  498. return nil, ErrBadAccessToken
  499. }
  500. if collAlias != "" {
  501. coll, err = db.GetCollection(collAlias)
  502. if err != nil {
  503. return nil, err
  504. }
  505. coll.hostName = hostName
  506. if coll.OwnerID != userID {
  507. return nil, ErrForbiddenCollection
  508. }
  509. collID = coll.ID
  510. }
  511. }
  512. rp := &PublicPost{}
  513. rp.Post, err = db.CreatePost(userID, collID, post)
  514. if err != nil {
  515. return rp, err
  516. }
  517. if coll != nil {
  518. coll.ForPublic()
  519. rp.Collection = &CollectionObj{Collection: *coll}
  520. }
  521. return rp, nil
  522. }
  523. func (db *datastore) CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error) {
  524. idLen := postIDLen
  525. friendlyID := store.GenerateFriendlyRandomString(idLen)
  526. // Handle appearance / font face
  527. appearance := post.Font
  528. if !post.isFontValid() {
  529. appearance = "norm"
  530. }
  531. var err error
  532. ownerID := sql.NullInt64{
  533. Valid: false,
  534. }
  535. ownerCollID := sql.NullInt64{
  536. Valid: false,
  537. }
  538. slug := sql.NullString{"", false}
  539. // If an alias was supplied, we'll add this to the collection as well.
  540. if userID > 0 {
  541. ownerID.Int64 = userID
  542. ownerID.Valid = true
  543. if collID > 0 {
  544. ownerCollID.Int64 = collID
  545. ownerCollID.Valid = true
  546. var slugVal string
  547. if post.Title != nil && *post.Title != "" {
  548. slugVal = getSlug(*post.Title, post.Language.String)
  549. if slugVal == "" {
  550. slugVal = getSlug(*post.Content, post.Language.String)
  551. }
  552. } else {
  553. slugVal = getSlug(*post.Content, post.Language.String)
  554. }
  555. if slugVal == "" {
  556. slugVal = friendlyID
  557. }
  558. slug = sql.NullString{slugVal, true}
  559. }
  560. }
  561. created := time.Now()
  562. if db.driverName == driverSQLite {
  563. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  564. created = created.UTC()
  565. }
  566. if post.Created != nil {
  567. created, err = time.Parse("2006-01-02T15:04:05Z", *post.Created)
  568. if err != nil {
  569. log.Error("Unable to parse Created time '%s': %v", *post.Created, err)
  570. created = time.Now()
  571. if db.driverName == driverSQLite {
  572. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  573. created = created.UTC()
  574. }
  575. }
  576. }
  577. stmt, err := db.Prepare("INSERT INTO posts (id, slug, title, content, text_appearance, language, rtl, privacy, owner_id, collection_id, created, updated, view_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + db.now() + ", ?)")
  578. if err != nil {
  579. return nil, err
  580. }
  581. defer stmt.Close()
  582. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  583. if err != nil {
  584. if db.isDuplicateKeyErr(err) {
  585. // Duplicate entry error; try a new slug
  586. // TODO: make this a little more robust
  587. slug = sql.NullString{id.GenSafeUniqueSlug(slug.String), true}
  588. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  589. if err != nil {
  590. return nil, handleFailedPostInsert(fmt.Errorf("Retried slug generation, still failed: %v", err))
  591. }
  592. } else {
  593. return nil, handleFailedPostInsert(err)
  594. }
  595. }
  596. // TODO: return Created field in proper format
  597. return &Post{
  598. ID: friendlyID,
  599. Slug: null.NewString(slug.String, slug.Valid),
  600. Font: appearance,
  601. Language: zero.NewString(post.Language.String, post.Language.Valid),
  602. RTL: zero.NewBool(post.IsRTL.Bool, post.IsRTL.Valid),
  603. OwnerID: null.NewInt(userID, true),
  604. CollectionID: null.NewInt(userID, true),
  605. Created: created.Truncate(time.Second).UTC(),
  606. Updated: time.Now().Truncate(time.Second).UTC(),
  607. Title: zero.NewString(*(post.Title), true),
  608. Content: *(post.Content),
  609. }, nil
  610. }
  611. // UpdateOwnedPost updates an existing post with only the given fields in the
  612. // supplied AuthenticatedPost.
  613. func (db *datastore) UpdateOwnedPost(post *AuthenticatedPost, userID int64) error {
  614. params := []interface{}{}
  615. var queryUpdates, sep, authCondition string
  616. if post.Slug != nil && *post.Slug != "" {
  617. queryUpdates += sep + "slug = ?"
  618. sep = ", "
  619. params = append(params, getSlug(*post.Slug, ""))
  620. }
  621. if post.Content != nil {
  622. queryUpdates += sep + "content = ?"
  623. sep = ", "
  624. params = append(params, post.Content)
  625. }
  626. if post.Title != nil {
  627. queryUpdates += sep + "title = ?"
  628. sep = ", "
  629. params = append(params, post.Title)
  630. }
  631. if post.Language.Valid {
  632. queryUpdates += sep + "language = ?"
  633. sep = ", "
  634. params = append(params, post.Language.String)
  635. }
  636. if post.IsRTL.Valid {
  637. queryUpdates += sep + "rtl = ?"
  638. sep = ", "
  639. params = append(params, post.IsRTL.Bool)
  640. }
  641. if post.Font != "" {
  642. queryUpdates += sep + "text_appearance = ?"
  643. sep = ", "
  644. params = append(params, post.Font)
  645. }
  646. if post.Created != nil {
  647. createTime, err := time.Parse(postMetaDateFormat, *post.Created)
  648. if err != nil {
  649. log.Error("Unable to parse Created date: %v", err)
  650. return fmt.Errorf("That's the incorrect format for Created date.")
  651. }
  652. queryUpdates += sep + "created = ?"
  653. sep = ", "
  654. params = append(params, createTime)
  655. }
  656. // WHERE parameters...
  657. // id = ?
  658. params = append(params, post.ID)
  659. // AND owner_id = ?
  660. authCondition = "(owner_id = ?)"
  661. params = append(params, userID)
  662. if queryUpdates == "" {
  663. return ErrPostNoUpdatableVals
  664. }
  665. queryUpdates += sep + "updated = " + db.now()
  666. res, err := db.Exec("UPDATE posts SET "+queryUpdates+" WHERE id = ? AND "+authCondition, params...)
  667. if err != nil {
  668. log.Error("Unable to update owned post: %v", err)
  669. return err
  670. }
  671. rowsAffected, _ := res.RowsAffected()
  672. if rowsAffected == 0 {
  673. // Show the correct error message if nothing was updated
  674. var dummy int
  675. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND "+authCondition, post.ID, params[len(params)-1]).Scan(&dummy)
  676. switch {
  677. case err == sql.ErrNoRows:
  678. return ErrUnauthorizedEditPost
  679. case err != nil:
  680. log.Error("Failed selecting from posts: %v", err)
  681. }
  682. return nil
  683. }
  684. return nil
  685. }
  686. func (db *datastore) GetCollectionBy(condition string, value interface{}) (*Collection, error) {
  687. c := &Collection{}
  688. // FIXME: change Collection to reflect database values. Add helper functions to get actual values
  689. var styleSheet, script, format zero.String
  690. row := db.QueryRow("SELECT id, alias, title, description, style_sheet, script, format, owner_id, privacy, view_count FROM collections WHERE "+condition, value)
  691. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &styleSheet, &script, &format, &c.OwnerID, &c.Visibility, &c.Views)
  692. switch {
  693. case err == sql.ErrNoRows:
  694. return nil, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  695. case db.isHighLoadError(err):
  696. return nil, ErrUnavailable
  697. case err != nil:
  698. log.Error("Failed selecting from collections: %v", err)
  699. return nil, err
  700. }
  701. c.StyleSheet = styleSheet.String
  702. c.Script = script.String
  703. c.Format = format.String
  704. c.Public = c.IsPublic()
  705. c.db = db
  706. return c, nil
  707. }
  708. func (db *datastore) GetCollection(alias string) (*Collection, error) {
  709. return db.GetCollectionBy("alias = ?", alias)
  710. }
  711. func (db *datastore) GetCollectionForPad(alias string) (*Collection, error) {
  712. c := &Collection{Alias: alias}
  713. row := db.QueryRow("SELECT id, alias, title, description, privacy FROM collections WHERE alias = ?", alias)
  714. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility)
  715. switch {
  716. case err == sql.ErrNoRows:
  717. return c, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  718. case err != nil:
  719. log.Error("Failed selecting from collections: %v", err)
  720. return c, ErrInternalGeneral
  721. }
  722. c.Public = c.IsPublic()
  723. return c, nil
  724. }
  725. func (db *datastore) GetCollectionByID(id int64) (*Collection, error) {
  726. return db.GetCollectionBy("id = ?", id)
  727. }
  728. func (db *datastore) GetCollectionFromDomain(host string) (*Collection, error) {
  729. return db.GetCollectionBy("host = ?", host)
  730. }
  731. func (db *datastore) UpdateCollection(c *SubmittedCollection, alias string) error {
  732. q := query.NewUpdate().
  733. SetStringPtr(c.Title, "title").
  734. SetStringPtr(c.Description, "description").
  735. SetNullString(c.StyleSheet, "style_sheet").
  736. SetNullString(c.Script, "script")
  737. if c.Format != nil {
  738. cf := &CollectionFormat{Format: c.Format.String}
  739. if cf.Valid() {
  740. q.SetNullString(c.Format, "format")
  741. }
  742. }
  743. var updatePass bool
  744. if c.Visibility != nil && (collVisibility(*c.Visibility)&CollProtected == 0 || c.Pass != "") {
  745. q.SetIntPtr(c.Visibility, "privacy")
  746. if c.Pass != "" {
  747. updatePass = true
  748. }
  749. }
  750. // WHERE values
  751. q.Where("alias = ? AND owner_id = ?", alias, c.OwnerID)
  752. if q.Updates == "" {
  753. return ErrPostNoUpdatableVals
  754. }
  755. // Find any current domain
  756. var collID int64
  757. var rowsAffected int64
  758. var changed bool
  759. var res sql.Result
  760. err := db.QueryRow("SELECT id FROM collections WHERE alias = ?", alias).Scan(&collID)
  761. if err != nil {
  762. log.Error("Failed selecting from collections: %v. Some things won't work.", err)
  763. }
  764. // Update MathJax value
  765. if c.MathJax {
  766. if db.driverName == driverSQLite {
  767. _, err = db.Exec("INSERT OR REPLACE INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?)", collID, "render_mathjax", "1")
  768. } else {
  769. _, err = db.Exec("INSERT INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?) "+db.upsert("collection_id", "attribute")+" value = ?", collID, "render_mathjax", "1", "1")
  770. }
  771. if err != nil {
  772. log.Error("Unable to insert render_mathjax value: %v", err)
  773. return err
  774. }
  775. } else {
  776. _, err = db.Exec("DELETE FROM collectionattributes WHERE collection_id = ? AND attribute = ?", collID, "render_mathjax")
  777. if err != nil {
  778. log.Error("Unable to delete render_mathjax value: %v", err)
  779. return err
  780. }
  781. }
  782. // Update rest of the collection data
  783. res, err = db.Exec("UPDATE collections SET "+q.Updates+" WHERE "+q.Conditions, q.Params...)
  784. if err != nil {
  785. log.Error("Unable to update collection: %v", err)
  786. return err
  787. }
  788. rowsAffected, _ = res.RowsAffected()
  789. if !changed || rowsAffected == 0 {
  790. // Show the correct error message if nothing was updated
  791. var dummy int
  792. err := db.QueryRow("SELECT 1 FROM collections WHERE alias = ? AND owner_id = ?", alias, c.OwnerID).Scan(&dummy)
  793. switch {
  794. case err == sql.ErrNoRows:
  795. return ErrUnauthorizedEditPost
  796. case err != nil:
  797. log.Error("Failed selecting from collections: %v", err)
  798. }
  799. if !updatePass {
  800. return nil
  801. }
  802. }
  803. if updatePass {
  804. hashedPass, err := auth.HashPass([]byte(c.Pass))
  805. if err != nil {
  806. log.Error("Unable to create hash: %s", err)
  807. return impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  808. }
  809. if db.driverName == driverSQLite {
  810. _, err = db.Exec("INSERT OR REPLACE INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?)", alias, hashedPass)
  811. } else {
  812. _, err = db.Exec("INSERT INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?) "+db.upsert("collection_id")+" password = ?", alias, hashedPass, hashedPass)
  813. }
  814. if err != nil {
  815. return err
  816. }
  817. }
  818. return nil
  819. }
  820. const postCols = "id, slug, text_appearance, language, rtl, privacy, owner_id, collection_id, pinned_position, created, updated, view_count, title, content"
  821. // getEditablePost returns a PublicPost with the given ID only if the given
  822. // edit token is valid for the post.
  823. func (db *datastore) GetEditablePost(id, editToken string) (*PublicPost, error) {
  824. // FIXME: code duplicated from getPost()
  825. // TODO: add slight logic difference to getPost / one func
  826. var ownerName sql.NullString
  827. p := &Post{}
  828. row := db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE id = ? LIMIT 1", id)
  829. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  830. switch {
  831. case err == sql.ErrNoRows:
  832. return nil, ErrPostNotFound
  833. case err != nil:
  834. log.Error("Failed selecting from collections: %v", err)
  835. return nil, err
  836. }
  837. if p.Content == "" && p.Title.String == "" {
  838. return nil, ErrPostUnpublished
  839. }
  840. res := p.processPost()
  841. if ownerName.Valid {
  842. res.Owner = &PublicUser{Username: ownerName.String}
  843. }
  844. return &res, nil
  845. }
  846. func (db *datastore) PostIDExists(id string) bool {
  847. var dummy bool
  848. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ?", id).Scan(&dummy)
  849. return err == nil && dummy
  850. }
  851. // GetPost gets a public-facing post object from the database. If collectionID
  852. // is > 0, the post will be retrieved by slug and collection ID, rather than
  853. // post ID.
  854. // TODO: break this into two functions:
  855. // - GetPost(id string)
  856. // - GetCollectionPost(slug string, collectionID int64)
  857. func (db *datastore) GetPost(id string, collectionID int64) (*PublicPost, error) {
  858. var ownerName sql.NullString
  859. p := &Post{}
  860. var row *sql.Row
  861. var where string
  862. params := []interface{}{id}
  863. if collectionID > 0 {
  864. where = "slug = ? AND collection_id = ?"
  865. params = append(params, collectionID)
  866. } else {
  867. where = "id = ?"
  868. }
  869. row = db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE "+where+" LIMIT 1", params...)
  870. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  871. switch {
  872. case err == sql.ErrNoRows:
  873. if collectionID > 0 {
  874. return nil, ErrCollectionPageNotFound
  875. }
  876. return nil, ErrPostNotFound
  877. case err != nil:
  878. log.Error("Failed selecting from collections: %v", err)
  879. return nil, err
  880. }
  881. if p.Content == "" && p.Title.String == "" {
  882. return nil, ErrPostUnpublished
  883. }
  884. res := p.processPost()
  885. if ownerName.Valid {
  886. res.Owner = &PublicUser{Username: ownerName.String}
  887. }
  888. return &res, nil
  889. }
  890. // TODO: don't duplicate getPost() functionality
  891. func (db *datastore) GetOwnedPost(id string, ownerID int64) (*PublicPost, error) {
  892. p := &Post{}
  893. var row *sql.Row
  894. where := "id = ? AND owner_id = ?"
  895. params := []interface{}{id, ownerID}
  896. row = db.QueryRow("SELECT "+postCols+" FROM posts WHERE "+where+" LIMIT 1", params...)
  897. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  898. switch {
  899. case err == sql.ErrNoRows:
  900. return nil, ErrPostNotFound
  901. case err != nil:
  902. log.Error("Failed selecting from collections: %v", err)
  903. return nil, err
  904. }
  905. if p.Content == "" && p.Title.String == "" {
  906. return nil, ErrPostUnpublished
  907. }
  908. res := p.processPost()
  909. return &res, nil
  910. }
  911. func (db *datastore) GetPostProperty(id string, collectionID int64, property string) (interface{}, error) {
  912. propSelects := map[string]string{
  913. "views": "view_count AS views",
  914. }
  915. selectQuery, ok := propSelects[property]
  916. if !ok {
  917. return nil, impart.HTTPError{http.StatusBadRequest, fmt.Sprintf("Invalid property: %s.", property)}
  918. }
  919. var res interface{}
  920. var row *sql.Row
  921. if collectionID != 0 {
  922. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE slug = ? AND collection_id = ? LIMIT 1", id, collectionID)
  923. } else {
  924. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE id = ? LIMIT 1", id)
  925. }
  926. err := row.Scan(&res)
  927. switch {
  928. case err == sql.ErrNoRows:
  929. return nil, impart.HTTPError{http.StatusNotFound, "Post not found."}
  930. case err != nil:
  931. log.Error("Failed selecting post: %v", err)
  932. return nil, err
  933. }
  934. return res, nil
  935. }
  936. // GetPostsCount modifies the CollectionObj to include the correct number of
  937. // standard (non-pinned) posts. It will return future posts if `includeFuture`
  938. // is true.
  939. func (db *datastore) GetPostsCount(c *CollectionObj, includeFuture bool) {
  940. var count int64
  941. timeCondition := ""
  942. if !includeFuture {
  943. timeCondition = "AND created <= " + db.now()
  944. }
  945. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE collection_id = ? AND pinned_position IS NULL "+timeCondition, c.ID).Scan(&count)
  946. switch {
  947. case err == sql.ErrNoRows:
  948. c.TotalPosts = 0
  949. case err != nil:
  950. log.Error("Failed selecting from collections: %v", err)
  951. c.TotalPosts = 0
  952. }
  953. c.TotalPosts = int(count)
  954. }
  955. // GetPosts retrieves all posts for the given Collection.
  956. // It will return future posts if `includeFuture` is true.
  957. // It will include only standard (non-pinned) posts unless `includePinned` is true.
  958. // TODO: change includeFuture to isOwner, since that's how it's used
  959. func (db *datastore) GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error) {
  960. collID := c.ID
  961. cf := c.NewFormat()
  962. order := "DESC"
  963. if cf.Ascending() && !forceRecentFirst {
  964. order = "ASC"
  965. }
  966. pagePosts := cf.PostsPerPage()
  967. start := page*pagePosts - pagePosts
  968. if page == 0 {
  969. start = 0
  970. pagePosts = 1000
  971. }
  972. limitStr := ""
  973. if page > 0 {
  974. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  975. }
  976. timeCondition := ""
  977. if !includeFuture {
  978. timeCondition = "AND created <= " + db.now()
  979. }
  980. pinnedCondition := ""
  981. if !includePinned {
  982. pinnedCondition = "AND pinned_position IS NULL"
  983. }
  984. rows, err := db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? "+pinnedCondition+" "+timeCondition+" ORDER BY created "+order+limitStr, collID)
  985. if err != nil {
  986. log.Error("Failed selecting from posts: %v", err)
  987. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  988. }
  989. defer rows.Close()
  990. // TODO: extract this common row scanning logic for queries using `postCols`
  991. posts := []PublicPost{}
  992. for rows.Next() {
  993. p := &Post{}
  994. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  995. if err != nil {
  996. log.Error("Failed scanning row: %v", err)
  997. break
  998. }
  999. p.extractData()
  1000. p.formatContent(cfg, c, includeFuture)
  1001. posts = append(posts, p.processPost())
  1002. }
  1003. err = rows.Err()
  1004. if err != nil {
  1005. log.Error("Error after Next() on rows: %v", err)
  1006. }
  1007. return &posts, nil
  1008. }
  1009. // GetPostsTagged retrieves all posts on the given Collection that contain the
  1010. // given tag.
  1011. // It will return future posts if `includeFuture` is true.
  1012. // TODO: change includeFuture to isOwner, since that's how it's used
  1013. func (db *datastore) GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error) {
  1014. collID := c.ID
  1015. cf := c.NewFormat()
  1016. order := "DESC"
  1017. if cf.Ascending() {
  1018. order = "ASC"
  1019. }
  1020. pagePosts := cf.PostsPerPage()
  1021. start := page*pagePosts - pagePosts
  1022. if page == 0 {
  1023. start = 0
  1024. pagePosts = 1000
  1025. }
  1026. limitStr := ""
  1027. if page > 0 {
  1028. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  1029. }
  1030. timeCondition := ""
  1031. if !includeFuture {
  1032. timeCondition = "AND created <= " + db.now()
  1033. }
  1034. var rows *sql.Rows
  1035. var err error
  1036. if db.driverName == driverSQLite {
  1037. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) regexp ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, `.*#`+strings.ToLower(tag)+`\b.*`)
  1038. } else {
  1039. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) RLIKE ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, "#"+strings.ToLower(tag)+"[[:>:]]")
  1040. }
  1041. if err != nil {
  1042. log.Error("Failed selecting from posts: %v", err)
  1043. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  1044. }
  1045. defer rows.Close()
  1046. // TODO: extract this common row scanning logic for queries using `postCols`
  1047. posts := []PublicPost{}
  1048. for rows.Next() {
  1049. p := &Post{}
  1050. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  1051. if err != nil {
  1052. log.Error("Failed scanning row: %v", err)
  1053. break
  1054. }
  1055. p.extractData()
  1056. p.formatContent(cfg, c, includeFuture)
  1057. posts = append(posts, p.processPost())
  1058. }
  1059. err = rows.Err()
  1060. if err != nil {
  1061. log.Error("Error after Next() on rows: %v", err)
  1062. }
  1063. return &posts, nil
  1064. }
  1065. func (db *datastore) GetAPFollowers(c *Collection) (*[]RemoteUser, error) {
  1066. rows, err := db.Query("SELECT actor_id, inbox, shared_inbox FROM remotefollows f INNER JOIN remoteusers u ON f.remote_user_id = u.id WHERE collection_id = ?", c.ID)
  1067. if err != nil {
  1068. log.Error("Failed selecting from followers: %v", err)
  1069. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve followers."}
  1070. }
  1071. defer rows.Close()
  1072. followers := []RemoteUser{}
  1073. for rows.Next() {
  1074. f := RemoteUser{}
  1075. err = rows.Scan(&f.ActorID, &f.Inbox, &f.SharedInbox)
  1076. followers = append(followers, f)
  1077. }
  1078. return &followers, nil
  1079. }
  1080. // CanCollect returns whether or not the given user can add the given post to a
  1081. // collection. This is true when a post is already owned by the user.
  1082. // NOTE: this is currently only used to potentially add owned posts to a
  1083. // collection. This has the SIDE EFFECT of also generating a slug for the post.
  1084. // FIXME: make this side effect more explicit (or extract it)
  1085. func (db *datastore) CanCollect(cpr *ClaimPostRequest, userID int64) bool {
  1086. var title, content string
  1087. var lang sql.NullString
  1088. err := db.QueryRow("SELECT title, content, language FROM posts WHERE id = ? AND owner_id = ?", cpr.ID, userID).Scan(&title, &content, &lang)
  1089. switch {
  1090. case err == sql.ErrNoRows:
  1091. return false
  1092. case err != nil:
  1093. log.Error("Failed on post CanCollect(%s, %d): %v", cpr.ID, userID, err)
  1094. return false
  1095. }
  1096. // Since we have the post content and the post is collectable, generate the
  1097. // post's slug now.
  1098. cpr.Slug = getSlugFromPost(title, content, lang.String)
  1099. return true
  1100. }
  1101. func (db *datastore) AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error) {
  1102. qRes, err := db.Exec(query, params...)
  1103. if err != nil {
  1104. if db.isDuplicateKeyErr(err) && slugIdx > -1 {
  1105. s := id.GenSafeUniqueSlug(p.Slug)
  1106. if s == p.Slug {
  1107. // Sanity check to prevent infinite recursion
  1108. return qRes, fmt.Errorf("GenSafeUniqueSlug generated nothing unique: %s", s)
  1109. }
  1110. p.Slug = s
  1111. params[slugIdx] = p.Slug
  1112. return db.AttemptClaim(p, query, params, slugIdx)
  1113. }
  1114. return qRes, fmt.Errorf("attemptClaim: %s", err)
  1115. }
  1116. return qRes, nil
  1117. }
  1118. func (db *datastore) DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error) {
  1119. postClaimReqs := map[string]bool{}
  1120. res := []ClaimPostResult{}
  1121. for i := range postIDs {
  1122. postID := postIDs[i]
  1123. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1124. // Perform post validation
  1125. if postID == "" {
  1126. r.ErrorMessage = "Missing post ID. "
  1127. }
  1128. if _, ok := postClaimReqs[postID]; ok {
  1129. r.Code = 429
  1130. r.ErrorMessage = "You've already tried anonymizing this post."
  1131. r.ID = postID
  1132. res = append(res, r)
  1133. continue
  1134. }
  1135. postClaimReqs[postID] = true
  1136. var err error
  1137. // Get full post information to return
  1138. var fullPost *PublicPost
  1139. fullPost, err = db.GetPost(postID, 0)
  1140. if err != nil {
  1141. if err, ok := err.(impart.HTTPError); ok {
  1142. r.Code = err.Status
  1143. r.ErrorMessage = err.Message
  1144. r.ID = postID
  1145. res = append(res, r)
  1146. continue
  1147. } else {
  1148. log.Error("Error getting post in dispersePosts: %v", err)
  1149. }
  1150. }
  1151. if fullPost.OwnerID.Int64 != userID {
  1152. r.Code = http.StatusConflict
  1153. r.ErrorMessage = "Post is already owned by someone else."
  1154. r.ID = postID
  1155. res = append(res, r)
  1156. continue
  1157. }
  1158. var qRes sql.Result
  1159. var query string
  1160. var params []interface{}
  1161. // Do AND owner_id = ? for sanity.
  1162. // This should've been caught and returned with a good error message
  1163. // just above.
  1164. query = "UPDATE posts SET collection_id = NULL WHERE id = ? AND owner_id = ?"
  1165. params = []interface{}{postID, userID}
  1166. qRes, err = db.Exec(query, params...)
  1167. if err != nil {
  1168. r.Code = http.StatusInternalServerError
  1169. r.ErrorMessage = "A glitch happened on our end."
  1170. r.ID = postID
  1171. res = append(res, r)
  1172. log.Error("dispersePosts (post %s): %v", postID, err)
  1173. continue
  1174. }
  1175. // Post was successfully dispersed
  1176. r.Code = http.StatusOK
  1177. r.Post = fullPost
  1178. rowsAffected, _ := qRes.RowsAffected()
  1179. if rowsAffected == 0 {
  1180. // This was already claimed, but return 200
  1181. r.Code = http.StatusOK
  1182. }
  1183. res = append(res, r)
  1184. }
  1185. return &res, nil
  1186. }
  1187. func (db *datastore) ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error) {
  1188. postClaimReqs := map[string]bool{}
  1189. res := []ClaimPostResult{}
  1190. postCollAlias := collAlias
  1191. for i := range *posts {
  1192. p := (*posts)[i]
  1193. if &p == nil {
  1194. continue
  1195. }
  1196. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1197. // Perform post validation
  1198. if p.ID == "" {
  1199. r.ErrorMessage = "Missing post ID `id`. "
  1200. }
  1201. if _, ok := postClaimReqs[p.ID]; ok {
  1202. r.Code = 429
  1203. r.ErrorMessage = "You've already tried claiming this post."
  1204. r.ID = p.ID
  1205. res = append(res, r)
  1206. continue
  1207. }
  1208. postClaimReqs[p.ID] = true
  1209. canCollect := db.CanCollect(&p, userID)
  1210. if !canCollect && p.Token == "" {
  1211. // TODO: ensure post isn't owned by anyone else when a valid modify
  1212. // token is given.
  1213. r.ErrorMessage += "Missing post Edit Token `token`."
  1214. }
  1215. if r.ErrorMessage != "" {
  1216. // Post validate failed
  1217. r.Code = http.StatusBadRequest
  1218. r.ID = p.ID
  1219. res = append(res, r)
  1220. continue
  1221. }
  1222. var err error
  1223. var qRes sql.Result
  1224. var query string
  1225. var params []interface{}
  1226. var slugIdx int = -1
  1227. var coll *Collection
  1228. if collAlias == "" {
  1229. // Posts are being claimed at /posts/claim, not
  1230. // /collections/{alias}/collect, so use given individual collection
  1231. // to associate post with.
  1232. postCollAlias = p.CollectionAlias
  1233. }
  1234. if postCollAlias != "" {
  1235. // Associate this post with a collection
  1236. if p.CreateCollection {
  1237. // This is a new collection
  1238. // TODO: consider removing this. This seriously complicates this
  1239. // method and adds another (unnecessary?) logic path.
  1240. coll, err = db.CreateCollection(cfg, postCollAlias, "", userID)
  1241. if err != nil {
  1242. if err, ok := err.(impart.HTTPError); ok {
  1243. r.Code = err.Status
  1244. r.ErrorMessage = err.Message
  1245. } else {
  1246. r.Code = http.StatusInternalServerError
  1247. r.ErrorMessage = "Unknown error occurred creating collection"
  1248. }
  1249. r.ID = p.ID
  1250. res = append(res, r)
  1251. continue
  1252. }
  1253. } else {
  1254. // Attempt to add to existing collection
  1255. coll, err = db.GetCollection(postCollAlias)
  1256. if err != nil {
  1257. if err, ok := err.(impart.HTTPError); ok {
  1258. if err.Status == http.StatusNotFound {
  1259. // Show obfuscated "forbidden" response, as if attempting to add to an
  1260. // unowned blog.
  1261. r.Code = ErrForbiddenCollection.Status
  1262. r.ErrorMessage = ErrForbiddenCollection.Message
  1263. } else {
  1264. r.Code = err.Status
  1265. r.ErrorMessage = err.Message
  1266. }
  1267. } else {
  1268. r.Code = http.StatusInternalServerError
  1269. r.ErrorMessage = "Unknown error occurred claiming post with collection"
  1270. }
  1271. r.ID = p.ID
  1272. res = append(res, r)
  1273. continue
  1274. }
  1275. if coll.OwnerID != userID {
  1276. r.Code = ErrForbiddenCollection.Status
  1277. r.ErrorMessage = ErrForbiddenCollection.Message
  1278. r.ID = p.ID
  1279. res = append(res, r)
  1280. continue
  1281. }
  1282. }
  1283. if p.Slug == "" {
  1284. p.Slug = p.ID
  1285. }
  1286. if canCollect {
  1287. // User already owns this post, so just add it to the given
  1288. // collection.
  1289. query = "UPDATE posts SET collection_id = ?, slug = ? WHERE id = ? AND owner_id = ?"
  1290. params = []interface{}{coll.ID, p.Slug, p.ID, userID}
  1291. slugIdx = 1
  1292. } else {
  1293. query = "UPDATE posts SET owner_id = ?, collection_id = ?, slug = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1294. params = []interface{}{userID, coll.ID, p.Slug, p.ID, p.Token}
  1295. slugIdx = 2
  1296. }
  1297. } else {
  1298. query = "UPDATE posts SET owner_id = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1299. params = []interface{}{userID, p.ID, p.Token}
  1300. }
  1301. qRes, err = db.AttemptClaim(&p, query, params, slugIdx)
  1302. if err != nil {
  1303. r.Code = http.StatusInternalServerError
  1304. r.ErrorMessage = "An unknown error occurred."
  1305. r.ID = p.ID
  1306. res = append(res, r)
  1307. log.Error("claimPosts (post %s): %v", p.ID, err)
  1308. continue
  1309. }
  1310. // Get full post information to return
  1311. var fullPost *PublicPost
  1312. if p.Token != "" {
  1313. fullPost, err = db.GetEditablePost(p.ID, p.Token)
  1314. } else {
  1315. fullPost, err = db.GetPost(p.ID, 0)
  1316. }
  1317. if err != nil {
  1318. if err, ok := err.(impart.HTTPError); ok {
  1319. r.Code = err.Status
  1320. r.ErrorMessage = err.Message
  1321. r.ID = p.ID
  1322. res = append(res, r)
  1323. continue
  1324. }
  1325. }
  1326. if fullPost.OwnerID.Int64 != userID {
  1327. r.Code = http.StatusConflict
  1328. r.ErrorMessage = "Post is already owned by someone else."
  1329. r.ID = p.ID
  1330. res = append(res, r)
  1331. continue
  1332. }
  1333. // Post was successfully claimed
  1334. r.Code = http.StatusOK
  1335. r.Post = fullPost
  1336. if coll != nil {
  1337. r.Post.Collection = &CollectionObj{Collection: *coll}
  1338. }
  1339. rowsAffected, _ := qRes.RowsAffected()
  1340. if rowsAffected == 0 {
  1341. // This was already claimed, but return 200
  1342. r.Code = http.StatusOK
  1343. }
  1344. res = append(res, r)
  1345. }
  1346. return &res, nil
  1347. }
  1348. func (db *datastore) UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error {
  1349. if pos <= 0 || pos > 20 {
  1350. pos = db.GetLastPinnedPostPos(collID) + 1
  1351. if pos == -1 {
  1352. pos = 1
  1353. }
  1354. }
  1355. var err error
  1356. if pinned {
  1357. _, err = db.Exec("UPDATE posts SET pinned_position = ? WHERE id = ?", pos, postID)
  1358. } else {
  1359. _, err = db.Exec("UPDATE posts SET pinned_position = NULL WHERE id = ?", postID)
  1360. }
  1361. if err != nil {
  1362. log.Error("Unable to update pinned post: %v", err)
  1363. return err
  1364. }
  1365. return nil
  1366. }
  1367. func (db *datastore) GetLastPinnedPostPos(collID int64) int64 {
  1368. var lastPos sql.NullInt64
  1369. err := db.QueryRow("SELECT MAX(pinned_position) FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL", collID).Scan(&lastPos)
  1370. switch {
  1371. case err == sql.ErrNoRows:
  1372. return -1
  1373. case err != nil:
  1374. log.Error("Failed selecting from posts: %v", err)
  1375. return -1
  1376. }
  1377. if !lastPos.Valid {
  1378. return -1
  1379. }
  1380. return lastPos.Int64
  1381. }
  1382. func (db *datastore) GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error) {
  1383. // FIXME: sqlite-backed instances don't include ellipsis on truncated titles
  1384. timeCondition := ""
  1385. if !includeFuture {
  1386. timeCondition = "AND created <= " + db.now()
  1387. }
  1388. rows, err := db.Query("SELECT id, slug, title, "+db.clip("content", 80)+", pinned_position FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL "+timeCondition+" ORDER BY pinned_position ASC", coll.ID)
  1389. if err != nil {
  1390. log.Error("Failed selecting pinned posts: %v", err)
  1391. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve pinned posts."}
  1392. }
  1393. defer rows.Close()
  1394. posts := []PublicPost{}
  1395. for rows.Next() {
  1396. p := &Post{}
  1397. err = rows.Scan(&p.ID, &p.Slug, &p.Title, &p.Content, &p.PinnedPosition)
  1398. if err != nil {
  1399. log.Error("Failed scanning row: %v", err)
  1400. break
  1401. }
  1402. p.extractData()
  1403. pp := p.processPost()
  1404. pp.Collection = coll
  1405. posts = append(posts, pp)
  1406. }
  1407. return &posts, nil
  1408. }
  1409. func (db *datastore) GetCollections(u *User, hostName string) (*[]Collection, error) {
  1410. rows, err := db.Query("SELECT id, alias, title, description, privacy, view_count FROM collections WHERE owner_id = ? ORDER BY id ASC", u.ID)
  1411. if err != nil {
  1412. log.Error("Failed selecting from collections: %v", err)
  1413. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user collections."}
  1414. }
  1415. defer rows.Close()
  1416. colls := []Collection{}
  1417. for rows.Next() {
  1418. c := Collection{}
  1419. err = rows.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility, &c.Views)
  1420. if err != nil {
  1421. log.Error("Failed scanning row: %v", err)
  1422. break
  1423. }
  1424. c.hostName = hostName
  1425. c.URL = c.CanonicalURL()
  1426. c.Public = c.IsPublic()
  1427. colls = append(colls, c)
  1428. }
  1429. err = rows.Err()
  1430. if err != nil {
  1431. log.Error("Error after Next() on rows: %v", err)
  1432. }
  1433. return &colls, nil
  1434. }
  1435. func (db *datastore) GetPublishableCollections(u *User, hostName string) (*[]Collection, error) {
  1436. c, err := db.GetCollections(u, hostName)
  1437. if err != nil {
  1438. return nil, err
  1439. }
  1440. if len(*c) == 0 {
  1441. return nil, impart.HTTPError{http.StatusInternalServerError, "You don't seem to have any blogs; they might've moved to another account. Try logging out and logging into your other account."}
  1442. }
  1443. return c, nil
  1444. }
  1445. func (db *datastore) GetMeStats(u *User) userMeStats {
  1446. s := userMeStats{}
  1447. // User counts
  1448. colls, _ := db.GetUserCollectionCount(u.ID)
  1449. s.TotalCollections = colls
  1450. var articles, collPosts uint64
  1451. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NULL", u.ID).Scan(&articles)
  1452. if err != nil && err != sql.ErrNoRows {
  1453. log.Error("Couldn't get articles count for user %d: %v", u.ID, err)
  1454. }
  1455. s.TotalArticles = articles
  1456. err = db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NOT NULL", u.ID).Scan(&collPosts)
  1457. if err != nil && err != sql.ErrNoRows {
  1458. log.Error("Couldn't get coll posts count for user %d: %v", u.ID, err)
  1459. }
  1460. s.CollectionPosts = collPosts
  1461. return s
  1462. }
  1463. func (db *datastore) GetTotalCollections() (collCount int64, err error) {
  1464. err = db.QueryRow(`
  1465. SELECT COUNT(*)
  1466. FROM collections c
  1467. LEFT JOIN users u ON u.id = c.owner_id
  1468. WHERE u.status = 0`).Scan(&collCount)
  1469. if err != nil {
  1470. log.Error("Unable to fetch collections count: %v", err)
  1471. }
  1472. return
  1473. }
  1474. func (db *datastore) GetTotalPosts() (postCount int64, err error) {
  1475. err = db.QueryRow(`
  1476. SELECT COUNT(*)
  1477. FROM posts p
  1478. LEFT JOIN users u ON u.id = p.owner_id
  1479. WHERE u.status = 0`).Scan(&postCount)
  1480. if err != nil {
  1481. log.Error("Unable to fetch posts count: %v", err)
  1482. }
  1483. return
  1484. }
  1485. func (db *datastore) GetTopPosts(u *User, alias string) (*[]PublicPost, error) {
  1486. params := []interface{}{u.ID}
  1487. where := ""
  1488. if alias != "" {
  1489. where = " AND alias = ?"
  1490. params = append(params, alias)
  1491. }
  1492. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON p.collection_id = c.id WHERE p.owner_id = ?"+where+" ORDER BY p.view_count DESC, created DESC LIMIT 25", params...)
  1493. if err != nil {
  1494. log.Error("Failed selecting from posts: %v", err)
  1495. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user top posts."}
  1496. }
  1497. defer rows.Close()
  1498. posts := []PublicPost{}
  1499. var gotErr bool
  1500. for rows.Next() {
  1501. p := Post{}
  1502. c := Collection{}
  1503. var alias, title, description sql.NullString
  1504. var views sql.NullInt64
  1505. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &alias, &title, &description, &views)
  1506. if err != nil {
  1507. log.Error("Failed scanning User.getPosts() row: %v", err)
  1508. gotErr = true
  1509. break
  1510. }
  1511. p.extractData()
  1512. pubPost := p.processPost()
  1513. if alias.Valid && alias.String != "" {
  1514. c.Alias = alias.String
  1515. c.Title = title.String
  1516. c.Description = description.String
  1517. c.Views = views.Int64
  1518. pubPost.Collection = &CollectionObj{Collection: c}
  1519. }
  1520. posts = append(posts, pubPost)
  1521. }
  1522. err = rows.Err()
  1523. if err != nil {
  1524. log.Error("Error after Next() on rows: %v", err)
  1525. }
  1526. if gotErr && len(posts) == 0 {
  1527. // There were a lot of errors
  1528. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1529. }
  1530. return &posts, nil
  1531. }
  1532. func (db *datastore) GetAnonymousPosts(u *User) (*[]PublicPost, error) {
  1533. rows, err := db.Query("SELECT id, view_count, title, created, updated, content FROM posts WHERE owner_id = ? AND collection_id IS NULL ORDER BY created DESC", u.ID)
  1534. if err != nil {
  1535. log.Error("Failed selecting from posts: %v", err)
  1536. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user anonymous posts."}
  1537. }
  1538. defer rows.Close()
  1539. posts := []PublicPost{}
  1540. for rows.Next() {
  1541. p := Post{}
  1542. err = rows.Scan(&p.ID, &p.ViewCount, &p.Title, &p.Created, &p.Updated, &p.Content)
  1543. if err != nil {
  1544. log.Error("Failed scanning row: %v", err)
  1545. break
  1546. }
  1547. p.extractData()
  1548. posts = append(posts, p.processPost())
  1549. }
  1550. err = rows.Err()
  1551. if err != nil {
  1552. log.Error("Error after Next() on rows: %v", err)
  1553. }
  1554. return &posts, nil
  1555. }
  1556. func (db *datastore) GetUserPosts(u *User) (*[]PublicPost, error) {
  1557. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, p.created, p.updated, p.content, p.text_appearance, p.language, p.rtl, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON collection_id = c.id WHERE p.owner_id = ? ORDER BY created ASC", u.ID)
  1558. if err != nil {
  1559. log.Error("Failed selecting from posts: %v", err)
  1560. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user posts."}
  1561. }
  1562. defer rows.Close()
  1563. posts := []PublicPost{}
  1564. var gotErr bool
  1565. for rows.Next() {
  1566. p := Post{}
  1567. c := Collection{}
  1568. var alias, title, description sql.NullString
  1569. var views sql.NullInt64
  1570. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &p.Created, &p.Updated, &p.Content, &p.Font, &p.Language, &p.RTL, &alias, &title, &description, &views)
  1571. if err != nil {
  1572. log.Error("Failed scanning User.getPosts() row: %v", err)
  1573. gotErr = true
  1574. break
  1575. }
  1576. p.extractData()
  1577. pubPost := p.processPost()
  1578. if alias.Valid && alias.String != "" {
  1579. c.Alias = alias.String
  1580. c.Title = title.String
  1581. c.Description = description.String
  1582. c.Views = views.Int64
  1583. pubPost.Collection = &CollectionObj{Collection: c}
  1584. }
  1585. posts = append(posts, pubPost)
  1586. }
  1587. err = rows.Err()
  1588. if err != nil {
  1589. log.Error("Error after Next() on rows: %v", err)
  1590. }
  1591. if gotErr && len(posts) == 0 {
  1592. // There were a lot of errors
  1593. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1594. }
  1595. return &posts, nil
  1596. }
  1597. func (db *datastore) GetUserPostsCount(userID int64) int64 {
  1598. var count int64
  1599. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ?", userID).Scan(&count)
  1600. switch {
  1601. case err == sql.ErrNoRows:
  1602. return 0
  1603. case err != nil:
  1604. log.Error("Failed selecting posts count for user %d: %v", userID, err)
  1605. return 0
  1606. }
  1607. return count
  1608. }
  1609. // ChangeSettings takes a User and applies the changes in the given
  1610. // userSettings, MODIFYING THE USER with successful changes.
  1611. func (db *datastore) ChangeSettings(app *App, u *User, s *userSettings) error {
  1612. var errPass error
  1613. q := query.NewUpdate()
  1614. // Update email if given
  1615. if s.Email != "" {
  1616. encEmail, err := data.Encrypt(app.keys.EmailKey, s.Email)
  1617. if err != nil {
  1618. log.Error("Couldn't encrypt email %s: %s\n", s.Email, err)
  1619. return impart.HTTPError{http.StatusInternalServerError, "Unable to encrypt email address."}
  1620. }
  1621. q.SetBytes(encEmail, "email")
  1622. // Update the email if something goes awry updating the password
  1623. defer func() {
  1624. if errPass != nil {
  1625. db.UpdateEncryptedUserEmail(u.ID, encEmail)
  1626. }
  1627. }()
  1628. u.Email = zero.StringFrom(s.Email)
  1629. }
  1630. // Update username if given
  1631. var newUsername string
  1632. if s.Username != "" {
  1633. var ie *impart.HTTPError
  1634. newUsername, ie = getValidUsername(app, s.Username, u.Username)
  1635. if ie != nil {
  1636. // Username is invalid
  1637. return *ie
  1638. }
  1639. if !author.IsValidUsername(app.cfg, newUsername) {
  1640. // Ensure the username is syntactically correct.
  1641. return impart.HTTPError{http.StatusPreconditionFailed, "Username isn't valid."}
  1642. }
  1643. t, err := db.Begin()
  1644. if err != nil {
  1645. log.Error("Couldn't start username change transaction: %v", err)
  1646. return err
  1647. }
  1648. _, err = t.Exec("UPDATE users SET username = ? WHERE id = ?", newUsername, u.ID)
  1649. if err != nil {
  1650. t.Rollback()
  1651. if db.isDuplicateKeyErr(err) {
  1652. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1653. }
  1654. log.Error("Unable to update users table: %v", err)
  1655. return ErrInternalGeneral
  1656. }
  1657. _, err = t.Exec("UPDATE collections SET alias = ? WHERE alias = ? AND owner_id = ?", newUsername, u.Username, u.ID)
  1658. if err != nil {
  1659. t.Rollback()
  1660. if db.isDuplicateKeyErr(err) {
  1661. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1662. }
  1663. log.Error("Unable to update collection: %v", err)
  1664. return ErrInternalGeneral
  1665. }
  1666. // Keep track of name changes for redirection
  1667. db.RemoveCollectionRedirect(t, newUsername)
  1668. _, err = t.Exec("UPDATE collectionredirects SET new_alias = ? WHERE new_alias = ?", newUsername, u.Username)
  1669. if err != nil {
  1670. log.Error("Unable to update collectionredirects: %v", err)
  1671. }
  1672. _, err = t.Exec("INSERT INTO collectionredirects (prev_alias, new_alias) VALUES (?, ?)", u.Username, newUsername)
  1673. if err != nil {
  1674. log.Error("Unable to add new collectionredirect: %v", err)
  1675. }
  1676. err = t.Commit()
  1677. if err != nil {
  1678. t.Rollback()
  1679. log.Error("Rolling back after Commit(): %v\n", err)
  1680. return err
  1681. }
  1682. u.Username = newUsername
  1683. }
  1684. // Update passphrase if given
  1685. if s.NewPass != "" {
  1686. // Check if user has already set a password
  1687. var err error
  1688. u.HasPass, err = db.IsUserPassSet(u.ID)
  1689. if err != nil {
  1690. errPass = impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve user data."}
  1691. return errPass
  1692. }
  1693. if u.HasPass {
  1694. // Check if currently-set password is correct
  1695. hashedPass := u.HashedPass
  1696. if len(hashedPass) == 0 {
  1697. authUser, err := db.GetUserForAuthByID(u.ID)
  1698. if err != nil {
  1699. errPass = err
  1700. return errPass
  1701. }
  1702. hashedPass = authUser.HashedPass
  1703. }
  1704. if !auth.Authenticated(hashedPass, []byte(s.OldPass)) {
  1705. errPass = impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1706. return errPass
  1707. }
  1708. }
  1709. hashedPass, err := auth.HashPass([]byte(s.NewPass))
  1710. if err != nil {
  1711. errPass = impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  1712. return errPass
  1713. }
  1714. q.SetBytes(hashedPass, "password")
  1715. }
  1716. // WHERE values
  1717. q.Append(u.ID)
  1718. if q.Updates == "" {
  1719. if s.Username == "" {
  1720. return ErrPostNoUpdatableVals
  1721. }
  1722. // Nothing to update except username. That was successful, so return now.
  1723. return nil
  1724. }
  1725. res, err := db.Exec("UPDATE users SET "+q.Updates+" WHERE id = ?", q.Params...)
  1726. if err != nil {
  1727. log.Error("Unable to update collection: %v", err)
  1728. return err
  1729. }
  1730. rowsAffected, _ := res.RowsAffected()
  1731. if rowsAffected == 0 {
  1732. // Show the correct error message if nothing was updated
  1733. var dummy int
  1734. err := db.QueryRow("SELECT 1 FROM users WHERE id = ?", u.ID).Scan(&dummy)
  1735. switch {
  1736. case err == sql.ErrNoRows:
  1737. return ErrUnauthorizedGeneral
  1738. case err != nil:
  1739. log.Error("Failed selecting from users: %v", err)
  1740. }
  1741. return nil
  1742. }
  1743. if s.NewPass != "" && !u.HasPass {
  1744. u.HasPass = true
  1745. }
  1746. return nil
  1747. }
  1748. func (db *datastore) ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error {
  1749. var dbPass []byte
  1750. err := db.QueryRow("SELECT password FROM users WHERE id = ?", userID).Scan(&dbPass)
  1751. switch {
  1752. case err == sql.ErrNoRows:
  1753. return ErrUserNotFound
  1754. case err != nil:
  1755. log.Error("Couldn't SELECT user password for change: %v", err)
  1756. return err
  1757. }
  1758. if !sudo && !auth.Authenticated(dbPass, []byte(curPass)) {
  1759. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1760. }
  1761. _, err = db.Exec("UPDATE users SET password = ? WHERE id = ?", hashedPass, userID)
  1762. if err != nil {
  1763. log.Error("Could not update passphrase: %v", err)
  1764. return err
  1765. }
  1766. return nil
  1767. }
  1768. func (db *datastore) RemoveCollectionRedirect(t *sql.Tx, alias string) error {
  1769. _, err := t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ?", alias)
  1770. if err != nil {
  1771. log.Error("Unable to delete from collectionredirects: %v", err)
  1772. return err
  1773. }
  1774. return nil
  1775. }
  1776. func (db *datastore) GetCollectionRedirect(alias string) (new string) {
  1777. row := db.QueryRow("SELECT new_alias FROM collectionredirects WHERE prev_alias = ?", alias)
  1778. err := row.Scan(&new)
  1779. if err != nil && err != sql.ErrNoRows {
  1780. log.Error("Failed selecting from collectionredirects: %v", err)
  1781. }
  1782. return
  1783. }
  1784. func (db *datastore) DeleteCollection(alias string, userID int64) error {
  1785. c := &Collection{Alias: alias}
  1786. var username string
  1787. row := db.QueryRow("SELECT username FROM users WHERE id = ?", userID)
  1788. err := row.Scan(&username)
  1789. if err != nil {
  1790. return err
  1791. }
  1792. // Ensure user isn't deleting their main blog
  1793. if alias == username {
  1794. return impart.HTTPError{http.StatusForbidden, "You cannot currently delete your primary blog."}
  1795. }
  1796. row = db.QueryRow("SELECT id FROM collections WHERE alias = ? AND owner_id = ?", alias, userID)
  1797. err = row.Scan(&c.ID)
  1798. switch {
  1799. case err == sql.ErrNoRows:
  1800. return impart.HTTPError{http.StatusNotFound, "Collection doesn't exist or you're not allowed to delete it."}
  1801. case err != nil:
  1802. log.Error("Failed selecting from collections: %v", err)
  1803. return ErrInternalGeneral
  1804. }
  1805. t, err := db.Begin()
  1806. if err != nil {
  1807. return err
  1808. }
  1809. // Float all collection's posts
  1810. _, err = t.Exec("UPDATE posts SET collection_id = NULL WHERE collection_id = ? AND owner_id = ?", c.ID, userID)
  1811. if err != nil {
  1812. t.Rollback()
  1813. return err
  1814. }
  1815. // Remove redirects to or from this collection
  1816. _, err = t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ? OR new_alias = ?", alias, alias)
  1817. if err != nil {
  1818. t.Rollback()
  1819. return err
  1820. }
  1821. // Remove any optional collection password
  1822. _, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  1823. if err != nil {
  1824. t.Rollback()
  1825. return err
  1826. }
  1827. // Finally, delete collection itself
  1828. _, err = t.Exec("DELETE FROM collections WHERE id = ?", c.ID)
  1829. if err != nil {
  1830. t.Rollback()
  1831. return err
  1832. }
  1833. err = t.Commit()
  1834. if err != nil {
  1835. t.Rollback()
  1836. return err
  1837. }
  1838. return nil
  1839. }
  1840. func (db *datastore) IsCollectionAttributeOn(id int64, attr string) bool {
  1841. var v string
  1842. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&v)
  1843. switch {
  1844. case err == sql.ErrNoRows:
  1845. return false
  1846. case err != nil:
  1847. log.Error("Couldn't SELECT value in isCollectionAttributeOn for attribute '%s': %v", attr, err)
  1848. return false
  1849. }
  1850. return v == "1"
  1851. }
  1852. func (db *datastore) CollectionHasAttribute(id int64, attr string) bool {
  1853. var dummy string
  1854. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&dummy)
  1855. switch {
  1856. case err == sql.ErrNoRows:
  1857. return false
  1858. case err != nil:
  1859. log.Error("Couldn't SELECT value in collectionHasAttribute for attribute '%s': %v", attr, err)
  1860. return false
  1861. }
  1862. return true
  1863. }
  1864. // DeleteAccount will delete the entire account for userID
  1865. func (db *datastore) DeleteAccount(userID int64) error {
  1866. // Get all collections
  1867. rows, err := db.Query("SELECT id, alias FROM collections WHERE owner_id = ?", userID)
  1868. if err != nil {
  1869. log.Error("Unable to get collections: %v", err)
  1870. return err
  1871. }
  1872. defer rows.Close()
  1873. colls := []Collection{}
  1874. var c Collection
  1875. for rows.Next() {
  1876. err = rows.Scan(&c.ID, &c.Alias)
  1877. if err != nil {
  1878. log.Error("Unable to scan collection cols: %v", err)
  1879. return err
  1880. }
  1881. colls = append(colls, c)
  1882. }
  1883. // Start transaction
  1884. t, err := db.Begin()
  1885. if err != nil {
  1886. log.Error("Unable to begin: %v", err)
  1887. return err
  1888. }
  1889. // Clean up all collection related information
  1890. var res sql.Result
  1891. for _, c := range colls {
  1892. // Delete tokens
  1893. res, err = t.Exec("DELETE FROM collectionattributes WHERE collection_id = ?", c.ID)
  1894. if err != nil {
  1895. t.Rollback()
  1896. log.Error("Unable to delete attributes on %s: %v", c.Alias, err)
  1897. return err
  1898. }
  1899. rs, _ := res.RowsAffected()
  1900. log.Info("Deleted %d for %s from collectionattributes", rs, c.Alias)
  1901. // Remove any optional collection password
  1902. res, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  1903. if err != nil {
  1904. t.Rollback()
  1905. log.Error("Unable to delete passwords on %s: %v", c.Alias, err)
  1906. return err
  1907. }
  1908. rs, _ = res.RowsAffected()
  1909. log.Info("Deleted %d for %s from collectionpasswords", rs, c.Alias)
  1910. // Remove redirects to this collection
  1911. res, err = t.Exec("DELETE FROM collectionredirects WHERE new_alias = ?", c.Alias)
  1912. if err != nil {
  1913. t.Rollback()
  1914. log.Error("Unable to delete redirects on %s: %v", c.Alias, err)
  1915. return err
  1916. }
  1917. rs, _ = res.RowsAffected()
  1918. log.Info("Deleted %d for %s from collectionredirects", rs, c.Alias)
  1919. // Remove any collection keys
  1920. res, err = t.Exec("DELETE FROM collectionkeys WHERE collection_id = ?", c.ID)
  1921. if err != nil {
  1922. t.Rollback()
  1923. log.Error("Unable to delete keys on %s: %v", c.Alias, err)
  1924. return err
  1925. }
  1926. rs, _ = res.RowsAffected()
  1927. log.Info("Deleted %d for %s from collectionkeys", rs, c.Alias)
  1928. // TODO: federate delete collection
  1929. // Remove remote follows
  1930. res, err = t.Exec("DELETE FROM remotefollows WHERE collection_id = ?", c.ID)
  1931. if err != nil {
  1932. t.Rollback()
  1933. log.Error("Unable to delete remote follows on %s: %v", c.Alias, err)
  1934. return err
  1935. }
  1936. rs, _ = res.RowsAffected()
  1937. log.Info("Deleted %d for %s from remotefollows", rs, c.Alias)
  1938. }
  1939. // Delete collections
  1940. res, err = t.Exec("DELETE FROM collections WHERE owner_id = ?", userID)
  1941. if err != nil {
  1942. t.Rollback()
  1943. log.Error("Unable to delete collections: %v", err)
  1944. return err
  1945. }
  1946. rs, _ := res.RowsAffected()
  1947. log.Info("Deleted %d from collections", rs)
  1948. // Delete tokens
  1949. res, err = t.Exec("DELETE FROM accesstokens WHERE user_id = ?", userID)
  1950. if err != nil {
  1951. t.Rollback()
  1952. log.Error("Unable to delete access tokens: %v", err)
  1953. return err
  1954. }
  1955. rs, _ = res.RowsAffected()
  1956. log.Info("Deleted %d from accesstokens", rs)
  1957. // Delete user attributes
  1958. res, err = t.Exec("DELETE FROM oauth_users WHERE user_id = ?", userID)
  1959. if err != nil {
  1960. t.Rollback()
  1961. log.Error("Unable to delete oauth_users: %v", err)
  1962. return err
  1963. }
  1964. rs, _ = res.RowsAffected()
  1965. log.Info("Deleted %d from oauth_users", rs)
  1966. // Delete posts
  1967. // TODO: should maybe get each row so we can federate a delete
  1968. // if so needs to be outside of transaction like collections
  1969. res, err = t.Exec("DELETE FROM posts WHERE owner_id = ?", userID)
  1970. if err != nil {
  1971. t.Rollback()
  1972. log.Error("Unable to delete posts: %v", err)
  1973. return err
  1974. }
  1975. rs, _ = res.RowsAffected()
  1976. log.Info("Deleted %d from posts", rs)
  1977. // Delete user attributes
  1978. res, err = t.Exec("DELETE FROM userattributes WHERE user_id = ?", userID)
  1979. if err != nil {
  1980. t.Rollback()
  1981. log.Error("Unable to delete attributes: %v", err)
  1982. return err
  1983. }
  1984. rs, _ = res.RowsAffected()
  1985. log.Info("Deleted %d from userattributes", rs)
  1986. // Delete user invites
  1987. res, err = t.Exec("DELETE FROM userinvites WHERE owner_id = ?", userID)
  1988. if err != nil {
  1989. t.Rollback()
  1990. log.Error("Unable to delete invites: %v", err)
  1991. return err
  1992. }
  1993. rs, _ = res.RowsAffected()
  1994. log.Info("Deleted %d from userinvites", rs)
  1995. // Delete the user
  1996. res, err = t.Exec("DELETE FROM users WHERE id = ?", userID)
  1997. if err != nil {
  1998. t.Rollback()
  1999. log.Error("Unable to delete user: %v", err)
  2000. return err
  2001. }
  2002. rs, _ = res.RowsAffected()
  2003. log.Info("Deleted %d from users", rs)
  2004. // Commit all changes to the database
  2005. err = t.Commit()
  2006. if err != nil {
  2007. t.Rollback()
  2008. log.Error("Unable to commit: %v", err)
  2009. return err
  2010. }
  2011. // TODO: federate delete actor
  2012. return nil
  2013. }
  2014. func (db *datastore) GetAPActorKeys(collectionID int64) ([]byte, []byte) {
  2015. var pub, priv []byte
  2016. err := db.QueryRow("SELECT public_key, private_key FROM collectionkeys WHERE collection_id = ?", collectionID).Scan(&pub, &priv)
  2017. switch {
  2018. case err == sql.ErrNoRows:
  2019. // Generate keys
  2020. pub, priv = activitypub.GenerateKeys()
  2021. _, err = db.Exec("INSERT INTO collectionkeys (collection_id, public_key, private_key) VALUES (?, ?, ?)", collectionID, pub, priv)
  2022. if err != nil {
  2023. log.Error("Unable to INSERT new activitypub keypair: %v", err)
  2024. return nil, nil
  2025. }
  2026. case err != nil:
  2027. log.Error("Couldn't SELECT collectionkeys: %v", err)
  2028. return nil, nil
  2029. }
  2030. return pub, priv
  2031. }
  2032. func (db *datastore) CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error {
  2033. _, err := db.Exec("INSERT INTO userinvites (id, owner_id, max_uses, created, expires, inactive) VALUES (?, ?, ?, "+db.now()+", ?, 0)", id, userID, maxUses, expires)
  2034. return err
  2035. }
  2036. func (db *datastore) GetUserInvites(userID int64) (*[]Invite, error) {
  2037. rows, err := db.Query("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE owner_id = ? ORDER BY created DESC", userID)
  2038. if err != nil {
  2039. log.Error("Failed selecting from userinvites: %v", err)
  2040. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user invites."}
  2041. }
  2042. defer rows.Close()
  2043. is := []Invite{}
  2044. for rows.Next() {
  2045. i := Invite{}
  2046. err = rows.Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  2047. is = append(is, i)
  2048. }
  2049. return &is, nil
  2050. }
  2051. func (db *datastore) GetUserInvite(id string) (*Invite, error) {
  2052. var i Invite
  2053. err := db.QueryRow("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE id = ?", id).Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  2054. switch {
  2055. case err == sql.ErrNoRows, db.isIgnorableError(err):
  2056. return nil, impart.HTTPError{http.StatusNotFound, "Invite doesn't exist."}
  2057. case err != nil:
  2058. log.Error("Failed selecting invite: %v", err)
  2059. return nil, err
  2060. }
  2061. return &i, nil
  2062. }
  2063. // IsUsersInvite returns true if the user with ID created the invite with code
  2064. // and an error other than sql no rows, if any. Will return false in the event
  2065. // of an error.
  2066. func (db *datastore) IsUsersInvite(code string, userID int64) (bool, error) {
  2067. var id string
  2068. err := db.QueryRow("SELECT id FROM userinvites WHERE id = ? AND owner_id = ?", code, userID).Scan(&id)
  2069. if err != nil && err != sql.ErrNoRows {
  2070. log.Error("Failed selecting invite: %v", err)
  2071. return false, err
  2072. }
  2073. return id != "", nil
  2074. }
  2075. func (db *datastore) GetUsersInvitedCount(id string) int64 {
  2076. var count int64
  2077. err := db.QueryRow("SELECT COUNT(*) FROM usersinvited WHERE invite_id = ?", id).Scan(&count)
  2078. switch {
  2079. case err == sql.ErrNoRows:
  2080. return 0
  2081. case err != nil:
  2082. log.Error("Failed selecting users invited count: %v", err)
  2083. return 0
  2084. }
  2085. return count
  2086. }
  2087. func (db *datastore) CreateInvitedUser(inviteID string, userID int64) error {
  2088. _, err := db.Exec("INSERT INTO usersinvited (invite_id, user_id) VALUES (?, ?)", inviteID, userID)
  2089. return err
  2090. }
  2091. func (db *datastore) GetInstancePages() ([]*instanceContent, error) {
  2092. return db.GetAllDynamicContent("page")
  2093. }
  2094. func (db *datastore) GetAllDynamicContent(t string) ([]*instanceContent, error) {
  2095. where := ""
  2096. params := []interface{}{}
  2097. if t != "" {
  2098. where = " WHERE content_type = ?"
  2099. params = append(params, t)
  2100. }
  2101. rows, err := db.Query("SELECT id, title, content, updated, content_type FROM appcontent"+where, params...)
  2102. if err != nil {
  2103. log.Error("Failed selecting from appcontent: %v", err)
  2104. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve instance pages."}
  2105. }
  2106. defer rows.Close()
  2107. pages := []*instanceContent{}
  2108. for rows.Next() {
  2109. c := &instanceContent{}
  2110. err = rows.Scan(&c.ID, &c.Title, &c.Content, &c.Updated, &c.Type)
  2111. if err != nil {
  2112. log.Error("Failed scanning row: %v", err)
  2113. break
  2114. }
  2115. pages = append(pages, c)
  2116. }
  2117. err = rows.Err()
  2118. if err != nil {
  2119. log.Error("Error after Next() on rows: %v", err)
  2120. }
  2121. return pages, nil
  2122. }
  2123. func (db *datastore) GetDynamicContent(id string) (*instanceContent, error) {
  2124. c := &instanceContent{
  2125. ID: id,
  2126. }
  2127. err := db.QueryRow("SELECT title, content, updated, content_type FROM appcontent WHERE id = ?", id).Scan(&c.Title, &c.Content, &c.Updated, &c.Type)
  2128. switch {
  2129. case err == sql.ErrNoRows:
  2130. return nil, nil
  2131. case err != nil:
  2132. log.Error("Couldn't SELECT FROM appcontent for id '%s': %v", id, err)
  2133. return nil, err
  2134. }
  2135. return c, nil
  2136. }
  2137. func (db *datastore) UpdateDynamicContent(id, title, content, contentType string) error {
  2138. var err error
  2139. if db.driverName == driverSQLite {
  2140. _, err = db.Exec("INSERT OR REPLACE INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?)", id, title, content, contentType)
  2141. } else {
  2142. _, err = db.Exec("INSERT INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?) "+db.upsert("id")+" title = ?, content = ?, updated = "+db.now(), id, title, content, contentType, title, content)
  2143. }
  2144. if err != nil {
  2145. log.Error("Unable to INSERT appcontent for '%s': %v", id, err)
  2146. }
  2147. return err
  2148. }
  2149. func (db *datastore) GetAllUsers(page uint) (*[]User, error) {
  2150. limitStr := fmt.Sprintf("0, %d", adminUsersPerPage)
  2151. if page > 1 {
  2152. limitStr = fmt.Sprintf("%d, %d", (page-1)*adminUsersPerPage, adminUsersPerPage)
  2153. }
  2154. rows, err := db.Query("SELECT id, username, created, status FROM users ORDER BY created DESC LIMIT " + limitStr)
  2155. if err != nil {
  2156. log.Error("Failed selecting from users: %v", err)
  2157. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve all users."}
  2158. }
  2159. defer rows.Close()
  2160. users := []User{}
  2161. for rows.Next() {
  2162. u := User{}
  2163. err = rows.Scan(&u.ID, &u.Username, &u.Created, &u.Status)
  2164. if err != nil {
  2165. log.Error("Failed scanning GetAllUsers() row: %v", err)
  2166. break
  2167. }
  2168. users = append(users, u)
  2169. }
  2170. return &users, nil
  2171. }
  2172. func (db *datastore) GetAllUsersCount() int64 {
  2173. var count int64
  2174. err := db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
  2175. switch {
  2176. case err == sql.ErrNoRows:
  2177. return 0
  2178. case err != nil:
  2179. log.Error("Failed selecting all users count: %v", err)
  2180. return 0
  2181. }
  2182. return count
  2183. }
  2184. func (db *datastore) GetUserLastPostTime(id int64) (*time.Time, error) {
  2185. var t time.Time
  2186. err := db.QueryRow("SELECT created FROM posts WHERE owner_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2187. switch {
  2188. case err == sql.ErrNoRows:
  2189. return nil, nil
  2190. case err != nil:
  2191. log.Error("Failed selecting last post time from posts: %v", err)
  2192. return nil, err
  2193. }
  2194. return &t, nil
  2195. }
  2196. // SetUserStatus changes a user's status in the database. see Users.UserStatus
  2197. func (db *datastore) SetUserStatus(id int64, status UserStatus) error {
  2198. _, err := db.Exec("UPDATE users SET status = ? WHERE id = ?", status, id)
  2199. if err != nil {
  2200. return fmt.Errorf("failed to update user status: %v", err)
  2201. }
  2202. return nil
  2203. }
  2204. func (db *datastore) GetCollectionLastPostTime(id int64) (*time.Time, error) {
  2205. var t time.Time
  2206. err := db.QueryRow("SELECT created FROM posts WHERE collection_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2207. switch {
  2208. case err == sql.ErrNoRows:
  2209. return nil, nil
  2210. case err != nil:
  2211. log.Error("Failed selecting last post time from posts: %v", err)
  2212. return nil, err
  2213. }
  2214. return &t, nil
  2215. }
  2216. func (db *datastore) GenerateOAuthState(ctx context.Context, provider, clientID string) (string, error) {
  2217. state := store.Generate62RandomString(24)
  2218. _, err := db.ExecContext(ctx, "INSERT INTO oauth_client_states (state, provider, client_id, used, created_at) VALUES (?, ?, ?, FALSE, " + db.now() + ")", state, provider, clientID)
  2219. if err != nil {
  2220. return "", fmt.Errorf("unable to record oauth client state: %w", err)
  2221. }
  2222. return state, nil
  2223. }
  2224. func (db *datastore) ValidateOAuthState(ctx context.Context, state string) (string, string, error) {
  2225. var provider string
  2226. var clientID string
  2227. err := wf_db.RunTransactionWithOptions(ctx, db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error {
  2228. err := tx.QueryRow("SELECT provider, client_id FROM oauth_client_states WHERE state = ? AND used = FALSE", state).Scan(&provider, &clientID)
  2229. if err != nil {
  2230. return err
  2231. }
  2232. res, err := tx.ExecContext(ctx, "UPDATE oauth_client_states SET used = TRUE WHERE state = ?", state)
  2233. if err != nil {
  2234. return err
  2235. }
  2236. rowsAffected, err := res.RowsAffected()
  2237. if err != nil {
  2238. return err
  2239. }
  2240. if rowsAffected != 1 {
  2241. return fmt.Errorf("state not found")
  2242. }
  2243. return nil
  2244. })
  2245. if err != nil {
  2246. return "", "", nil
  2247. }
  2248. return provider, clientID, nil
  2249. }
  2250. func (db *datastore) RecordRemoteUserID(ctx context.Context, localUserID int64, remoteUserID, provider, clientID, accessToken string) error {
  2251. var err error
  2252. if db.driverName == driverSQLite {
  2253. _, err = db.ExecContext(ctx, "INSERT OR REPLACE INTO oauth_users (user_id, remote_user_id, provider, client_id, access_token) VALUES (?, ?, ?, ?, ?)", localUserID, remoteUserID, provider, clientID, accessToken)
  2254. } else {
  2255. _, err = db.ExecContext(ctx, "INSERT INTO oauth_users (user_id, remote_user_id, provider, client_id, access_token) VALUES (?, ?, ?, ?, ?) "+db.upsert("user")+" access_token = ?", localUserID, remoteUserID, provider, clientID, accessToken, accessToken)
  2256. }
  2257. if err != nil {
  2258. log.Error("Unable to INSERT oauth_users for '%d': %v", localUserID, err)
  2259. }
  2260. return err
  2261. }
  2262. // GetIDForRemoteUser returns a user ID associated with a remote user ID.
  2263. func (db *datastore) GetIDForRemoteUser(ctx context.Context, remoteUserID, provider, clientID string) (int64, error) {
  2264. var userID int64 = -1
  2265. err := db.
  2266. QueryRowContext(ctx, "SELECT user_id FROM oauth_users WHERE remote_user_id = ? AND provider = ? AND client_id = ?", remoteUserID, provider, clientID).
  2267. Scan(&userID)
  2268. // Not finding a record is OK.
  2269. if err != nil && err != sql.ErrNoRows {
  2270. return -1, err
  2271. }
  2272. return userID, nil
  2273. }
  2274. // DatabaseInitialized returns whether or not the current datastore has been
  2275. // initialized with the correct schema.
  2276. // Currently, it checks to see if the `users` table exists.
  2277. func (db *datastore) DatabaseInitialized() bool {
  2278. var dummy string
  2279. var err error
  2280. if db.driverName == driverSQLite {
  2281. err = db.QueryRow("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'users'").Scan(&dummy)
  2282. } else {
  2283. err = db.QueryRow("SHOW TABLES LIKE 'users'").Scan(&dummy)
  2284. }
  2285. switch {
  2286. case err == sql.ErrNoRows:
  2287. return false
  2288. case err != nil:
  2289. log.Error("Couldn't SHOW TABLES: %v", err)
  2290. return false
  2291. }
  2292. return true
  2293. }
  2294. func stringLogln(log *string, s string, v ...interface{}) {
  2295. *log += fmt.Sprintf(s+"\n", v...)
  2296. }
  2297. func handleFailedPostInsert(err error) error {
  2298. log.Error("Couldn't insert into posts: %v", err)
  2299. return err
  2300. }
  2301. func (db *datastore) GetProfilePageFromHandle(app *App, handle string) (string, error) {
  2302. actorIRI := ""
  2303. remoteUser, err := getRemoteUserFromHandle(app, handle)
  2304. if err != nil {
  2305. // can't find using handle in the table but the table may already have this user without
  2306. // handle from a previous version
  2307. // TODO: Make this determination. We should know whether a user exists without a handle, or doesn't exist at all
  2308. actorIRI = RemoteLookup(handle)
  2309. _, errRemoteUser := getRemoteUser(app, actorIRI)
  2310. // if it exists then we need to update the handle
  2311. if errRemoteUser == nil {
  2312. _, err := app.db.Exec("UPDATE remoteusers SET handle = ? WHERE actor_id = ?", handle, actorIRI)
  2313. if err != nil {
  2314. log.Error("Can't update handle (" + handle + ") in database for user " + actorIRI)
  2315. }
  2316. } else {
  2317. // this probably means we don't have the user in the table so let's try to insert it
  2318. // here we need to ask the server for the inboxes
  2319. remoteActor, err := activityserve.NewRemoteActor(actorIRI)
  2320. if err != nil {
  2321. log.Error("Couldn't fetch remote actor", err)
  2322. }
  2323. if debugging {
  2324. log.Info("%s %s %s %s", actorIRI, remoteActor.GetInbox(), remoteActor.GetSharedInbox(), handle)
  2325. }
  2326. _, err = app.db.Exec("INSERT INTO remoteusers (actor_id, inbox, shared_inbox, handle) VALUES(?, ?, ?, ?)", actorIRI, remoteActor.GetInbox(), remoteActor.GetSharedInbox(), handle)
  2327. if err != nil {
  2328. log.Error("Can't insert remote user in database", err)
  2329. return "", err
  2330. }
  2331. }
  2332. } else {
  2333. actorIRI = remoteUser.ActorID
  2334. }
  2335. return actorIRI, nil
  2336. }