S SmartDocs
Serie: Go go 34 righe · Aggiornato 2026-04-18

password.go

Go/Baasid/internal/auth/password.go

// Package auth contains password hashing and JWT utilities used by the
// authentication layer. Keeping these helpers separate from HTTP handlers
// makes them trivial to unit-test without spinning up Echo.
package auth

import (
	"fmt"

	"golang.org/x/crypto/bcrypt"
)

// bcryptCost controls how CPU-intensive hashing is. 10 is the library default
// and a good balance for interactive login on modern hardware.
const bcryptCost = 10

// HashPassword returns a bcrypt hash suitable for storing in system_user.password.
func HashPassword(plain string) (string, error) {
	if plain == "" {
		return "", fmt.Errorf("empty password")
	}
	b, err := bcrypt.GenerateFromPassword([]byte(plain), bcryptCost)
	if err != nil {
		return "", fmt.Errorf("bcrypt: %w", err)
	}
	return string(b), nil
}

// CheckPassword compares plaintext with a bcrypt hash and returns true on match.
func CheckPassword(hash, plain string) bool {
	if hash == "" || plain == "" {
		return false
	}
	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
}

Articoli correlati