generated from ViBiOh/goweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
108 lines (85 loc) · 2.51 KB
/
user.go
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
package user
import (
"context"
"errors"
"fmt"
"strings"
authModel "github.com/ViBiOh/auth/v2/pkg/model"
"github.com/ViBiOh/httputils/v4/pkg/logger"
httpModel "github.com/ViBiOh/httputils/v4/pkg/model"
"github.com/ViBiOh/ketchup/pkg/model"
)
// App of package
type App struct {
userStore model.UserStore
authApp model.AuthService
}
// New creates new App from Config
func New(userStore model.UserStore, authApp model.AuthService) App {
return App{
userStore: userStore,
authApp: authApp,
}
}
// StoreInContext read login user from context and store app user in context
func (a App) StoreInContext(ctx context.Context) context.Context {
id := authModel.ReadUser(ctx).ID
if id == 0 {
logger.Warn("no login user in context")
return ctx
}
item, err := a.userStore.GetByLoginID(ctx, id)
if err != nil || item.IsZero() {
logger.Error("get user with login %d: %s", id, err)
return ctx
}
return model.StoreUser(ctx, item)
}
// ListReminderUsers list users that need a reminder
func (a App) ListReminderUsers(ctx context.Context) ([]model.User, error) {
return a.userStore.ListReminderUsers(ctx)
}
// Create user
func (a App) Create(ctx context.Context, item model.User) (model.User, error) {
if err := a.check(ctx, model.User{}, item); err != nil {
return model.User{}, httpModel.WrapInvalid(err)
}
if err := a.authApp.Check(ctx, authModel.User{}, item.Login); err != nil {
return model.User{}, httpModel.WrapInvalid(err)
}
var output model.User
err := a.userStore.DoAtomic(ctx, func(ctx context.Context) error {
loginUser, err := a.authApp.Create(ctx, item.Login)
if err != nil {
return httpModel.WrapInternal(fmt.Errorf("create login: %w", err))
}
item.Login = loginUser
id, err := a.userStore.Create(ctx, item)
if err != nil {
return httpModel.WrapInternal(fmt.Errorf("create: %w", err))
}
item.ID = id
output = item
return nil
})
return output, err
}
func (a App) check(ctx context.Context, _, new model.User) error {
if new.IsZero() {
return nil
}
var output []error
if len(strings.TrimSpace(new.Email)) == 0 {
output = append(output, errors.New("email is required"))
}
if userWithEmail, err := a.userStore.GetByEmail(ctx, new.Email); err != nil {
output = append(output, errors.New("check if email already exists"))
} else if !userWithEmail.ID.IsZero() {
output = append(output, errors.New("email already used"))
}
return httpModel.ConcatError(output)
}
// Count users
func (a App) Count(ctx context.Context) (uint64, error) {
return a.userStore.Count(ctx)
}