Skip to content

Commit

Permalink
Updated mongodb driver (cesanta#316)
Browse files Browse the repository at this point in the history
  • Loading branch information
joda01 authored Sep 1, 2021
1 parent 49df24f commit dd934c6
Show file tree
Hide file tree
Showing 5 changed files with 240 additions and 78 deletions.
55 changes: 23 additions & 32 deletions auth_server/authn/mongo_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@
package authn

import (
"context"
"errors"
"fmt"
"io"
"time"

"github.com/cesanta/glog"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/crypto/bcrypt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"

"github.com/cesanta/docker_auth/auth_server/api"
"github.com/cesanta/docker_auth/auth_server/mgo_session"
Expand All @@ -38,7 +40,7 @@ type MongoAuthConfig struct {

type MongoAuth struct {
config *MongoAuthConfig
session *mgo.Session
session *mongo.Client
Collection string `yaml:"collection,omitempty"`
}

Expand All @@ -54,29 +56,22 @@ func NewMongoAuth(c *MongoAuthConfig) (*MongoAuth, error) {
if err != nil {
return nil, err
}

// Copy our session
tmp_session := session.Copy()
// Close up when we are done
defer tmp_session.Close()

// determine collection
collection := tmp_session.DB(c.MongoConfig.DialInfo.Database).C(c.Collection)
collection := session.Database(c.MongoConfig.DialInfo.Database).Collection(c.Collection)

// Create username index obj
index := mgo.Index{
Key: []string{"username"},
Unique: true,
DropDups: false, // Error on duplicate key document instead of drop.
index := mongo.IndexModel{
Keys: bson.M{"username": 1},
Options: options.Index().SetUnique(true),
}

// Enforce a username index. This is fine to do frequently per the docs:
// https://godoc.org/gopkg.in/mgo.v2#Collection.EnsureIndex:
// Once EnsureIndex returns successfully, following requests for the same index
// will not contact the server unless Collection.DropIndex is used to drop the same
// index, or Session.ResetIndexCache is called.
if err := collection.EnsureIndex(index); err != nil {
return nil, err
// Enforce a username index.
// mongodb will do no operation if index still exists.
// see: https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Collection.Indexes
_, erri := collection.Indexes().CreateOne(context.TODO(), index)
if erri != nil {
fmt.Println(erri.Error())
return nil, erri
}

return &MongoAuth{
Expand All @@ -100,20 +95,19 @@ func (mauth *MongoAuth) Authenticate(account string, password api.PasswordString
}

func (mauth *MongoAuth) authenticate(account string, password api.PasswordString) (bool, api.Labels, error) {
// Copy our session
tmp_session := mauth.session.Copy()
// Close up when we are done
defer tmp_session.Close()

// Get Users from MongoDB
glog.V(2).Infof("Checking user %s against Mongo Users. DB: %s, collection:%s",
account, mauth.config.MongoConfig.DialInfo.Database, mauth.config.Collection)
var dbUserRecord authUserEntry
collection := tmp_session.DB(mauth.config.MongoConfig.DialInfo.Database).C(mauth.config.Collection)
err := collection.Find(bson.M{"username": account}).One(&dbUserRecord)
collection := mauth.session.Database(mauth.config.MongoConfig.DialInfo.Database).Collection(mauth.config.Collection)


filter := bson.D{{"username", account}}
err := collection.FindOne(context.TODO(), filter).Decode(&dbUserRecord)

// If we connect and get no results we return a NoMatch so auth can fall-through
if err == mgo.ErrNotFound {
if err == mongo.ErrNoDocuments {
return false, nil, api.NoMatch
} else if err != nil {
return false, nil, err
Expand Down Expand Up @@ -147,10 +141,7 @@ func (c *MongoAuthConfig) Validate(configKey string) error {
}

func (ma *MongoAuth) Stop() {
// Close connection to MongoDB database (if any)
if ma.session != nil {
ma.session.Close()
}

}

func (ga *MongoAuth) Name() string {
Expand Down
59 changes: 35 additions & 24 deletions auth_server/authz/acl_mongo.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package authz

import (
"context"
"errors"
"fmt"
"io"
"log"
"sync"
"time"

"github.com/cesanta/glog"
"gopkg.in/mgo.v2"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"gopkg.in/mgo.v2/bson"

"github.com/cesanta/docker_auth/auth_server/api"
Expand All @@ -33,7 +36,8 @@ type aclMongoAuthorizer struct {
lock sync.RWMutex
config *ACLMongoConfig
staticAuthorizer api.Authorizer
session *mgo.Session
session *mongo.Client
context context.Context
updateTicker *time.Ticker
Collection string `yaml:"collection,omitempty"`
CacheTTL time.Duration `yaml:"cache_ttl,omitempty"`
Expand Down Expand Up @@ -99,9 +103,6 @@ func (ma *aclMongoAuthorizer) Stop() {
ma.updateTicker.Stop()

// Close connection to MongoDB database (if any)
if ma.session != nil {
ma.session.Close()
}
}

func (ma *aclMongoAuthorizer) Name() string {
Expand Down Expand Up @@ -139,35 +140,45 @@ func (ma *aclMongoAuthorizer) updateACLCache() error {
// Get ACL from MongoDB
var newACL MongoACL

// Copy our session
tmp_session := ma.session.Copy()

// Close up when we are done
defer tmp_session.Close()

collection := tmp_session.DB(ma.config.MongoConfig.DialInfo.Database).C(ma.config.Collection)
collection := ma.session.Database(ma.config.MongoConfig.DialInfo.Database).Collection(ma.config.Collection)

// Create sequence index obj
index := mgo.Index{
Key: []string{"seq"},
Unique: true,
DropDups: false, // Error on duplicate key document instead of drop.
// Create username index obj
index := mongo.IndexModel{
Keys: bson.M{"seq": 1},
Options: options.Index().SetUnique(true),
}

// Enforce a sequence index. This is fine to do frequently per the docs:
// https://godoc.org/gopkg.in/mgo.v2#Collection.EnsureIndex:
// Once EnsureIndex returns successfully, following requests for the same index
// will not contact the server unless Collection.DropIndex is used to drop the same
// index, or Session.ResetIndexCache is called.
if err := collection.EnsureIndex(index); err != nil {
// Enforce a username index.
// mongodb will do no operation if index still exists.
// see: https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Collection.Indexes
_, err := collection.Indexes().CreateOne(context.TODO(), index)
if err != nil {
fmt.Println(err.Error())
return err
}

// Get all ACLs that have the required key
if err := collection.Find(bson.M{}).Sort("seq").All(&newACL); err != nil {
cur, err := collection.Find(context.TODO(), bson.M{})

if err != nil {
return err
}

defer cur.Close(context.TODO())
for cur.Next(context.TODO()) {
var result MongoACLEntry
err := cur.Decode(&result) //Sort("seq")
if err != nil {
log.Fatal(err)
} else {
newACL = append(newACL, result)
}
// do something with result....
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}

glog.V(2).Infof("Number of new ACL entries from MongoDB: %d", len(newACL))

// It is possible that the top document in the collection exists with a nil Seq.
Expand Down
1 change: 1 addition & 0 deletions auth_server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ require (
github.com/schwarmco/go-cartesian-product v0.0.0-20180515110546-d5ee747a6dc9
github.com/sirupsen/logrus v1.8.0 // indirect
github.com/syndtr/goleveldb v1.0.0
go.mongodb.org/mongo-driver v1.7.1
go.opencensus.io v0.23.0 // indirect
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
Expand Down
Loading

0 comments on commit dd934c6

Please sign in to comment.