71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package idec
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/gob"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"gitrepo.ru/neonxp/idecnode/pkg/model"
|
|
"go.etcd.io/bbolt"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
var errPointFound = errors.New("point found")
|
|
|
|
func (i *IDEC) GetPointByAuth(pauth string) (*model.Point, error) {
|
|
point := new(model.Point)
|
|
|
|
return point, i.db.View(func(tx *bbolt.Tx) error {
|
|
bAuth := tx.Bucket([]byte(points))
|
|
if bAuth == nil {
|
|
return ErrUserNotFound
|
|
}
|
|
err := bAuth.ForEach(func(_, v []byte) error {
|
|
if err := gob.NewDecoder(bytes.NewBuffer(v)).Decode(point); err != nil {
|
|
return err
|
|
}
|
|
if point.AuthString == pauth {
|
|
return errPointFound
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err == errPointFound {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return ErrUserNotFound
|
|
})
|
|
}
|
|
|
|
func (i *IDEC) AddPoint(username, email, password string) (string, error) {
|
|
hpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
p := &model.Point{
|
|
Username: username,
|
|
Email: email,
|
|
Password: hpassword,
|
|
AuthString: uuid.NewString(),
|
|
}
|
|
|
|
return p.AuthString, i.db.Update(func(tx *bbolt.Tx) error {
|
|
pointsBucket, err := tx.CreateBucketIfNotExists([]byte(points))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
bPoint := bytes.NewBuffer([]byte{})
|
|
if err := gob.NewEncoder(bPoint).Encode(p); err != nil {
|
|
return err
|
|
}
|
|
|
|
return pointsBucket.Put([]byte(p.Email), bPoint.Bytes())
|
|
})
|
|
}
|