Last active
March 29, 2022 16:13
-
-
Save xyproto/60939b7580fae915f2905ac1c1a3f1f9 to your computer and use it in GitHub Desktop.
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 | |
// | |
// 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 := "[email protected]" | |
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