Skip to content

Commit

Permalink
Fixes after review
Browse files Browse the repository at this point in the history
  • Loading branch information
UnicoYal committed Sep 20, 2024
1 parent e347106 commit 9c9a019
Show file tree
Hide file tree
Showing 18 changed files with 138 additions and 61 deletions.
8 changes: 2 additions & 6 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: '3'
version: '3.9'

volumes:
postgres_volume:
Expand All @@ -17,8 +17,6 @@ services:
redis:
image: 'redis:latest'
command: redis-server
ports:
- '6379:6379'
volumes:
- redis:/data
networks:
Expand All @@ -29,8 +27,6 @@ services:
- "POSTGRES_DB=netflix"
- "POSTGRES_USER=test"
- "POSTGRES_PASSWORD=test"
ports:
- "5432:5432"
volumes:
- "postgres_volume:/var/lib/postgresql/data"
networks:
Expand All @@ -41,4 +37,4 @@ networks:
netflix:
default:
external:
name: netflix
name: netflix # Не забыть создать сеть перед деплоем
2 changes: 1 addition & 1 deletion validation-service/api/validation/validation.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ message ValidateRegistrationRequest {
string email = 1;
string password = 2;
string password_confirm = 3;
string sex = 4;
int32 sex = 4;
google.protobuf.Timestamp bitrhdate = 5;
}

Expand Down
6 changes: 2 additions & 4 deletions validation-service/cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"context"
"log"

"github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app"
Expand All @@ -10,12 +9,11 @@ import (
const serverPort = 5050

func main() {
ctx := context.Background()
a, err := app.New(ctx, serverPort)
a, ctx, err := app.New()

if err != nil {
log.Fatal(err)
}

a.Run()
a.Run(ctx)
}
15 changes: 15 additions & 0 deletions validation-service/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package config

type Config struct {
Listener Listener `yaml:"listener"`
}

type Listener struct {
Address string `yaml:"address"`
Port int `yaml:"port"`
}

type ConfigContextKey struct {
Address string
Port int
}
47 changes: 47 additions & 0 deletions validation-service/config/config_methods.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package config

import (
"context"
"os"
"path/filepath"

"gopkg.in/yaml.v3"
)

const cfgPath = "internal/config/config.yml"

func GetConfigFromContext(ctx context.Context) *Config {
value, ok := ctx.Value(ConfigContextKey{}).(*Config)
if !ok {
return nil
}

return value
}

func CreateConfigContext() (context.Context, error) {
ctx := context.Background()
config, err := readConf()
if err != nil {
return nil, err
}

return context.WithValue(ctx, ConfigContextKey{}, config), nil
}

func readConf() (*Config, error) {
cfg := &Config{}

filename, _ := filepath.Abs(cfgPath)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

err = yaml.Unmarshal(data, cfg)
if err != nil {
return nil, err
}

return cfg, nil
}
1 change: 1 addition & 0 deletions validation-service/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ require (
golang.org/x/text v0.16.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
3 changes: 3 additions & 0 deletions validation-service/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 h1:F29+wU6Ee6qgu9TddPgooOda
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1/go.mod h1:5KF+wpkbTSbGcR9zteSqZV6fqFOWBl4Yde8En8MryZA=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 changes: 1 addition & 1 deletion validation-service/internal/app/api/converter/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ func ToUserRegisterDataFromDesc(data *desc.ValidateRegistrationRequest) *model.U
func ToErrorsFromServ(data *model.ErrorResponse) *desc.ErrorMessage {
return &desc.ErrorMessage{
Code: data.Code,
Error: data.Error,
Error: data.ErrorObj.Error(),
}
}
4 changes: 3 additions & 1 deletion validation-service/internal/app/api/validation/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ type ValidationService interface {

type Implementation struct {
desc.UnimplementedValidationServer
ctx context.Context
validationService ValidationService
}

func NewImplementation(validationService ValidationService) *Implementation {
func NewImplementation(ctx context.Context, validationService ValidationService) *Implementation {
return &Implementation{
ctx: ctx,
validationService: validationService,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

func (i *Implementation) ValidateRegistration(ctx context.Context, req *desc.ValidateRegistrationRequest) (*desc.ValidationResponse, error) {
validData := i.validationService.ValidateRegistration(ctx, converter.ToUserRegisterDataFromDesc(req))
validData := i.validationService.ValidateRegistration(i.ctx, converter.ToUserRegisterDataFromDesc(req))
descErrors := make([]*desc.ErrorMessage, 0)
for _, errData := range validData.Errors {
descErrors = append(descErrors, converter.ToErrorsFromServ(&errData))
Expand Down
25 changes: 13 additions & 12 deletions validation-service/internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,39 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"

"github.com/go-park-mail-ru/2024_2_GOATS/validation-service/config"
validationAPI "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/api/validation"
validationService "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/service/validation"
desc "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/pb/validation"
)

type App struct {
serverPort int
validationService validationAPI.ValidationService
}

func New(ctx context.Context, serverPort int) (*App, error) {
validationService := validationService.NewService()
func New() (*App, context.Context, error) {
ctx, err := config.CreateConfigContext()
if err != nil {
log.Fatal("Failed to read config: %v", err)
}

return &App{
serverPort: serverPort,
validationService: validationService,
}, nil
validationService: validationService.NewService(ctx),
}, ctx, nil
}

func (a *App) Run() {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", a.serverPort))
func (a *App) Run(ctx context.Context) {
cfg := config.GetConfigFromContext(ctx)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.Listener.Port))
if err != nil {
log.Fatal("Failed to listen: %v", err)
}

validationSrv := validationService.NewService()
s := grpc.NewServer()
reflection.Register(s)
desc.RegisterValidationServer(s, validationAPI.NewImplementation(ctx, a.validationService))

desc.RegisterValidationServer(s, validationAPI.NewImplementation(validationSrv))

log.Printf("Server listening at %v", lis.Addr())
log.Printf("Server listening at %v:%d", cfg.Listener.Address, cfg.Listener.Port)

if err = s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
Expand Down
10 changes: 6 additions & 4 deletions validation-service/internal/app/errors/errors.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package errors

import "errors"

var (
ErrInvalidEmailCode = "invalid_email"
ErrInvalidEmailText = "email is incorrect"
ErrInvalidEmailText = errors.New("email is incorrect")
ErrInvalidPasswordCode = "invalid_password"
ErrInvalidPasswordText = "password is too short. The minimal len is 8"
ErrInvalidPasswordText = errors.New("password is too short. The minimal len is 8")
ErrInvalidSexCode = "invalid_sex"
ErrInvalidSexText = "only male or female allowed"
ErrInvalidSexText = errors.New("only male or female allowed")
ErrInvalidBirthdateCode = "invalid_birthdate"
ErrInvalidBirthdateText = "bithdate should be before current time"
ErrInvalidBirthdateText = errors.New("bithdate should be before current time")
)
6 changes: 3 additions & 3 deletions validation-service/internal/app/model/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ type UserRegisterData struct {
Email string
Password string
PasswordConfirm string
Sex string
Sex int32
Birthday int
}

type ErrorResponse struct {
Code string
Error string
Code string
ErrorObj error
}

type ValidationResponse struct {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package helpers

import (
"fmt"
"log"
"regexp"
"slices"
Expand All @@ -11,29 +10,33 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
)

const PasswordLength = 8
const Male = 0
const Female = 1
const Other = 2

var (
emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
passwordLength = 8
sexVals = []string{"male", "female"}
emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
sexVals = []int32{Male, Female, Other}
)

func ValidatePassword(pass, passConf string) error {
if passConf == "" {
log.Println("password confirm is missing, but now its OK")
}

if len(pass) < passwordLength {
log.Println(errVals.ErrInvalidPasswordText)
return fmt.Errorf(errVals.ErrInvalidPasswordText)
if len(pass) < PasswordLength {
log.Println(errVals.ErrInvalidPasswordText.Error())
return errVals.ErrInvalidPasswordText
}

return nil
}

func ValidateEmail(email string) error {
if !emailRegex.MatchString(email) {
log.Println(errVals.ErrInvalidEmailText)
return fmt.Errorf(errVals.ErrInvalidEmailText)
log.Println(errVals.ErrInvalidEmailText.Error())
return errVals.ErrInvalidEmailText
}

return nil
Expand All @@ -42,17 +45,17 @@ func ValidateEmail(email string) error {
func ValidateBirthdate(birthdate int) error {
ts := timestamppb.New(time.Now())
if int(ts.Seconds) < birthdate {
log.Println(errVals.ErrInvalidBirthdateCode)
return fmt.Errorf(errVals.ErrInvalidBirthdateText)
log.Println(errVals.ErrInvalidBirthdateText.Error())
return errVals.ErrInvalidBirthdateText
}

return nil
}

func ValidateSex(sex string) error {
func ValidateSex(sex int32) error {
if !slices.Contains(sexVals, sex) {
log.Println(errVals.ErrInvalidSexCode)
return fmt.Errorf(errVals.ErrInvalidSexText)
log.Println(errVals.ErrInvalidSexText.Error())
return errVals.ErrInvalidSexText
}

return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ func (s *serv) ValidateRegistration(ctx context.Context, userData *model.UserReg
errors := make([]model.ErrorResponse, 0)

if err := userHelper.ValidatePassword(userData.Password, userData.PasswordConfirm); err != nil {
success = AddError(errVals.ErrInvalidPasswordCode, err.Error(), &errors)
success = AddError(errVals.ErrInvalidPasswordCode, err, &errors)
}

if err := userHelper.ValidateEmail(userData.Email); err != nil {
success = AddError(errVals.ErrInvalidEmailCode, err.Error(), &errors)
success = AddError(errVals.ErrInvalidEmailCode, err, &errors)
}

if err := userHelper.ValidateBirthdate(userData.Birthday); err != nil {
success = AddError(errVals.ErrInvalidBirthdateCode, err.Error(), &errors)
success = AddError(errVals.ErrInvalidBirthdateCode, err, &errors)
}

if err := userHelper.ValidateSex(userData.Sex); err != nil {
success = AddError(errVals.ErrInvalidSexCode, err.Error(), &errors)
success = AddError(errVals.ErrInvalidSexCode, err, &errors)
}

return &model.ValidationResponse{
Expand All @@ -34,10 +34,10 @@ func (s *serv) ValidateRegistration(ctx context.Context, userData *model.UserReg
}
}

func AddError(code, err string, errors *[]model.ErrorResponse) bool {
func AddError(code string, err error, errors *[]model.ErrorResponse) bool {
errStruct := model.ErrorResponse{
Code: code,
Error: err,
Code: code,
ErrorObj: err,
}

*errors = append(*errors, errStruct)
Expand Down
12 changes: 9 additions & 3 deletions validation-service/internal/app/service/validation/validation.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package validation

import (
"context"

api "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/api/validation"
)

var _ api.ValidationService = (*serv)(nil)

type serv struct{}
type serv struct{
ctx context.Context
}

func NewService() *serv {
return &serv{}
func NewService(ctx context.Context) *serv {
return &serv{
ctx: ctx,
}
}
3 changes: 3 additions & 0 deletions validation-service/internal/config/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
listener:
address: localhost
port: 5050
Loading

0 comments on commit 9c9a019

Please sign in to comment.