Files
atlas/internal/auth/service.go
othman.suseno 54e76d9304
Some checks failed
CI / test-build (push) Failing after 2m1s
add authentication method
2025-12-14 23:55:12 +07:00

52 lines
1.2 KiB
Go

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
}