user.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. "strings"
  9. "miniflux.app/model"
  10. "github.com/lib/pq/hstore"
  11. "golang.org/x/crypto/bcrypt"
  12. )
  13. // SetLastLogin updates the last login date of a user.
  14. func (s *Storage) SetLastLogin(userID int64) error {
  15. query := `UPDATE users SET last_login_at=now() WHERE id=$1`
  16. _, err := s.db.Exec(query, userID)
  17. if err != nil {
  18. return fmt.Errorf(`store: unable to update last login date: %v`, err)
  19. }
  20. return nil
  21. }
  22. // UserExists checks if a user exists by using the given username.
  23. func (s *Storage) UserExists(username string) bool {
  24. var result bool
  25. s.db.QueryRow(`SELECT true FROM users WHERE username=LOWER($1)`, username).Scan(&result)
  26. return result
  27. }
  28. // AnotherUserExists checks if another user exists with the given username.
  29. func (s *Storage) AnotherUserExists(userID int64, username string) bool {
  30. var result bool
  31. s.db.QueryRow(`SELECT true FROM users WHERE id != $1 AND username=LOWER($2)`, userID, username).Scan(&result)
  32. return result
  33. }
  34. // CreateUser creates a new user.
  35. func (s *Storage) CreateUser(user *model.User) (err error) {
  36. password := ""
  37. extra := hstore.Hstore{Map: make(map[string]sql.NullString)}
  38. if user.Password != "" {
  39. password, err = hashPassword(user.Password)
  40. if err != nil {
  41. return err
  42. }
  43. }
  44. if len(user.Extra) > 0 {
  45. for key, value := range user.Extra {
  46. extra.Map[key] = sql.NullString{String: value, Valid: true}
  47. }
  48. }
  49. query := `
  50. INSERT INTO users
  51. (username, password, is_admin, extra)
  52. VALUES
  53. (LOWER($1), $2, $3, $4)
  54. RETURNING
  55. id, username, is_admin, language, theme, timezone, entry_direction, entries_per_page, keyboard_shortcuts, show_reading_time
  56. `
  57. err = s.db.QueryRow(query, user.Username, password, user.IsAdmin, extra).Scan(
  58. &user.ID,
  59. &user.Username,
  60. &user.IsAdmin,
  61. &user.Language,
  62. &user.Theme,
  63. &user.Timezone,
  64. &user.EntryDirection,
  65. &user.EntriesPerPage,
  66. &user.KeyboardShortcuts,
  67. &user.ShowReadingTime,
  68. )
  69. if err != nil {
  70. return fmt.Errorf(`store: unable to create user: %v`, err)
  71. }
  72. s.CreateCategory(&model.Category{Title: "All", UserID: user.ID})
  73. s.CreateIntegration(user.ID)
  74. return nil
  75. }
  76. // UpdateExtraField updates an extra field of the given user.
  77. func (s *Storage) UpdateExtraField(userID int64, field, value string) error {
  78. query := fmt.Sprintf(`UPDATE users SET extra = extra || hstore('%s', $1) WHERE id=$2`, field)
  79. _, err := s.db.Exec(query, value, userID)
  80. if err != nil {
  81. return fmt.Errorf(`store: unable to update user extra field: %v`, err)
  82. }
  83. return nil
  84. }
  85. // RemoveExtraField deletes an extra field for the given user.
  86. func (s *Storage) RemoveExtraField(userID int64, field string) error {
  87. query := `UPDATE users SET extra = delete(extra, $1) WHERE id=$2`
  88. _, err := s.db.Exec(query, field, userID)
  89. if err != nil {
  90. return fmt.Errorf(`store: unable to remove user extra field: %v`, err)
  91. }
  92. return nil
  93. }
  94. // UpdateUser updates a user.
  95. func (s *Storage) UpdateUser(user *model.User) error {
  96. if user.Password != "" {
  97. hashedPassword, err := hashPassword(user.Password)
  98. if err != nil {
  99. return err
  100. }
  101. query := `
  102. UPDATE users SET
  103. username=LOWER($1),
  104. password=$2,
  105. is_admin=$3,
  106. theme=$4,
  107. language=$5,
  108. timezone=$6,
  109. entry_direction=$7,
  110. entries_per_page=$8,
  111. keyboard_shortcuts=$9,
  112. show_reading_time=$10
  113. WHERE
  114. id=$11
  115. `
  116. _, err = s.db.Exec(
  117. query,
  118. user.Username,
  119. hashedPassword,
  120. user.IsAdmin,
  121. user.Theme,
  122. user.Language,
  123. user.Timezone,
  124. user.EntryDirection,
  125. user.EntriesPerPage,
  126. user.KeyboardShortcuts,
  127. user.ShowReadingTime,
  128. user.ID,
  129. )
  130. if err != nil {
  131. return fmt.Errorf(`store: unable to update user: %v`, err)
  132. }
  133. } else {
  134. query := `
  135. UPDATE users SET
  136. username=LOWER($1),
  137. is_admin=$2,
  138. theme=$3,
  139. language=$4,
  140. timezone=$5,
  141. entry_direction=$6,
  142. entries_per_page=$7,
  143. keyboard_shortcuts=$8,
  144. show_reading_time=$9
  145. WHERE
  146. id=$10
  147. `
  148. _, err := s.db.Exec(
  149. query,
  150. user.Username,
  151. user.IsAdmin,
  152. user.Theme,
  153. user.Language,
  154. user.Timezone,
  155. user.EntryDirection,
  156. user.EntriesPerPage,
  157. user.KeyboardShortcuts,
  158. user.ShowReadingTime,
  159. user.ID,
  160. )
  161. if err != nil {
  162. return fmt.Errorf(`store: unable to update user: %v`, err)
  163. }
  164. }
  165. if err := s.UpdateExtraField(user.ID, "custom_css", user.Extra["custom_css"]); err != nil {
  166. return fmt.Errorf(`store: unable to update user custom css: %v`, err)
  167. }
  168. return nil
  169. }
  170. // UserLanguage returns the language of the given user.
  171. func (s *Storage) UserLanguage(userID int64) (language string) {
  172. err := s.db.QueryRow(`SELECT language FROM users WHERE id = $1`, userID).Scan(&language)
  173. if err != nil {
  174. return "en_US"
  175. }
  176. return language
  177. }
  178. // UserByID finds a user by the ID.
  179. func (s *Storage) UserByID(userID int64) (*model.User, error) {
  180. query := `
  181. SELECT
  182. id,
  183. username,
  184. is_admin,
  185. theme,
  186. language,
  187. timezone,
  188. entry_direction,
  189. entries_per_page,
  190. keyboard_shortcuts,
  191. show_reading_time,
  192. last_login_at,
  193. extra
  194. FROM
  195. users
  196. WHERE
  197. id = $1
  198. `
  199. return s.fetchUser(query, userID)
  200. }
  201. // UserByUsername finds a user by the username.
  202. func (s *Storage) UserByUsername(username string) (*model.User, error) {
  203. query := `
  204. SELECT
  205. id,
  206. username,
  207. is_admin,
  208. theme,
  209. language,
  210. timezone,
  211. entry_direction,
  212. entries_per_page,
  213. keyboard_shortcuts,
  214. show_reading_time,
  215. last_login_at,
  216. extra
  217. FROM
  218. users
  219. WHERE
  220. username=LOWER($1)
  221. `
  222. return s.fetchUser(query, username)
  223. }
  224. // UserByExtraField finds a user by an extra field value.
  225. func (s *Storage) UserByExtraField(field, value string) (*model.User, error) {
  226. query := `
  227. SELECT
  228. id,
  229. username,
  230. is_admin,
  231. theme,
  232. language,
  233. timezone,
  234. entry_direction,
  235. entries_per_page,
  236. keyboard_shortcuts,
  237. show_reading_time,
  238. last_login_at,
  239. extra
  240. FROM
  241. users
  242. WHERE
  243. extra->$1=$2
  244. `
  245. return s.fetchUser(query, field, value)
  246. }
  247. // UserByAPIKey returns a User from an API Key.
  248. func (s *Storage) UserByAPIKey(token string) (*model.User, error) {
  249. query := `
  250. SELECT
  251. u.id,
  252. u.username,
  253. u.is_admin,
  254. u.theme,
  255. u.language,
  256. u.timezone,
  257. u.entry_direction,
  258. u.entries_per_page,
  259. u.keyboard_shortcuts,
  260. u.show_reading_time,
  261. u.last_login_at,
  262. u.extra
  263. FROM
  264. users u
  265. LEFT JOIN
  266. api_keys ON api_keys.user_id=u.id
  267. WHERE
  268. api_keys.token = $1
  269. `
  270. return s.fetchUser(query, token)
  271. }
  272. func (s *Storage) fetchUser(query string, args ...interface{}) (*model.User, error) {
  273. var extra hstore.Hstore
  274. user := model.NewUser()
  275. err := s.db.QueryRow(query, args...).Scan(
  276. &user.ID,
  277. &user.Username,
  278. &user.IsAdmin,
  279. &user.Theme,
  280. &user.Language,
  281. &user.Timezone,
  282. &user.EntryDirection,
  283. &user.EntriesPerPage,
  284. &user.KeyboardShortcuts,
  285. &user.ShowReadingTime,
  286. &user.LastLoginAt,
  287. &extra,
  288. )
  289. if err == sql.ErrNoRows {
  290. return nil, nil
  291. } else if err != nil {
  292. return nil, fmt.Errorf(`store: unable to fetch user: %v`, err)
  293. }
  294. for key, value := range extra.Map {
  295. if value.Valid {
  296. user.Extra[key] = value.String
  297. }
  298. }
  299. return user, nil
  300. }
  301. // RemoveUser deletes a user.
  302. func (s *Storage) RemoveUser(userID int64) error {
  303. ts, err := s.db.Begin()
  304. if err != nil {
  305. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  306. }
  307. if _, err := ts.Exec(`DELETE FROM users WHERE id=$1`, userID); err != nil {
  308. ts.Rollback()
  309. return fmt.Errorf(`store: unable to remove user #%d: %v`, userID, err)
  310. }
  311. if _, err := ts.Exec(`DELETE FROM integrations WHERE user_id=$1`, userID); err != nil {
  312. ts.Rollback()
  313. return fmt.Errorf(`store: unable to remove integration settings for user #%d: %v`, userID, err)
  314. }
  315. if err := ts.Commit(); err != nil {
  316. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  317. }
  318. return nil
  319. }
  320. // Users returns all users.
  321. func (s *Storage) Users() (model.Users, error) {
  322. query := `
  323. SELECT
  324. id,
  325. username,
  326. is_admin,
  327. theme,
  328. language,
  329. timezone,
  330. entry_direction,
  331. entries_per_page,
  332. keyboard_shortcuts,
  333. show_reading_time,
  334. last_login_at,
  335. extra
  336. FROM
  337. users
  338. ORDER BY username ASC
  339. `
  340. rows, err := s.db.Query(query)
  341. if err != nil {
  342. return nil, fmt.Errorf(`store: unable to fetch users: %v`, err)
  343. }
  344. defer rows.Close()
  345. var users model.Users
  346. for rows.Next() {
  347. var extra hstore.Hstore
  348. user := model.NewUser()
  349. err := rows.Scan(
  350. &user.ID,
  351. &user.Username,
  352. &user.IsAdmin,
  353. &user.Theme,
  354. &user.Language,
  355. &user.Timezone,
  356. &user.EntryDirection,
  357. &user.EntriesPerPage,
  358. &user.KeyboardShortcuts,
  359. &user.ShowReadingTime,
  360. &user.LastLoginAt,
  361. &extra,
  362. )
  363. if err != nil {
  364. return nil, fmt.Errorf(`store: unable to fetch users row: %v`, err)
  365. }
  366. for key, value := range extra.Map {
  367. if value.Valid {
  368. user.Extra[key] = value.String
  369. }
  370. }
  371. users = append(users, user)
  372. }
  373. return users, nil
  374. }
  375. // CheckPassword validate the hashed password.
  376. func (s *Storage) CheckPassword(username, password string) error {
  377. var hash string
  378. username = strings.ToLower(username)
  379. err := s.db.QueryRow("SELECT password FROM users WHERE username=$1", username).Scan(&hash)
  380. if err == sql.ErrNoRows {
  381. return fmt.Errorf(`store: unable to find this user: %s`, username)
  382. } else if err != nil {
  383. return fmt.Errorf(`store: unable to fetch user: %v`, err)
  384. }
  385. if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
  386. return fmt.Errorf(`store: invalid password for "%s" (%v)`, username, err)
  387. }
  388. return nil
  389. }
  390. // HasPassword returns true if the given user has a password defined.
  391. func (s *Storage) HasPassword(userID int64) (bool, error) {
  392. var result bool
  393. query := `SELECT true FROM users WHERE id=$1 AND password <> ''`
  394. err := s.db.QueryRow(query, userID).Scan(&result)
  395. if err == sql.ErrNoRows {
  396. return false, nil
  397. } else if err != nil {
  398. return false, fmt.Errorf(`store: unable to execute query: %v`, err)
  399. }
  400. if result {
  401. return true, nil
  402. }
  403. return false, nil
  404. }
  405. func hashPassword(password string) (string, error) {
  406. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  407. return string(bytes), err
  408. }