-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathclient_store.go
100 lines (85 loc) · 2.07 KB
/
client_store.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
package oauth2gorm
import (
"context"
"encoding/json"
"io"
"os"
"time"
"github.com/go-oauth2/oauth2/v4"
"github.com/go-oauth2/oauth2/v4/models"
"gorm.io/gorm"
)
type ClientStoreItem struct {
ID string
Secret string `gorm:"type:varchar(512)"`
Domain string `gorm:"type:varchar(512)"`
Data string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
func NewClientStore(config *Config) *ClientStore {
db, err := gorm.Open(config.Dialector, defaultConfig)
if err != nil {
panic(err)
}
// default client pool
s, err := db.DB()
if err != nil {
panic(err)
}
s.SetMaxIdleConns(10)
s.SetMaxOpenConns(100)
s.SetConnMaxLifetime(time.Hour)
return NewClientStoreWithDB(config, db)
}
func NewClientStoreWithDB(config *Config, db *gorm.DB) *ClientStore {
store := &ClientStore{
db: db,
tableName: "oauth2_clients",
stdout: os.Stderr,
}
if config.TableName != "" {
store.tableName = config.TableName
}
if !db.Migrator().HasTable(store.tableName) {
if err := db.Table(store.tableName).Migrator().CreateTable(&ClientStoreItem{}); err != nil {
panic(err)
}
}
return store
}
type ClientStore struct {
tableName string
db *gorm.DB
stdout io.Writer
}
func (s *ClientStore) toClientInfo(data []byte) (oauth2.ClientInfo, error) {
var cm models.Client
err := json.Unmarshal(data, &cm)
return &cm, err
}
func (s *ClientStore) GetByID(ctx context.Context, id string) (oauth2.ClientInfo, error) {
if id == "" {
return nil, nil
}
var item ClientStoreItem
err := s.db.WithContext(ctx).Table(s.tableName).Limit(1).Find(&item, "id = ?", id).Error
if err != nil {
return nil, err
}
return s.toClientInfo([]byte(item.Data))
}
func (s *ClientStore) Create(ctx context.Context, info oauth2.ClientInfo) error {
data, err := json.Marshal(info)
if err != nil {
return err
}
item := &ClientStoreItem{
ID: info.GetID(),
Secret: info.GetSecret(),
Domain: info.GetDomain(),
Data: string(data),
}
return s.db.WithContext(ctx).Table(s.tableName).Create(item).Error
}