This commit is contained in:
Stavros
2025-01-23 19:16:35 +02:00
parent 143b13af2c
commit 80d25551e0
16 changed files with 491 additions and 115 deletions

View File

@@ -0,0 +1,47 @@
package providers
import (
"encoding/json"
"errors"
"io"
"net/http"
)
type GithubEmailsResponse []struct {
Email string `json:"email"`
Primary bool `json:"primary"`
}
func GithubScopes() ([]string) {
return []string{"user:email"}
}
func GetGithubEmail(client *http.Client) (string, error) {
res, resErr := client.Get("https://api.github.com/user/emails")
if resErr != nil {
return "", resErr
}
body, bodyErr := io.ReadAll(res.Body)
if bodyErr != nil {
return "", bodyErr
}
var emails GithubEmailsResponse
jsonErr := json.Unmarshal(body, &emails)
if jsonErr != nil {
return "", jsonErr
}
for _, email := range emails {
if email.Primary {
return email.Email, nil
}
}
return "", errors.New("no primary email found")
}

View File

@@ -0,0 +1,86 @@
package providers
import (
"tinyauth/internal/oauth"
"tinyauth/internal/types"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
"golang.org/x/oauth2/endpoints"
)
func NewProviders(config types.OAuthConfig) *Providers {
return &Providers{
Config: config,
}
}
type Providers struct {
Config types.OAuthConfig
Github *oauth.OAuth
Google *oauth.OAuth
Microsoft *oauth.OAuth
}
func (providers *Providers) Init() {
if providers.Config.GithubClientId != "" && providers.Config.GithubClientSecret != "" {
log.Info().Msg("Initializing Github OAuth")
providers.Github = oauth.NewOAuth(oauth2.Config{
ClientID: providers.Config.GithubClientId,
ClientSecret: providers.Config.GithubClientSecret,
Scopes: GithubScopes(),
Endpoint: endpoints.GitHub,
})
providers.Github.Init()
}
}
func (providers *Providers) Login(code string, provider string) (string, error) {
switch provider {
case "github":
if providers.Github == nil {
return "", nil
}
exchangeErr := providers.Github.ExchangeToken(code)
if exchangeErr != nil {
return "", exchangeErr
}
client := providers.Github.GetClient()
email, emailErr := GetGithubEmail(client)
if emailErr != nil {
return "", emailErr
}
return email, nil
default:
return "", nil
}
}
func (providers *Providers) GetUser(provider string) (string, error) {
switch provider {
case "github":
if providers.Github == nil {
return "", nil
}
client := providers.Github.GetClient()
email, emailErr := GetGithubEmail(client)
if emailErr != nil {
return "", emailErr
}
return email, nil
default:
return "", nil
}
}
func (providers *Providers) GetAuthURL(provider string) string {
switch provider {
case "github":
if providers.Github == nil {
return ""
}
return providers.Github.GetAuthURL()
default:
return ""
}
}