@@ -2,6 +2,7 @@ package sql
22
33import (
44 "context"
5+ "errors"
56 "time"
67
78 "github.com/authorizerdev/authorizer/server/db/models"
@@ -14,13 +15,19 @@ func (p *provider) UpsertOTP(ctx context.Context, otp *models.OTP) (*models.OTP,
1415 if otp .ID == "" {
1516 otp .ID = uuid .New ().String ()
1617 }
17-
18+ // check if email or phone number is present
19+ if otp .Email == "" && otp .PhoneNumber == "" {
20+ return nil , errors .New ("email or phone_number is required" )
21+ }
22+ uniqueField := models .FieldNameEmail
23+ if otp .Email == "" && otp .PhoneNumber != "" {
24+ uniqueField = models .FieldNamePhoneNumber
25+ }
1826 otp .Key = otp .ID
1927 otp .CreatedAt = time .Now ().Unix ()
2028 otp .UpdatedAt = time .Now ().Unix ()
21-
2229 res := p .db .Clauses (clause.OnConflict {
23- Columns : []clause.Column {{Name : "email" }},
30+ Columns : []clause.Column {{Name : uniqueField }},
2431 DoUpdates : clause .AssignmentColumns ([]string {"otp" , "expires_at" , "updated_at" }),
2532 }).Create (& otp )
2633 if res .Error != nil {
@@ -33,14 +40,23 @@ func (p *provider) UpsertOTP(ctx context.Context, otp *models.OTP) (*models.OTP,
3340// GetOTPByEmail to get otp for a given email address
3441func (p * provider ) GetOTPByEmail (ctx context.Context , emailAddress string ) (* models.OTP , error ) {
3542 var otp models.OTP
36-
3743 result := p .db .Where ("email = ?" , emailAddress ).First (& otp )
3844 if result .Error != nil {
3945 return nil , result .Error
4046 }
4147 return & otp , nil
4248}
4349
50+ // GetOTPByPhoneNumber to get otp for a given phone number
51+ func (p * provider ) GetOTPByPhoneNumber (ctx context.Context , phoneNumber string ) (* models.OTP , error ) {
52+ var otp models.OTP
53+ result := p .db .Where ("phone_number = ?" , phoneNumber ).First (& otp )
54+ if result .Error != nil {
55+ return nil , result .Error
56+ }
57+ return & otp , nil
58+ }
59+
4460// DeleteOTP to delete otp
4561func (p * provider ) DeleteOTP (ctx context.Context , otp * models.OTP ) error {
4662 result := p .db .Delete (& models.OTP {
0 commit comments