87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package v1
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"git.badhouseplants.net/softplayer/softplayer-backend/internal/controllers"
|
|
"git.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/email"
|
|
proto_email "git.badhouseplants.net/softplayer/softplayer-go-proto/pkg/email"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/metadata"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
ctrl "sigs.k8s.io/controller-runtime"
|
|
)
|
|
|
|
type EmailServer struct {
|
|
proto_email.UnimplementedEmailValidationServer
|
|
emailConfig email.EmailConf
|
|
controller ctrl.Manager
|
|
// When dev mode is enabled, email won't be sent, instead the code will be returned in metadata
|
|
devMode bool
|
|
}
|
|
|
|
func InitEmailServer(controller ctrl.Manager, emailConfig *email.EmailConf, devMode bool) *EmailServer {
|
|
return &EmailServer{
|
|
controller: controller,
|
|
emailConfig: *emailConfig,
|
|
devMode: devMode,
|
|
}
|
|
}
|
|
|
|
// Send the validation code to email
|
|
func (c *EmailServer) SendRequest(ctx context.Context, in *proto_email.RequestValidation) (*emptypb.Empty, error) {
|
|
// Validation
|
|
if len(in.GetUserId()) == 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "user id must not be empty")
|
|
}
|
|
|
|
// Body
|
|
emailSvc := controllers.EmailSvc{
|
|
Data: controllers.EmailData{
|
|
UserID: in.GetUserId(),
|
|
},
|
|
EmailConfig: c.emailConfig,
|
|
Controller: c.controller,
|
|
DevMode: c.devMode,
|
|
}
|
|
err := emailSvc.SendVerification(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if c.devMode {
|
|
header := metadata.Pairs("code", emailSvc.Data.Code)
|
|
if err := grpc.SendHeader(ctx, header); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return &emptypb.Empty{}, nil
|
|
}
|
|
|
|
func (c *EmailServer) ValidateEmail(ctx context.Context, in *proto_email.ConfirmValidation) (*emptypb.Empty, error) {
|
|
// Validation
|
|
if len(in.GetUserId()) == 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "user id must not be empty")
|
|
}
|
|
if in.GetCode() == 0 {
|
|
return nil, status.Error(codes.InvalidArgument, "code must not be empty")
|
|
}
|
|
|
|
// Body
|
|
emailSvc := controllers.EmailSvc{
|
|
Data: controllers.EmailData{
|
|
UserID: in.GetUserId(),
|
|
Code: fmt.Sprintf("%d", in.GetCode()),
|
|
},
|
|
EmailConfig: c.emailConfig,
|
|
Controller: c.controller,
|
|
}
|
|
err := emailSvc.ConfirmVerification(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &emptypb.Empty{}, nil
|
|
}
|