Planner/apis/users.go

70 lines
1.5 KiB
Go
Raw Normal View History

2025-02-12 19:29:00 +01:00
package apis
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
2025-04-16 23:24:23 +02:00
"planner/core"
2025-02-12 19:29:00 +01:00
)
func getUserByName(c *gin.Context) {
var q struct {
Name string `fdb:"name"`
}
if c.ShouldBind(&q) == nil {
2025-04-16 23:24:23 +02:00
user, err := core.UserGet(db, q.Name)
if err != nil {
c.String(http.StatusInternalServerError, "Unable to get user: "+err.Error())
return
2025-02-12 19:29:00 +01:00
}
c.JSON(http.StatusOK, user)
}
}
func createUser(c *gin.Context) {
2025-04-16 23:24:23 +02:00
var u core.User
2025-02-12 19:29:00 +01:00
if c.ShouldBind(&u) == nil {
2025-04-16 23:24:23 +02:00
err := u.Create(db)
if err != nil {
c.String(http.StatusInternalServerError, "Unable to create user: "+err.Error())
return
}
2025-02-12 19:29:00 +01:00
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 {
2025-04-16 23:24:23 +02:00
user, err := core.UserGet(db, q.Username)
if err != nil {
c.String(http.StatusInternalServerError, "Unable to get user: "+err.Error())
return
2025-02-12 19:29:00 +01:00
}
if user.Password == q.Password {
2025-04-16 23:24:23 +02:00
c.JSON(http.StatusOK, gin.H{"username": user.Username})
2025-02-12 19:29:00 +01:00
} 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)
}