Created
October 3, 2018 16:06
-
-
Save xyproto/1e37bdf1e5d07538ff971534b6ac73e1 to your computer and use it in GitHub Desktop.
List user properties with permissionbolt and simplebolt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", "[email protected]") | |
userstate.AddUser("roger", "hunter1", "[email protected]") | |
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