1
|
|
|
package auth |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
|
6
|
|
|
"github.com/memnix/memnix-rest/infrastructures" |
7
|
|
|
"github.com/memnix/memnix-rest/pkg/crypto" |
8
|
|
|
"github.com/pkg/errors" |
9
|
|
|
) |
10
|
|
|
|
11
|
|
|
// GenerateEncryptedPassword generates a password hash using the crypto helper. |
12
|
|
|
func GenerateEncryptedPassword(ctx context.Context, password string) ([]byte, error) { |
13
|
|
|
_, span := infrastructures.GetTracerInstance().Tracer().Start(ctx, "GenerateEncryptedPassword") |
14
|
|
|
defer span.End() |
15
|
|
|
hash, err := crypto.GetCryptoHelperInstance().GetCryptoHelper().Hash(password) |
16
|
|
|
if err != nil { |
17
|
|
|
return nil, err |
18
|
|
|
} |
19
|
|
|
return hash, nil |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
// ComparePasswords compares a hashed password with its possible plaintext equivalent. |
23
|
|
|
// |
24
|
|
|
// password is the plaintext password to verify. |
25
|
|
|
// hash is the bcrypt hashed password. |
26
|
|
|
// |
27
|
|
|
// Returns true if the password matches, false if it does not. |
28
|
|
|
// Returns nil on success, or an error on failure. |
29
|
|
|
func ComparePasswords(ctx context.Context, password string, hash []byte) (bool, error) { |
30
|
|
|
_, span := infrastructures.GetTracerInstance().Tracer().Start(ctx, "ComparePasswords") |
31
|
|
|
defer span.End() |
32
|
|
|
return crypto.GetCryptoHelperInstance().GetCryptoHelper().Verify(password, hash) |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// VerifyPassword verifies a password |
36
|
|
|
// Returns an error if the password is invalid. |
37
|
|
|
func VerifyPassword(password string) error { |
38
|
|
|
// Convert password to byte array |
39
|
|
|
passwordBytes := []byte(password) |
40
|
|
|
if len(passwordBytes) < crypto.MinPasswordLength { |
41
|
|
|
return errors.New("password too short") |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if len(passwordBytes) > crypto.MaxPasswordLength { |
45
|
|
|
return errors.New("password too long") |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return nil |
49
|
|
|
} |
50
|
|
|
|