-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
set_google_oauth_token.go
65 lines (50 loc) · 1.4 KB
/
set_google_oauth_token.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
package organization
import (
"context"
"log"
v "github.com/RussellLuo/validating/v3"
"github.com/th0th/poeticmetric/backend/pkg/depot"
"github.com/th0th/poeticmetric/backend/pkg/env"
"github.com/th0th/poeticmetric/backend/pkg/model"
)
type SetGoogleOauthTokenPayload struct {
Code *string `json:"code"`
}
func SetGoogleOauthToken(dp *depot.Depot, id uint64, payload *SetGoogleOauthTokenPayload) error {
modelOrganization := &model.Organization{}
err := validateSetGoogleOauthTokenPayload(modelOrganization, payload)
if err != nil {
return err
}
err = dp.Postgres().
Model(&model.Organization{}).
Select("google_oauth_refresh_token").
Where("id = ?", id).
Updates(modelOrganization).
Error
if err != nil {
return err
}
return nil
}
func validateSetGoogleOauthTokenPayload(modelOrganization *model.Organization, payload *SetGoogleOauthTokenPayload) error {
errs := v.Validate(v.Schema{
v.F("code", payload.Code): v.All(
v.Nonzero[*string]().Msg("This field is required."),
v.Is(func(t *string) bool {
ctx := context.Background()
token, err := env.GetGoogleOauthConfig().Exchange(ctx, *payload.Code)
if err != nil {
log.Println(err)
return false
}
modelOrganization.GoogleOauthRefreshToken = &token.RefreshToken
return true
}).Msg("Couldn't authenticate with Google. Please try again."),
),
})
if len(errs) > 0 {
return errs
}
return nil
}