-
Notifications
You must be signed in to change notification settings - Fork 118
/
provider.go
93 lines (80 loc) · 1.76 KB
/
provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package oauth
import (
"fmt"
"net"
"net/http"
"time"
"github.com/qingwave/weave/pkg/config"
"github.com/qingwave/weave/pkg/model"
"golang.org/x/oauth2"
)
const (
GithubAuthType = "github"
WeChatAuthType = "wechat"
EmptyAuthType = "nil"
)
var (
defaultHttpClient = &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
},
Timeout: 10 * time.Second,
}
)
func IsEmptyAuthType(authType string) bool {
return authType == "" || authType == EmptyAuthType
}
type UserInfo struct {
ID string
Url string
AuthType string
Username string
DisplayName string
Email string
AvatarUrl string
}
func (ui *UserInfo) User() *model.User {
return &model.User{
Name: ui.Username,
Email: ui.Email,
Avatar: ui.AvatarUrl,
AuthInfos: []model.AuthInfo{
{
AuthType: ui.AuthType,
AuthId: ui.ID,
Url: ui.Url,
},
},
}
}
type OAuthManager struct {
conf map[string]config.OAuthConfig
}
func NewOAuthManager(conf map[string]config.OAuthConfig) *OAuthManager {
return &OAuthManager{
conf: conf,
}
}
func (m *OAuthManager) GetAuthProvider(authType string) (AuthProvider, error) {
var provider AuthProvider
conf, ok := m.conf[authType]
if !ok {
return nil, fmt.Errorf("auth type %s not found in config", authType)
}
switch authType {
case GithubAuthType:
provider = NewGithubAuth(conf.ClientId, conf.ClientSecret)
case WeChatAuthType:
provider = NewWeChatAuth(conf.ClientId, conf.ClientSecret)
default:
return nil, fmt.Errorf("unknown auth type: %s", authType)
}
return provider, nil
}
type AuthProvider interface {
GetToken(code string) (*oauth2.Token, error)
GetUserInfo(token *oauth2.Token) (*UserInfo, error)
}