Skip to content

Commit

Permalink
add username/password to mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
alexferl committed Sep 24, 2019
1 parent 72b221c commit 5fe2cd6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions backend/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const (
)

type MongoDBBackend struct {
Username string
Password string
Session *mgo.Session
Timeout time.Duration
Uri string
Expand All @@ -41,6 +43,10 @@ func (mb *MongoDBBackend) Init() (err error) {

for {
mb.Session, err = mgo.DialWithTimeout(mb.Uri, mb.Timeout)
if mb.Username != "" && mb.Password != "" {
creds := mgo.Credential{Username: mb.Username, Password: mb.Password}
err = mb.Session.Login(&creds)
}
if err != nil {
d := b.Duration()
logrus.Errorf("%s, reconnecting in %s", err, d)
Expand Down
8 changes: 8 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ type Config struct {
}

type MongoDBBackend struct {
Username string
Password string
Timeout time.Duration
Uri string
}
Expand All @@ -40,6 +42,8 @@ func NewConfig() *Config {
LogRequestsDisabled: false,
BackendType: "mongodb",
MongoDBBackend: MongoDBBackend{
Username: "",
Password: "",
Timeout: time.Duration(5) * time.Second,
Uri: "mongodb://127.0.0.1",
},
Expand All @@ -62,6 +66,10 @@ func (cnf *Config) addFlags(fs *pflag.FlagSet) {
fs.BoolVar(&cnf.LogRequestsDisabled, "log-requests-disabled", cnf.LogRequestsDisabled, "Log HTTP requests.")
fs.StringVar(&cnf.BackendType, "backend-type", cnf.BackendType,
"Type of backend to use to store short URLs")
fs.StringVar(&cnf.MongoDBBackend.Username, "backend-mongodb-username", cnf.MongoDBBackend.Username,
"MongoDB username")
fs.StringVar(&cnf.MongoDBBackend.Password, "backend-mongodb-password", cnf.MongoDBBackend.Password,
"MongoDB password")
fs.DurationVar(&cnf.MongoDBBackend.Timeout, "backend-mongodb-timeout", cnf.MongoDBBackend.Timeout,
"Timeout connecting/reading/writing to MongoDB")
fs.StringVar(&cnf.MongoDBBackend.Uri, "backend-mongodb-uri", cnf.MongoDBBackend.Uri,
Expand Down

0 comments on commit 5fe2cd6

Please sign in to comment.