Skip to content

Instantly share code, notes, and snippets.

@xyproto
Last active March 29, 2022 16:13
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/60939b7580fae915f2905ac1c1a3f1f9 to your computer and use it in GitHub Desktop.
Save xyproto/60939b7580fae915f2905ac1c1a3f1f9 to your computer and use it in GitHub Desktop.
package main
//
// Example program for checking errors when adding users.
//
// HOWEVER it might be better to instead check that the values are as expected
// in the Redis database AFTER adding them.
//
import (
"log"
permissions "github.com/xyproto/permissions2"
"github.com/xyproto/simpleredis"
)
// Add a user, while also checking for error values
func AddUserWithCheck(state *permissions.UserState, username, password, email string) error {
// Create a password hash
passwordHash := state.HashPassword(username, password)
pool := state.Pool()
dbindex := state.DatabaseIndex()
// Get a variable for state.usernames
stateUsernames := simpleredis.NewSet(pool, "usernames")
stateUsernames.SelectDatabase(dbindex)
// Add user
if err := stateUsernames.Add(username); err != nil {
return err
}
// Get a variable for state.users
stateUsers := simpleredis.NewHashMap(pool, "users")
stateUsers.SelectDatabase(dbindex)
// Add password
if err := stateUsers.Set(username, "password", passwordHash); err != nil {
return err
}
// Add email
if err := stateUsers.Set(username, "email", email); err != nil {
return err
}
// Additional fields
additionalfields := []string{"loggedin", "confirmed", "admin"}
for _, fieldname := range additionalfields {
if err := stateUsers.Set(username, fieldname, "false"); err != nil {
return err
}
}
// Success
return nil
}
func main() {
state := permissions.NewUserStateSimple()
username := "bob"
password := "hunter1"
email := "bob@zombo.com"
if err := AddUserWithCheck(state, username, password, email); err != nil {
log.Fatalln(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment