slaventius 2 years ago
parent de6b7dff0f
commit 77cd8613c1
  1. 1
      .vscode/launch.json
  2. 29
      internal/authDB.go
  3. 9
      internal/config/config.go
  4. 14
      internal/customer/amodel.go
  5. 33
      internal/customer/customer.go
  6. 12
      internal/customer/repository.go
  7. 4
      vendor/git.slaventius.ru/test3k/umate/pkg/kafka/auth.kafka.go

@ -19,6 +19,7 @@
"ARANGO_HOST": "127.0.0.1", "ARANGO_HOST": "127.0.0.1",
"ARANGO_USER": "root", "ARANGO_USER": "root",
"ARANGO_PASSWORD": "dbpassword", "ARANGO_PASSWORD": "dbpassword",
"MINUTES_REREGISTRATION": "2"
}, },
"args": [] "args": []
} }

@ -27,6 +27,7 @@ type AuthDBServer struct {
mu sync.Mutex mu sync.Mutex
ctx context.Context ctx context.Context
kafkaWriter *kafka.KafkaWriter kafkaWriter *kafka.KafkaWriter
config *config.Config
logger *logger.Logger logger *logger.Logger
repo *repo.CustomerRepository repo *repo.CustomerRepository
api.UnimplementedAuthDBServer api.UnimplementedAuthDBServer
@ -51,6 +52,7 @@ func NewServer(ctx context.Context, config *config.Config) *AuthDBServer {
ctx: ctx, ctx: ctx,
repo: repo, repo: repo,
kafkaWriter: kafka.NewWriter(ctx, logger, apiKafka.TopicRegistrations, net.JoinHostPort(config.Kafka.Host, strconv.Itoa(config.Kafka.Port))), kafkaWriter: kafka.NewWriter(ctx, logger, apiKafka.TopicRegistrations, net.JoinHostPort(config.Kafka.Host, strconv.Itoa(config.Kafka.Port))),
config: config,
logger: logger, logger: logger,
} }
} }
@ -81,7 +83,7 @@ func (s *AuthDBServer) Login(ctx context.Context, req *api.LoginRequest) (*api.L
} }
// //
if customer.Password != s.getMD5Hash(req.Password) { if customer.Password != s.getMD5Hash(req.GetPassword()) {
return nil, errors.New("password incorrect") return nil, errors.New("password incorrect")
} }
@ -98,24 +100,29 @@ func (s *AuthDBServer) Registration(ctx context.Context, req *api.RegistrationRe
customer, ok := s.repo.Customers[req.GetLogin()] customer, ok := s.repo.Customers[req.GetLogin()]
if !ok { if !ok {
hash := s.getMD5Hash(req.GetPassword()) hash := s.getMD5Hash(req.GetPassword())
customer = s.repo.NewCustomer(req.GetLogin(), hash, req.GetEmail(), strconv.Itoa(time.Now().Nanosecond())) customer = s.repo.NewCustomer(req.GetLogin(), hash, req.GetEmail())
// //
erk := customer.Add() erk := customer.Add(s.config.MinutesReregistration)
if erk != nil { if erk != nil {
return nil, erk return nil, erk
} }
// Добавим в локальную копию // Добавим в локальную копию
s.repo.Customers[req.GetLogin()] = customer s.repo.Customers[req.GetLogin()] = customer
} else if customer.Confirmed || time.Now().Before(customer.Time) { } else if customer.Confirmed || time.Now().Before(customer.TimeReregistration) {
return nil, errors.New("login already registered") return nil, errors.New("login already registered")
} else { // Обновим время регистрации } else { // Обновим время регистрации
customer.Refresh() ers := customer.Refresh(s.config.MinutesReregistration)
if ers != nil {
return nil, ers
}
s.repo.Customers[customer.Login] = customer
} }
// TODO // TODO
value, era := json.Marshal(customer.MessageRegistration) _, era := json.Marshal(customer.MessageRegistration)
if era != nil { if era != nil {
return nil, era return nil, era
} }
@ -124,12 +131,12 @@ func (s *AuthDBServer) Registration(ctx context.Context, req *api.RegistrationRe
s.logger.Printf("publication code %s to %s ...", customer.MessageRegistration.Code, customer.MessageRegistration.Email) s.logger.Printf("publication code %s to %s ...", customer.MessageRegistration.Code, customer.MessageRegistration.Email)
// Отправим уведомление о необходимости подтверждения // Отправим уведомление о необходимости подтверждения
err := s.kafkaWriter.WriteMessage([]byte(customer.Login), value) // err := s.kafkaWriter.WriteMessage([]byte(customer.Login), value)
if err != nil { // if err != nil {
s.logger.Error(err) // s.logger.Error(err)
return nil, err // return nil, err
} // }
// //
s.logger.Printf("publication code %s to %s completed", customer.MessageRegistration.Code, customer.MessageRegistration.Email) s.logger.Printf("publication code %s to %s completed", customer.MessageRegistration.Code, customer.MessageRegistration.Email)

@ -28,10 +28,11 @@ type sentryConfig struct {
// ... // ...
type Config struct { type Config struct {
App appConfig App appConfig
Kafka kafkaConfig Kafka kafkaConfig
Sentry sentryConfig Sentry sentryConfig
Arango arangoConfig Arango arangoConfig
MinutesReregistration int `envconfig:"MINUTES_REREGISTRATION"` // number of minutes until the next registration
} }
func NewConfig() *Config { func NewConfig() *Config {

@ -25,15 +25,14 @@ type Row struct {
// Базовые поля // Базовые поля
type SimpleRow struct { type SimpleRow struct {
Row Row
ID string `json:"id"` ID string `json:"id"`
CreatedAt string `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt string `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt string `json:"deleted_at"`
} }
func NewSimpleRow(ctx context.Context, database driver.Database, collection driver.Collection) *SimpleRow { func NewSimpleRow(ctx context.Context, database driver.Database, collection driver.Collection) *SimpleRow {
now := time.Now() now := time.Now()
nowStr := now.Format(StampTemplate) // nowStr := now.Format(StampTemplate)
key := strconv.Itoa(now.Nanosecond() * -1) key := strconv.Itoa(now.Nanosecond() * -1)
return &SimpleRow{ return &SimpleRow{
@ -44,9 +43,8 @@ func NewSimpleRow(ctx context.Context, database driver.Database, collection driv
key: key, key: key,
}, },
ID: key, ID: key,
CreatedAt: nowStr, CreatedAt: now,
UpdatedAt: nowStr, UpdatedAt: now,
DeletedAt: DateTemplatePast,
} }
} }

@ -1,6 +1,7 @@
package customer package customer
import ( import (
"strconv"
"time" "time"
apiKafka "git.slaventius.ru/test3k/umate/pkg/kafka" apiKafka "git.slaventius.ru/test3k/umate/pkg/kafka"
@ -9,14 +10,28 @@ import (
// Покупатель // Покупатель
type Customer struct { type Customer struct {
SimpleRow SimpleRow
Login string Login string `json:"login"`
Password string Password string `json:"password"`
Confirmed bool Confirmed bool `json:"confirmed"`
apiKafka.MessageRegistration apiKafka.MessageRegistration
Time time.Time TimeReregistration time.Time `json:"reregistration_at"` // Время начиная с которого допустима повторная регистрация
} }
func (c *Customer) Add() error { func (c *Customer) refreshCode(minutes int) string {
return strconv.Itoa(time.Now().Nanosecond())
}
func (c *Customer) refreshTime(minutes int) time.Time {
return time.Now().Add(time.Minute * time.Duration(minutes))
}
func (c *Customer) Add(minutes int) error {
c.Code = c.refreshCode(minutes)
c.TimeReregistration = c.refreshTime(minutes)
//
meta, err := c.collection.CreateDocument(c.ctx, c) meta, err := c.collection.CreateDocument(c.ctx, c)
if err != nil { if err != nil {
return err return err
@ -28,6 +43,9 @@ func (c *Customer) Add() error {
} }
func (c *Customer) Update() error { func (c *Customer) Update() error {
c.UpdatedAt = time.Now()
//
_, err := c.collection.UpdateDocument(c.ctx, c.key, c) _, err := c.collection.UpdateDocument(c.ctx, c.key, c)
return err return err
@ -37,8 +55,9 @@ func (c *Customer) Delete() error {
return c.SimpleRow.Delete() return c.SimpleRow.Delete()
} }
func (c *Customer) Refresh() error { func (c *Customer) Refresh(minutes int) error {
c.Time = time.Now().Add(time.Minute * 15) c.Code = c.refreshCode(minutes)
c.TimeReregistration = c.refreshTime(minutes)
return c.Update() return c.Update()
} }

@ -35,15 +35,15 @@ func NewCustomerRepository(ctx context.Context, database *arango_db.DataBase) *C
} }
// Новый покупатель // Новый покупатель
func (r *CustomerRepository) NewCustomer(login string, password string, email string, code string) Customer { func (r *CustomerRepository) NewCustomer(login string, password string, email string) Customer {
return Customer{ return Customer{
SimpleRow: *NewSimpleRow(r.ctx, r.database, r.collection), SimpleRow: *NewSimpleRow(r.ctx, r.database, r.collection),
Login: login, Login: login,
Password: password, Password: password,
Time: time.Now().Add(time.Minute * 15), TimeReregistration: time.Now(),
MessageRegistration: kafka.MessageRegistration{ MessageRegistration: kafka.MessageRegistration{
Email: email, Email: email,
Code: code, Code: time.Now().Format(StampTemplate),
}, },
} }
} }

@ -6,6 +6,6 @@ const (
// Структура сообщения передаваемого при регистрации // Структура сообщения передаваемого при регистрации
type MessageRegistration struct { type MessageRegistration struct {
Code string Code string `json:"code"`
Email string Email string `json:"email"`
} }

Loading…
Cancel
Save