blob: c21b86ea1331815f3b0d149a5f4220bf13aa93ba [file] [log] [blame]
iomodocf795602021-03-07 23:14:15 +04001package app
2
3import (
iomodo352127d2021-03-26 20:10:32 +04004 "github.com/giolekva/pcloud/core/kg/log"
iomodocf795602021-03-07 23:14:15 +04005 "github.com/giolekva/pcloud/core/kg/model"
6 "github.com/pkg/errors"
iomodo493dd482021-04-02 00:07:51 +04007 "golang.org/x/crypto/bcrypt"
iomodocf795602021-03-07 23:14:15 +04008)
9
10// GetUser returns user
11func (a *App) GetUser(userID string) (*model.User, error) {
12 user, err := a.store.User().Get(userID)
13 if err != nil {
14 return nil, errors.Wrap(err, "can't get user from store")
15 }
16 return user, nil
17}
iomodo352127d2021-03-26 20:10:32 +040018
iomodo5c377be2021-03-26 20:39:28 +040019// CreateUser creates a user. For now it is used only for creation of the very first user
iomodo352127d2021-03-26 20:10:32 +040020func (a *App) CreateUser(user *model.User) (*model.User, error) {
21 if !a.isFirstUserAccount() {
22 return nil, errors.New("not a first user")
23 }
24
iomodo352127d2021-03-26 20:10:32 +040025 updatedUser, err := a.store.User().Save(user)
26 if err != nil {
27 return nil, errors.Wrap(err, "can't save user to the DB")
28 }
29 return updatedUser, nil
30}
31
iomodo5c377be2021-03-26 20:39:28 +040032//GetUsers returns list of users
33func (a *App) GetUsers(page, perPage int) ([]*model.User, error) {
34 users, err := a.store.User().GetAllWithOptions(page, perPage)
35 if err != nil {
36 return nil, errors.Wrap(err, "can't get users with options from store")
37 }
38 return users, nil
39}
40
iomodo352127d2021-03-26 20:10:32 +040041func (a *App) isFirstUserAccount() bool {
42 count, err := a.store.User().Count()
43 if err != nil {
44 a.logger.Error("error fetching first user account", log.Err(err))
45 }
46 return count > 0
47}
iomodo493dd482021-04-02 00:07:51 +040048
49// HashPassword hashes user's password
50func HashPassword(password string) string {
51 if password == "" {
52 return ""
53 }
54
55 hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
56 if err != nil {
57 panic(err)
58 }
59
60 return string(hash)
61}