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.
 
 
 
 
 

2643 lines
80 KiB

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