replacing depracated grpc Dial + camelcases vars + fixing issues

This commit is contained in:
Salim Amine Bou Aram 2024-11-01 01:23:34 +01:00
parent 41bcb74462
commit 45cada4fa5
10 changed files with 100 additions and 65 deletions

View File

@ -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, 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 ( var (
account *models.Account account *models.Account
@ -40,12 +40,12 @@ func (h *SilverMobiHandler) Register(ctx context.Context, username string, passw
username, username,
password, password,
email, email,
phone_number, phoneNumber,
map[string]any{ map[string]any{
"first_name": first_name, "first_name": firstName,
"last_name": last_name, "last_name": lastName,
"email": email, "email": email,
"phone_number": phone_number, "phone_number": phoneNumber,
}, },
"silvermobi", "silvermobi",
); err != nil { ); err != nil {

View File

@ -20,7 +20,7 @@ func generateRandomPassword(length int) (string, error) {
} }
func (h *SilverMobiHandler) ForgetAccount(ctx context.Context, username string, namespace string) (response bool, func (h *SilverMobiHandler) ForgetAccount(ctx context.Context, username string, namespace string) (response bool,
access_Code string) { accessCode string) {
var ( var (
err error err error

View File

@ -3,7 +3,7 @@ package handler
import ( import (
"fmt" "fmt"
routing "git.coopgo.io/coopgo-platform/routing-service" "git.coopgo.io/coopgo-platform/routing-service"
"github.com/paulmach/orb" "github.com/paulmach/orb"
"github.com/paulmach/orb/geojson" "github.com/paulmach/orb/geojson"
) )

View File

@ -8,8 +8,8 @@ import (
gomail "gopkg.in/mail.v2" gomail "gopkg.in/mail.v2"
) )
func (h *SilverMobiHandler) PutFirebase(ctx context.Context, id string, token string, device_platform string) (err error) { func (h *SilverMobiHandler) PutFirebase(ctx context.Context, id string, token string, devicePlatform string) (err error) {
err = h.Storage.CreateFirebaseToken(id, token, device_platform) err = h.Storage.CreateFirebaseToken(id, token, devicePlatform)
return err return err
} }

View File

@ -97,7 +97,7 @@ func (h *SilverMobiHandler) SetAccountType(ctx context.Context, id string, accou
} }
return nil 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 var resp *grpcapi.GetAccountResponse
request := &grpcapi.GetAccountRequest{ request := &grpcapi.GetAccountRequest{
@ -138,7 +138,8 @@ func (h *SilverMobiHandler) GetAccountPhone(ctx context.Context, id string) (pho
return "", errors.New("invalid request ") 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 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()) account := h.Services.MobilityAccounts.ToAccountModel(resp.Account.ToStorageType())
phone_validation = false phoneValidation = false
birth_validation = false birthValidation = false
type_validation = false typeValidation = false
if account.LocalCredentials.PhoneNumberVerified { if account.LocalCredentials.PhoneNumberVerified {
phone_validation = true phoneValidation = true
} }
if account.BirthDate != "" { if account.BirthDate != "" {
birth_validation = true birthValidation = true
} }
if account.Type != "" { if account.Type != "" {
type_validation = true typeValidation = true
} }
log.Info().Msg("Getting phone and birth validation for " + account.Email) log.Info().Msg("Getting phone and birth validation for " + account.Email)
return phone_validation, birth_validation, type_validation, nil return phoneValidation, birthValidation, typeValidation, nil
} }

View File

@ -17,7 +17,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context,
var ( var (
results *geojson.FeatureCollection results *geojson.FeatureCollection
rawfc []byte rawFc []byte
) )
log.Info(). log.Info().
@ -33,7 +33,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context,
return nil, err 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 " + log.Error().Str("requestID", requestID).Err(err).Msg("GRPC GeoAutocomplete " +
"protocol buffer conversion error") "protocol buffer conversion error")
return nil, err return nil, err
@ -41,7 +41,7 @@ func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context,
resp = &grpcproto.GeoAutocompleteResponse{ resp = &grpcproto.GeoAutocompleteResponse{
FeatureCollection: &grpcproto.GeoAutocompleteResponse_FeatureCollectionRaw{ FeatureCollection: &grpcproto.GeoAutocompleteResponse_FeatureCollectionRaw{
FeatureCollectionRaw: string(rawfc), FeatureCollectionRaw: string(rawFc),
}, },
} }

View File

@ -2,19 +2,20 @@ package grpcserver
import ( import (
"context" "context"
"fmt" "net"
"git.coopgo.io/coopgo-apps/silvermobi/handler" "git.coopgo.io/coopgo-apps/silvermobi/handler"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto" grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth" grpcauth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags" grpcctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/spf13/viper" "github.com/spf13/viper"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"net"
) )
type contextKey string type contextKey string
@ -42,37 +43,51 @@ func NoAuth(method string) bool {
return false 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) { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
var (
newCtx context.Context
err error
)
print(info.FullMethod) print(info.FullMethod)
if NoAuth(info.FullMethod) { if NoAuth(info.FullMethod) {
return handler(ctx, req) return handler(ctx, req)
} }
var newCtx context.Context
var err error if newCtx, err = authFunc(ctx); err != nil {
newCtx, err = authFunc(ctx)
if err != nil {
return nil, err return nil, err
} }
return handler(newCtx, req) return handler(newCtx, req)
} }
} }
func StreamAuthServerInterceptor(authFunc grpc_auth.AuthFunc) grpc.StreamServerInterceptor { func StreamAuthServerInterceptor(authFunc grpcauth.AuthFunc) grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo,
handler grpc.StreamHandler) error {
var (
newCtx context.Context
err error
)
if NoAuth(info.FullMethod) { if NoAuth(info.FullMethod) {
wrapped := grpc_middleware.WrapServerStream(stream) wrapped := grpcmiddleware.WrapServerStream(stream)
wrapped.WrappedContext = stream.Context() wrapped.WrappedContext = stream.Context()
return handler(srv, wrapped) return handler(srv, wrapped)
} }
var newCtx context.Context
var err error if newCtx, err = authFunc(stream.Context()); err != nil {
newCtx, err = authFunc(stream.Context())
if err != nil {
return err return err
} }
wrapped := grpc_middleware.WrapServerStream(stream)
wrapped := grpcmiddleware.WrapServerStream(stream)
wrapped.WrappedContext = newCtx wrapped.WrappedContext = newCtx
return handler(srv, wrapped) return handler(srv, wrapped)
} }
} }
@ -87,17 +102,19 @@ type SolidarityService struct {
Config *viper.Viper Config *viper.Viper
Handler *handler.SilverMobiHandler Handler *handler.SilverMobiHandler
SolidarityClient grpcproto.SolidarityServiceClient SolidarityClient grpcproto.SolidarityServiceClient
grpcproto.UnimplementedSolidarityServiceServer // Add this client grpcproto.UnimplementedSolidarityServiceServer
} }
func NewSolidarityService(cfg *viper.Viper, handler *handler.SilverMobiHandler) SolidarityService { func NewSolidarityService(cfg *viper.Viper, handler *handler.SilverMobiHandler) SolidarityService {
solidarityServiceAddress := cfg.GetString("solidarity_service.address") 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 { if err != nil {
log.Fatal().Err(err) log.Fatal().Err(err)
} }
solidarityClient := grpcproto.NewSolidarityServiceClient(conn) solidarityClient := grpcproto.NewSolidarityServiceClient(conn)
return SolidarityService{ return SolidarityService{
Config: cfg, Config: cfg,
Handler: handler, Handler: handler,
@ -115,53 +132,60 @@ func NewSilvermobiGRPCService(cfg *viper.Viper, handler *handler.SilverMobiHandl
func Run(done chan error, cfg *viper.Viper, handler *handler.SilverMobiHandler) { func Run(done chan error, cfg *viper.Viper, handler *handler.SilverMobiHandler) {
var ( var (
address = cfg.GetString("services.external.grpc.ip") + ":" + cfg.GetString("services.external.grpc.port") address = cfg.GetString("services.external.grpc.ip") + ":" + cfg.GetString("services.external.grpc.port")
jwt_secret = cfg.GetString("identification.local.jwt_secret") jwtSecret = cfg.GetString("identification.local.jwt_secret")
) )
log.Info().Msg("GRPC server on " + address) log.Info().Msg("GRPC server on " + address)
server := grpc.NewServer( server := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( grpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(
grpc_ctxtags.StreamServerInterceptor(), grpcctxtags.StreamServerInterceptor(),
StreamAuthServerInterceptor(GRPCAuthFunc(jwt_secret)), StreamAuthServerInterceptor(GRPCAuthFunc(jwtSecret)),
)), )),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( grpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(
grpc_ctxtags.UnaryServerInterceptor(), grpcctxtags.UnaryServerInterceptor(),
UnaryAuthServerInterceptor(GRPCAuthFunc(jwt_secret)), UnaryAuthServerInterceptor(GRPCAuthFunc(jwtSecret)),
)), )),
) )
solidarity_service := NewSolidarityService(cfg, handler) solidarityService := NewSolidarityService(cfg, handler)
silvermobi_service := NewSilvermobiGRPCService(cfg, handler) silvermobiService := NewSilvermobiGRPCService(cfg, handler)
grpcproto.RegisterSilvermobiGRPCServer(server, silvermobi_service) grpcproto.RegisterSilvermobiGRPCServer(server, silvermobiService)
grpcproto.RegisterSolidarityServiceServer(server, &solidarity_service) grpcproto.RegisterSolidarityServiceServer(server, &solidarityService)
l, err := net.Listen("tcp", address) l, err := net.Listen("tcp", address)
if err != nil { if err != nil {
log.Fatal().Err(err) 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") log.Error().Err(err).Msg("gRPC service ended")
done <- err done <- err
} }
} }
func GRPCAuthFunc(jwtKey string) grpc_auth.AuthFunc { func GRPCAuthFunc(jwtKey string) grpcauth.AuthFunc {
return func(ctx context.Context) (context.Context, error) { 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 { if err != nil {
return nil, err return nil, err
} }
claims := jwt.MapClaims{} 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 return []byte(jwtKey), nil
}) })
if err != nil || !token.Valid { if err != nil || !token.Valid {
fmt.Println(err)
return nil, status.Errorf(codes.Unauthenticated, "Invalid or expired token") return nil, status.Errorf(codes.Unauthenticated, "Invalid or expired token")
} }
ctx = context.WithValue(ctx, contextKeyUser, claims["sub"].(string)) ctx = context.WithValue(ctx, contextKeyUser, claims["sub"].(string))
return ctx, nil return ctx, nil
} }
} }

View File

@ -7,6 +7,7 @@ import (
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi" mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage" ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/structpb"
) )
@ -15,7 +16,8 @@ type MobilityAccountService struct {
} }
func NewMobilityAccountService(mobilityAccountsDial string) (MobilityAccountService, error) { 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) client := mobilityaccounts.NewMobilityAccountsClient(mobilityAccountsConn)
if err != nil { if err != nil {

View File

@ -6,6 +6,7 @@ import (
"github.com/appleboy/gorush/rpc/proto" "github.com/appleboy/gorush/rpc/proto"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/structpb"
) )
@ -36,7 +37,8 @@ type PushService struct {
} }
func NewPushService(address string) (*PushService, error) { 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 { if err != nil {
return nil, err return nil, err
@ -48,6 +50,12 @@ func NewPushService(address string) (*PushService, error) {
} }
func (s *PushService) Send(notification Notification) error { func (s *PushService) Send(notification Notification) error {
var (
resp *proto.NotificationReply
err error
)
log.Debug(). log.Debug().
Int32("Platform", notification.Platform). Int32("Platform", notification.Platform).
Strs("recipients", notification.Recipients). Strs("recipients", notification.Recipients).
@ -55,7 +63,7 @@ func (s *PushService) Send(notification Notification) error {
Str("notification_title", notification.Title). Str("notification_title", notification.Title).
Msg("Send notification") 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, Data: notification.Data,
ID: notification.ID, ID: notification.ID,
Platform: notification.Platform, Platform: notification.Platform,

View File

@ -2,7 +2,7 @@ package services
import ( import (
"git.coopgo.io/coopgo-platform/geocode" "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/rs/zerolog/log"
"github.com/spf13/viper" "github.com/spf13/viper"
) )