From 45cada4fa5332ac54892708dd8d87250cbddf332 Mon Sep 17 00:00:00 2001 From: Salim Amine Bou Aram Date: Fri, 1 Nov 2024 01:23:34 +0100 Subject: [PATCH] replacing depracated grpc Dial + camelcases vars + fixing issues --- handler/authentication.go | 10 +- handler/forget_password.go | 2 +- handler/geo.go | 2 +- handler/notifications.go | 4 +- handler/onboarding_validation.go | 19 ++-- servers/grpcapi/server/geo.go | 6 +- .../grpcapi/server/silvermobi-grpc-server.go | 104 +++++++++++------- services/mobility-accounts.go | 4 +- services/push.go | 12 +- services/services.go | 2 +- 10 files changed, 100 insertions(+), 65 deletions(-) diff --git a/handler/authentication.go b/handler/authentication.go index a384026..ebc3b78 100644 --- a/handler/authentication.go +++ b/handler/authentication.go @@ -28,7 +28,7 @@ func (h *SilverMobiHandler) Login(ctx context.Context, username string, password } func (h *SilverMobiHandler) Register(ctx context.Context, username string, password string, email string, - phone_number string, first_name string, last_name string) (jwt string, err error) { + phoneNumber string, firstName string, lastName string) (jwt string, err error) { var ( account *models.Account @@ -40,12 +40,12 @@ func (h *SilverMobiHandler) Register(ctx context.Context, username string, passw username, password, email, - phone_number, + phoneNumber, map[string]any{ - "first_name": first_name, - "last_name": last_name, + "first_name": firstName, + "last_name": lastName, "email": email, - "phone_number": phone_number, + "phone_number": phoneNumber, }, "silvermobi", ); err != nil { diff --git a/handler/forget_password.go b/handler/forget_password.go index b76ca24..f4bd591 100644 --- a/handler/forget_password.go +++ b/handler/forget_password.go @@ -20,7 +20,7 @@ func generateRandomPassword(length int) (string, error) { } func (h *SilverMobiHandler) ForgetAccount(ctx context.Context, username string, namespace string) (response bool, - access_Code string) { + accessCode string) { var ( err error diff --git a/handler/geo.go b/handler/geo.go index ee01149..78b813e 100644 --- a/handler/geo.go +++ b/handler/geo.go @@ -3,7 +3,7 @@ package handler import ( "fmt" - routing "git.coopgo.io/coopgo-platform/routing-service" + "git.coopgo.io/coopgo-platform/routing-service" "github.com/paulmach/orb" "github.com/paulmach/orb/geojson" ) diff --git a/handler/notifications.go b/handler/notifications.go index 819bd3d..cfd8720 100644 --- a/handler/notifications.go +++ b/handler/notifications.go @@ -8,8 +8,8 @@ import ( gomail "gopkg.in/mail.v2" ) -func (h *SilverMobiHandler) PutFirebase(ctx context.Context, id string, token string, device_platform string) (err error) { - err = h.Storage.CreateFirebaseToken(id, token, device_platform) +func (h *SilverMobiHandler) PutFirebase(ctx context.Context, id string, token string, devicePlatform string) (err error) { + err = h.Storage.CreateFirebaseToken(id, token, devicePlatform) return err } diff --git a/handler/onboarding_validation.go b/handler/onboarding_validation.go index 1baf0d5..3d53aab 100644 --- a/handler/onboarding_validation.go +++ b/handler/onboarding_validation.go @@ -97,7 +97,7 @@ func (h *SilverMobiHandler) SetAccountType(ctx context.Context, id string, accou } return nil } -func (h *SilverMobiHandler) GetAccountType(ctx context.Context, id string) (account_type string, err error) { +func (h *SilverMobiHandler) GetAccountType(ctx context.Context, id string) (accountType string, err error) { var resp *grpcapi.GetAccountResponse request := &grpcapi.GetAccountRequest{ @@ -138,7 +138,8 @@ func (h *SilverMobiHandler) GetAccountPhone(ctx context.Context, id string) (pho return "", errors.New("invalid request ") } -func (h *SilverMobiHandler) CheckValidation(ctx context.Context, id string) (phone_validation, birth_validation, type_validation bool, err error) { +func (h *SilverMobiHandler) CheckValidation(ctx context.Context, id string) (phoneValidation, birthValidation, + typeValidation bool, err error) { var resp *grpcapi.GetAccountResponse @@ -153,22 +154,22 @@ func (h *SilverMobiHandler) CheckValidation(ctx context.Context, id string) (pho account := h.Services.MobilityAccounts.ToAccountModel(resp.Account.ToStorageType()) - phone_validation = false - birth_validation = false - type_validation = false + phoneValidation = false + birthValidation = false + typeValidation = false if account.LocalCredentials.PhoneNumberVerified { - phone_validation = true + phoneValidation = true } if account.BirthDate != "" { - birth_validation = true + birthValidation = true } if account.Type != "" { - type_validation = true + typeValidation = true } log.Info().Msg("Getting phone and birth validation for " + account.Email) - return phone_validation, birth_validation, type_validation, nil + return phoneValidation, birthValidation, typeValidation, nil } diff --git a/servers/grpcapi/server/geo.go b/servers/grpcapi/server/geo.go index 3d5db42..a9a150c 100644 --- a/servers/grpcapi/server/geo.go +++ b/servers/grpcapi/server/geo.go @@ -17,7 +17,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context, var ( results *geojson.FeatureCollection - rawfc []byte + rawFc []byte ) log.Info(). @@ -33,7 +33,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context, return nil, err } - if rawfc, err = results.MarshalJSON(); err != nil { + if rawFc, err = results.MarshalJSON(); err != nil { log.Error().Str("requestID", requestID).Err(err).Msg("GRPC GeoAutocomplete " + "protocol buffer conversion error") return nil, err @@ -41,7 +41,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context, resp = &grpcproto.GeoAutocompleteResponse{ FeatureCollection: &grpcproto.GeoAutocompleteResponse_FeatureCollectionRaw{ - FeatureCollectionRaw: string(rawfc), + FeatureCollectionRaw: string(rawFc), }, } diff --git a/servers/grpcapi/server/silvermobi-grpc-server.go b/servers/grpcapi/server/silvermobi-grpc-server.go index b4f9785..5a5cbee 100644 --- a/servers/grpcapi/server/silvermobi-grpc-server.go +++ b/servers/grpcapi/server/silvermobi-grpc-server.go @@ -2,19 +2,20 @@ package grpcserver import ( "context" - "fmt" + "net" + "git.coopgo.io/coopgo-apps/silvermobi/handler" grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto" "github.com/golang-jwt/jwt/v4" - grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" - grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth" - grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags" + grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware" + grpcauth "github.com/grpc-ecosystem/go-grpc-middleware/auth" + grpcctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags" "github.com/rs/zerolog/log" "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" - "net" ) type contextKey string @@ -42,37 +43,51 @@ func NoAuth(method string) bool { return false } -func UnaryAuthServerInterceptor(authFunc grpc_auth.AuthFunc) grpc.UnaryServerInterceptor { +func UnaryAuthServerInterceptor(authFunc grpcauth.AuthFunc) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + + var ( + newCtx context.Context + err error + ) + print(info.FullMethod) + if NoAuth(info.FullMethod) { return handler(ctx, req) } - var newCtx context.Context - var err error - newCtx, err = authFunc(ctx) - if err != nil { + + if newCtx, err = authFunc(ctx); err != nil { return nil, err } + return handler(newCtx, req) } } -func StreamAuthServerInterceptor(authFunc grpc_auth.AuthFunc) grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func StreamAuthServerInterceptor(authFunc grpcauth.AuthFunc) grpc.StreamServerInterceptor { + return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, + handler grpc.StreamHandler) error { + + var ( + newCtx context.Context + err error + ) + if NoAuth(info.FullMethod) { - wrapped := grpc_middleware.WrapServerStream(stream) + wrapped := grpcmiddleware.WrapServerStream(stream) wrapped.WrappedContext = stream.Context() + return handler(srv, wrapped) } - var newCtx context.Context - var err error - newCtx, err = authFunc(stream.Context()) - if err != nil { + + if newCtx, err = authFunc(stream.Context()); err != nil { return err } - wrapped := grpc_middleware.WrapServerStream(stream) + + wrapped := grpcmiddleware.WrapServerStream(stream) wrapped.WrappedContext = newCtx + return handler(srv, wrapped) } } @@ -84,20 +99,22 @@ type SilvermobiGRPCService struct { } type SolidarityService struct { - Config *viper.Viper - Handler *handler.SilverMobiHandler - SolidarityClient grpcproto.SolidarityServiceClient - grpcproto.UnimplementedSolidarityServiceServer // Add this client + Config *viper.Viper + Handler *handler.SilverMobiHandler + SolidarityClient grpcproto.SolidarityServiceClient + grpcproto.UnimplementedSolidarityServiceServer } func NewSolidarityService(cfg *viper.Viper, handler *handler.SilverMobiHandler) SolidarityService { solidarityServiceAddress := cfg.GetString("solidarity_service.address") - conn, err := grpc.Dial(solidarityServiceAddress, grpc.WithInsecure()) + + conn, err := grpc.NewClient(solidarityServiceAddress, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatal().Err(err) } solidarityClient := grpcproto.NewSolidarityServiceClient(conn) + return SolidarityService{ Config: cfg, Handler: handler, @@ -114,54 +131,61 @@ func NewSilvermobiGRPCService(cfg *viper.Viper, handler *handler.SilverMobiHandl func Run(done chan error, cfg *viper.Viper, handler *handler.SilverMobiHandler) { var ( - address = cfg.GetString("services.external.grpc.ip") + ":" + cfg.GetString("services.external.grpc.port") - jwt_secret = cfg.GetString("identification.local.jwt_secret") + address = cfg.GetString("services.external.grpc.ip") + ":" + cfg.GetString("services.external.grpc.port") + jwtSecret = cfg.GetString("identification.local.jwt_secret") ) log.Info().Msg("GRPC server on " + address) server := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( - grpc_ctxtags.StreamServerInterceptor(), - StreamAuthServerInterceptor(GRPCAuthFunc(jwt_secret)), + grpc.StreamInterceptor(grpcmiddleware.ChainStreamServer( + grpcctxtags.StreamServerInterceptor(), + StreamAuthServerInterceptor(GRPCAuthFunc(jwtSecret)), )), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( - grpc_ctxtags.UnaryServerInterceptor(), - UnaryAuthServerInterceptor(GRPCAuthFunc(jwt_secret)), + grpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer( + grpcctxtags.UnaryServerInterceptor(), + UnaryAuthServerInterceptor(GRPCAuthFunc(jwtSecret)), )), ) - solidarity_service := NewSolidarityService(cfg, handler) + solidarityService := NewSolidarityService(cfg, handler) - silvermobi_service := NewSilvermobiGRPCService(cfg, handler) - grpcproto.RegisterSilvermobiGRPCServer(server, silvermobi_service) - grpcproto.RegisterSolidarityServiceServer(server, &solidarity_service) + silvermobiService := NewSilvermobiGRPCService(cfg, handler) + grpcproto.RegisterSilvermobiGRPCServer(server, silvermobiService) + grpcproto.RegisterSolidarityServiceServer(server, &solidarityService) l, err := net.Listen("tcp", address) if err != nil { log.Fatal().Err(err) } - if err := server.Serve(l); err != nil { + if err = server.Serve(l); err != nil { log.Error().Err(err).Msg("gRPC service ended") done <- err } } -func GRPCAuthFunc(jwtKey string) grpc_auth.AuthFunc { +func GRPCAuthFunc(jwtKey string) grpcauth.AuthFunc { return func(ctx context.Context) (context.Context, error) { - tokenString, err := grpc_auth.AuthFromMD(ctx, "bearer") + + var token *jwt.Token + + tokenString, err := grpcauth.AuthFromMD(ctx, "bearer") + if err != nil { return nil, err } claims := jwt.MapClaims{} - token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { + + token, err = jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { return []byte(jwtKey), nil }) + if err != nil || !token.Valid { - fmt.Println(err) return nil, status.Errorf(codes.Unauthenticated, "Invalid or expired token") } + ctx = context.WithValue(ctx, contextKeyUser, claims["sub"].(string)) + return ctx, nil } } diff --git a/services/mobility-accounts.go b/services/mobility-accounts.go index 39aad76..70b8bf8 100644 --- a/services/mobility-accounts.go +++ b/services/mobility-accounts.go @@ -7,6 +7,7 @@ import ( mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi" ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/structpb" ) @@ -15,7 +16,8 @@ type MobilityAccountService struct { } func NewMobilityAccountService(mobilityAccountsDial string) (MobilityAccountService, error) { - mobilityAccountsConn, err := grpc.Dial(mobilityAccountsDial, grpc.WithInsecure()) + mobilityAccountsConn, err := grpc.NewClient(mobilityAccountsDial, + grpc.WithTransportCredentials(insecure.NewCredentials())) client := mobilityaccounts.NewMobilityAccountsClient(mobilityAccountsConn) if err != nil { diff --git a/services/push.go b/services/push.go index c4f387e..0920d9a 100644 --- a/services/push.go +++ b/services/push.go @@ -6,6 +6,7 @@ import ( "github.com/appleboy/gorush/rpc/proto" "github.com/rs/zerolog/log" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/structpb" ) @@ -36,7 +37,8 @@ type PushService struct { } func NewPushService(address string) (*PushService, error) { - conn, err := grpc.Dial(address, grpc.WithInsecure()) + conn, err := grpc.NewClient(address, + grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return nil, err @@ -48,6 +50,12 @@ func NewPushService(address string) (*PushService, error) { } func (s *PushService) Send(notification Notification) error { + + var ( + resp *proto.NotificationReply + err error + ) + log.Debug(). Int32("Platform", notification.Platform). Strs("recipients", notification.Recipients). @@ -55,7 +63,7 @@ func (s *PushService) Send(notification Notification) error { Str("notification_title", notification.Title). Msg("Send notification") - if resp, err := s.Client.Send(context.Background(), &proto.NotificationRequest{ + if resp, err = s.Client.Send(context.Background(), &proto.NotificationRequest{ Data: notification.Data, ID: notification.ID, Platform: notification.Platform, diff --git a/services/services.go b/services/services.go index 8215e6d..b5bae49 100644 --- a/services/services.go +++ b/services/services.go @@ -2,7 +2,7 @@ package services import ( "git.coopgo.io/coopgo-platform/geocode" - routing "git.coopgo.io/coopgo-platform/routing-service" + "git.coopgo.io/coopgo-platform/routing-service" "github.com/rs/zerolog/log" "github.com/spf13/viper" )