gonotes/internal/auth/oauth.go

67 lines
1.6 KiB
Go
Raw Normal View History

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