This commit is contained in:
2021-01-02 11:56:24 +01:00
parent 39e5c84cf6
commit 96ab03a5fb
12 changed files with 301 additions and 120 deletions

View File

@@ -1,44 +1,76 @@
package handlers
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"gitlab.larvit.se/power-plan/api/src/db"
"gitlab.larvit.se/power-plan/auth/src/db"
"gitlab.larvit.se/power-plan/auth/src/utils"
)
// UserCreate creates a new user
func UserCreate(c *fiber.Ctx) error {
type UserInput struct {
Username string `json:"username"`
Password string `json:"password"`
// AccountCreate creates a new account
func (h Handlers) AccountCreate(c *fiber.Ctx) error {
type AccountInput struct {
AccountName string `json:"accountName"`
Password string `json:"password"`
Fields []db.AccountCreateInputFields `json:"fields"`
}
userInput := new(UserInput)
accountInput := new(AccountInput)
if err := c.BodyParser(userInput); err != nil {
if err := c.BodyParser(accountInput); err != nil {
return c.Status(400).JSON([]ResJSONError{
{Error: err.Error()},
})
}
fmt.Println(accountInput)
var errors []ResJSONError
if userInput.Username == "" {
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "username"})
}
if userInput.Password == "" {
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "password"})
if accountInput.AccountName == "" {
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "accountName"})
}
if len(errors) != 0 {
return c.Status(400).JSON(errors)
}
createdUser := db.User{
ID: uuid.New(),
Username: userInput.Username,
newAccountID, uuidErr := uuid.NewRandom()
if uuidErr != nil {
log.Fatal("Could not create new Uuid, err: " + uuidErr.Error())
}
return c.Status(201).JSON(createdUser)
hashedPwd, pwdErr := utils.HashPassword(accountInput.Password)
if pwdErr != nil {
log.Fatal("Could not hash password, err: " + pwdErr.Error())
}
apiKey := utils.RandString(60)
createdAccount, err := h.Db.AccountCreate(db.AccountCreateInput{
ID: newAccountID,
AccountName: accountInput.AccountName,
APIKey: apiKey,
Fields: accountInput.Fields,
Password: hashedPwd,
})
if err != nil {
if strings.HasPrefix(err.Error(), "ERROR: duplicate key") {
return c.Status(409).JSON([]ResJSONError{{Error: "accountName is already taken"}})
}
return c.Status(500).JSON([]ResJSONError{{Error: err.Error()}})
}
return c.Status(201).JSON(createdAccount)
}
// AccountAuthAPIKey auths an APIKey
func (h Handlers) AccountAuthAPIKey(c *fiber.Ctx) error {
return c.Status(200).JSON("key höhö")
}