From 43968452fb970eb69606a76033f33bcbba83d807 Mon Sep 17 00:00:00 2001 From: QLeelulu Date: Tue, 20 Nov 2018 11:41:40 +0800 Subject: [PATCH] mongo auth with authSource --- conf/files/db.json.sample | 5 +++++ db/mgo.go | 29 +++++++++++++++++++---------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/conf/files/db.json.sample b/conf/files/db.json.sample index f7d63bb..413b0b5 100644 --- a/conf/files/db.json.sample +++ b/conf/files/db.json.sample @@ -3,6 +3,11 @@ "127.0.0.1:27017" ], "Database": "cronsun", + "#AuthSource": "AuthSource Specify the database name associated with the user’s credentials.", + "#AuthSource": "AuthSource defaults to the cronsun's Database.", + "#AuthSource": "If connect mongodb like './bin/mongo mytest -u "test" -p "123" --authenticationDatabase admin' ,", + "#AuthSource": "the AuthSource is 'admin'. ", + "AuthSource": "", "UserName": "", "Password": "", "#Timeout": "connect timeout duration/second", diff --git a/db/mgo.go b/db/mgo.go index 50d500e..329e45a 100644 --- a/db/mgo.go +++ b/db/mgo.go @@ -1,6 +1,7 @@ package db import ( + "net/url" "strings" "time" @@ -9,11 +10,14 @@ import ( ) type Config struct { - Hosts []string - UserName string - Password string - Database string - Timeout time.Duration // second + Hosts []string + // AuthSource Specify the database name associated with the user’s credentials. + // authSource defaults to the database specified in the connection string. + AuthSource string + UserName string + Password string + Database string + Timeout time.Duration // second } type Mdb struct { @@ -29,17 +33,22 @@ func NewMdb(c *Config) (*Mdb, error) { } func (m *Mdb) connect() error { - // url: [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options] - url := strings.Join(m.Config.Hosts, ",") + // connectionString: [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options] + // via: https://docs.mongodb.com/manual/reference/connection-string/ + connectionString := strings.Join(m.Config.Hosts, ",") if len(m.Config.UserName) > 0 && len(m.Config.Password) > 0 { - url = m.Config.UserName + ":" + m.Config.Password + "@" + url + connectionString = m.Config.UserName + ":" + url.QueryEscape(m.Config.Password) + "@" + connectionString } if len(m.Config.Database) > 0 { - url += "/" + m.Config.Database + connectionString += "/" + m.Config.Database } - session, err := mgo.DialWithTimeout(url, m.Config.Timeout) + if len(m.Config.AuthSource) > 0 { + connectionString += "?authSource=" + m.Config.AuthSource + } + + session, err := mgo.DialWithTimeout(connectionString, m.Config.Timeout) if err != nil { return err }