Add IdProvider interface.

This commit is contained in:
Yang Luo
2021-02-21 22:33:53 +08:00
parent 62c69a89c1
commit 40fb336e95
4 changed files with 150 additions and 80 deletions

View File

@ -16,43 +16,32 @@ package controllers
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http"
"sync" "sync"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/casdoor/casdoor/idp"
"github.com/casdoor/casdoor/object" "github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util" "github.com/casdoor/casdoor/util"
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
var githubEndpoint = oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
}
var githubOauthConfig = &oauth2.Config{
ClientID: beego.AppConfig.String("GithubAuthClientID"),
ClientSecret: beego.AppConfig.String("GithubAuthClientSecret"),
RedirectURL: "",
Scopes: []string{"user:email", "read:user"},
Endpoint: githubEndpoint,
}
func (c *ApiController) AuthLogin() { func (c *ApiController) AuthLogin() {
applicationName := c.Input().Get("application") applicationName := c.Input().Get("application")
providerName := c.Input().Get("provider") providerName := c.Input().Get("provider")
code := c.Input().Get("code") code := c.Input().Get("code")
state := c.Input().Get("state") state := c.Input().Get("state")
method := c.Input().Get("method") method := c.Input().Get("method")
RedirectURL := c.Input().Get("redirect_url") redirectUrl := c.Input().Get("redirect_url")
application := object.GetApplication(fmt.Sprintf("admin/%s", applicationName)) application := object.GetApplication(fmt.Sprintf("admin/%s", applicationName))
provider := object.GetProvider(fmt.Sprintf("admin/%s", providerName)) provider := object.GetProvider(fmt.Sprintf("admin/%s", providerName))
githubOauthConfig.ClientID = provider.ClientId
githubOauthConfig.ClientSecret = provider.ClientSecret idProvider := idp.GetIdProvider(provider.Type)
oauthConfig := idProvider.GetConfig()
oauthConfig.ClientID = provider.ClientId
oauthConfig.ClientSecret = provider.ClientSecret
oauthConfig.RedirectURL = redirectUrl
var resp Response var resp Response
var res authResponse var res authResponse
@ -65,11 +54,9 @@ func (c *ApiController) AuthLogin() {
return return
} }
githubOauthConfig.RedirectURL = RedirectURL
// https://github.com/golang/oauth2/issues/123#issuecomment-103715338 // https://github.com/golang/oauth2/issues/123#issuecomment-103715338
ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, httpClient) ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, httpClient)
token, err := githubOauthConfig.Exchange(ctx, code) token, err := oauthConfig.Exchange(ctx, code)
if err != nil { if err != nil {
res.IsAuthenticated = false res.IsAuthenticated = false
panic(err) panic(err)
@ -83,58 +70,19 @@ func (c *ApiController) AuthLogin() {
} }
var wg sync.WaitGroup var wg sync.WaitGroup
var tempUserEmail []userEmailFromGithub
var tempUserAccount userInfoFromGithub
wg.Add(2) wg.Add(2)
go func() { go func() {
req, err := http.NewRequest("GET", "https://api.github.com/user/emails", nil) res.Email = idProvider.GetEmail(httpClient, token)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token "+token.AccessToken)
response, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
err = json.Unmarshal(contents, &tempUserEmail)
if err != nil {
res.IsAuthenticated = false
panic(err)
}
for _, v := range tempUserEmail {
if v.Primary == true {
res.Email = v.Email
break
}
}
wg.Done() wg.Done()
}() }()
go func() { go func() {
req, err := http.NewRequest("GET", "https://api.github.com/user", nil) res.Method, res.Avatar = idProvider.GetLoginAndAvatar(httpClient, token)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token "+token.AccessToken)
response2, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response2.Body.Close()
contents2, err := ioutil.ReadAll(response2.Body)
err = json.Unmarshal(contents2, &tempUserAccount)
if err != nil {
res.IsAuthenticated = false
panic(err)
}
wg.Done() wg.Done()
}() }()
wg.Wait() wg.Wait()
if method == "signup" { if method == "signup" {
userId := object.HasGithub(application, tempUserAccount.Login) userId := object.HasGithub(application, res.Method)
if userId != "" { if userId != "" {
//if len(object.GetMemberAvatar(userId)) == 0 { //if len(object.GetMemberAvatar(userId)) == 0 {
// avatar := UploadAvatarToOSS(tempUserAccount.AvatarUrl, userId) // avatar := UploadAvatarToOSS(tempUserAccount.AvatarUrl, userId)
@ -148,13 +96,11 @@ func (c *ApiController) AuthLogin() {
c.SetSessionUser(userId) c.SetSessionUser(userId)
util.LogInfo(c.Ctx, "API: [%s] signed in", userId) util.LogInfo(c.Ctx, "API: [%s] signed in", userId)
res.IsSignedUp = true res.IsSignedUp = true
_ = object.LinkUserAccount(userId, "github", tempUserAccount.Login) _ = object.LinkUserAccount(userId, "github", res.Method)
} else { } else {
res.IsSignedUp = false res.IsSignedUp = false
} }
} }
res.Method = tempUserAccount.Login
res.Avatar = tempUserAccount.AvatarUrl
resp = Response{Status: "ok", Msg: "success", Data: res} resp = Response{Status: "ok", Msg: "success", Data: res}
} else { } else {
memberId := c.GetSessionUser() memberId := c.GetSessionUser()
@ -164,7 +110,7 @@ func (c *ApiController) AuthLogin() {
c.ServeJSON() c.ServeJSON()
return return
} }
linkRes := object.LinkUserAccount(memberId, "github_account", tempUserAccount.Login) linkRes := object.LinkUserAccount(memberId, "github_account", res.Method)
if linkRes { if linkRes {
resp = Response{Status: "ok", Msg: "success", Data: linkRes} resp = Response{Status: "ok", Msg: "success", Data: linkRes}
} else { } else {

View File

@ -14,18 +14,6 @@
package controllers package controllers
type userEmailFromGithub struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Visibility string `json:"visibility"`
}
type userInfoFromGithub struct {
Login string `json:"login"`
AvatarUrl string `json:"avatar_url"`
}
type authResponse struct { type authResponse struct {
IsAuthenticated bool `json:"isAuthenticated"` IsAuthenticated bool `json:"isAuthenticated"`
IsSignedUp bool `json:"isSignedUp"` IsSignedUp bool `json:"isSignedUp"`

101
idp/github.go Normal file
View File

@ -0,0 +1,101 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package idp
import (
"encoding/json"
"io/ioutil"
"net/http"
"golang.org/x/oauth2"
)
type GithubIdProvider struct{}
func (idp *GithubIdProvider) GetConfig() *oauth2.Config {
var githubEndpoint = oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
}
var githubOauthConfig = &oauth2.Config{
Scopes: []string{"user:email", "read:user"},
Endpoint: githubEndpoint,
}
return githubOauthConfig
}
func (idp *GithubIdProvider) GetEmail(httpClient *http.Client, token *oauth2.Token) string {
res := ""
type GithubEmail struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Visibility string `json:"visibility"`
}
var githubEmails []GithubEmail
req, err := http.NewRequest("GET", "https://api.github.com/user/emails", nil)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token "+token.AccessToken)
response, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
err = json.Unmarshal(contents, &githubEmails)
if err != nil {
panic(err)
}
for _, v := range githubEmails {
if v.Primary == true {
res = v.Email
break
}
}
return res
}
func (idp *GithubIdProvider) GetLoginAndAvatar(httpClient *http.Client, token *oauth2.Token) (string, string) {
type GithubUser struct {
Login string `json:"login"`
AvatarUrl string `json:"avatar_url"`
}
var githubUser GithubUser
req, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token "+token.AccessToken)
response2, err := httpClient.Do(req)
if err != nil {
panic(err)
}
defer response2.Body.Close()
contents2, err := ioutil.ReadAll(response2.Body)
err = json.Unmarshal(contents2, &githubUser)
if err != nil {
panic(err)
}
return githubUser.Login, githubUser.AvatarUrl
}

35
idp/provider.go Normal file
View File

@ -0,0 +1,35 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package idp
import (
"net/http"
"golang.org/x/oauth2"
)
type IdProvider interface {
GetConfig() *oauth2.Config
GetEmail(httpClient *http.Client, token *oauth2.Token) string
GetLoginAndAvatar(httpClient *http.Client, token *oauth2.Token) (string, string)
}
func GetIdProvider(providerType string) IdProvider {
if providerType == "github" {
return &GithubIdProvider{}
}
return nil
}