initial auth route

This commit is contained in:
2023-08-15 14:48:55 -03:00
parent a47d9727ad
commit 4d1884f3a4
7 changed files with 166 additions and 5 deletions
+70
View File
@@ -0,0 +1,70 @@
package routes
import (
"api/models"
"log"
"os"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
)
func Login(c *fiber.Ctx) error {
var data map[string]string
if err := c.BodyParser(&data); err != nil {
log.Printf("Bad Request on parse: %v\n", err)
return fiber.ErrBadRequest
}
var user models.User
if user.Id == 0 {
return c.JSON(fiber.Map{
"message": "Usuário não encontrado",
"userId": 0,
"userType": "",
"userName": "",
"token": ""})
}
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["password"])); err != nil {
return c.JSON(fiber.Map{
"message": "Senha inválida",
"userId": 0,
"userType": "",
"userName": "",
"token": ""})
}
type customClaims struct {
Userid string `json:"user"`
jwt.StandardClaims
}
tok := customClaims{
Userid: strconv.Itoa(int(user.Id)),
StandardClaims: jwt.StandardClaims{
Issuer: strconv.Itoa(int(user.Id)),
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
},
}
claims := jwt.NewWithClaims(jwt.SigningMethodHS256, tok)
token, err := claims.SignedString([]byte(os.Getenv("API_SECRET")))
if err != nil {
return fiber.ErrInternalServerError
}
return c.JSON(fiber.Map{
"message": "",
"userId": user.Id,
"userType": user.UserType,
"userName": user.Name,
"token": token})
}
+2
View File
@@ -6,4 +6,6 @@ func Setup(app *fiber.App) {
app.Get("/", GetVersion)
app.Post("/login", Login)
}