- Add brotli compression (level 5) to long-lived SSE event streams (HandleGameEvents, HandleSnakeEvents) to reduce wire payload - Fix all errcheck violations with nolint annotations for best-effort calls - Fix goimports: separate stdlib, third-party, and local import groups - Fix staticcheck: add package comments, use tagged switch - Zero lint issues remaining
37 lines
868 B
Go
37 lines
868 B
Go
// Package auth provides password hashing and verification using bcrypt.
|
|
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"regexp"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const bcryptCost = 12
|
|
|
|
var usernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`)
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
|
|
return string(hash), err
|
|
}
|
|
|
|
func CheckPassword(password, hash string) bool {
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
|
}
|
|
|
|
func ValidateUsername(username string) error {
|
|
if !usernameRegex.MatchString(username) {
|
|
return errors.New("username must be 3-20 characters, alphanumeric and underscore only")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ValidatePassword(password string) error {
|
|
if len(password) < 8 {
|
|
return errors.New("password must be at least 8 characters")
|
|
}
|
|
return nil
|
|
}
|