add authentication method
Some checks failed
CI / test-build (push) Failing after 2m1s

This commit is contained in:
2025-12-14 23:55:12 +07:00
parent ed96137bad
commit 54e76d9304
18 changed files with 2197 additions and 34 deletions

51
internal/auth/service.go Normal file
View File

@@ -0,0 +1,51 @@
package auth
import (
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/bcrypt"
)
// Service provides authentication operations
type Service struct {
jwtSecret []byte
}
// New creates a new auth service
func New(secret string) *Service {
if secret == "" {
// Generate a random secret if not provided (not recommended for production)
secret = generateSecret()
}
return &Service{
jwtSecret: []byte(secret),
}
}
// HashPassword hashes a password using bcrypt
func (s *Service) HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
// VerifyPassword verifies a password against a hash
func (s *Service) VerifyPassword(hashedPassword, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
// generateSecret generates a random secret for JWT signing
func generateSecret() string {
b := make([]byte, 32)
rand.Read(b)
return base64.URLEncoding.EncodeToString(b)
}
// GetSecret returns the JWT secret
func (s *Service) GetSecret() []byte {
return s.jwtSecret
}