Passed
Pull Request — main (#166)
by Yume
01:56
created

auth.GenerateEncryptedPassword   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
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