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.
 
 
 
 
 

2218 lines
66 KiB

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