auth.ComparePasswords   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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