initial auth route
This commit is contained in:
@@ -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})
|
||||
}
|
||||
@@ -6,4 +6,6 @@ func Setup(app *fiber.App) {
|
||||
|
||||
app.Get("/", GetVersion)
|
||||
|
||||
app.Post("/login", Login)
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user