create global function for password encryption and password match

This commit is contained in:
rinosukmandityo
2020-02-07 21:11:15 +07:00
parent 8201787dd3
commit cff2f200e0
5 changed files with 29 additions and 18 deletions

View File

@@ -2,9 +2,6 @@ package mongo
import (
"context"
"crypto/md5"
"fmt"
"io"
"time"
"github.com/rinosukmandityo/hexagonal-login/helper"
@@ -64,13 +61,9 @@ func (r *loginMongoRepository) Authenticate(username, password string) (bool, *m
}
return false, user, errors.Wrap(e, "repository.Login.Authenticate")
}
tPass := md5.New()
io.WriteString(tPass, password)
ePassword := fmt.Sprintf("%x", tPass.Sum(nil))
if ePassword != user.Password {
if !repo.IsPasswordMatch(password, user.Password) {
return false, user, errors.Wrap(errors.New("Password is incorrect"), "repository.Login.Authenticate")
}
return true, user, nil
}

View File

@@ -93,6 +93,7 @@ func (r *userMongoRepository) Store(user *m.User) error {
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
c := r.client.Database(r.database).Collection(new(m.User).TableName())
user.Password = repo.EncryptPassword(user.Password)
if _, e := c.InsertOne(ctx, user); e != nil {
return errors.Wrap(e, "repository.User.Store")
}

24
repositories/password.go Normal file
View File

@@ -0,0 +1,24 @@
package repositories
import (
"crypto/md5"
"fmt"
"io"
)
func IsPasswordMatch(password, userpass string) bool {
ePassword := EncryptPassword(password)
if ePassword != userpass {
return false
}
return true
}
func EncryptPassword(password string) string {
tPass := md5.New()
io.WriteString(tPass, password)
ePassword := fmt.Sprintf("%x", tPass.Sum(nil))
return ePassword
}

View File

@@ -1,9 +1,7 @@
package redis
import (
"crypto/md5"
"fmt"
"io"
"strconv"
"github.com/rinosukmandityo/hexagonal-login/helper"
@@ -62,12 +60,7 @@ func (r *loginRedisRepository) Authenticate(username, password string) (bool, *m
user.Address = data["Address"]
user.IsActive, _ = strconv.ParseBool(data["IsActive"])
tPass := md5.New()
io.WriteString(tPass, password)
ePassword := fmt.Sprintf("%x", tPass.Sum(nil))
if ePassword != user.Password {
if repo.IsPasswordMatch(password, user.Password) {
return false, user, errors.Wrap(errors.New("Password is incorrect"), "repository.Login.Authenticate")
}
return true, user, nil

View File

@@ -86,7 +86,7 @@ func (r *userRedisRepository) Store(user *m.User) error {
"ID": user.ID,
"Username": user.Username,
"Email": user.Email,
"Password": user.Password,
"Password": repo.EncryptPassword(user.Password),
"Name": user.Name,
"Address": user.Address,
"IsActive": user.IsActive,