Skip to content

Commit

Permalink
Change otp login -> otp verification
Browse files Browse the repository at this point in the history
  • Loading branch information
Kannan112 committed Dec 19, 2023
1 parent a98e373 commit 2bc2358
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 93 deletions.
Binary file modified cmd/api/tmp/api.exe
Binary file not shown.
32 changes: 5 additions & 27 deletions pkg/api/handler/otp.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"net/http"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -40,14 +39,12 @@ func (cr *OtpHandler) SendOtp(c *gin.Context) {
var phno req.OTPData
err := c.Bind(&phno)
if err != nil {
fmt.Println("e1")
c.JSON(http.StatusBadRequest, res.Response{
StatusCode: 422,
Message: "unable to process the request",
Data: nil,
Errors: err.Error(),
})
fmt.Println("e2")
return
}

Expand All @@ -62,10 +59,7 @@ func (cr *OtpHandler) SendOtp(c *gin.Context) {
return
}

fmt.Println(isSignIn)

if !isSignIn {
fmt.Println("login err")
c.JSON(http.StatusBadRequest, res.Response{
StatusCode: 400,
Message: "no user found",
Expand All @@ -74,7 +68,6 @@ func (cr *OtpHandler) SendOtp(c *gin.Context) {
})
return
}
fmt.Println("otp send near", phno)
err = cr.otpUseCase.SendOtp(c.Request.Context(), phno)
if err != nil {
c.JSON(http.StatusBadRequest, res.Response{
Expand All @@ -89,7 +82,7 @@ func (cr *OtpHandler) SendOtp(c *gin.Context) {
c.JSON(http.StatusCreated, res.Response{
StatusCode: 201,
Message: "otp send",
Data: nil,
Data: phno.PhoneNumber,
Errors: nil,
})
}
Expand Down Expand Up @@ -119,7 +112,6 @@ func (cr *OtpHandler) ValidateOtp(c *gin.Context) {
return
}
err = cr.otpUseCase.VerifyOTP(c, otpDetails)

if err != nil {
c.JSON(http.StatusBadRequest, res.Response{
StatusCode: 400,
Expand All @@ -129,24 +121,10 @@ func (cr *OtpHandler) ValidateOtp(c *gin.Context) {
})
return
}
fmt.Println("test me verify")
ss, err := cr.userUseCase.OtpLogin(otpDetails.Phone)
if err != nil {
c.JSON(http.StatusBadRequest, res.Response{
StatusCode: 400,
Message: "failed to login",
Data: nil,
Errors: err.Error(),
})
return
}

c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("UserAuth", ss, 3600*24*30, "", "", false, true)
c.JSON(http.StatusOK, res.Response{
StatusCode: 200,
Message: "login successful",
Data: nil,
c.JSON(http.StatusCreated, res.Response{
StatusCode: 201,
Message: "user account verified",
Data: otpDetails.Phone,
Errors: nil,
})
}
2 changes: 1 addition & 1 deletion pkg/di/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions pkg/domain/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package domain
import "time"

type Users struct {
ID uint `gorm:"primaryKey;unique;not null"`
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email" gorm:"unique;not null"`
Mobile string `json:"mobile" binding:"required,eq=10" gorm:"unique"`
Images string `json:"images"`
Password string `json:"password"`
IsBlocked bool `gorm:"default:false"`
CreatedAt time.Time
ID uint `gorm:"primaryKey;unique;not null"`
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email" gorm:"unique;not null"`
Mobile string `json:"mobile" binding:"required,eq=10" gorm:"unique"`
Images string `json:"images"`
Verify bool `json:"verify" gorm:"default:false"`
Password string `json:"password"`
IsBlocked bool `gorm:"default:false"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP"`
}
type UsersData struct {
ID uint `gorm:"primaryKey;unique;not null"`
Expand Down
3 changes: 2 additions & 1 deletion pkg/repository/interface/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ type UserRepository interface {
UserLogin(ctx context.Context, email string) (domain.Users, error)
AuthSignUp(Oauth req.GoogleAuth) (res.UserResponse, error)
AuthLogin(email string) (bool, error)
CheckVerifyPhone(mobileNo string) (bool, error)
IsSignIn(phno string) (bool, error)
OtpLogin(phone string) (int, error)
FindAddress(ctx context.Context, userId int) (bool, error)
AddAddress(id int, address req.AddAddress) error
UpdateAddress(id int, addressId int, address req.AddAddress) error
ListAllAddress(id int) ([]domain.Addresss, error)
DeleteAddress(ctx context.Context, userId, AddressesId int) ([]domain.Addresss, error)
ViewProfile(id int) (res.UserData, error)
EditProfile(id int, profile req.UserReq) (res.UserData, error)
AccountVerify(phone string) error
}
29 changes: 29 additions & 0 deletions pkg/repository/mockrepo/mock_user.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 26 additions & 16 deletions pkg/repository/userRepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ func (c *userDatabase) UserLogin(ctx context.Context, email string) (domain.User
}
func (c *userDatabase) AuthSignUp(Oauth req.GoogleAuth) (res.UserResponse, error) {
var userData res.UserResponse
query := `INSERT INTO users (name, email)
VALUES ($1, $2)
query := `INSERT INTO users (name, email,verify)
VALUES ($1, $2, $3)
RETURNING id, name, email`
err := c.DB.Raw(query, Oauth.Name, Oauth.Email).Scan(&userData).Error
err := c.DB.Raw(query, Oauth.Name, Oauth.Email, true).Scan(&userData).Error

return userData, err
}
Expand All @@ -72,15 +72,10 @@ func (c *userDatabase) IsSignIn(phone string) (bool, error) {
query := "SELECT EXISTS(SELECT 1 FROM users WHERE mobile=?)"
var isSignIn bool
err := c.DB.Raw(query, phone).Scan(&isSignIn).Error
return isSignIn, err
}

// OtpLogin retrieves the user ID based on the provided phone number.
func (c *userDatabase) OtpLogin(phone string) (int, error) {
var id int
query := "SELECT id FROM users WHERE mobile=?"
err := c.DB.Raw(query, phone).Scan(&id).Error
return id, err
if err != nil {
return false, err
}
return isSignIn, nil
}

// AddAddress adds a new address for a user.
Expand Down Expand Up @@ -121,8 +116,6 @@ func (c *userDatabase) UpdateAddress(id int, addressID int, address req.AddAddre
return err
}
}

// Check if the address belongs to the user.
var check bool
addressExists := `
SELECT EXISTS(SELECT * FROM addresses WHERE users_id = $1 AND id = $2)
Expand Down Expand Up @@ -231,11 +224,28 @@ func (c *userDatabase) DeleteAddress(ctx context.Context, userID, addressID int)
func (c *userDatabase) FindAddress(ctx context.Context, userID int) (bool, error) {
var exists bool
checkAddress := `
SELECT EXISTS(SELECT * FROM addresses WHERE users_id = $1 AND is_default = true)
`
SELECT EXISTS(SELECT * FROM addresses WHERE users_id = $1 AND is_default = true)`
err := c.DB.Raw(checkAddress, userID).Scan(&exists).Error
if err != nil {
return false, err
}
return exists, nil
}

func (c *userDatabase) CheckVerifyPhone(mobileNo string) (bool, error) {
var verify bool
verifyAccountPhone := `SELECT EXISTS(select * from users where mobile=$1 and verify=$2)`
err := c.DB.Raw(verifyAccountPhone, mobileNo, true).Scan(&verify).Error
if err != nil {
return false, err
}
return verify, nil
}

func (c *userDatabase) AccountVerify(phone string) error {
query := `UPDATE users set verify=$1 WHERE mobile=$2`
if err := c.DB.Exec(query, true, phone).Error; err != nil {
return err
}
return nil
}
1 change: 0 additions & 1 deletion pkg/usecase/interface/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ type UserUseCase interface {
UserSignUp(ctx context.Context, user req.UserReq) (res.UserData, error)
UserLogin(ctx context.Context, user req.LoginReq) (string, error)
IsSignIn(phno string) (bool, error)
OtpLogin(phone string) (string, error)
FindAddress(ctx context.Context, userId int) (bool, error)
AddAddress(id int, body req.AddAddress) error
UpdateAddress(id int, addressId int, address req.AddAddress) error
Expand Down
44 changes: 25 additions & 19 deletions pkg/usecase/otpUsecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,66 +2,72 @@ package usecase

import (
"context"
"errors"
"fmt"

"github.com/kannan112/go-gin-clean-arch/pkg/common/req"
"github.com/kannan112/go-gin-clean-arch/pkg/config"
interfaces "github.com/kannan112/go-gin-clean-arch/pkg/repository/interface"
services "github.com/kannan112/go-gin-clean-arch/pkg/usecase/interface"
"github.com/twilio/twilio-go"
openapi "github.com/twilio/twilio-go/rest/verify/v2"
)

type OtpUseCase struct {
cfg config.Config
cfg config.Config
UserRepo interfaces.UserRepository
}

func NewOtpUseCase(cfg config.Config) services.OtpUseCase {
func NewOtpUseCase(cfg config.Config, UserRepo interfaces.UserRepository) services.OtpUseCase {
return &OtpUseCase{
cfg: cfg,
cfg: cfg,
UserRepo: UserRepo,
}
}

func (c *OtpUseCase) SendOtp(ctx context.Context, phno req.OTPData) error {
check, err := c.UserRepo.IsSignIn(phno.PhoneNumber)
if err != nil {
return errors.New(err.Error())
}
if !check {
return errors.New("failed to find your account")
}
client := twilio.NewRestClientWithParams(twilio.ClientParams{
Username: c.cfg.TWILIOACCOUNTSID,
Password: c.cfg.TWILIOAUTHTOKEN,
})
params := &openapi.CreateVerificationParams{}
params.SetTo(phno.PhoneNumber)
params.SetChannel("sms")
_, err := client.VerifyV2.CreateVerification(c.cfg.TWILIOSERVICESID, params)
return err
_, err = client.VerifyV2.CreateVerification(c.cfg.TWILIOSERVICESID, params)
if err != nil {
return err
}
return nil
}

// func (c *OtpUseCase) ValidateOtp(otpDetails req.VerifyOtp) (*openapi.VerifyV2VerificationCheck, error) {
// var client *twilio.RestClient = twilio.NewRestClientWithParams(twilio.ClientParams{
// Username: c.cfg.TWILIOACCOUNTSID,
// Password: c.cfg.TWILIOAUTHTOKEN,
// })
// params := &openapi.CreateVerificationCheckParams{}
// params.SetTo(otpDetails.User.PhoneNumber)
// params.SetCode(otpDetails.Code)
// resp, err := client.VerifyV2.CreateVerificationCheck(c.cfg.TWILIOSERVICESID, params)
// return resp, err
// }
func (c *OtpUseCase) VerifyOTP(ctx context.Context, userData req.Otpverifier) error {

client := twilio.NewRestClientWithParams(twilio.ClientParams{
Password: c.cfg.TWILIOAUTHTOKEN,
Username: c.cfg.TWILIOACCOUNTSID,
})
fmt.Println("phone", userData.Phone, "otp", userData.Pin)
params := &openapi.CreateVerificationCheckParams{}
params.SetTo(userData.Phone)
params.SetCode(userData.Pin)
resp, err := client.VerifyV2.CreateVerificationCheck(c.cfg.TWILIOSERVICESID, params)
if err != nil {
return fmt.Errorf(err.Error())
return errors.New("sorry, the otp has expired or is no longer valid. please generate a new otp to continue.")
} else if *resp.Status == "approved" {
fmt.Println("Correct!")
err := c.UserRepo.AccountVerify(userData.Phone)
if err != nil {
return err
}
return nil
} else {
return fmt.Errorf("incorrect")
}
return nil

}
Loading

0 comments on commit 2bc2358

Please sign in to comment.