/
account.go
52 lines (43 loc) · 1.27 KB
/
account.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
package pgsql
import (
"context"
"net/http"
"github.com/crouse/pms/internal"
"github.com/crouse/pms/internal/errors"
"github.com/go-pg/pg"
"go.uber.org/zap"
)
// NewAccountDB returns a new AccountDB instance
func NewAccountDB(c *pg.DB, l *zap.Logger) *AccountDB {
return &AccountDB{c, l}
}
// AccountDB represents the client for user table
type AccountDB struct {
cl *pg.DB
log *zap.Logger
}
// Create creates a new user on database
func (a *AccountDB) Create(c context.Context, usr *model.User) error {
var user = new(model.User)
res, err := a.cl.Query(user, "select id from users where username = ? or email = ? and deleted_at is null", usr.Username, usr.Email)
if err != nil {
a.log.Error("AccountDB Error: ", zap.Error(err))
return apperr.DB
}
if res.RowsReturned() != 0 {
return apperr.New(http.StatusBadRequest, "Username or email already exists.")
}
if err := a.cl.Insert(usr); err != nil {
a.log.Warn("AccountDB Error: ", zap.Error(err))
return apperr.DB
}
return nil
}
// ChangePassword changes user's password
func (a *AccountDB) ChangePassword(c context.Context, usr *model.User) error {
_, err := a.cl.Model(usr).Column("password", "updated_at").WherePK().Update()
if err != nil {
a.log.Warn("AccountDB Error: ", zap.Error(err))
}
return err
}