miniflux/storage/user.go

351 lines
8.6 KiB
Go
Raw Normal View History

2017-11-20 06:10:04 +01:00
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package storage
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
2017-11-23 07:22:33 +01:00
"github.com/lib/pq/hstore"
2017-12-13 06:48:13 +01:00
"github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/model"
2017-11-23 07:22:33 +01:00
2017-11-20 06:10:04 +01:00
"golang.org/x/crypto/bcrypt"
)
2017-11-28 06:30:04 +01:00
// SetLastLogin updates the last login date of a user.
2017-11-20 06:10:04 +01:00
func (s *Storage) SetLastLogin(userID int64) error {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:SetLastLogin] userID=%d", userID))
query := "UPDATE users SET last_login_at=now() WHERE id=$1"
_, err := s.db.Exec(query, userID)
if err != nil {
return fmt.Errorf("unable to update last login date: %v", err)
}
return nil
}
2017-11-28 06:30:04 +01:00
// UserExists checks if a user exists by using the given username.
2017-11-20 06:10:04 +01:00
func (s *Storage) UserExists(username string) bool {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UserExists] username=%s", username))
var result int
s.db.QueryRow(`SELECT count(*) as c FROM users WHERE username=$1`, username).Scan(&result)
return result >= 1
}
2017-11-28 06:30:04 +01:00
// AnotherUserExists checks if another user exists with the given username.
2017-11-20 06:10:04 +01:00
func (s *Storage) AnotherUserExists(userID int64, username string) bool {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:AnotherUserExists] userID=%d, username=%s", userID, username))
var result int
s.db.QueryRow(`SELECT count(*) as c FROM users WHERE id != $1 AND username=$2`, userID, username).Scan(&result)
return result >= 1
}
2017-11-28 06:30:04 +01:00
// CreateUser creates a new user.
2017-11-23 07:22:33 +01:00
func (s *Storage) CreateUser(user *model.User) (err error) {
2017-11-20 06:10:04 +01:00
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:CreateUser] username=%s", user.Username))
2017-11-23 07:22:33 +01:00
password := ""
extra := hstore.Hstore{Map: make(map[string]sql.NullString)}
2017-11-20 06:10:04 +01:00
2017-11-23 07:22:33 +01:00
if user.Password != "" {
password, err = hashPassword(user.Password)
if err != nil {
return err
}
2017-11-20 06:10:04 +01:00
}
2017-11-23 07:22:33 +01:00
if len(user.Extra) > 0 {
for key, value := range user.Extra {
extra.Map[key] = sql.NullString{String: value, Valid: true}
}
}
2017-11-25 19:40:23 +01:00
query := `INSERT INTO users
(username, password, is_admin, extra)
VALUES
($1, $2, $3, $4)
RETURNING id, language, theme, timezone`
err = s.db.QueryRow(query, strings.ToLower(user.Username), password, user.IsAdmin, extra).Scan(
&user.ID,
&user.Language,
&user.Theme,
&user.Timezone,
)
2017-11-20 06:10:04 +01:00
if err != nil {
return fmt.Errorf("unable to create user: %v", err)
}
s.CreateCategory(&model.Category{Title: "All", UserID: user.ID})
2017-12-03 04:32:14 +01:00
s.CreateIntegration(user.ID)
2017-11-20 06:10:04 +01:00
return nil
}
2017-11-28 06:30:04 +01:00
// UpdateExtraField updates an extra field of the given user.
2017-11-25 01:09:10 +01:00
func (s *Storage) UpdateExtraField(userID int64, field, value string) error {
query := fmt.Sprintf(`UPDATE users SET extra = hstore('%s', $1) WHERE id=$2`, field)
_, err := s.db.Exec(query, value, userID)
if err != nil {
return fmt.Errorf("unable to update user extra field: %v", err)
}
return nil
}
2017-11-28 06:30:04 +01:00
// RemoveExtraField deletes an extra field for the given user.
2017-11-25 01:09:10 +01:00
func (s *Storage) RemoveExtraField(userID int64, field string) error {
query := `UPDATE users SET extra = delete(extra, $1) WHERE id=$2`
_, err := s.db.Exec(query, field, userID)
if err != nil {
return fmt.Errorf("unable to remove user extra field: %v", err)
}
return nil
}
2017-11-28 06:30:04 +01:00
// UpdateUser updates a user.
2017-11-20 06:10:04 +01:00
func (s *Storage) UpdateUser(user *model.User) error {
2017-12-03 02:04:01 +01:00
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UpdateUser] userID=%d", user.ID))
2017-12-16 03:55:57 +01:00
2017-11-20 06:10:04 +01:00
if user.Password != "" {
hashedPassword, err := hashPassword(user.Password)
if err != nil {
return err
}
2017-12-03 02:04:01 +01:00
query := `UPDATE users SET
username=LOWER($1),
password=$2,
is_admin=$3,
theme=$4,
language=$5,
timezone=$6,
entry_direction=$7
WHERE id=$8`
_, err = s.db.Exec(
query,
user.Username,
hashedPassword,
user.IsAdmin,
user.Theme,
user.Language,
user.Timezone,
user.EntryDirection,
user.ID,
)
2017-11-20 06:10:04 +01:00
if err != nil {
return fmt.Errorf("unable to update user: %v", err)
}
} else {
2017-12-03 02:04:01 +01:00
query := `UPDATE users SET
username=$1,
is_admin=$2,
theme=$3,
language=$4,
timezone=$5,
entry_direction=$6
WHERE id=$7`
_, err := s.db.Exec(
query,
user.Username,
user.IsAdmin,
user.Theme,
user.Language,
user.Timezone,
user.EntryDirection,
user.ID,
)
2017-11-20 06:10:04 +01:00
if err != nil {
return fmt.Errorf("unable to update user: %v", err)
}
}
return nil
}
2017-11-28 06:30:04 +01:00
// UserByID finds a user by the ID.
func (s *Storage) UserByID(userID int64) (*model.User, error) {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UserByID] userID=%d", userID))
2017-12-03 02:04:01 +01:00
query := `SELECT
id, username, is_admin, theme, language, timezone, entry_direction, extra
FROM users
WHERE id = $1`
2017-11-20 06:10:04 +01:00
var user model.User
2017-11-25 01:09:10 +01:00
var extra hstore.Hstore
2017-12-03 02:04:01 +01:00
row := s.db.QueryRow(query, userID)
err := row.Scan(
&user.ID,
&user.Username,
&user.IsAdmin,
&user.Theme,
&user.Language,
&user.Timezone,
&user.EntryDirection,
&extra,
)
2017-11-20 06:10:04 +01:00
if err == sql.ErrNoRows {
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("unable to fetch user: %v", err)
}
2017-11-25 01:09:10 +01:00
user.Extra = make(map[string]string)
for key, value := range extra.Map {
if value.Valid {
user.Extra[key] = value.String
}
}
2017-11-20 06:10:04 +01:00
return &user, nil
}
2017-11-28 06:30:04 +01:00
// UserByUsername finds a user by the username.
func (s *Storage) UserByUsername(username string) (*model.User, error) {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UserByUsername] username=%s", username))
2017-12-03 02:04:01 +01:00
query := `SELECT
id, username, is_admin, theme, language, timezone, entry_direction
FROM users
WHERE username=LOWER($1)`
2017-11-20 06:10:04 +01:00
var user model.User
2017-12-03 02:04:01 +01:00
row := s.db.QueryRow(query, username)
err := row.Scan(
&user.ID,
&user.Username,
&user.IsAdmin,
&user.Theme,
&user.Language,
&user.Timezone,
&user.EntryDirection,
)
2017-11-20 06:10:04 +01:00
if err == sql.ErrNoRows {
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("unable to fetch user: %v", err)
2017-11-23 07:22:33 +01:00
}
return &user, nil
}
2017-11-28 06:30:04 +01:00
// UserByExtraField finds a user by an extra field value.
func (s *Storage) UserByExtraField(field, value string) (*model.User, error) {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UserByExtraField] field=%s", field))
2017-12-03 02:04:01 +01:00
query := `SELECT
id, username, is_admin, theme, language, timezone, entry_direction
FROM users
WHERE extra->$1=$2`
2017-11-23 07:22:33 +01:00
var user model.User
row := s.db.QueryRow(query, field, value)
2017-12-03 02:04:01 +01:00
err := row.Scan(
&user.ID,
&user.Username,
&user.IsAdmin,
&user.Theme,
&user.Language,
&user.Timezone,
&user.EntryDirection,
)
2017-11-23 07:22:33 +01:00
if err == sql.ErrNoRows {
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("unable to fetch user: %v", err)
2017-11-20 06:10:04 +01:00
}
return &user, nil
}
2017-11-28 06:30:04 +01:00
// RemoveUser deletes a user.
2017-11-20 06:10:04 +01:00
func (s *Storage) RemoveUser(userID int64) error {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:RemoveUser] userID=%d", userID))
result, err := s.db.Exec("DELETE FROM users WHERE id = $1", userID)
if err != nil {
return fmt.Errorf("unable to remove this user: %v", err)
}
count, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("unable to remove this user: %v", err)
}
if count == 0 {
2017-11-28 06:30:04 +01:00
return errors.New("nothing has been removed")
2017-11-20 06:10:04 +01:00
}
return nil
}
2017-11-28 06:30:04 +01:00
// Users returns all users.
func (s *Storage) Users() (model.Users, error) {
defer helper.ExecutionTime(time.Now(), "[Storage:Users]")
2017-12-03 02:04:01 +01:00
query := `SELECT
id, username, is_admin, theme, language, timezone, last_login_at
FROM users
ORDER BY username ASC`
2017-11-20 06:10:04 +01:00
2017-12-03 02:04:01 +01:00
rows, err := s.db.Query(query)
2017-11-20 06:10:04 +01:00
if err != nil {
return nil, fmt.Errorf("unable to fetch users: %v", err)
}
defer rows.Close()
2017-12-03 02:04:01 +01:00
var users model.Users
2017-11-20 06:10:04 +01:00
for rows.Next() {
var user model.User
err := rows.Scan(
&user.ID,
&user.Username,
&user.IsAdmin,
&user.Theme,
&user.Language,
&user.Timezone,
&user.LastLoginAt,
)
if err != nil {
return nil, fmt.Errorf("unable to fetch users row: %v", err)
}
users = append(users, &user)
}
return users, nil
}
2017-11-28 06:30:04 +01:00
// CheckPassword validate the hashed password.
2017-11-20 06:10:04 +01:00
func (s *Storage) CheckPassword(username, password string) error {
defer helper.ExecutionTime(time.Now(), "[Storage:CheckPassword]")
var hash string
username = strings.ToLower(username)
err := s.db.QueryRow("SELECT password FROM users WHERE username=$1", username).Scan(&hash)
if err == sql.ErrNoRows {
2017-11-28 06:30:04 +01:00
return fmt.Errorf("unable to find this user: %s", username)
2017-11-20 06:10:04 +01:00
} else if err != nil {
2017-11-28 06:30:04 +01:00
return fmt.Errorf("unable to fetch user: %v", err)
2017-11-20 06:10:04 +01:00
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
2017-12-23 01:30:17 +01:00
return fmt.Errorf(`invalid password for "%s" (%v)`, username, err)
2017-11-20 06:10:04 +01:00
}
return nil
}
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}