Skip to content

Instantly share code, notes, and snippets.

@xyproto
Created October 3, 2018 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xyproto/1e37bdf1e5d07538ff971534b6ac73e1 to your computer and use it in GitHub Desktop.
Save xyproto/1e37bdf1e5d07538ff971534b6ac73e1 to your computer and use it in GitHub Desktop.
List user properties with permissionbolt and simplebolt
package main
import (
"fmt"
"github.com/coreos/bbolt"
"github.com/xyproto/permissionbolt"
"github.com/xyproto/simplebolt"
"log"
"os"
"path"
"strings"
)
// GetProps retrieves the properties for a given username
func GetProps(db *bolt.DB, username string) ([]string, error) {
var props []string
return props, (*bolt.DB)(db).View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte("users"))
if bucket == nil {
return simplebolt.ErrBucketNotFound
}
// Loop through the keys
return bucket.ForEach(func(byteKey, _ []byte) error {
combinedKey := string(byteKey)
if strings.HasPrefix(combinedKey, username+":") {
fields := strings.SplitN(combinedKey, ":", 2)
props = append(props, string(fields[1]))
}
return nil // Continue ForEach
})
})
}
// GetDB retrieves the underlying Bolt database from the permissionbolt.UserState
func GetDB(userstate *permissionbolt.UserState) *bolt.DB {
return (*bolt.DB)(userstate.Database())
}
func main() {
userstate, err := permissionbolt.NewUserState(path.Join(os.TempDir(), "bolt1.db"), true)
if err != nil {
log.Fatal(err)
}
defer userstate.Close()
userstate.AddUser("bob", "hunter1", "bob@zombo.com")
userstate.AddUser("roger", "hunter1", "bob@zombo.com")
userstate.Users().Set("bob", "hello", "yes")
if !userstate.HasUser("bob") {
log.Fatalln("Error, user bob should exist")
}
db := GetDB(userstate)
l, err := GetProps(db, "bob")
fmt.Println(l, err)
l, err = GetProps(db, "roger")
fmt.Println(l, err)
userstate.RemoveUser("bob")
userstate.RemoveUser("roger")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment