forked from chaitin/MonkeyCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom.go
More file actions
83 lines (71 loc) · 1.71 KB
/
custom.go
File metadata and controls
83 lines (71 loc) · 1.71 KB
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
package oauth
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/google/uuid"
"golang.org/x/oauth2"
"github.com/chaitin/MonkeyCode/backend/domain"
)
type CustomOAuth struct {
cfg domain.OAuthConfig
oauth *oauth2.Config
}
func NewCustomOAuth(config domain.OAuthConfig) domain.OAuther {
c := &CustomOAuth{
cfg: config,
oauth: &oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: config.AuthorizeURL,
TokenURL: config.TokenURL,
},
RedirectURL: config.RedirectURI,
Scopes: config.Scopes,
},
}
return c
}
// GetAuthorizeURL implements domain.OAuther.
func (c *CustomOAuth) GetAuthorizeURL() (string, string) {
state := uuid.NewString()
url := c.oauth.AuthCodeURL(state)
return state, url
}
// GetUserInfo implements domain.OAuther.
func (c *CustomOAuth) GetUserInfo(code string) (*domain.OAuthUserInfo, error) {
info, err := c.getUserInfo(code)
if err != nil {
return nil, err
}
return &domain.OAuthUserInfo{
ID: fmt.Sprint(info[c.cfg.IDField]),
AvatarURL: fmt.Sprint(info[c.cfg.AvatarField]),
Name: fmt.Sprint(info[c.cfg.NameField]),
}, nil
}
type UserInfo map[string]any
func (c *CustomOAuth) getUserInfo(code string) (UserInfo, error) {
token, err := c.oauth.Exchange(context.Background(), code)
if err != nil {
return nil, err
}
client := c.oauth.Client(context.Background(), token)
res, err := client.Get(c.cfg.UserInfoURL)
if err != nil {
return nil, err
}
defer res.Body.Close()
buf, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
var userInfo UserInfo
err = json.Unmarshal(buf, &userInfo)
if err != nil {
return nil, err
}
return userInfo, nil
}