package auth import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "log" "net/http" "forgejo.gwairfelin.com/max/gonotes/internal/conf" "golang.org/x/oauth2" ) type userInfo struct { preferred_username string } func GenerateStateOAUTHCookie(w http.ResponseWriter, prefix string) string { b := make([]byte, 16) rand.Read(b) state := base64.URLEncoding.EncodeToString(b) cookie := http.Cookie{ Name: "oauthstate", Value: state, MaxAge: 30, Secure: true, HttpOnly: true, Path: prefix, } http.SetCookie(w, &cookie) return state } func GetUserData(code string, oauth *oauth2.Config) (map[string]any, error) { // Use code to get token and get user info from Google. token, err := oauth.Exchange(context.Background(), code) if err != nil { return nil, fmt.Errorf("code exchange wrong: %s", err.Error()) } request, err := http.NewRequest("GET", conf.Conf.OIDC.UserinfoURL, nil) if err != nil { return nil, fmt.Errorf("failed to init http client for userinfo: %s", err.Error()) } request.Header.Set("Authorization", fmt.Sprintf("token %s", token.AccessToken)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, fmt.Errorf("failed getting user info: %s", err.Error()) } defer response.Body.Close() uInf := make(map[string]any) err = json.NewDecoder(response.Body).Decode(&uInf) if err != nil { return nil, fmt.Errorf("failed to parse response as json: %s", err.Error()) } log.Printf("Contents of user data response %s", uInf) return uInf, nil }