reprogl
100 строк · 1.5 Кб
1package repositories
2
3import (
4"database/sql"
5"errors"
6"time"
7
8"xelbot.com/reprogl/models"
9)
10
11type UserRepository struct {
12DB *sql.DB
13}
14
15func (ur *UserRepository) GetLoggedUserByUsername(username string) (*models.LoggedUser, error) {
16query := `
17SELECT
18u.id,
19u.username,
20u.user_type,
21u.password,
22u.password_salt
23FROM users AS u
24WHERE (u.username = ?)`
25
26user := models.LoggedUser{}
27err := ur.DB.QueryRow(query, username).Scan(
28&user.ID,
29&user.Username,
30&user.Role,
31&user.PasswordHash,
32&user.Salt)
33
34if err != nil {
35if errors.Is(err, sql.ErrNoRows) {
36return nil, models.RecordNotFound
37} else {
38return nil, err
39}
40}
41
42return &user, nil
43}
44
45func (ur *UserRepository) Find(id int) (*models.User, error) {
46query := `
47SELECT
48u.id,
49u.username,
50u.mail,
51u.user_type,
52u.display_name,
53u.avatar_variant,
54u.time_created,
55u.gender
56FROM users AS u
57WHERE (u.id = ?)`
58
59user := models.User{}
60err := ur.DB.QueryRow(query, id).Scan(
61&user.ID,
62&user.Username,
63&user.Email,
64&user.Role,
65&user.DisplayName,
66&user.AvatarVariant,
67&user.CreatedAt,
68&user.Gender)
69
70if err != nil {
71if errors.Is(err, sql.ErrNoRows) {
72return nil, models.RecordNotFound
73} else {
74return nil, err
75}
76}
77
78return &user, nil
79}
80
81func (ur *UserRepository) SaveLoginEvent(id int, ip string) error {
82query := `
83UPDATE
84users
85SET
86last_login = ?,
87login_count = login_count + 1,
88ip_last = ?
89WHERE
90id = ?`
91
92_, err := ur.DB.Exec(
93query,
94time.Now().Format("2006-01-02 15:04:05.000"),
95ip,
96id,
97)
98
99return err
100}
101