/
config.go
93 lines (80 loc) · 1.83 KB
/
config.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
package omniauth
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"golang.org/x/oauth2"
)
type IConfig interface {
Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
ExchangeAuthInfoByToken(token *oauth2.Token) (*Auth, error)
}
func NewConfig(config *oauth2.Config) *Config {
return &Config{
Config: config,
}
}
type Config struct {
*oauth2.Config
self IConfig
}
func (c *Config) GetSelf() IConfig {
if c.self != nil {
return c.self
}
return c
}
func (c *Config) SetSelf(self IConfig) *Config {
c.self = self
return c
}
type Claims struct {
ID string `json:"sub"`
Name string `json:"name"`
Email string `json:"email"`
Picture string `json:"picture"`
}
var (
ErrMissingIdToken = errors.New("missing id_token")
ErrInvalidIdToken = errors.New("invalid id_token")
)
func (c *Config) ExchangeAuthInfo(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*Auth, error) {
token, err := c.GetSelf().Exchange(ctx, code, opts...)
if err != nil {
return nil, err
}
return c.GetSelf().ExchangeAuthInfoByToken(token)
}
func (c *Config) ExchangeAuthInfoByToken(token *oauth2.Token) (*Auth, error) {
idToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, ErrMissingIdToken
}
parts := strings.Split(idToken, ".")
if len(parts) != 3 {
return nil, ErrInvalidIdToken
}
payload, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
info := &RawInfo{}
claims := &Claims{}
for _, v := range []any{info, claims} {
d := json.NewDecoder(bytes.NewReader(payload))
d.UseNumber()
if err := d.Decode(v); err != nil {
return nil, err
}
}
return &Auth{
ID: claims.ID,
Name: claims.Name,
Email: claims.Email,
Picture: claims.Picture,
RawInfo: *info,
}, nil
}