refactoring

This commit is contained in:
2023-12-08 07:35:04 +01:00
parent 4a6326a5ab
commit f1d60881e5
32 changed files with 5949 additions and 434 deletions

View File

@@ -0,0 +1,35 @@
package grpcserver
import (
"context"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"strings"
)
func (s SilvermobiGRPCService) GetAccountInfo(ctx context.Context, req *grpcproto.AccountInfoRequest) (res *grpcproto.AccountInfoResponse, err error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Errorf(codes.Unauthenticated, "Missing metadata")
}
authHeader, ok := md["authorization"]
if !ok || len(authHeader) == 0 {
return nil, status.Errorf(codes.Unauthenticated, "Missing authorization header")
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
account, err := s.Handler.GetAccountInfos(context.Background(), id)
log.Info().
Str("ID", account.ID).
Msg("GetAccountInfo")
if err != nil {
return nil, err
}
return &grpcproto.AccountInfoResponse{
FirstName: account.FirstName,
LastName: account.LastName,
}, nil
}

View File

@@ -0,0 +1,46 @@
package grpcserver
import (
"context"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"strings"
)
func (s SilvermobiGRPCService) PutFirebaseToken(ctx context.Context, req *grpcproto.FirebaseTokenRequest) (resp *grpcproto.FirebaseTokenResponse, err error) {
if req.Token == "" || req.DevicePlatform == "" {
return &grpcproto.FirebaseTokenResponse{
Result: false,
}, nil
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return &grpcproto.FirebaseTokenResponse{
Result: false,
}, status.Errorf(codes.Unauthenticated, "Missing metadata")
}
authHeader, ok := md["authorization"]
if !ok || len(authHeader) == 0 {
return &grpcproto.FirebaseTokenResponse{
Result: false,
}, status.Errorf(codes.Unauthenticated, "Missing authorization header")
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("PutFirebaseToken")
err = s.Handler.PutFirebase(context.Background(), id, req.Token, req.DevicePlatform)
if err != nil {
return &grpcproto.FirebaseTokenResponse{
Result: false,
}, status.Errorf(codes.Unknown, "Database error")
}
return &grpcproto.FirebaseTokenResponse{
Result: true,
}, nil
}

View File

@@ -0,0 +1,99 @@
package grpcserver
import (
"context"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/google/uuid"
"github.com/paulmach/orb/geojson"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"io"
)
func (s SilvermobiGRPCService) GeoAutocomplete(ctx context.Context, in *grpcproto.GeoAutocompleteRequest) (resp *grpcproto.GeoAutocompleteResponse, err error) {
log.Info().
Str("text", in.Text).
Msg("GeoAutocompleteRequest")
requestid := uuid.NewString()
log.Debug().Str("requestid", requestid).Msg("GRPC GeoAutocomplete start")
if err == io.EOF {
log.Debug().Str("requestid", requestid).Msg("GRPC GeoAutocomplete EOF")
return nil, err
}
if err != nil {
log.Error().Str("requestid", requestid).Err(err).Msg("GRPC GeoAutocomplete other error")
return nil, err
}
results, err := s.Handler.GeoAutocomplete(in.Text, in.Lat, in.Lon)
if err != nil {
log.Error().Str("requestid", requestid).Err(err).Msg("GRPC GeoAutocomplete geocoding error")
return nil, err
}
rawfc, err := results.MarshalJSON()
if err != nil {
log.Error().Str("requestid", requestid).Err(err).Msg("GRPC GeoAutocomplete protocol buffer conversion error")
return nil, err
}
resp = &grpcproto.GeoAutocompleteResponse{
FeatureCollection: &grpcproto.GeoAutocompleteResponse_FeatureCollectionRaw{
FeatureCollectionRaw: string(rawfc),
},
}
return resp, nil
}
func (s SilvermobiGRPCService) GeoRoute(ctx context.Context, req *grpcproto.GeoRouteRequest) (*grpcproto.GeoRouteResponse, error) {
locations_raw, ok := req.Locations.(*grpcproto.GeoRouteRequest_LocationsRaw)
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "could not read departure")
}
locations, err := geojson.UnmarshalFeatureCollection([]byte(locations_raw.LocationsRaw))
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
route, err := s.Handler.GeoRoute(*locations)
if err != nil {
return nil, err
}
return &grpcproto.GeoRouteResponse{
Polyline: route.Polyline.String(),
}, nil
}
func (s SilvermobiGRPCService) GeoRouteWithReturn(ctx context.Context, req *grpcproto.GeoRouteWithReturnRequest) (*grpcproto.GeoRouteWithReturnResponse, error) {
locations_raw, ok := req.Locations.(*grpcproto.GeoRouteWithReturnRequest_LocationsRaw)
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "could not read departure")
}
locations, err := geojson.UnmarshalFeatureCollection([]byte(locations_raw.LocationsRaw))
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
route, err := s.Handler.GeoRoute(*locations)
if err != nil {
return nil, err
}
return_route, err := s.Handler.GeoReturnRoute(*locations)
if err != nil {
return nil, err
}
return &grpcproto.GeoRouteWithReturnResponse{
Polyline: route.Polyline.String(),
ReturnPolyline: return_route.Polyline.String(),
}, nil
}

View File

@@ -4,7 +4,9 @@ import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
@@ -24,6 +26,9 @@ func (s SilvermobiGRPCService) SetPhoneNumber(ctx context.Context, req *grpcprot
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("SetPhoneNumber")
if err = s.Handler.UpdatePhoneNumber(
context.Background(),
id,
@@ -40,13 +45,15 @@ func (s SilvermobiGRPCService) VerifyPhoneNumber(ctx context.Context, req *grpcp
if !ok {
return nil, status.Errorf(codes.Unauthenticated, "Missing metadata")
}
authHeader, ok := md["authorization"]
if !ok || len(authHeader) == 0 {
return nil, status.Errorf(codes.Unauthenticated, "Missing authorization header")
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("VerifyPhoneNumber")
if err = s.Handler.VerifyPhoneNumber(
context.Background(),
id,
@@ -71,6 +78,9 @@ func (s SilvermobiGRPCService) SetBirthDate(ctx context.Context, req *grpcproto.
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("SetBirthDate")
birthdate := time.Unix(req.Birthdate.Seconds, int64(req.Birthdate.Nanos)).UTC()
birthdateString := birthdate.Format("2006-01-02T15:04:05Z")
if err = s.Handler.UpdateBirthDate(ctx, id, birthdateString); err != nil {
@@ -93,6 +103,9 @@ func (s SilvermobiGRPCService) SetAccountType(ctx context.Context, req *grpcprot
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("SetAccountType")
if req.GetType() != grpcproto.AccountTypeRequest_PASSENGER && req.GetType() != grpcproto.AccountTypeRequest_DRIVER {
return nil, status.Errorf(codes.InvalidArgument, "Type should be PASSENGER or DRIVER")
}
@@ -116,6 +129,9 @@ func (s SilvermobiGRPCService) GetAccountType(ctx context.Context, req *grpcprot
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
log.Info().
Str("User ID", id).
Msg("GetAccountType")
if req.Request == nil || !*req.Request {
return nil, status.Errorf(codes.InvalidArgument, "request arg should be true")
}
@@ -146,13 +162,13 @@ func (s SilvermobiGRPCService) GetValidation(ctx context.Context, req *grpcproto
if !ok {
return nil, status.Errorf(codes.Unauthenticated, "Missing metadata")
}
authHeader, ok := md["authorization"]
if !ok || len(authHeader) == 0 {
return nil, status.Errorf(codes.Unauthenticated, "Missing authorization header")
}
tokenString := strings.TrimPrefix(authHeader[0], "Bearer ")
id := ExtractIdFromToken(tokenString)
fmt.Println(id)
phone_validation, birth_validation, type_validation, err := s.Handler.CheckValidation(ctx, id)
if err != nil {
return nil, err

View File

@@ -2,6 +2,7 @@ package grpcserver
import (
"context"
"fmt"
"git.coopgo.io/coopgo-apps/silvermobi/handler"
grpcproto "git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/golang-jwt/jwt/v4"
@@ -28,6 +29,9 @@ func NoAuth(method string) bool {
"/SilvermobiGRPC/UpdatePassword",
"/SilvermobiGRPC/AuthRegister",
"/SilvermobiGRPC/AuthLogin",
"/SilvermobiGRPC/GeoAutocomplete",
"/SilvermobiGRPC/GeoRouteWithReturn",
"/SilvermobiGRPC/GeoRoute",
}
for _, m := range noAuthMethods {
@@ -53,6 +57,7 @@ func UnaryAuthServerInterceptor(authFunc grpc_auth.AuthFunc) grpc.UnaryServerInt
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 {
if NoAuth(info.FullMethod) {
@@ -78,6 +83,28 @@ type SilvermobiGRPCService struct {
grpcproto.UnimplementedSilvermobiGRPCServer
}
type SolidarityService struct {
Config *viper.Viper
Handler *handler.SilvermobiHandler
SolidarityClient grpcproto.SolidarityServiceClient
grpcproto.UnimplementedSolidarityServiceServer // Add this client
}
func NewSolidarityService(cfg *viper.Viper, handler *handler.SilvermobiHandler) SolidarityService {
solidarityServiceAddress := cfg.GetString("solidarity_service.address")
conn, err := grpc.Dial(solidarityServiceAddress, grpc.WithInsecure())
if err != nil {
log.Fatal().Err(err)
}
solidarityClient := grpcproto.NewSolidarityServiceClient(conn)
return SolidarityService{
Config: cfg,
Handler: handler,
SolidarityClient: solidarityClient,
}
}
func NewSilvermobiGRPCService(cfg *viper.Viper, handler *handler.SilvermobiHandler) SilvermobiGRPCService {
return SilvermobiGRPCService{
Config: cfg,
@@ -87,7 +114,7 @@ func NewSilvermobiGRPCService(cfg *viper.Viper, handler *handler.SilvermobiHandl
func Run(done chan error, cfg *viper.Viper, handler *handler.SilvermobiHandler) {
var (
address = "0.0.0.0:" + 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")
)
@@ -104,8 +131,11 @@ func Run(done chan error, cfg *viper.Viper, handler *handler.SilvermobiHandler)
)),
)
service := NewSilvermobiGRPCService(cfg, handler)
grpcproto.RegisterSilvermobiGRPCServer(server, service)
solidarity_service := NewSolidarityService(cfg, handler)
silvermobi_service := NewSilvermobiGRPCService(cfg, handler)
grpcproto.RegisterSilvermobiGRPCServer(server, silvermobi_service)
grpcproto.RegisterSolidarityServiceServer(server, &solidarity_service)
l, err := net.Listen("tcp", address)
if err != nil {
log.Fatal().Err(err)
@@ -128,6 +158,7 @@ func GRPCAuthFunc(jwtKey string) grpc_auth.AuthFunc {
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))

View File

@@ -0,0 +1,77 @@
package grpcserver
import (
"context"
"fmt"
"git.coopgo.io/coopgo-apps/silvermobi/servers/grpcapi/proto"
"github.com/rs/zerolog/log"
)
func (s *SolidarityService) SetDriverRegularAvailabilities(ctx context.Context, req *proto.DriverRegularAvailabilities) (resp *proto.DriverAvailabilitiesResponse, err error) {
log.Info().
Str("Driver ID", req.DriverRequest.Driver.Id).
Msg("SetDriverRegularAvailabilities")
resp, err = s.SolidarityClient.SetDriverRegularAvailabilities(ctx, req)
return resp, err
}
func (s *SolidarityService) SetDriverPunctualAvailabilities(ctx context.Context, req *proto.DriverPunctualAvailabilities) (resp *proto.DriverAvailabilitiesResponse, err error) {
log.Info().
Str("Driver ID", req.DriverRequest.Driver.Id).
Msg("SetDriverRegularAvailabilities")
resp, err = s.SolidarityClient.SetDriverPunctualAvailabilities(ctx, req)
return resp, err
}
func (s *SolidarityService) CreateBooking(ctx context.Context, req *proto.CreateBookingRequest) (resp *proto.CreateBookingResponse, err error) {
log.Info().
Str("Booking ID", req.Booking.Id).
Msg("CreateBooking")
resp, err = s.SolidarityClient.CreateBooking(ctx, req)
if err == nil {
_ = s.Handler.SendNotification(req.Booking.DriverId, "Silvermobi", "Vous avez reçu une demande de trajet. \n Pour plus de détails, veuillez consulter l'interface \"Mes Trajets\" dans l'application SilverMobi.")
err = s.Handler.SendEmail(req.Booking.DriverId, "Silvermobi", "Vous avez reçu une demande de trajet. \n Pour plus de détails, veuillez consulter l'interface \"Mes Trajets\" dans l'application SilverMobi.")
fmt.Println(err)
}
return resp, err
}
func (s *SolidarityService) UpdateBooking(ctx context.Context, req *proto.UpdateBookingRequest) (resp *proto.UpdateBookingResponse, err error) {
log.Info().
Str("Booking ID", req.BookingId).
Msg("UpdateBooking")
resp, err = s.SolidarityClient.UpdateBooking(ctx, req)
return resp, err
}
func (s *SolidarityService) GetBooking(ctx context.Context, req *proto.GetBookingRequest) (resp *proto.GetBookingResponse, err error) {
log.Info().
Str("Booking ID", req.BookingId).
Msg("GetBooking")
resp, err = s.SolidarityClient.GetBooking(ctx, req)
return resp, err
}
func (s *SolidarityService) GetBookingsByStatus(ctx context.Context, req *proto.GetBookingsByStatusRequest) (resp *proto.GetBookingsByStatusResponse, err error) {
log.Info().
Str("User ID", req.UserId).
Msg("GetBookingByStatus")
resp, err = s.SolidarityClient.GetBookingsByStatus(ctx, req)
return resp, err
}
func (s *SolidarityService) DriverJourneys(ctx context.Context, req *proto.DriverJourneysRequest) (resp *proto.DriverJourneysResponse, err error) {
log.Info().
Str("Address", req.Departure.Address).
Msg("DriverJourneys")
resp, err = s.SolidarityClient.DriverJourneys(ctx, req)
return resp, err
}
func (s *SolidarityService) SetPassengerTrip(ctx context.Context, req *proto.PassengerTripRequest) (resp *proto.PassengerTripResponse, err error) {
log.Info().
Str("Passenger ID", req.Passenger.Id).
Msg("SetPassengerTrip")
resp, err = s.SolidarityClient.SetPassengerTrip(ctx, req)
return resp, err
}