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)
}
{
id: 1,
name: "Роман",
description: "Такая категория для мечтателей любви",
_links: {
self: {
href: "https://localhost:8080/books/categories/1"
}
},.
etc
}
HTTP/1.1 500 Internal server error
{
title: "Database connection error",
error: "Failed to connect to the database [name]",
request: "POST www.habr.com/post",
time: "11.11.2023 ...",
errorTraceID "uuid"
... и что-нибудь свое если нужно типа код ошибки и прочего
}
psql -U postgres -d postgres
CREATE USER new_user WITH SUPERUSER PASSWORD 'new_password';
DROP ROLE postgres;