Goth pkg 与 Go 中的 net/http

问题描述 投票:0回答:1

有人将

goth
pkg 与
go std lib
一起使用吗?我在获取用户时遇到问题。我正在尝试获取用户详细信息,但收到此错误 您必须选择一个提供商 谁能告诉我这里出了什么问题吗?

谢谢你
我正在使用这个pkg

哥特包

这是我点击此按钮时从前端得到的内容

 const HandleClick = () => {
    if (window !== undefined) {
      window.location.href =
        "http://localhost:8000/api/v1/auth/google/callback";
    }
  };

错误

you must select a provider

我的谷歌设置
enter image description here

我的后端Go代码

// Index Route
func SetupRoutes() http.Handler {

    rootRoutes := http.NewServeMux()
    helpers.SocialAuthHelper()

    // Set up user routes
    userRoutes := UserRoutes()
    rootRoutes.Handle("/api/v1/", middlewares.LogMiddleware(http.StripPrefix("/api/v1", userRoutes).(http.HandlerFunc)))

    rootRoutes.HandleFunc("/", middlewares.LogMiddleware(func(w http.ResponseWriter, r *http.Request) {
        panic(utils.NewErrorHandler("Path Not Found", http.StatusBadRequest))
    }))

    rootRoutes.HandleFunc("/{$}", middlewares.LogMiddleware(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/html")
        html := `<h1>Server is working. To See Frontend <a href="http://localhost:3000"> Click Here </a></h1>`
        w.Write([]byte(html))
    }))

    return rootRoutes

}


// User Routes

func UserRoutes() *http.ServeMux {

    router := http.NewServeMux()

    // router.HandleFunc("POST /register", controllers.UserRegister)

    // Social Auth
    router.HandleFunc("GET /auth/{provider}/callback", controllers.GetGoogleAuthCallbackFunc)
    // router.HandleFunc("GET /auth/{provider}", controllers.HandleProviderLogin)

    router.HandleFunc("/", middlewares.LogMiddleware(func(w http.ResponseWriter, r *http.Request) {
        panic(utils.NewErrorHandler("Path Not Found", http.StatusBadRequest))
    }))

    return router

}

// Controller


type key int

const ProviderKey key = 0

// Middleware to set provider into context
func SetProviderInContext(r *http.Request, provider string) *http.Request {
    ctx := context.WithValue(r.Context(), ProviderKey, provider)
    return r.WithContext(ctx)
}

// Extract provider from context
func GetProviderFromContext(r *http.Request) string {
    provider, ok := r.Context().Value(ProviderKey).(string)
    if !ok {
        return ""
    }
    return provider
}

func GetGoogleAuthCallbackFunc(w http.ResponseWriter, r *http.Request) {

    // We have to check if we are geting {provider} from params
    helpers.SocialAuthHelper()

    value := r.PathValue("provider")
    fmt.Println("value", value)

    // Extract the provider from the URL path
    pathSegments := strings.Split(r.URL.Path, "/")
    if len(pathSegments) < 4 {
        http.Error(w, "Invalid request", http.StatusBadRequest)
        return
    }
    provider := pathSegments[2] // Extracting 'google' from '/auth/google/callback'

    fmt.Println("provider", provider)

    // // Set provider in request context
    // r = SetProviderInContext(r, provider)

    // // Check if the provider is correctly set
    // fmt.Println("provider", GetProviderFromContext(r))

    // get the user from the session

    user, err := gothic.CompleteUserAuth(w, r)
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    fmt.Println(user)

    // redirect the user
    http.Redirect(w, r, "http://localhost:3000", http.StatusFound)

}




后端日志

Go Projects/Social Auth$ go run main.go
INFO[0000] Connected to MongoDB successfully. Connection 
WARN[2024-09-14 20:58:50] Server running on:8000                       
INFO[2024-09-14 20:58:54] Request Received: GET /                      
INFO[2024-09-14 20:58:54] Response Status: 200 GET /                   
INFO[2024-09-14 20:58:54] Request Received: GET /                      
INFO[2024-09-14 20:58:54] Response Status: 200 GET /                   
INFO[2024-09-14 20:58:58] Request Received: GET /api/v1/auth/google/callback 
value google
provider google
INFO[2024-09-14 20:58:58] Response Status: 200 GET /api/v1/auth/google/callback 
INFO[2024-09-14 20:58:58] Request Received: GET /favicon.ico           

我试过了

window.location.href = "http://localhost:8000/api/v1/auth/google/callback?provider=google";

然后我收到这个错误

could not find a matching session for this request

enter image description here

我期待它应该打开谷歌身份验证。

go oauth-2.0
1个回答
0
投票

我找到解决方案了

我们必须这样手动添加

provider

// Controller
 func HandleProviderLogin(w http.ResponseWriter, r *http.Request) {
    // Extract the provider (e.g., "google")
    pathSegments := strings.Split(r.URL.Path, "/")
    if len(pathSegments) < 3 {
        http.Error(w, "Invalid request", http.StatusBadRequest)
        return
    }
    provider := pathSegments[2] // Extracting 'google' from '/auth/google'

    // Add provider as a query parameter
    q := r.URL.Query()
    q.Add("provider", provider)
    r.URL.RawQuery = q.Encode()

    // Begin the authentication process
    gothic.BeginAuthHandler(w, r)
}

func GetGoogleAuthCallbackFunc(w http.ResponseWriter, r *http.Request) {

    helpers.SocialAuthHelper()

    // We have to check if we are getting {provider} from the path
    value := r.URL.Path
    fmt.Println("value", value)

    // Extract the provider from the URL path
    pathSegments := strings.Split(r.URL.Path, "/")
    if len(pathSegments) < 4 {
        http.Error(w, "Invalid request", http.StatusBadRequest)
        return
    }
    provider := pathSegments[2] // Extracting 'google' from '/auth/google/callback'

    // Log the extracted provider
    fmt.Println("provider", provider)

    // Add provider as a query parameter (this is what `gothic.CompleteUserAuth` expects)
    q := r.URL.Query()
    q.Add("provider", provider)
    r.URL.RawQuery = q.Encode()

    // Complete the authentication process
    user, err := gothic.CompleteUserAuth(w, r)
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }

    // Log the authenticated user
    fmt.Println(user)

    // Redirect the user after authentication
    http.Redirect(w, r, "http://localhost:3000", http.StatusFound)
}


// For routes  we need to add that

router.HandleFunc("GET /auth/{provider}/callback", controllers.GetGoogleAuthCallbackFunc)
router.HandleFunc("GET /auth/{provider}", controllers.HandleProviderLogin)

所以基本上从前端我们会选择

/auth/{provider}
路线。就我而言是

  const HandleClick = () => {
    if (window !== undefined) {
      window.location.href = "http://localhost:8000/api/v1/auth/google";
    }
  };

所以我们将选择

/auth/{provider}
路线。后端会自动调用回调,即
/auth/{provider}/callback

© www.soinside.com 2019 - 2024. All rights reserved.