feat(loyalty): customer PIN
Adds the 6-digit customer PIN that approves every action moving EnakPoint or EnakCoin on the customer's request (docs/prd-point-coin.md K8, F11, Q16, Q17, PC-301). Migration 000093 adds the PIN columns to customers and the customer_security_events table. PIN data is read and written only through CustomerPinRepository, never the Customer entity, so the hash cannot reach a customer response. Only a bcrypt hash is stored. - /customer/pin: status, OTP (pin_setup, pin_reset), create, change, reset. The OTP must be for that purpose and sent to the customer's own number; the existing OTP validation checks neither. A new PIN is checked (6 digits, confirmed, not one digit, not a run up or down, not the birth date as DDMMYY or YYMMDD) before the OTP is spent. - Five wrong attempts in a row lock the PIN for 30 minutes; the counter is incremented in one statement so attempts at the same time all count, and a lock that ran out starts a new series. A locked PIN is refused even when right. The customer is told by WhatsApp, as there is no push channel to customers yet; only the attempt that reached the limit alerts. - A reset through OTP lifts the lock and holds outgoing transfers for 24 hours; paying and exchanging still work, and a held transfer costs no attempt. - VerifyPin(ctx, customer, pin, action) for the flows that follow, with PIN_NOT_SET, PIN_INVALID (attempts left), PIN_LOCKED and TRANSFER_BLOCKED (until when), which PinErrorResponse turns into distinct codes and statuses. - DELETE /marketing/customers/:id/pin (loyalty managers, reason required) and GET /marketing/customers/:id/security-events, scoped to the organization. Every PIN event is in the security log with IP and user agent. No message or binding error contains a PIN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fc97c78300
commit
8370851ed2
@@ -0,0 +1,128 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"apskel-pos-be/internal/appcontext"
|
||||
"apskel-pos-be/internal/constants"
|
||||
"apskel-pos-be/internal/contract"
|
||||
"apskel-pos-be/internal/models"
|
||||
"apskel-pos-be/internal/processor"
|
||||
"apskel-pos-be/internal/repository"
|
||||
)
|
||||
|
||||
// CustomerPinService serves the customer's PIN (docs/prd-point-coin.md F11) and the
|
||||
// dashboard's view of it.
|
||||
type CustomerPinService interface {
|
||||
Status(ctx context.Context, customerID uuid.UUID) *contract.Response
|
||||
RequestOtp(ctx context.Context, customerID uuid.UUID, req *contract.RequestPinOtpRequest) *contract.Response
|
||||
CreatePin(ctx context.Context, customerID uuid.UUID, req *contract.CreateCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response
|
||||
ChangePin(ctx context.Context, customerID uuid.UUID, req *contract.ChangeCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response
|
||||
ResetPin(ctx context.Context, customerID uuid.UUID, req *contract.ResetCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response
|
||||
|
||||
RemovePin(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.RemoveCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response
|
||||
ListSecurityEvents(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, page, limit int) *contract.Response
|
||||
}
|
||||
|
||||
type CustomerPinServiceImpl struct {
|
||||
pins *processor.CustomerPinProcessor
|
||||
}
|
||||
|
||||
func NewCustomerPinService(pins *processor.CustomerPinProcessor) *CustomerPinServiceImpl {
|
||||
return &CustomerPinServiceImpl{pins: pins}
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) Status(ctx context.Context, customerID uuid.UUID) *contract.Response {
|
||||
status, err := s.pins.Status(ctx, customerID)
|
||||
if err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return contract.BuildSuccessResponse(status)
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) RequestOtp(ctx context.Context, customerID uuid.UUID, req *contract.RequestPinOtpRequest) *contract.Response {
|
||||
otp, err := s.pins.RequestOtp(ctx, customerID, req.Purpose)
|
||||
if err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return contract.BuildSuccessResponse(otp)
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) CreatePin(ctx context.Context, customerID uuid.UUID, req *contract.CreateCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response {
|
||||
if err := s.pins.CreatePin(ctx, customerID, req.OtpToken, req.OtpCode, req.Pin, req.ConfirmPin, info); err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return s.Status(ctx, customerID)
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) ChangePin(ctx context.Context, customerID uuid.UUID, req *contract.ChangeCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response {
|
||||
if err := s.pins.ChangePin(ctx, customerID, req.OldPin, req.Pin, req.ConfirmPin, info); err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return s.Status(ctx, customerID)
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) ResetPin(ctx context.Context, customerID uuid.UUID, req *contract.ResetCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response {
|
||||
if err := s.pins.ResetPin(ctx, customerID, req.OtpToken, req.OtpCode, req.Pin, req.ConfirmPin, info); err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return s.Status(ctx, customerID)
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) RemovePin(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, req *contract.RemoveCustomerPinRequest, info models.CustomerPinRequestInfo) *contract.Response {
|
||||
if err := s.pins.RemovePinByAdmin(ctx, apctx.OrganizationID, customerID, apctx.UserID, req.Reason, info); err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return contract.BuildSuccessResponse(map[string]interface{}{"message": "PIN removed; the customer has to create a new one"})
|
||||
}
|
||||
|
||||
func (s *CustomerPinServiceImpl) ListSecurityEvents(ctx context.Context, apctx *appcontext.ContextInfo, customerID uuid.UUID, page, limit int) *contract.Response {
|
||||
events, err := s.pins.ListEvents(ctx, apctx.OrganizationID, customerID, page, limit)
|
||||
if err != nil {
|
||||
return PinErrorResponse(err)
|
||||
}
|
||||
return contract.BuildSuccessResponse(events)
|
||||
}
|
||||
|
||||
// PinErrorResponse turns an error from a PIN-guarded action into a response the apps
|
||||
// can act on. A *processor.PinError keeps its code (PIN_NOT_SET, PIN_INVALID,
|
||||
// PIN_LOCKED, TRANSFER_BLOCKED) and puts the attempts left or the time it lifts in the
|
||||
// response data. Other errors map to a validation or server error.
|
||||
func PinErrorResponse(err error) *contract.Response {
|
||||
var pinErr *processor.PinError
|
||||
if errors.As(err, &pinErr) {
|
||||
data := map[string]interface{}{"code": pinErr.Code}
|
||||
switch pinErr.Code {
|
||||
case processor.PinErrInvalid:
|
||||
data["remaining_attempts"] = pinErr.RemainingAttempts
|
||||
case processor.PinErrLocked:
|
||||
data["locked_until"] = pinErr.Until
|
||||
case processor.PinErrTransferBlocked:
|
||||
data["transfer_blocked_until"] = pinErr.Until
|
||||
}
|
||||
return &contract.Response{
|
||||
Success: false,
|
||||
Data: data,
|
||||
Errors: []*contract.ResponseError{contract.NewResponseError(pinErr.Code, constants.CustomerPinServiceEntity, pinErr.Error())},
|
||||
}
|
||||
}
|
||||
|
||||
code := constants.InternalServerErrorCode
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrPinCustomerNotFound):
|
||||
code = constants.NotFoundErrorCode
|
||||
case errors.Is(err, processor.ErrPinOtpTooSoon):
|
||||
code = constants.TooManyRequestsErrorCode
|
||||
case errors.Is(err, processor.ErrInvalidPinInput),
|
||||
errors.Is(err, processor.ErrPinAlreadySet),
|
||||
errors.Is(err, processor.ErrPinOtpInvalid),
|
||||
errors.Is(err, processor.ErrPinNoPhone):
|
||||
code = constants.ValidationErrorCode
|
||||
}
|
||||
return contract.BuildErrorResponse([]*contract.ResponseError{
|
||||
contract.NewResponseError(code, constants.CustomerPinServiceEntity, err.Error()),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"apskel-pos-be/internal/processor"
|
||||
"apskel-pos-be/internal/repository"
|
||||
"apskel-pos-be/internal/util"
|
||||
)
|
||||
|
||||
func TestPinErrorResponse(t *testing.T) {
|
||||
until := time.Date(2026, 9, 30, 12, 30, 0, 0, time.UTC)
|
||||
for name, c := range map[string]struct {
|
||||
err error
|
||||
code string
|
||||
status int
|
||||
data map[string]interface{}
|
||||
}{
|
||||
"not set": {&processor.PinError{Code: processor.PinErrNotSet}, "PIN_NOT_SET", http.StatusForbidden, map[string]interface{}{"code": "PIN_NOT_SET"}},
|
||||
"invalid": {fmt.Errorf("pay: %w", &processor.PinError{Code: processor.PinErrInvalid, RemainingAttempts: 2}), "PIN_INVALID", http.StatusBadRequest, map[string]interface{}{"code": "PIN_INVALID", "remaining_attempts": 2}},
|
||||
"locked": {&processor.PinError{Code: processor.PinErrLocked, Until: &until}, "PIN_LOCKED", http.StatusLocked, map[string]interface{}{"code": "PIN_LOCKED", "locked_until": &until}},
|
||||
"transfer": {&processor.PinError{Code: processor.PinErrTransferBlocked, Until: &until}, "TRANSFER_BLOCKED", http.StatusForbidden, map[string]interface{}{"code": "TRANSFER_BLOCKED", "transfer_blocked_until": &until}},
|
||||
} {
|
||||
resp := PinErrorResponse(c.err)
|
||||
assert.False(t, resp.Success, name)
|
||||
assert.Equal(t, c.code, resp.Errors[0].Code, name)
|
||||
assert.Equal(t, c.status, util.MapErrorCodeToHttpStatus(resp.Errors[0].Code), name)
|
||||
assert.Equal(t, c.data, resp.Data, name)
|
||||
}
|
||||
|
||||
for name, c := range map[string]struct {
|
||||
err error
|
||||
status int
|
||||
}{
|
||||
"weak PIN": {fmt.Errorf("%w: too easy", processor.ErrInvalidPinInput), http.StatusBadRequest},
|
||||
"bad OTP": {processor.ErrPinOtpInvalid, http.StatusBadRequest},
|
||||
"already set": {processor.ErrPinAlreadySet, http.StatusBadRequest},
|
||||
"too soon": {processor.ErrPinOtpTooSoon, http.StatusTooManyRequests},
|
||||
"no customer": {repository.ErrPinCustomerNotFound, http.StatusNotFound},
|
||||
"anything else": {fmt.Errorf("db down"), http.StatusInternalServerError},
|
||||
} {
|
||||
resp := PinErrorResponse(c.err)
|
||||
assert.Equal(t, c.status, util.MapErrorCodeToHttpStatus(resp.Errors[0].Code), name)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user