forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yandex.go
73 lines (61 loc) · 1.85 KB
/
yandex.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
package auth
import (
"encoding/json"
"golang.org/x/oauth2"
"golang.org/x/oauth2/yandex"
)
var _ Provider = (*Yandex)(nil)
// NameYandex is the unique name of the Yandex provider.
const NameYandex string = "yandex"
// Yandex allows authentication via Yandex OAuth2.
type Yandex struct {
*baseProvider
}
// NewYandexProvider creates new Yandex provider instance with some defaults.
//
// Docs: https://yandex.ru/dev/id/doc/en/
func NewYandexProvider() *Yandex {
return &Yandex{&baseProvider{
scopes: []string{"login:email", "login:avatar", "login:info"},
authUrl: yandex.Endpoint.AuthURL,
tokenUrl: yandex.Endpoint.TokenURL,
userApiUrl: "https://login.yandex.ru/info",
}}
}
// FetchAuthUser returns an AuthUser instance based on Yandex's user api.
//
// API reference: https://yandex.ru/dev/id/doc/en/user-information#response-format
func (p *Yandex) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
data, err := p.FetchRawUserData(token)
if err != nil {
return nil, err
}
rawUser := map[string]any{}
if err := json.Unmarshal(data, &rawUser); err != nil {
return nil, err
}
extracted := struct {
Id string `json:"id"`
Name string `json:"real_name"`
Username string `json:"login"`
Email string `json:"default_email"`
IsAvatarEmpty bool `json:"is_avatar_empty"`
AvatarId string `json:"default_avatar_id"`
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
return nil, err
}
user := &AuthUser{
Id: extracted.Id,
Name: extracted.Name,
Username: extracted.Username,
Email: extracted.Email,
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
}
if !extracted.IsAvatarEmpty {
user.AvatarUrl = "https://avatars.yandex.net/get-yapic/" + extracted.AvatarId + "/islands-200"
}
return user, nil
}