Skip to content

authentication tool #4277

@j1m1l0k0

Description

@j1m1l0k0

Describe the feature you would like to see

// use -> ./passgen --username=john.doe --email=[email protected] --name="John Doe" --password=123"
// or with --file (optimal) -> ./passgen --username=john.doe --email=[email protected] --name="John Doe" --password=123" --file users.yml

package main

import (
"flag"
"fmt"
"os"

"golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v3"

)

type User struct {
Email string yaml:"email"
Name string yaml:"name"
Password string yaml:"password"
}

type UsersFile struct {
Users map[string]User yaml:"users"
}

func main() {
// Command-line arguments
file := flag.String("file", "users.yml", "Path to the users YAML file (optional)")
username := flag.String("username", "", "Username (key name in users.yml)")
email := flag.String("email", "", "User email")
name := flag.String("name", "", "User full name")
password := flag.String("password", "", "User password (plaintext, will be hashed with bcrypt)")

flag.Parse()

// Required fields validation
if *username == "" || *email == "" || *name == "" || *password == "" {
	fmt.Println("Error: --username, --email, --name and --password are all required.")
	fmt.Println("Optional: --file=path/to/users.yml")
	return
}

filename := *file

// Load existing file if it exists
var usersFile UsersFile
if data, err := os.ReadFile(filename); err == nil {
	if err := yaml.Unmarshal(data, &usersFile); err != nil {
		fmt.Println("Error parsing YAML file:", err)
		return
	}
}

// Ensure map is initialized
if usersFile.Users == nil {
	usersFile.Users = make(map[string]User)
}

// Generate bcrypt hash
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
if err != nil {
	fmt.Println("Error generating bcrypt hash:", err)
	return
}

// Create the new user entry
newUser := User{
	Email:    *email,
	Name:     *name,
	Password: string(hashedPassword),
}

// Add or update the user
usersFile.Users[*username] = newUser

// Convert struct back to YAML
out, err := yaml.Marshal(&usersFile)
if err != nil {
	fmt.Println("Error writing YAML:", err)
	return
}

// Save file
if err := os.WriteFile(filename, out, 0644); err != nil {
	fmt.Println("Error saving file:", err)
	return
}

fmt.Printf("User '%s' added or updated successfully in %s!\n", *username, filename)

}

Describe how you would like to see this feature implemented

No response

Describe any alternatives you've considered

I wrote this small utility in Go so that you can generate access for multiple users while maintaining the existing ones in users.yml. I hope it helps with your project! Good luck and success.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions