-
Notifications
You must be signed in to change notification settings - Fork 14
/
apple.go
102 lines (79 loc) · 2.11 KB
/
apple.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
94
95
96
97
98
99
100
101
102
package social
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"github.com/Timothylock/go-signin-with-apple/apple"
"github.com/coretrix/hitrix/pkg/helper"
"github.com/coretrix/hitrix/service/component/config"
)
type Apple struct {
TeamID string
ClientID string
AndroidClientID string
KeyID string
PrivateKey string
}
func NewAppleSocial(
configService config.IConfig,
) (IUserData, error) {
if !helper.ExistsInDir(".apple-id.json", configService.GetFolderPath()) {
return nil, errors.New(configService.GetFolderPath() + "/.apple-id.json does not exists")
}
credentialsFile := configService.GetFolderPath() + "/.apple-id.json"
var dat []byte
var configApple = &Apple{}
var err error
if dat, err = os.ReadFile(credentialsFile); err != nil {
return nil, err
}
if err := json.Unmarshal(dat, configApple); err != nil {
return nil, err
}
return configApple, nil
}
func (a *Apple) GetUserData(ctx context.Context, token string, isAndroid bool) (*UserData, error) {
if isAndroid && a.AndroidClientID == "" {
return nil, fmt.Errorf("you must set AndroidClientID")
}
if !isAndroid && a.ClientID == "" {
return nil, fmt.Errorf("you must set ClientID")
}
clientID := a.ClientID
if isAndroid {
clientID = a.AndroidClientID
}
secret, err := apple.GenerateClientSecret(a.PrivateKey, a.TeamID, clientID, a.KeyID)
if err != nil {
return nil, err
}
client := apple.New()
req := apple.AppValidationTokenRequest{
ClientID: clientID,
ClientSecret: secret,
Code: token,
}
var resp apple.ValidationResponse
err = client.VerifyAppToken(ctx, req, &resp)
if err != nil {
return nil, err
}
if resp.Error != "" {
return nil, fmt.Errorf(resp.Error)
}
claim, err := apple.GetClaims(resp.IDToken)
if err != nil {
return nil, err
}
idClaim, ok := (*claim)["sub"]
if !ok {
return nil, fmt.Errorf("apple returned claims with 'sub' missling")
}
emailClaim, ok := (*claim)["email"]
if !ok {
return nil, fmt.Errorf("apple returned claims with 'email' missling")
}
return &UserData{ID: idClaim.(string), Email: emailClaim.(string)}, nil
}