[server][core] move password verification functions into separate package

This commit is contained in:
Abhishek Shroff
2024-10-24 21:35:04 +05:30
parent 4c61cac059
commit dcdfa43c4d
3 changed files with 8 additions and 5 deletions
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/shroff/phylum/server/internal/core/db"
"github.com/shroff/phylum/server/internal/core/errors"
"github.com/shroff/phylum/server/internal/core/util/crypt"
"golang.org/x/exp/rand"
)
@@ -28,7 +29,7 @@ func (m manager) VerifyUserPassword(email, password string) (User, error) {
}
return User{}, err
} else {
if b, err := verifyPassword(password, user.PasswordHash); err != nil {
if b, err := crypt.VerifyPassword(password, user.PasswordHash); err != nil {
return User{}, err
} else if !b {
return User{}, ErrCredentialsInvalid
+2 -1
View File
@@ -7,12 +7,13 @@ import (
"github.com/google/uuid"
"github.com/shroff/phylum/server/internal/core/db"
"github.com/shroff/phylum/server/internal/core/errors"
"github.com/shroff/phylum/server/internal/core/util/crypt"
)
var ErrUserExists = errors.NewError(http.StatusNotFound, "user_already_exists", "user already exists")
func (m manager) CreateUser(username, displayName, password string, root uuid.UUID) (User, error) {
if hash, err := generateArgon2EncodedHash(password, defaultArgon2Params()); err != nil {
if hash, err := crypt.GenerateArgon2EncodedHash(password); err != nil {
return User{}, err
} else if u, err := m.db.CreateUser(m.ctx, db.CreateUserParams{
Username: username,
@@ -1,4 +1,4 @@
package user
package crypt
import (
"crypto/rand"
@@ -29,7 +29,8 @@ func defaultArgon2Params() Argon2Params {
}
}
func generateArgon2EncodedHash(password string, p Argon2Params) (string, error) {
func GenerateArgon2EncodedHash(password string) (string, error) {
p := defaultArgon2Params()
salt, err := generateRandomBytes(p.salt)
if err != nil {
return "", err
@@ -44,7 +45,7 @@ func generateArgon2EncodedHash(password string, p Argon2Params) (string, error)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash), nil
}
func verifyPassword(password, encodedHash string) (bool, error) {
func VerifyPassword(password, encodedHash string) (bool, error) {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeHash(encodedHash)