-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathclient_store.go
127 lines (105 loc) · 2.48 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package mysql
import (
"database/sql"
"fmt"
"time"
"github.com/jmoiron/sqlx"
jsoniter "github.com/json-iterator/go"
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/models"
)
type ClientStore struct {
db *sqlx.DB
tableName string
initTableDisabled bool
maxLifetime time.Duration
maxOpenConns int
maxIdleConns int
}
// ClientStoreItem data item
type ClientStoreItem struct {
ID string `db:"id"`
Secret string `db:"secret"`
Domain string `db:"domain"`
Data string `db:"data"`
}
// NewClientStore creates PostgreSQL store instance
func NewClientStore(db *sqlx.DB, options ...ClientStoreOption) (*ClientStore, error) {
store := &ClientStore{
db: db,
tableName: "oauth2_clients",
maxLifetime: time.Hour * 2,
maxOpenConns: 50,
maxIdleConns: 25,
}
for _, o := range options {
o(store)
}
var err error
if !store.initTableDisabled {
err = store.initTable()
}
if err != nil {
return store, err
}
store.db.SetMaxOpenConns(store.maxOpenConns)
store.db.SetMaxIdleConns(store.maxIdleConns)
store.db.SetConnMaxLifetime(store.maxLifetime)
return store, err
}
func (s *ClientStore) initTable() error {
query := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id VARCHAR(255) NOT NULL PRIMARY KEY,
secret VARCHAR(255) NOT NULL,
domain VARCHAR(255) NOT NULL,
data TEXT NOT NULL
);
`, s.tableName)
stmt, err := s.db.Prepare(query)
if err != nil {
return err
}
_, err = stmt.Exec()
if err != nil {
return err
}
return nil
}
func (s *ClientStore) toClientInfo(data string) (oauth2.ClientInfo, error) {
var cm models.Client
err := jsoniter.Unmarshal([]byte(data), &cm)
return &cm, err
}
// GetByID retrieves and returns client information by id
func (s *ClientStore) GetByID(id string) (oauth2.ClientInfo, error) {
if id == "" {
return nil, nil
}
var item ClientStoreItem
err := s.db.QueryRowx(fmt.Sprintf("SELECT * FROM %s WHERE id = ?", s.tableName), id).StructScan(&item)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
}
return s.toClientInfo(item.Data)
}
// Create creates and stores the new client information
func (s *ClientStore) Create(info oauth2.ClientInfo) error {
data, err := jsoniter.Marshal(info)
if err != nil {
return err
}
_, err = s.db.Exec(fmt.Sprintf("INSERT INTO %s (id, secret, domain, data) VALUES (?,?,?,?)", s.tableName),
info.GetID(),
info.GetSecret(),
info.GetDomain(),
string(data),
)
if err != nil {
return err
}
return nil
}