71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"os"
|
|
"playback-device-server/users"
|
|
)
|
|
|
|
const DEFAULT_USERNAME = "admin"
|
|
const MIN_PASSWORD_LENGTH = 8
|
|
const USER_DATABASE_DIR = "."
|
|
|
|
func main() {
|
|
userDatabase := users.UserDatabase{}
|
|
userDatabase.SetDirectory(USER_DATABASE_DIR)
|
|
err := userDatabase.Initialize()
|
|
if err != nil {
|
|
fmt.Println(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
defer userDatabase.Close()
|
|
|
|
exists, error := userDatabase.UsernameExists(DEFAULT_USERNAME)
|
|
if error != nil {
|
|
fmt.Println(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
|
|
if !exists {
|
|
password, error := generateRandomPassword(MIN_PASSWORD_LENGTH)
|
|
if error != nil {
|
|
fmt.Println(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
|
|
fmt.Println()
|
|
fmt.Println("Creating default admin user:")
|
|
fmt.Printf("Username: %s\n", DEFAULT_USERNAME)
|
|
fmt.Printf("Password: %s\n", password)
|
|
fmt.Println()
|
|
|
|
user := users.User{Username: DEFAULT_USERNAME, Password: password, IsAdmin: true}
|
|
_, error = userDatabase.CreateUser(user.Username, user.Password, user.IsAdmin)
|
|
if error != nil {
|
|
fmt.Println(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func generateRandomPassword(length int) (string, error) {
|
|
numBytes := length * 3 / 4 // Base64 encoding increases length by 4/3
|
|
|
|
randomBytes := make([]byte, numBytes)
|
|
_, err := rand.Read(randomBytes)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
password := base64.URLEncoding.EncodeToString(randomBytes)
|
|
|
|
if len(password) > length {
|
|
password = password[:length]
|
|
}
|
|
|
|
return password, nil
|
|
}
|