user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package storage // import "miniflux.app/storage"
  5. import (
  6. "database/sql"
  7. "fmt"
  8. "runtime"
  9. "strings"
  10. "miniflux.app/logger"
  11. "miniflux.app/model"
  12. "github.com/lib/pq"
  13. "golang.org/x/crypto/bcrypt"
  14. )
  15. // CountUsers returns the total number of users.
  16. func (s *Storage) CountUsers() int {
  17. var result int
  18. err := s.db.QueryRow(`SELECT count(*) FROM users`).Scan(&result)
  19. if err != nil {
  20. return 0
  21. }
  22. return result
  23. }
  24. // SetLastLogin updates the last login date of a user.
  25. func (s *Storage) SetLastLogin(userID int64) error {
  26. query := `UPDATE users SET last_login_at=now() WHERE id=$1`
  27. _, err := s.db.Exec(query, userID)
  28. if err != nil {
  29. return fmt.Errorf(`store: unable to update last login date: %v`, err)
  30. }
  31. return nil
  32. }
  33. // UserExists checks if a user exists by using the given username.
  34. func (s *Storage) UserExists(username string) bool {
  35. var result bool
  36. s.db.QueryRow(`SELECT true FROM users WHERE username=LOWER($1)`, username).Scan(&result)
  37. return result
  38. }
  39. // AnotherUserExists checks if another user exists with the given username.
  40. func (s *Storage) AnotherUserExists(userID int64, username string) bool {
  41. var result bool
  42. s.db.QueryRow(`SELECT true FROM users WHERE id != $1 AND username=LOWER($2)`, userID, username).Scan(&result)
  43. return result
  44. }
  45. // CreateUser creates a new user.
  46. func (s *Storage) CreateUser(userCreationRequest *model.UserCreationRequest) (*model.User, error) {
  47. var hashedPassword string
  48. if userCreationRequest.Password != "" {
  49. var err error
  50. hashedPassword, err = hashPassword(userCreationRequest.Password)
  51. if err != nil {
  52. return nil, err
  53. }
  54. }
  55. query := `
  56. INSERT INTO users
  57. (username, password, is_admin, google_id, openid_connect_id)
  58. VALUES
  59. (LOWER($1), $2, $3, $4, $5)
  60. RETURNING
  61. id,
  62. username,
  63. is_admin,
  64. language,
  65. theme,
  66. timezone,
  67. entry_direction,
  68. entries_per_page,
  69. keyboard_shortcuts,
  70. show_reading_time,
  71. entry_swipe,
  72. stylesheet,
  73. google_id,
  74. openid_connect_id
  75. `
  76. tx, err := s.db.Begin()
  77. if err != nil {
  78. return nil, fmt.Errorf(`store: unable to start transaction: %v`, err)
  79. }
  80. var user model.User
  81. err = tx.QueryRow(
  82. query,
  83. userCreationRequest.Username,
  84. hashedPassword,
  85. userCreationRequest.IsAdmin,
  86. userCreationRequest.GoogleID,
  87. userCreationRequest.OpenIDConnectID,
  88. ).Scan(
  89. &user.ID,
  90. &user.Username,
  91. &user.IsAdmin,
  92. &user.Language,
  93. &user.Theme,
  94. &user.Timezone,
  95. &user.EntryDirection,
  96. &user.EntriesPerPage,
  97. &user.KeyboardShortcuts,
  98. &user.ShowReadingTime,
  99. &user.EntrySwipe,
  100. &user.Stylesheet,
  101. &user.GoogleID,
  102. &user.OpenIDConnectID,
  103. )
  104. if err != nil {
  105. tx.Rollback()
  106. return nil, fmt.Errorf(`store: unable to create user: %v`, err)
  107. }
  108. _, err = tx.Exec(`INSERT INTO categories (user_id, title) VALUES ($1, $2)`, user.ID, "All")
  109. if err != nil {
  110. tx.Rollback()
  111. return nil, fmt.Errorf(`store: unable to create user default category: %v`, err)
  112. }
  113. _, err = tx.Exec(`INSERT INTO integrations (user_id) VALUES ($1)`, user.ID)
  114. if err != nil {
  115. tx.Rollback()
  116. return nil, fmt.Errorf(`store: unable to create integration row: %v`, err)
  117. }
  118. if err := tx.Commit(); err != nil {
  119. return nil, fmt.Errorf(`store: unable to commit transaction: %v`, err)
  120. }
  121. return &user, nil
  122. }
  123. // UpdateUser updates a user.
  124. func (s *Storage) UpdateUser(user *model.User) error {
  125. if user.Password != "" {
  126. hashedPassword, err := hashPassword(user.Password)
  127. if err != nil {
  128. return err
  129. }
  130. query := `
  131. UPDATE users SET
  132. username=LOWER($1),
  133. password=$2,
  134. is_admin=$3,
  135. theme=$4,
  136. language=$5,
  137. timezone=$6,
  138. entry_direction=$7,
  139. entries_per_page=$8,
  140. keyboard_shortcuts=$9,
  141. show_reading_time=$10,
  142. entry_swipe=$11,
  143. stylesheet=$12,
  144. google_id=$13,
  145. openid_connect_id=$14
  146. WHERE
  147. id=$15
  148. `
  149. _, err = s.db.Exec(
  150. query,
  151. user.Username,
  152. hashedPassword,
  153. user.IsAdmin,
  154. user.Theme,
  155. user.Language,
  156. user.Timezone,
  157. user.EntryDirection,
  158. user.EntriesPerPage,
  159. user.KeyboardShortcuts,
  160. user.ShowReadingTime,
  161. user.EntrySwipe,
  162. user.Stylesheet,
  163. user.GoogleID,
  164. user.OpenIDConnectID,
  165. user.ID,
  166. )
  167. if err != nil {
  168. return fmt.Errorf(`store: unable to update user: %v`, err)
  169. }
  170. } else {
  171. query := `
  172. UPDATE users SET
  173. username=LOWER($1),
  174. is_admin=$2,
  175. theme=$3,
  176. language=$4,
  177. timezone=$5,
  178. entry_direction=$6,
  179. entries_per_page=$7,
  180. keyboard_shortcuts=$8,
  181. show_reading_time=$9,
  182. entry_swipe=$10,
  183. stylesheet=$11,
  184. google_id=$12,
  185. openid_connect_id=$13
  186. WHERE
  187. id=$14
  188. `
  189. _, err := s.db.Exec(
  190. query,
  191. user.Username,
  192. user.IsAdmin,
  193. user.Theme,
  194. user.Language,
  195. user.Timezone,
  196. user.EntryDirection,
  197. user.EntriesPerPage,
  198. user.KeyboardShortcuts,
  199. user.ShowReadingTime,
  200. user.EntrySwipe,
  201. user.Stylesheet,
  202. user.GoogleID,
  203. user.OpenIDConnectID,
  204. user.ID,
  205. )
  206. if err != nil {
  207. return fmt.Errorf(`store: unable to update user: %v`, err)
  208. }
  209. }
  210. return nil
  211. }
  212. // UserLanguage returns the language of the given user.
  213. func (s *Storage) UserLanguage(userID int64) (language string) {
  214. err := s.db.QueryRow(`SELECT language FROM users WHERE id = $1`, userID).Scan(&language)
  215. if err != nil {
  216. return "en_US"
  217. }
  218. return language
  219. }
  220. // UserByID finds a user by the ID.
  221. func (s *Storage) UserByID(userID int64) (*model.User, error) {
  222. query := `
  223. SELECT
  224. id,
  225. username,
  226. is_admin,
  227. theme,
  228. language,
  229. timezone,
  230. entry_direction,
  231. entries_per_page,
  232. keyboard_shortcuts,
  233. show_reading_time,
  234. entry_swipe,
  235. last_login_at,
  236. stylesheet,
  237. google_id,
  238. openid_connect_id
  239. FROM
  240. users
  241. WHERE
  242. id = $1
  243. `
  244. return s.fetchUser(query, userID)
  245. }
  246. // UserByUsername finds a user by the username.
  247. func (s *Storage) UserByUsername(username string) (*model.User, error) {
  248. query := `
  249. SELECT
  250. id,
  251. username,
  252. is_admin,
  253. theme,
  254. language,
  255. timezone,
  256. entry_direction,
  257. entries_per_page,
  258. keyboard_shortcuts,
  259. show_reading_time,
  260. entry_swipe,
  261. last_login_at,
  262. stylesheet,
  263. google_id,
  264. openid_connect_id
  265. FROM
  266. users
  267. WHERE
  268. username=LOWER($1)
  269. `
  270. return s.fetchUser(query, username)
  271. }
  272. // UserByField finds a user by a field value.
  273. func (s *Storage) UserByField(field, value string) (*model.User, error) {
  274. query := `
  275. SELECT
  276. id,
  277. username,
  278. is_admin,
  279. theme,
  280. language,
  281. timezone,
  282. entry_direction,
  283. entries_per_page,
  284. keyboard_shortcuts,
  285. show_reading_time,
  286. entry_swipe,
  287. last_login_at,
  288. stylesheet,
  289. google_id,
  290. openid_connect_id
  291. FROM
  292. users
  293. WHERE
  294. %s=$1
  295. `
  296. return s.fetchUser(fmt.Sprintf(query, pq.QuoteIdentifier(field)), value)
  297. }
  298. // AnotherUserWithFieldExists returns true if a user has the value set for the given field.
  299. func (s *Storage) AnotherUserWithFieldExists(userID int64, field, value string) bool {
  300. var result bool
  301. s.db.QueryRow(fmt.Sprintf(`SELECT true FROM users WHERE id <> $1 AND %s=$2`, pq.QuoteIdentifier(field)), userID, value).Scan(&result)
  302. return result
  303. }
  304. // UserByAPIKey returns a User from an API Key.
  305. func (s *Storage) UserByAPIKey(token string) (*model.User, error) {
  306. query := `
  307. SELECT
  308. u.id,
  309. u.username,
  310. u.is_admin,
  311. u.theme,
  312. u.language,
  313. u.timezone,
  314. u.entry_direction,
  315. u.entries_per_page,
  316. u.keyboard_shortcuts,
  317. u.show_reading_time,
  318. u.entry_swipe,
  319. u.last_login_at,
  320. u.stylesheet,
  321. u.google_id,
  322. u.openid_connect_id
  323. FROM
  324. users u
  325. LEFT JOIN
  326. api_keys ON api_keys.user_id=u.id
  327. WHERE
  328. api_keys.token = $1
  329. `
  330. return s.fetchUser(query, token)
  331. }
  332. func (s *Storage) fetchUser(query string, args ...interface{}) (*model.User, error) {
  333. var user model.User
  334. err := s.db.QueryRow(query, args...).Scan(
  335. &user.ID,
  336. &user.Username,
  337. &user.IsAdmin,
  338. &user.Theme,
  339. &user.Language,
  340. &user.Timezone,
  341. &user.EntryDirection,
  342. &user.EntriesPerPage,
  343. &user.KeyboardShortcuts,
  344. &user.ShowReadingTime,
  345. &user.EntrySwipe,
  346. &user.LastLoginAt,
  347. &user.Stylesheet,
  348. &user.GoogleID,
  349. &user.OpenIDConnectID,
  350. )
  351. if err == sql.ErrNoRows {
  352. return nil, nil
  353. } else if err != nil {
  354. return nil, fmt.Errorf(`store: unable to fetch user: %v`, err)
  355. }
  356. return &user, nil
  357. }
  358. // RemoveUser deletes a user.
  359. func (s *Storage) RemoveUser(userID int64) error {
  360. tx, err := s.db.Begin()
  361. if err != nil {
  362. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  363. }
  364. if _, err := tx.Exec(`DELETE FROM users WHERE id=$1`, userID); err != nil {
  365. tx.Rollback()
  366. return fmt.Errorf(`store: unable to remove user #%d: %v`, userID, err)
  367. }
  368. if _, err := tx.Exec(`DELETE FROM integrations WHERE user_id=$1`, userID); err != nil {
  369. tx.Rollback()
  370. return fmt.Errorf(`store: unable to remove integration settings for user #%d: %v`, userID, err)
  371. }
  372. if err := tx.Commit(); err != nil {
  373. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  374. }
  375. return nil
  376. }
  377. // RemoveUserAsync deletes user data without locking the database.
  378. func (s *Storage) RemoveUserAsync(userID int64) {
  379. go func() {
  380. deleteUserFeeds(s.db, userID)
  381. s.db.Exec(`DELETE FROM users WHERE id=$1`, userID)
  382. s.db.Exec(`DELETE FROM integrations WHERE user_id=$1`, userID)
  383. logger.Debug(`[MASS DELETE] User #%d has been deleted (%d GoRoutines)`, userID, runtime.NumGoroutine())
  384. }()
  385. }
  386. // Users returns all users.
  387. func (s *Storage) Users() (model.Users, error) {
  388. query := `
  389. SELECT
  390. id,
  391. username,
  392. is_admin,
  393. theme,
  394. language,
  395. timezone,
  396. entry_direction,
  397. entries_per_page,
  398. keyboard_shortcuts,
  399. show_reading_time,
  400. entry_swipe,
  401. last_login_at,
  402. stylesheet,
  403. google_id,
  404. openid_connect_id
  405. FROM
  406. users
  407. ORDER BY username ASC
  408. `
  409. rows, err := s.db.Query(query)
  410. if err != nil {
  411. return nil, fmt.Errorf(`store: unable to fetch users: %v`, err)
  412. }
  413. defer rows.Close()
  414. var users model.Users
  415. for rows.Next() {
  416. var user model.User
  417. err := rows.Scan(
  418. &user.ID,
  419. &user.Username,
  420. &user.IsAdmin,
  421. &user.Theme,
  422. &user.Language,
  423. &user.Timezone,
  424. &user.EntryDirection,
  425. &user.EntriesPerPage,
  426. &user.KeyboardShortcuts,
  427. &user.ShowReadingTime,
  428. &user.EntrySwipe,
  429. &user.LastLoginAt,
  430. &user.Stylesheet,
  431. &user.GoogleID,
  432. &user.OpenIDConnectID,
  433. )
  434. if err != nil {
  435. return nil, fmt.Errorf(`store: unable to fetch users row: %v`, err)
  436. }
  437. users = append(users, &user)
  438. }
  439. return users, nil
  440. }
  441. // CheckPassword validate the hashed password.
  442. func (s *Storage) CheckPassword(username, password string) error {
  443. var hash string
  444. username = strings.ToLower(username)
  445. err := s.db.QueryRow("SELECT password FROM users WHERE username=$1", username).Scan(&hash)
  446. if err == sql.ErrNoRows {
  447. return fmt.Errorf(`store: unable to find this user: %s`, username)
  448. } else if err != nil {
  449. return fmt.Errorf(`store: unable to fetch user: %v`, err)
  450. }
  451. if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
  452. return fmt.Errorf(`store: invalid password for "%s" (%v)`, username, err)
  453. }
  454. return nil
  455. }
  456. // HasPassword returns true if the given user has a password defined.
  457. func (s *Storage) HasPassword(userID int64) (bool, error) {
  458. var result bool
  459. query := `SELECT true FROM users WHERE id=$1 AND password <> ''`
  460. err := s.db.QueryRow(query, userID).Scan(&result)
  461. if err == sql.ErrNoRows {
  462. return false, nil
  463. } else if err != nil {
  464. return false, fmt.Errorf(`store: unable to execute query: %v`, err)
  465. }
  466. if result {
  467. return true, nil
  468. }
  469. return false, nil
  470. }
  471. func hashPassword(password string) (string, error) {
  472. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  473. return string(bytes), err
  474. }
  475. func deleteUserFeeds(db *sql.DB, userID int64) {
  476. query := `SELECT id FROM feeds WHERE user_id=$1`
  477. rows, err := db.Query(query, userID)
  478. if err != nil {
  479. logger.Error(`store: unable to get user feeds: %v`, err)
  480. return
  481. }
  482. defer rows.Close()
  483. var feedIDs []int64
  484. for rows.Next() {
  485. var feedID int64
  486. rows.Scan(&feedID)
  487. feedIDs = append(feedIDs, feedID)
  488. }
  489. worker := func(jobs <-chan int64, results chan<- bool) {
  490. for feedID := range jobs {
  491. logger.Debug(`[MASS DELETE] Deleting feed #%d for user #%d (%d GoRoutines)`, feedID, userID, runtime.NumGoroutine())
  492. deleteUserEntries(db, userID, feedID)
  493. db.Exec(`DELETE FROM feeds WHERE id=$1`, feedID)
  494. results <- true
  495. }
  496. }
  497. numJobs := len(feedIDs)
  498. jobs := make(chan int64, numJobs)
  499. results := make(chan bool, numJobs)
  500. for w := 0; w < 2; w++ {
  501. go worker(jobs, results)
  502. }
  503. for j := 0; j < numJobs; j++ {
  504. jobs <- feedIDs[j]
  505. }
  506. close(jobs)
  507. for a := 1; a <= numJobs; a++ {
  508. <-results
  509. }
  510. }
  511. func deleteUserEntries(db *sql.DB, userID int64, feedID int64) {
  512. rows, err := db.Query(`SELECT id FROM entries WHERE user_id=$1 AND feed_id=$2`, userID, feedID)
  513. if err != nil {
  514. logger.Error(`store: unable to get user feed entries: %v`, err)
  515. return
  516. }
  517. defer rows.Close()
  518. for rows.Next() {
  519. var entryID int64
  520. rows.Scan(&entryID)
  521. logger.Debug(`[MASS DELETE] Deleting entry #%d for user #%d (%d GoRoutines)`, entryID, userID, runtime.NumGoroutine())
  522. db.Exec(`DELETE FROM enclosures WHERE entry_id=$1 AND user_id=$2`, entryID, userID)
  523. db.Exec(`DELETE FROM entries WHERE id=$1 AND user_id=$2`, entryID, userID)
  524. }
  525. }