A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 

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