95 lines
2.3 KiB
Go
95 lines
2.3 KiB
Go
package bouquins
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
// GiteaProvider implements OAuth2 client with custom gitea server
|
|
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"
|
|
}
|
|
|
|
// ProfileURL returns redirect URL for oauth2 auth
|
|
func (p GiteaProvider) ProfileURL(conf *Conf) string {
|
|
for _, c := range conf.ProvidersConf {
|
|
if c.Name == p.Name() {
|
|
return c.ProfileURL
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// Icon returns icon CSS class for provider
|
|
func (p GiteaProvider) Icon() string {
|
|
return "giteaicon"
|
|
}
|
|
|
|
// 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: conf.ExternalURL + "/callback",
|
|
Endpoint: oauth2.Endpoint{c.AuthURL, c.TokenURL, oauth2.AuthStyleAutoDetect},
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetUser returns github primary email
|
|
func (p GiteaProvider) GetUser(app *Bouquins, token *oauth2.Token) (string, error) {
|
|
apiReq, err := http.NewRequest("GET", p.ProfileURL(app.Conf), nil)
|
|
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
|
|
}
|