func YandexRedirectHandler(w http.ResponseWriter, r *http.Request) {
url := configs.OauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func YandexCallbackHandler(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
token, err := configs.OauthConfig.Exchange(r.Context(), code)
if err != nil {
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
resp, err := http.Get("https://login.yandex.ru/info?format=json&oauth_token=" + token.AccessToken)
if err != nil {
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var userinfo struct {
ID string `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"default_email"`
}
err = json.NewDecoder(resp.Body).Decode(&userinfo)
if err != nil {
http.Error(w, "Failed to decode user info", http.StatusInternalServerError)
return
}
// 1 означает яндекс
userID := store.GetUserID(r.Context(), userinfo.ID, 1)
println(userID)
// Если не найден
if userID == "" {
// Register the user in the database
err = store.CreateUser(r.Context(), userinfo.ID, userinfo.FirstName, userinfo.LastName, userinfo.Email, 1)
if err != nil {
http.Error(w, "Failed to register user", http.StatusInternalServerError)
return
}
}
// Генерация JWT токена
tokenString, err := oauth.GenerateToken(userID)
if err != nil {
http.Error(w, "Failed to generate JWT token", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "http://localhost:3000/login?token="+tokenString, http.StatusTemporaryRedirect)
}