summaryrefslogtreecommitdiff
path: root/pkg/handler/user.go
blob: 9506c856b8bcb8b701ee5a2b383ef7cb86413041 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package handler

import (
	"encoding/json"
	"net/mail"
	"strings"

	"github.com/alexedwards/scs/v2"
	"github.com/labstack/echo/v4"
	"gitrepo.ru/neonxp/track/pkg/models"
	"go.etcd.io/bbolt"
	"go.neonxp.ru/objectid"
	"golang.org/x/crypto/bcrypt"
)

var (
	ErrInvalidPasswordLen     = echo.NewHTTPError(400, "Неверная длина пароля (должно быть от 8 до 32 символов)")
	ErrPasswordsNotSame       = echo.NewHTTPError(400, "Пароли не совпадают")
	ErrInvalidEmailOrPassword = echo.NewHTTPError(400, "Неверный email или пароль")
)

type User struct {
	db       *bbolt.DB
	sessions *scs.SessionManager
}

func NewUser(db *bbolt.DB, sessions *scs.SessionManager) *User {
	return &User{
		db:       db,
		sessions: sessions,
	}
}

func (u *User) Register(c echo.Context) error {
	req := new(RegisterRequest)
	if err := c.Bind(req); err != nil {
		return err
	}

	if _, err := mail.ParseAddress(req.Email); err != nil {
		return echo.NewHTTPError(400, err.Error())
	}

	if len(req.Password) < 8 || len(req.Password) > 32 {
		return ErrInvalidPasswordLen
	}

	if req.Password != req.Password2 {
		return ErrPasswordsNotSame
	}

	password, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	user := &models.User{
		ID:       objectid.New(),
		Email:    req.Email,
		Password: password,
	}

	err = u.db.Update(func(tx *bbolt.Tx) error {
		users, err := tx.CreateBucketIfNotExists([]byte("users"))
		if err != nil {
			return err
		}

		jb, err := json.Marshal(user)
		if err != nil {
			return err
		}

		if err := users.Put([]byte(strings.ToLower(user.Email)), jb); err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return err
	}

	return c.JSON(201, UserResponse{
		ID:    user.ID,
		Email: user.Email,
	})
}

func (u *User) Login(c echo.Context) error {
	req := new(LoginRequest)
	if err := c.Bind(req); err != nil {
		return err
	}

	user := new(models.User)

	err := u.db.View(func(tx *bbolt.Tx) error {
		users := tx.Bucket([]byte("users"))
		jb := users.Get([]byte(strings.ToLower(req.Email)))
		if jb == nil {
			return ErrInvalidEmailOrPassword
		}
		if err := json.Unmarshal(jb, user); err != nil {
			return err
		}
		if err := bcrypt.CompareHashAndPassword(user.Password, []byte(req.Password)); err != nil {
			return ErrInvalidEmailOrPassword
		}

		return nil
	})
	if err != nil {
		return err
	}

	u.sessions.Put(c.Request().Context(), "user", user)

	return c.JSON(200, UserResponse{
		ID:    user.ID,
		Email: user.Email,
	})
}

func (u *User) User(c echo.Context) error {
	uu := u.sessions.Get(c.Request().Context(), "user")
	if uu == nil {
		return echo.ErrForbidden
	}
	user, ok := uu.(*models.User)
	if !ok {
		return echo.ErrForbidden
	}

	return c.JSON(200, UserResponse{
		ID:    user.ID,
		Email: user.Email,
	})
}

type RegisterRequest struct {
	Email     string `json:"email"`
	Password  string `json:"password"`
	Password2 string `json:"password2"`
}

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type UserResponse struct {
	ID    objectid.ID `json:"id"`
	Email string      `json:"email"`
}