-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapikey-manager.go
270 lines (228 loc) · 6.53 KB
/
apikey-manager.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"html/template"
"io/ioutil"
"log"
"time"
"github.com/GoAdminGroup/go-admin/template/types"
"github.com/dgrijalva/jwt-go"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type APIKey struct {
ID uint `gorm:"primaryKey"`
Key string
Deadline time.Time
Details string
signed string
CreatedAt time.Time
UpdatedAt time.Time
}
type APIKeyManager struct {
db *gorm.DB
privateKey *rsa.PrivateKey
}
func NewAPIKeyManager(db *gorm.DB, privateKeyPath string) (*APIKeyManager, error) {
privateKeyData, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
return nil, err
}
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyData)
if err != nil {
return nil, err
}
return &APIKeyManager{
db: db,
privateKey: privateKey,
}, nil
}
func (m *APIKeyManager) RemoveAPIKey(key string) error {
return m.db.Where("key = ?", key).Delete(&APIKey{}).Error
}
func (m *APIKeyManager) ValidateAPIKey(tokenString string) (bool, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return &m.privateKey.PublicKey, nil
})
if err != nil {
return false, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
key := claims["key"].(string)
var apiKey APIKey
if err := m.db.Where("key = ?", key).First(&apiKey).Error; err != nil {
return false, err
}
err = token.Claims.Valid()
if err != nil {
// Handle the expiration error
return false, err
}
return true, nil
}
return false, fmt.Errorf("invalid token")
}
// ValidateNewAPIKey validates a new API key token.
func (m *APIKeyManager) ValidateNewAPIKey(tokenString string) (bool, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return &m.privateKey.PublicKey, nil
})
if err != nil {
return false, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
key := claims["key"].(string)
var apiKey APIKey
if err := m.db.Where("key = ?", key).First(&apiKey).Error; err != nil {
// Save the key in the database
apiKey.Key = key
// Parse expiration claim and set it as the deadline
if exp, ok := claims["exp"].(float64); ok {
apiKey.Deadline = time.Unix(int64(exp), 0)
}
// Set other APIKey fields as needed
apiKey.Details = "Additional details" // Example of populating the Details field
if err := m.db.Create(&apiKey).Error; err != nil {
return false, err
}
}
err = token.Claims.Valid()
if err != nil {
return false, err
}
return true, nil
}
return false, fmt.Errorf("invalid token")
}
func (m *APIKeyManager) EditAPIKey(tokenString string, newDeadline time.Time) (string, error) {
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return "", err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
var apiKey APIKey
claims["exp"] = newDeadline.Unix()
key := claims["key"].(string)
if err := m.db.Where("key = ?", key).First(&apiKey).Error; err != nil {
return "", err
}
apiKey.Deadline = newDeadline
apiKey.UpdatedAt = time.Now()
token = jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
signedToken, err := token.SignedString(m.privateKey)
if err != nil {
return "", err
}
apiKey.signed = signedToken
if err := m.db.Save(&apiKey).Error; err != nil {
return "", err
}
return signedToken, nil
}
return "", fmt.Errorf("invalid token claims")
}
func (m *APIKeyManager) GenerateAPIKey(details string, deadline time.Time) (string, error) {
var apiKey APIKey
key := generateRandomKey()
claims := jwt.MapClaims{
"key": key,
"details": details,
"exp": deadline.Unix(),
}
apiKey.Deadline = deadline
apiKey.UpdatedAt = time.Now()
apiKey.Details = details
apiKey.Key = key
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
signedToken, err := token.SignedString(m.privateKey)
if err != nil {
return "", err
}
apiKey.signed = signedToken
if err := m.db.Save(&apiKey).Error; err != nil {
return "", err
}
return signedToken, nil
}
func generateRandomKey() string {
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
// Handle the error appropriately
panic(err)
}
return fmt.Sprintf("%x", key)
}
func (m *APIKeyManager) getKeys() []map[string]types.InfoItem {
var apiKeys []APIKey
var keys []map[string]types.InfoItem = []map[string]types.InfoItem{}
result := m.db.Find(&apiKeys)
if result.Error != nil {
return []map[string]types.InfoItem{}
}
for _, v := range apiKeys {
keys = append(keys, map[string]types.InfoItem{
"id": {Content: template.HTML(fmt.Sprintf("%v", v.ID))},
"key": {Content: template.HTML(v.Key)},
"deadline": {Content: template.HTML(v.Deadline.String())},
"details": {Content: template.HTML(v.Details)},
"created_at": {Content: template.HTML(v.CreatedAt.String())},
"updated_at": {Content: template.HTML(v.UpdatedAt.String())},
})
}
return keys
}
func init_apikeymanager() (*APIKeyManager, error) {
db, err := gorm.Open(sqlite.Open("api_keys.db"), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
// Auto-migrate the APIKey model
if err := db.AutoMigrate(&APIKey{}); err != nil {
log.Fatal(err)
}
// Create a new APIKeyManager
return NewAPIKeyManager(db, privateKeyPath)
}
// func testapimanager() {
// // Connect to the database
// db, err := gorm.Open(sqlite.Open("api_keys.db"), &gorm.Config{})
// if err != nil {
// log.Fatal(err)
// }
// // Auto-migrate the APIKey model
// if err := db.AutoMigrate(&APIKey{}); err != nil {
// log.Fatal(err)
// }
// // Create a new APIKeyManager
// apiKeyManager := NewAPIKeyManager(db)
// // Generate a new API key
// apiKey, err := apiKeyManager.GenerateAPIKey("Key Details", time.Now().Add(24*time.Hour))
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Generated API Key: %s\n", apiKey.Key)
// // Edit the API key deadline
// if err := apiKeyManager.EditAPIKey(apiKey.Key, time.Now().Add(48*time.Hour)); err != nil {
// log.Fatal(err)
// }
// fmt.Println("API Key deadline edited successfully")
// // Remove the API key
// if err := apiKeyManager.RemoveAPIKey(apiKey.Key); err != nil {
// log.Fatal(err)
// }
// fmt.Println("API Key removed successfully")
// // Validate an API key token
// token := "your-token" // Replace with a valid token
// valid, err := apiKeyManager.ValidateAPIKey(token)
// if err != nil {
// log.Fatal(err)
// }
// if valid {
// fmt.Println("API Key token is valid")
// } else {
// fmt.Println("API Key token is invalid")
// }
// }