go-bouquins/bouquins/gitea.go

89 lines
2.2 KiB
Go
Raw Normal View History

2019-09-08 08:41:10 +00:00
package bouquins
import (
"encoding/json"
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
)
// GithubProvider implements OAuth2 client with github.com
type GiteaProvider string
type giteaProfile struct {
AvatarURL string `json:"avatar_url"`
Created string `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int64 `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin string `json:"last_login"`
Login string `json:"login"`
}
func init() {
Providers = append(Providers, GiteaProvider("gitea"))
}
// Name returns name of provider
func (p GiteaProvider) Name() string {
return string(p)
}
// Label returns label of provider
func (p GiteaProvider) Label() string {
return "Gitea"
}
// Icon returns icon CSS class for provider
func (p GiteaProvider) Icon() string {
return "giteaicon" // TODO
}
// Config returns OAuth configuration for this provider
func (p GiteaProvider) Config(conf *Conf) *oauth2.Config {
for _, c := range conf.ProvidersConf {
if c.Name == p.Name() {
return &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: "http://localhost:9000/callback", // TODO
Endpoint: oauth2.Endpoint{
"https://git.meutel.net/login/oauth/authorize", // TODO
"https://git.meutel.net/login/oauth/access_token", // TODO
oauth2.AuthStyleAutoDetect,
},
}
}
}
return nil
}
// GetUser returns github primary email
func (p GiteaProvider) GetUser(token *oauth2.Token) (string, error) {
apiReq, err := http.NewRequest("GET", "https://git.meutel.net/api/v1/user", nil) // TODO
apiReq.Header.Add("Accept", "application/json")
apiReq.Header.Add("Authorization", "token "+token.AccessToken)
client := &http.Client{}
response, err := client.Do(apiReq)
defer response.Body.Close()
if err != nil {
log.Println("Auth error", err)
return "", fmt.Errorf("Authentification error")
}
dec := json.NewDecoder(response.Body)
var profile giteaProfile
err = dec.Decode(&profile)
if err != nil {
log.Printf("Error reading %s API response %v", p.Name(), err)
return "", fmt.Errorf("Error reading %s API response", p.Name())
}
userEmail := profile.Email
log.Println("User email:", userEmail)
return userEmail, nil
}