-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_drive_token_service.go
78 lines (62 loc) · 1.75 KB
/
google_drive_token_service.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
package fundrive
import (
"context"
"golang.org/x/oauth2"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
type newDriveServiceRequest struct {
UserID string `json:"user_id"`
Email string `json:"email"`
}
func (service *GoogleDriveService) newDriveService(ctx context.Context, req *newDriveServiceRequest) (*drive.Service, error) {
getTokenReq := GetTokenRequest{
UserID: req.UserID,
Email: req.Email,
}
token, err := service.OAuthService.GetToken(ctx, &getTokenReq)
if err != nil {
return nil, err
}
newTokenServiceReq := newTokenServiceRequest{
UserID: req.UserID,
Email: req.Email,
Token: token,
}
srv, err := service.newTokenService(ctx, &newTokenServiceReq)
if err != nil {
return nil, err
}
return srv, nil
}
type newTokenServiceRequest struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Token *oauth2.Token `json:"token"`
}
// newTokenService creates a new Google Drive service using the provided token.
// If the token is invalid, it will refresh the token and create a new service.
func (service *GoogleDriveService) newTokenService(
ctx context.Context,
req *newTokenServiceRequest,
) (*drive.Service, error) {
if !req.Token.Valid() {
refreshedToken, err := service.OAuthService.RefreshToken(ctx, req.Token)
if err != nil {
return nil, err
}
req.Token = refreshedToken
saveTokenReq := SaveTokenRequest{
UserID: req.UserID,
Email: req.Email,
Token: req.Token,
}
if err = service.OAuthService.SaveToken(ctx, &saveTokenReq); err != nil {
return nil, err
}
}
tokenSource := oauth2.StaticTokenSource(req.Token)
opt := []option.ClientOption{option.WithTokenSource(tokenSource)}
srv, err := drive.NewService(ctx, opt...)
return srv, err
}