feat: kavenegar sdk, otp generation and verifying
This commit is contained in:
+27
-1
@@ -7,6 +7,8 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type OTPRepository struct {
|
||||
@@ -27,7 +29,7 @@ func (r *OTPRepository) Create(ctx context.Context, phone string, otp *domain.OT
|
||||
return fmt.Errorf("failed to marshal otp: %w", err)
|
||||
}
|
||||
|
||||
ttl := time.Until(otp.ExpiredAt)
|
||||
ttl := time.Until(otp.ExpiresAt)
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("OTP expired already")
|
||||
}
|
||||
@@ -48,6 +50,30 @@ func (r *OTPRepository) Delete(ctx context.Context, phone string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *OTPRepository) Get(ctx context.Context, phone string) (*domain.OTP, error) {
|
||||
key := r.getOTPKey(phone)
|
||||
|
||||
result, err := r.redis.Client().Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return nil, fmt.Errorf("otp code not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var otp domain.OTP
|
||||
if err := json.Unmarshal([]byte(result), &otp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if otp.IsExpired() {
|
||||
r.Delete(ctx, phone)
|
||||
return nil, fmt.Errorf("otp is expired")
|
||||
}
|
||||
return &otp, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *OTPRepository) getOTPKey(phone string) string {
|
||||
return fmt.Sprintf("challenge:%s", phone)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user