idecnode/pkg/idec/point.go

72 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-10-20 03:39:07 +03:00
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) {
2024-10-20 03:39:07 +03:00
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 {
2024-10-20 03:39:07 +03:00
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())
})
}