Skip to content

Commit

Permalink
normal update
Browse files Browse the repository at this point in the history
  • Loading branch information
Kannan112 committed Dec 19, 2023
1 parent 2328a13 commit a98e373
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 35 deletions.
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": []
}
118 changes: 89 additions & 29 deletions pkg/api/handler/google-auth.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package handler

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"

"github.com/gin-gonic/gin"
"github.com/kannan112/go-gin-clean-arch/pkg/common/req"
"github.com/kannan112/go-gin-clean-arch/pkg/common/res"
"github.com/kannan112/go-gin-clean-arch/pkg/config"
"github.com/kannan112/go-gin-clean-arch/pkg/domain"
services "github.com/kannan112/go-gin-clean-arch/pkg/usecase/interface"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/google"
"golang.org/x/oauth2"
)

type AuthHandler struct {
Expand All @@ -20,60 +23,117 @@ type AuthHandler struct {
Config config.Config
}

func NewAuthHandler(userAuthUsecase services.UserUseCase, adminAuthUsecase services.AdminUsecase, config config.Config) *AuthHandler {
func NewAuthHandler(userAuthUsecase services.UserUseCase, adminAuthUsecase services.AdminUsecase, config config.Config, AuthUseCase services.AuthUserCase) *AuthHandler {
return &AuthHandler{
UserAuthUsecase: userAuthUsecase,
AdminAuthUsecase: adminAuthUsecase,
Config: config,
AuthUseCase: AuthUseCase,
}
}

func (c *AuthHandler) UseGoogleAuthLoginPage(ctx *gin.Context) {
ctx.HTML(200, "googleauth.html", nil)
func SetUpConfig(c *AuthHandler) *oauth2.Config {
conf := &oauth2.Config{
ClientID: c.Config.GoauthClientID,
ClientSecret: c.Config.GoauthClientSRC,
RedirectURL: c.Config.Redirect_URL,
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
},
Endpoint: google.Endpoint,
}
return conf
}

func (c *AuthHandler) UserGoogleAuthInitialize(ctx *gin.Context) {
goauthclientID := c.Config.GoauthClientID
goauthClientSrc := c.Config.GoauthClientSRC
callbackUrl := c.Config.Redirect_URL
goth.UseProviders(
google.New(goauthclientID, goauthClientSrc, callbackUrl, "email", "profile"),
)

// start google login
gothic.BeginAuthHandler(ctx.Writer, ctx.Request)
func (auth *AuthHandler) GoogleLogin(ctx *gin.Context) {
googleConfig := SetUpConfig(auth) // &c.Config
url := googleConfig.AuthCodeURL("randomstate")
ctx.Redirect(http.StatusSeeOther, url)
}

func (c *AuthHandler) UserGoogoleAuthCallBack(ctx *gin.Context) {
googleuser, err := gothic.CompleteUserAuth(ctx.Writer, ctx.Request)
func (c *AuthHandler) GoogleAuthCallback(ctx *gin.Context) {
state := ctx.Query("state")
if state != "randomstate" {
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusNonAuthoritativeInfo,
Message: "some internal server error occured",
Data: nil,
Errors: "failed to match with state",
})
return
}
code := ctx.Query("code")
googleConfig := SetUpConfig(c)
token, err := googleConfig.Exchange(ctx, code)
if err != nil {
ctx.JSON(http.StatusInternalServerError, res.Response{
StatusCode: http.StatusInternalServerError,
Message: "failed to get user details",
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusNonAuthoritativeInfo,
Message: "Error exchanging code for token",
Data: nil,
Errors: err,
Errors: err.Error(),
})
return
}
data := domain.Users{
Name: googleuser.Name,
Email: googleuser.Email,
Images: googleuser.AvatarURL,

resp, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)

if err != nil {
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusNonAuthoritativeInfo,
Message: "Error getting user info from Google:",
Data: nil,
Errors: err.Error(),
})
return
}

accessToken, refreshToken, err := c.AuthUseCase.GoogleLoginUser(ctx, data)
tokens := map[string]string{
"accessToken": accessToken,
"refreshToken": refreshToken,
authData, err := ioutil.ReadAll(resp.Body)
if err != nil {
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusNonAuthoritativeInfo,
Message: "failed to read:",
Data: nil,
Errors: err.Error(),
})
return
}

var userInfo domain.GoAuthUserInfo
err = json.Unmarshal(authData, &userInfo)
if err != nil {
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusNonAuthoritativeInfo,
Message: "failed to write:",
Data: nil,
Errors: err.Error(),
})
return
}
fmt.Printf("ID: %s\nEmail: %s\nName: %s\n", userInfo.ID, userInfo.Email, userInfo.Name)

data := req.GoogleAuth{
Name: userInfo.Name,
Email: userInfo.Email,
}
fmt.Println("testingAneERror")
accessToken, refreshToken, err := c.AuthUseCase.GoogleLoginUser(ctx, data)
if err != nil {
ctx.JSON(http.StatusNonAuthoritativeInfo, res.Response{
StatusCode: http.StatusBadGateway,
Message: "some internal server error occured",
Data: nil,
Errors: err.Error(),
})
return
}
tokens := map[string]string{
"accessToken": accessToken,
"refreshToken": refreshToken,
}

fmt.Println("testingAne")

ctx.JSON(http.StatusOK, res.Response{
StatusCode: http.StatusOK,
Message: "successfully login",
Expand Down
6 changes: 4 additions & 2 deletions pkg/api/routers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import (
"github.com/kannan112/go-gin-clean-arch/pkg/api/middleware"
)

func SetupUserRoutes(engine *gin.Engine, userHandler *handler.UserHandler, cartHandler *handler.CartHandler, productHandler *handler.ProductHandler, orderHandler *handler.OrderHandler, wishlistHandler *handler.WishlistHandler, couponHandler *handler.CouponHandler, walletHandler *handler.WalletHandler, otpHandler *handler.OtpHandler, renew *handler.RenewHandler, auth *handler.AuthHandler) {
func SetupUserRoutes(engine *gin.Engine, userHandler *handler.UserHandler, cartHandler *handler.CartHandler, productHandler *handler.ProductHandler, orderHandler *handler.OrderHandler, wishlistHandler *handler.WishlistHandler, couponHandler *handler.CouponHandler, walletHandler *handler.WalletHandler, otpHandler *handler.OtpHandler, renew *handler.RenewHandler, authHandler *handler.AuthHandler) {

engine.POST("/renew", renew.GetAccessToken)
engine.GET("/googleauth", auth.UseGoogleAuthLoginPage)
auth := engine.Group("/auth")
auth.GET("/google/login", authHandler.GoogleLogin)
auth.GET("/google/callback", authHandler.GoogleAuthCallback)

user := engine.Group("/user")
{
Expand Down
3 changes: 2 additions & 1 deletion pkg/di/wire_gen.go

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

4 changes: 2 additions & 2 deletions pkg/domain/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ 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; not null"`
Mobile string `json:"mobile" binding:"required,eq=10" gorm:"unique"`
Images string `json:"images"`
Password string `json:"password" gorm:"not null"`
Password string `json:"password"`
IsBlocked bool `gorm:"default:false"`
CreatedAt time.Time
}
Expand Down
2 changes: 1 addition & 1 deletion tmp/build-errors.log

Large diffs are not rendered by default.

0 comments on commit a98e373

Please sign in to comment.