user.go 13 KB

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