2024-06-05 15:53:24 +00:00
|
|
|
package libs
|
|
|
|
|
|
|
|
import (
|
2024-06-07 12:52:09 +00:00
|
|
|
"errors"
|
2024-06-05 15:53:24 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/go-playground/validator/v10"
|
2024-06-07 12:52:09 +00:00
|
|
|
"golang-test/types"
|
|
|
|
"net/http"
|
2024-06-05 15:53:24 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-06-07 12:52:09 +00:00
|
|
|
type ValidationErrorsType struct {
|
|
|
|
Errors map[string]string `json:"errors"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetValidationErrors(errs validator.ValidationErrors) ValidationErrorsType {
|
|
|
|
errors := make(map[string]string)
|
2024-06-05 15:53:24 +00:00
|
|
|
for _, err := range errs {
|
|
|
|
errors[err.Field()] = err.Error()
|
|
|
|
}
|
|
|
|
|
2024-06-07 12:52:09 +00:00
|
|
|
return ValidationErrorsType{Errors: errors}
|
2024-06-05 15:53:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func ToSnakeCase(str string) string {
|
|
|
|
var result []rune
|
|
|
|
for i, r := range str {
|
|
|
|
if i > 0 && 'A' <= r && r <= 'Z' {
|
|
|
|
result = append(result, '_')
|
|
|
|
}
|
|
|
|
result = append(result, r)
|
|
|
|
}
|
|
|
|
return strings.ToLower(string(result))
|
|
|
|
}
|
2024-06-07 12:52:09 +00:00
|
|
|
|
|
|
|
func GetTokenFromHeaders(c *gin.Context) (string, error) {
|
|
|
|
if c.Request.Header["Authorization"] == nil {
|
|
|
|
return "", errors.New("Authorization required")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(strings.Split(c.Request.Header["Authorization"][0], " ")) < 2 {
|
|
|
|
c.JSON(http.StatusUnauthorized, types.ErrorResponse{Message: "Invalid token. Please login"})
|
|
|
|
return "", errors.New("Authorization required")
|
|
|
|
}
|
|
|
|
token := strings.Split(c.Request.Header["Authorization"][0], " ")[1]
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|