online-order/utils/common.go

47 lines
1.1 KiB
Go
Raw Normal View History

2023-10-27 09:51:58 +00:00
package utils
import (
"errors"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
2023-10-27 22:12:56 +00:00
"online-order/entity"
2023-10-27 09:51:58 +00:00
)
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// Function used to parse API response
2023-10-29 23:33:40 +00:00
func ResponseJSON(c *gin.Context, httpCode int, msg string, data interface{}) {
2023-10-27 09:51:58 +00:00
c.JSON(httpCode, Response{
2023-10-29 23:33:40 +00:00
Code: httpCode,
2023-10-27 09:51:58 +00:00
Message: msg,
Data: data,
})
}
// Allow to cypher a given word
func HashString(password string) (string, error) {
if password == "" {
return "", entity.ErrInvalidPassword
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashedPassword), nil
}
// Compare a cyphered word and a plain word
func CheckHashedString(plain_word, hashed_word string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashed_word), []byte(plain_word))
2023-10-27 22:12:56 +00:00
if err == bcrypt.ErrMismatchedHashAndPassword {
2023-10-27 09:51:58 +00:00
return errors.New("incorrect password associated with identifier")
}
return err
}