-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.go
More file actions
689 lines (636 loc) · 22.5 KB
/
connection.go
File metadata and controls
689 lines (636 loc) · 22.5 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
package keycloak
import (
"encoding/json"
"fmt"
"github.com/getevo/evo/v2"
"github.com/getevo/evo/v2/lib/curl"
"github.com/getevo/evo/v2/lib/log"
"github.com/getevo/evo/v2/lib/settings"
"github.com/getevo/evo/v2/lib/text"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/tidwall/gjson"
"strings"
"time"
)
var conn *Connection
var timeout = 5 * time.Second
func GetInstance() *Connection {
return conn
}
func (connection *Connection) UpdateAdminToken(realm string) (*JWT, error) {
result, err := connection.Post("", "/protocol/openid-connect/token", curl.Param{
"client_id": connection.Settings.Client,
"client_secret": connection.Settings.ClientSecret,
"grant_type": "client_credentials",
}, timeout)
if err != nil {
return nil, err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return nil, fmt.Errorf(parsed.Get("error").String())
}
var j JWT
err = json.Unmarshal(result.Bytes(), &j)
if err != nil {
return nil, err
}
connection.Admin = &j
return &j, nil
}
// GetUsers retrieves a list of users from the server.
//
// Parameters:
// - max: The maximum number of users to retrieve (limited to 100).
// - offset: The offset value for pagination.
// - extra: Additional parameters to include in the request.
//
// Returns:
// - users: The list of User objects retrieved from the server.
// - error: Any error that occurred during the request.
//
// The User struct represents a user in the system and contains information such as ID, username,
// first name, last name, email, and more.
//
// The curl.QueryParam type is a map of string keys to any values, representing the additional parameters
// to include in the request.
//
// The curl.Header type is a map of string keys to string values, representing HTTP header fields.
// The Clone method is used to create a copy of a header instance.
func (connection *Connection) GetUsers(max int, offset int, extra map[string]string) ([]UserInstance, error) {
var users []UserInstance
if max > 100 {
max = 100
}
var params = curl.QueryParam{
"max": max,
"first": offset,
}
for k, v := range extra {
params[k] = v
}
result, err := connection.Get("/admin", "/users", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
}, params)
if err != nil {
return users, err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return nil, fmt.Errorf(parsed.Get("error").String())
}
err = json.Unmarshal(result.Bytes(), &users)
if err != nil {
return nil, err
}
return users, nil
}
// Block sets the Enabled field of the user to false and saves the changes using the EditUser method of the Connection struct.
// It takes a pointer to a User struct as a parameter and returns an error if there is any issue editing the user.
// Example usage:
//
// conn := &Connection{}
// user := &User{ID: "user1", Enabled: true}
// err := conn.Block(user)
// if err != nil {
// fmt.Println("Error blocking user:", err)
// }
//
// The User struct should have the following fields:
//
// ID string `json:"id" form:"id"`
// Username string `json:"username" form:"username"`
// FirstName string `json:"firstName" form:"firstName"`
// LastName string `json:"lastName" form:"lastName"`
// Email string `json:"email" form:"email"`
// CreatedAt int64 `json:"createdTimestamp"`
// RegistrationDate time.Time `json:"-"`
// IsAdmin bool `json:"-" form:"is_admin"`
// EmailVerified bool `json:"emailVerified"`
// Enabled bool `json:"enabled" form:"enabled"`
// Attributes Attributes `json:"attributes"`
// Credentials *[]Credentials `json:"credentials,omitempty"`
// RequiredActions *[]string `json:"requiredActions,omitempty"`
// Access *map[string]bool `json:"access,omitempty"`
// ClientRoles *map[string][]string `json:"clientRoles,omitempty"`
// RealmRoles *[]string `json:"realmRoles,omitempty"`
// Groups *[]string `json:"groups,omitempty"`
// FederationLink *string `json:"federationLink,omitempty"`
// Totp *bool `json:"totp,omitempty"`
// connection *Connection
func (connection *Connection) Block(user *UserInstance) error {
user.Enabled = false
return connection.EditUser(user)
}
/*func (c *Connection) RefreshToken(input *JWT) (*JWT,error) {
input.
}*/
// Login sends a POST request to the specified endpoint with the provided username, password, client ID, client secret, and grant type.
// It returns a JWT (JSON Web Token) and an error if any.
// The JWT contains access token, ID token, expiration duration, refresh expiration duration, refresh token, token type, not before policy, session state, and scope.
func (connection *Connection) Login(username, password string) (*JWT, error) {
result, err := connection.Post("", "/protocol/openid-connect/token", curl.Param{
"username": username,
"password": password,
"client_id": connection.Settings.Client,
"client_secret": connection.Settings.ClientSecret,
"grant_type": "password",
})
if err != nil {
return nil, err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return nil, fmt.Errorf(parsed.Get("error").String())
}
var j JWT
err = json.Unmarshal(result.Bytes(), &j)
if err != nil {
return nil, err
}
//c.Admin = &jwt
return &j, nil
}
// ChangePassword updates the password for a given user in the specified realm.
// It sends a PUT request to the server's reset-password endpoint, providing the user ID and new password as JSON payload.
// The access token of the admin user is used for authentication.
// If the request is successful and the response status code is 204, it returns nil.
// If the response body contains an error message, it returns an error with the error message.
// If any error occurs during the request or parsing of the response, it returns the error.
// If the response status code is not 204 and the error message is empty, it returns an error message "unable to change password".
func (connection *Connection) ChangePassword(user *UserInstance, password string) error {
resp, err := connection.Put("admin", "/users/"+user.UUID+"/reset-password", curl.BodyJSON(
map[string]interface{}{
"temporary": false,
"type": "password",
"value": password,
}))
if err != nil {
return err
}
if resp.Response().StatusCode == 204 {
return nil
}
var result = gjson.Parse(resp.String())
if connection.Settings.Debug {
fmt.Println(resp.Dump())
}
if result.Get("error").String() != "" {
return fmt.Errorf(result.Get("error").String())
}
return fmt.Errorf("unable to change password")
}
// ResetPasswordOtpIsValid checks if the provided OTP (One-Time Password) is valid for a given user.
// It queries the database for a reset entry matching the user ID and OTP, and checks if it was created within the last hour.
// If a matching reset entry is found, the method returns true; otherwise, it returns false.
//
// Parameters:
// - otp: The One-Time Password to validate.
// - user: The user for whom the OTP is being validated.
//
// Returns:
// - bool: true if the OTP is valid, false otherwise.
func (connection *Connection) ResetPasswordOtpIsValid(otp string, user *UserInstance) bool {
var reset Reset
if evo.GetDBO().Where("uuid = ? AND otp = ? AND created_at > DATE_SUB(NOW(),INTERVAL 1 HOUR)", user.UUID, otp).Take(&reset).RowsAffected == 0 {
return false
}
return true
}
// ResetPasswordRequest sends a request to reset the password for a user.
// It creates a new Reset struct with the given user ID and a random OTP (One-Time Password).
// The Used field is set to false.
// The Reset struct is saved in the database using the GetDBO() function from evo package.
// If an error occurs during the database save operation, it is returned along with the reset struct.
// Otherwise, the reset struct and nil error are returned.
func (connection *Connection) ResetPasswordRequest(user *UserInstance) (Reset, error) {
var reset = Reset{
IDUser: user.UUID,
OTP: text.Random(32),
Used: false,
}
var err = evo.GetDBO().Create(&reset).Error
return reset, err
}
// CreateUser creates a new user in the system using the provided user object.
// It takes a reference to a Connection object and a pointer to a User object.
// It returns an error if any during the creation process.
func (connection *Connection) CreateUser(user *UserInstance) error {
result, err := connection.Post("admin", "/users", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
}, curl.BodyJSON(user), timeout)
if err != nil && err.Error() != "unexpected end of JSON input" {
return err
}
if err != nil {
return err
}
if result.Response().StatusCode == 409 {
return fmt.Errorf("duplicate user")
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return fmt.Errorf(parsed.Get("error").String())
}
if result.Response().StatusCode > 299 {
return fmt.Errorf("unable to create user")
}
// Extract UUID from Location header since Keycloak returns empty body
// Location header format: https://.../admin/realms/{realm}/users/{uuid}
location := result.Response().Header.Get("Location")
if location != "" {
parts := strings.Split(location, "/")
if len(parts) > 0 {
user.UUID = parts[len(parts)-1]
}
}
// If UUID was extracted, fetch the full user details including createdTimestamp
/* if user.UUID != "" {
u, err = connection.GetUser(user.UUID)
if err != nil {
return err
}
}*/
return nil
}
// RefreshToken sends a request to refresh the JWT token using the provided refresh token.
func (connection *Connection) RefreshToken(refreshToken string) (*JWT, error) {
result, err := connection.Post("", "/protocol/openid-connect/token", curl.Param{
"client_id": connection.Settings.Client,
"grant_type": "refresh_token",
"refresh_token": refreshToken,
"client_secret": connection.Settings.ClientSecret,
})
if err != nil {
return nil, err
}
if connection.Settings.Debug {
fmt.Println(result.Dump())
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return nil, fmt.Errorf(parsed.Get("error").String())
}
var j JWT
err = json.Unmarshal(result.Bytes(), &j)
if err != nil {
return nil, err
}
return &j, nil
}
// EditUser modifies the information of a user in the system.
//
// The user parameter should be a pointer to a User object containing the updated information.
// Returns an error if there is a problem with the API request or if the API returns an error message.
// If the API request is successful, the User object in the connection object is updated with the modified information.
func (connection *Connection) EditUser(user *UserInstance) error {
result, err := connection.Put("admin", "/users/"+user.UUID, curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
}, curl.BodyJSON(user))
if err != nil {
return err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return fmt.Errorf(parsed.Get("error").String())
}
return nil
}
func (connection *Connection) DeleteUser(uuid string) error {
result, err := connection.Delete("admin", "/users/"+uuid, curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
})
if err != nil {
return err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return fmt.Errorf(parsed.Get("error").String())
}
return nil
}
// GetUser retrieves a user with the specified ID from the admin API.
// It returns the user object and any error encountered.
func (connection *Connection) GetUser(id string) (UserInstance, error) {
var user UserInstance
result, err := connection.Get("admin", "/users/"+id, curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
})
if err != nil {
return user, err
}
if msg := gjson.Parse(result.String()).Get("error").String(); msg != "" {
return user, fmt.Errorf(msg)
}
err = json.Unmarshal(result.Bytes(), &user)
if err != nil {
return user, err
}
return user, nil
}
// GetUserRealmRoles retrieves all effective realm roles for a user (including roles from groups and composite roles).
// It takes the user UUID as a parameter and returns a slice of role names.
func (connection *Connection) GetUserRealmRoles(uuid string) ([]string, error) {
var roles []Role
result, err := connection.Get("admin", "/users/"+uuid+"/role-mappings/realm/composite", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
})
if err != nil {
return nil, err
}
if msg := gjson.Parse(result.String()).Get("error").String(); msg != "" {
return nil, fmt.Errorf(msg)
}
err = json.Unmarshal(result.Bytes(), &roles)
if err != nil {
return nil, err
}
var roleNames []string
for _, role := range roles {
roleNames = append(roleNames, role.Name)
}
return roleNames, nil
}
// GetUserRealmRoles retrieves the realm roles for a user by UUID using the default connection.
func GetUserRealmRoles(uuid string) ([]string, error) {
if conn == nil {
return nil, fmt.Errorf("keycloak: not connected")
}
return conn.GetUserRealmRoles(uuid)
}
// GetUserByEmail retrieves a user from the system by their email address.
// The email address is passed as a string argument.
// It returns a User struct representing the user found, and an error if any.
// If the user is not found, it returns an error "user not found".
// The returned User struct contains various user details such as ID, username, first name, last name, email, etc.
// An example usage may be:
//
// user, err := connection.GetUserByEmail("test@example.com")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(user.Username)
func (connection *Connection) GetUserByEmail(email string) (UserInstance, error) {
var user UserInstance
result, err := connection.Get("/admin", "/users?email="+email+"&max=1", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
})
if err != nil {
return user, err
}
if msg := gjson.Parse(result.String()).Get("error").String(); msg != "" {
return user, fmt.Errorf(msg)
}
res := result.String()
data := gjson.Parse(res)
if len(data.Array()) == 0 {
return user, fmt.Errorf("user not found")
}
err = json.Unmarshal([]byte(data.Get("0").String()), &user)
if err != nil {
return user, err
}
return user, nil
}
// Debug sets the debug state of the Connection.
func (connection *Connection) Debug(state bool) {
connection.Settings.Debug = state
}
// VerifyOffline verifies the offline access token and extracts the claims from it.
// It takes the accessToken string and claims interface{}, and returns a Spec and an error.
//
// Finally, the function returns the extracted Spec and nil error.
func (connection *Connection) VerifyOffline(accessToken string, claims interface{}) (Spec, error) {
var spec Spec
token, err := jwt.ParseSigned(accessToken, []jose.SignatureAlgorithm{jose.ES512, jose.HS384, jose.HS256, jose.RS256, jose.SignatureAlgorithm(jose.RSA_OAEP), jose.ES256})
if err != nil {
log.Error(err)
return spec, err
}
err = token.Claims(connection.Certificate, &spec)
if spec.Iat != nil {
spec.AuthTime = int(time.Now().Unix()) - *spec.Iat
}
if err != nil {
return spec, err
}
if claims != nil {
err := token.Claims(connection.Certificate, claims)
if err != nil {
return Spec{}, err
}
}
return spec, nil
}
// ParseToken parses the access token and verifies it online or offline based on the strict flag.
func (connection *Connection) ParseToken(accessToken string, claims interface{}, strict bool) (Spec, error) {
var spec Spec
if strict {
var err = connection.VerifyOnline(accessToken)
if err != nil {
return spec, err
}
}
return connection.VerifyOffline(accessToken, claims)
}
// VerifyOnline verifies if a token is valid by making a POST request to the token introspection endpoint.
// It takes a token as input and returns an error if the token is invalid.
func (connection *Connection) VerifyOnline(token string) error {
var result, err = connection.Post("", "/protocol/openid-connect/token/introspect", curl.Param{
"client_id": connection.Settings.Client,
"client_secret": connection.Settings.ClientSecret,
"token": token,
})
if err != nil {
return err
}
var parsed = gjson.Parse(result.String())
if !parsed.Get("active").Bool() {
return fmt.Errorf("invalid user access token")
}
if parsed.Get("error").String() != "" {
return fmt.Errorf(parsed.Get("error").String())
}
return nil
}
// Impersonate impersonates a user and obtains a JWT token for the specified user.
//
// Parameters:
// - user: The user object representing the user to impersonate.
// - internalToken: Flag indicating whether to request an access token or a refresh token.
// When set to true, a refresh token will be requested. Otherwise, an access token will be requested.
//
// Returns:
// - *JWT: The JWT token obtained after successful impersonation.
// - error: An error if an issue occurs during the impersonation process.
//
// Example usage:
// user := &User{ID: "user123"}
// jwtToken, err := connection.Impersonate(user, true)
//
// if err != nil {
// fmt.Println("Failed to impersonate user:", err)
// return
// }
//
// fmt.Println("Impersonation successful. JWT token:", jwtToken)
//
// Note: The User and JWT types are defined in the code, please refer to their declarations for details.
func (connection *Connection) Impersonate(user *UserInstance, internalToken bool) (*JWT, error) {
var requestTokenType = "urn:ietf:params:oauth:token-type:access_token"
if internalToken {
requestTokenType = "urn:ietf:params:oauth:token-type:refresh_token"
}
result, err := connection.Post("auth", "/protocol/openid-connect/token", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
}, curl.Param{
"requested_subject": user.UUID,
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"client_id": connection.Settings.Client,
"requested_token_type": requestTokenType,
"client_secret": connection.Settings.ClientSecret,
})
if err != nil {
return nil, err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return nil, fmt.Errorf(parsed.Get("error").String())
}
var j JWT
err = json.Unmarshal(result.Bytes(), &j)
if err != nil {
return nil, err
}
return &j, nil
}
// Sessions returns a list of sessions for the specified user.
func (connection *Connection) Sessions(u *UserInstance) ([]Session, error) {
var sessions []Session
var result, err = connection.Get("admin", "/users/"+u.UUID+"/sessions", curl.Header{
"Authorization": "Bearer " + connection.Admin.AccessToken,
})
if err != nil {
return sessions, err
}
var parsed = gjson.Parse(result.String())
if parsed.Get("error").String() != "" {
return sessions, fmt.Errorf(parsed.Get("error").String())
}
err = json.Unmarshal(result.Bytes(), &sessions)
if err != nil {
return nil, err
}
return sessions, nil
}
// LogoutSession logs out a session by making an HTTP DELETE request to the server.
// It takes a session object as a parameter and returns an error if any.
// The session ID is used to construct the URL for the logout request.
// The authorization header is set with the access token of the admin.
// If the response status code is 204, it means the logout was successful and nil error is returned.
// Otherwise, an error is returned indicating the failure to logout.
func (connection *Connection) LogoutSession(session *Session) error {
resp, err := connection.Delete("admin", "/sessions/"+session.ID)
if err != nil {
return err
}
if resp.Response().StatusCode == 204 {
return nil
}
return fmt.Errorf("unable to logout")
}
// LogoutAllSessions logs out all sessions for the given user.
// It sends a POST request to the server's logout endpoint with the user's ID.
// The request is authenticated with the administrator's access token.
// If the request is successful and the server returns a 204 status code, nil error is returned.
// If the request fails or the server returns a different status code, an error is returned with the message "unable to logout".
func (connection *Connection) LogoutAllSessions(user *UserInstance) error {
resp, err := connection.Post("admin", "/users/"+user.UUID+"/logout")
if err != nil {
return err
}
if resp.Response().StatusCode == 204 {
return nil
}
return fmt.Errorf("unable to logout")
}
// Connect establishes a connection using the provided settings.
// It returns a pointer to a Connection object and an error.
func Connect(s ...Settings) (*Connection, error) {
var config Settings
if len(s) == 0 {
if conn != nil {
return conn, nil
}
config = Settings{
Server: settings.Get("AUTH.KEYCLOAK.SERVER").String(),
Realm: settings.Get("AUTH.KEYCLOAK.REALM").String(),
ClientSecret: settings.Get("AUTH.KEYCLOAK.SECRET").String(),
Client: settings.Get("AUTH.KEYCLOAK.CLIENT").String(),
Debug: settings.Get("AUTH.KEYCLOAK.DEBUG").Bool(),
BasePath: settings.Get("AUTH.KEYCLOAK.BASEPATH").String(),
}
} else {
config = s[0]
}
config.Server = strings.TrimRight(config.Server, "/") + "/"
var connection = Connection{
Settings: &config,
}
defer func() {
if len(s) == 0 {
conn = &connection
}
}()
resp, err := connection.Get("", "protocol/openid-connect/certs")
if err != nil {
return &connection, err
}
if config.Debug {
fmt.Println(resp.Dump())
}
connection.Certificate = jose.JSONWebKeySet{}
err = resp.ToJSON(&connection.Certificate)
if err != nil {
log.Error(err)
return &connection, err
}
j, err := connection.UpdateAdminToken(config.Realm)
if err != nil {
log.Error(err)
return &connection, err
}
var claims map[string]interface{}
token, err := connection.ParseToken(j.AccessToken, &claims, false)
if err != nil {
return nil, err
}
if token.Exp != nil && token.Iat != nil {
go func() {
for {
expTime := time.Unix(int64(*token.Exp), 0).Add(-time.Minute)
waitDuration := time.Until(expTime)
now := time.Now()
if now.After(expTime) {
log.Error("keycloak admin token expiration time is too close or already passed.")
waitDuration = 5 * time.Minute
}
time.Sleep(waitDuration)
_, err = connection.UpdateAdminToken(config.Realm)
if err != nil {
log.Error(err)
}
}
}()
} else {
return &connection, fmt.Errorf("invalid admin token")
}
return &connection, nil
}
func SetDebug(v bool) {
if conn == nil {
return
}
conn.Settings.Debug = v
}