Gluecode for database/handlers

This commit is contained in:
Imbus 2024-03-12 20:44:40 +01:00
parent ad4d439887
commit 9b67a580da
4 changed files with 55 additions and 6 deletions

View file

@ -12,7 +12,9 @@ import (
// Interface for the database
type Database interface {
// Insert a new user into the database, password should be hashed before calling
AddUser(username string, password string) error
RemoveUser(username string) error
PromoteToAdmin(username string) error
GetUserId(username string) (int, error)

View file

@ -15,7 +15,7 @@ type GlobalState interface {
UserDelete(c *fiber.Ctx) error // To delete a user
Login(c *fiber.Ctx) error // To get the token
LoginRenew(c *fiber.Ctx) error // To renew the token
// CreateProject(c *fiber.Ctx) error // To create a new project
CreateProject(c *fiber.Ctx) error // To create a new project
// GetProjects(c *fiber.Ctx) error // To get all projects
// GetProject(c *fiber.Ctx) error // To get a specific project
// UpdateProject(c *fiber.Ctx) error // To update a project
@ -58,7 +58,7 @@ type GState struct {
// @Failure 500 {string} string "Internal server error"
// @Router /api/register [post]
func (gs *GState) Register(c *fiber.Ctx) error {
u := new(types.User)
u := new(types.NewUser)
if err := c.BodyParser(u); err != nil {
return c.Status(400).SendString(err.Error())
}
@ -142,3 +142,24 @@ func (gs *GState) LoginRenew(c *fiber.Ctx) error {
}
return c.JSON(fiber.Map{"token": t})
}
// CreateProject is a simple handler that creates a new project
func (gs *GState) CreateProject(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
p := new(types.NewProject)
if err := c.BodyParser(p); err != nil {
return c.Status(400).SendString(err.Error())
}
// Get the username from the token and set it as the owner of the project
// This is ugly but
claims := user.Claims.(jwt.MapClaims)
p.Owner = claims["name"].(string)
if err := gs.Db.AddProject(p.Name, p.Description, p.Owner); err != nil {
return c.Status(500).SendString(err.Error())
}
return c.Status(200).SendString("Project added")
}

View file

@ -0,0 +1,21 @@
package types
import (
"time"
)
// Project is a struct that holds the information about a project
type Project struct {
ID int `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Description string `json:"description" db:"description"`
Owner string `json:"owner" db:"owner"`
Created time.Time `json:"created" db:"created"`
}
// As it arrives from the client
type NewProject struct {
Name string `json:"name"`
Description string `json:"description"`
Owner string `json:"owner"`
}

View file

@ -16,6 +16,11 @@ func (u *User) ToPublicUser() (*PublicUser, error) {
}, nil
}
type NewUser struct {
Username string `json:"username"`
Password string `json:"password"`
}
// PublicUser represents a user that is safe to send over the API (no password)
type PublicUser struct {
UserId string `json:"userId"`