A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

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