Planner/apis/users.go
Manuel Forcén Muñoz bc6b57bc54 API package refactor
2025-02-12 19:29:00 +01:00

64 lines
1.2 KiB
Go

package apis
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
. "planner/core"
)
func getUserByName(c *gin.Context) {
var q struct {
Name string `fdb:"name"`
}
if c.ShouldBind(&q) == nil {
user := User{
Username: q.Name,
}
db.Take(&user)
fmt.Println(user)
c.JSON(http.StatusOK, user)
}
}
func createUser(c *gin.Context) {
var u User
if c.ShouldBind(&u) == nil {
db.Create(&u)
c.Status(http.StatusCreated)
} else {
fmt.Print("Could not bind model")
c.String(http.StatusInternalServerError, "Unable to bind user")
}
}
func login(c *gin.Context) {
var q struct {
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
}
if c.ShouldBind(&q) == nil {
if q.Username == "" {
c.String(http.StatusBadRequest, "Login data is null")
} else {
user := User{
Username: q.Username,
}
db.Take(&user)
if user.Password == q.Password {
c.JSON(http.StatusOK, map[string]string{"username": user.Username})
} else {
c.Status(http.StatusForbidden)
}
}
} else {
c.String(http.StatusBadRequest, "Unable to bind data")
}
}
func bindUserAPIs(r *gin.Engine) {
r.POST("/login", login)
r.GET("/user", getUserByName)
r.POST("/user", createUser)
}