Reworking stuff

This commit is contained in:
2023-05-08 15:29:19 +02:00
parent c4a97644ed
commit 61590f684e
25 changed files with 1349 additions and 883 deletions

View File

@@ -1,48 +0,0 @@
package handlers
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
// AccountDel godoc
// @Summary Delete an account
// @Description Requires Authorization-header with role "admin" or a matching account id
// @Description Example: Authorization: bearer xxx
// @Description Where "xxx" is a valid JWT token
// @ID account-del
// @Accept json
// @Produce json
// @Param id path string true "Account ID"
// @Success 204 {string} string ""
// @Failure 400 {object} []ResJSONError
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 404 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /account/:id [delete]
func (h Handlers) AccountDel(c *fiber.Ctx) error {
accountID := c.Params("accountID")
_, uuidErr := uuid.Parse(accountID)
if uuidErr != nil {
return c.Status(400).JSON([]ResJSONError{{Error: "Invalid uuid format"}})
}
authErr := h.RequireAdminRoleOrAccountID(c, accountID)
if authErr != nil {
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
}
err := h.Db.AccountDel(accountID)
if err != nil {
if err.Error() == "No account found for given accountID" {
return c.Status(404).JSON([]ResJSONError{{Error: err.Error()}})
} else {
return c.Status(500).JSON([]ResJSONError{{Error: "Database error when trying to remove account"}})
}
}
return c.Status(204).Send(nil)
}

View File

@@ -1,79 +0,0 @@
package handlers
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
// AccountGet godoc
// @Summary Get account by id
// @Description Requires Authorization-header with either role "admin" or with a matching account id.
// @Description Example: Authorization: bearer xxx
// @Description Where "xxx" is a valid JWT token
// @ID get-account-by-id
// @Accept json
// @Produce json
// @Param id path string true "Account ID"
// @Success 200 {object} db.Account
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /account/{id} [get]
func (h Handlers) AccountGet(c *fiber.Ctx) error {
accountID := c.Params("accountID")
_, uuidErr := uuid.Parse(accountID)
if uuidErr != nil {
return c.Status(400).JSON([]ResJSONError{{Error: "Invalid uuid format"}})
}
authErr := h.RequireAdminRoleOrAccountID(c, accountID)
if authErr != nil {
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
}
account, accountErr := h.Db.AccountGet(accountID, "", "")
if accountErr != nil {
if accountErr.Error() == "no rows in result set" {
return c.Status(404).JSON([]ResJSONError{{Error: "No account found for given accountID"}})
} else {
return c.Status(500).JSON([]ResJSONError{{Error: accountErr.Error()}})
}
}
return c.JSON(account)
}
// AccountGet godoc
// @Summary Get accounts
// @Description Requires Authorization-header with role "admin".
// @Description Example: Authorization: bearer xxx
// @Description Where "xxx" is a valid JWT token
// @Accept json
// @Produce json
// @Success 200 {object} []db.Account
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /accounts [get]
func (h Handlers) AccountsGet(c *fiber.Ctx) error {
accountID := c.Params("accountID")
authErr := h.RequireAdminRole(c)
if authErr != nil {
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
}
account, accountErr := h.Db.AccountGet(accountID, "", "")
if accountErr != nil {
if accountErr.Error() == "no rows in result set" {
return c.Status(404).JSON([]ResJSONError{{Error: "No account found for given accountID"}})
} else {
return c.Status(500).JSON([]ResJSONError{{Error: accountErr.Error()}})
}
}
return c.JSON(account)
}

View File

@@ -1,149 +0,0 @@
package handlers
import (
"errors"
"strings"
"time"
"gitea.larvit.se/pwrpln/auth-api/src/db"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gofiber/fiber/v2"
)
func (h Handlers) returnTokens(account db.Account, c *fiber.Ctx) error {
expirationTime := time.Now().Add(15 * time.Minute)
claims := &Claims{
AccountID: account.ID.String(),
AccountName: account.Name,
AccountFields: account.Fields,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(h.JwtKey)
if err != nil {
h.Log.Error("Could not create token string", "err", err.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Could not create JWT token string"}})
}
renewalToken, renewalTokenErr := h.Db.RenewalTokenCreate(account.ID.String())
if renewalTokenErr != nil {
h.Log.Error("Could not create renewal token", "err", renewalTokenErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Could not create renewal token"}})
}
return c.Status(200).JSON(ResToken{
JWT: tokenString,
RenewalToken: renewalToken,
})
}
func (h Handlers) parseJWT(JWT string) (Claims, error) {
h.Log.Debug("Parsing JWT", "JWT", JWT)
trimmedJWT := strings.TrimPrefix(JWT, "bearer ") // Since the Authorization header should always start with "bearer "
h.Log.Debug("JWT trimmed", "JWT", JWT, "trimmedJWT", trimmedJWT)
claims := &Claims{}
token, err := jwt.ParseWithClaims(trimmedJWT, claims, func(token *jwt.Token) (interface{}, error) {
return h.JwtKey, nil
})
if err != nil {
return Claims{}, err
}
if !token.Valid {
err := errors.New("invalid token")
return Claims{}, err
}
return *claims, nil
}
func (h Handlers) parseHeaders(c *fiber.Ctx) map[string]string {
headersMap := make(map[string]string)
headersString := c.Request().Header.String()
headersLines := strings.Split(headersString, "\r\n")
for _, line := range headersLines {
lineParts := strings.Split(line, ": ")
if len(lineParts) == 1 {
if len(line) != 0 {
h.Log.Debug("Ignoring header line", "line", line)
}
} else {
headersMap[lineParts[0]] = lineParts[1]
}
}
return headersMap
}
// RequireAdminRole returns nil if no error is found
func (h Handlers) RequireAdminRole(c *fiber.Ctx) error {
headers := h.parseHeaders(c)
if headers["Authorization"] == "" {
return errors.New("authorization header is missing")
}
claims, claimsErr := h.parseJWT(headers["Authorization"])
if claimsErr != nil {
return claimsErr
}
if claims.AccountFields == nil {
return errors.New("account have no fields at all")
}
if claims.AccountFields["role"] == nil {
return errors.New("account have no field named \"role\"")
}
for _, role := range claims.AccountFields["role"] {
if role == "admin" {
return nil
}
}
return errors.New("no \"admin\" role found on account")
}
// RequireAdminRoleOrAccountID returns nil if no error is found
func (h Handlers) RequireAdminRoleOrAccountID(c *fiber.Ctx, accountID string) error {
headers := h.parseHeaders(c)
if headers["Authorization"] == "" {
return errors.New("authorization header is missing")
}
claims, claimsErr := h.parseJWT(headers["Authorization"])
if claimsErr != nil {
return claimsErr
}
if claims.AccountID == accountID {
return nil
}
if claims.AccountFields == nil {
return errors.New("AccountID does not match and account have no fields at all")
}
if claims.AccountFields["role"] == nil {
return errors.New("AccountID does not match and account have no field named \"role\"")
}
for _, role := range claims.AccountFields["role"] {
if role == "admin" {
return nil
}
}
return errors.New("AccountID does not match and no \"admin\" role found on account")
}

View File

@@ -1,27 +0,0 @@
package handlers
import (
"github.com/gofiber/fiber/v2"
)
// Log all requests
func (h Handlers) LogReq(c *fiber.Ctx) error {
h.Log.Debug("http request", "method", c.Method(), "url", c.OriginalURL())
c.Next()
return nil
}
// RequireJSON is a middleware that makes sure the request content-type always is application/json (or nothing, defaulting to application/json)
func (h Handlers) RequireJSON(c *fiber.Ctx) error {
c.Accepts("application/json")
contentType := string(c.Request().Header.ContentType())
if contentType != "application/json" && contentType != "" {
h.Log.Debug("Invalid content-type in request", "content-type", contentType)
return c.Status(415).JSON([]ResJSONError{{Error: "Invalid content-type"}})
}
c.Next()
return nil
}

View File

@@ -1,200 +0,0 @@
package handlers
import (
"strings"
"gitea.larvit.se/pwrpln/auth-api/src/db"
"gitea.larvit.se/pwrpln/auth-api/src/utils"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
type AccountInput struct {
Name string `json:"name"`
Password string `json:"password"`
Fields []db.AccountCreateInputFields `json:"fields"`
}
type AuthInput struct {
Name string `json:"name"`
Password string `json:"password"`
}
// AccountCreate godoc
// @Summary Create an account
// @Description Requires Authorization-header with role "admin".
// @Description Example: Authorization: bearer xxx
// @Description Where "xxx" is a valid JWT token
// @ID account-create
// @Accept json
// @Produce json
// @Param body body AccountInput true "Account object to be written to database"
// @Success 201 {object} db.CreatedAccount
// @Failure 400 {object} []ResJSONError
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 409 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /account [post]
func (h Handlers) AccountCreate(c *fiber.Ctx) error {
authErr := h.RequireAdminRole(c)
if authErr != nil {
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
}
accountInput := new(AccountInput)
if err := c.BodyParser(accountInput); err != nil {
return c.Status(400).JSON([]ResJSONError{
{Error: err.Error()},
})
}
var errors []ResJSONError
if accountInput.Name == "" {
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "name"})
}
if len(errors) != 0 {
return c.Status(400).JSON(errors)
}
newAccountID, uuidErr := uuid.NewRandom()
if uuidErr != nil {
h.Log.Error("Could not create new Uuid", "err", uuidErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Could not create new account UUID"}})
}
hashedPwd, pwdErr := utils.HashPassword(accountInput.Password)
if pwdErr != nil {
h.Log.Error("Could not hash password", "err", pwdErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Could not hash password: \"" + pwdErr.Error() + "\""}})
}
createdAccount, err := h.Db.AccountCreate(db.AccountCreateInput{
ID: newAccountID,
Name: accountInput.Name,
APIKey: utils.RandString(60),
Fields: accountInput.Fields,
Password: hashedPwd,
})
if err != nil {
if strings.HasPrefix(err.Error(), "ERROR: duplicate key") {
return c.Status(409).JSON([]ResJSONError{{Error: "Name is already taken", Field: "name"}})
}
return c.Status(500).JSON([]ResJSONError{{Error: err.Error()}})
}
return c.Status(201).JSON(createdAccount)
}
// AccountAuthAPIKey godoc
// @Summary Authenticate account by API Key
// @Description Authenticate account by API Key
// @ID auth-account-by-api-key
// @Accept json
// @Produce json
// @Param body body string true "API Key as a string in JSON format (just encapsulate the string with \" and you're fine)"
// @Success 200 {object} ResToken
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /auth/api-key [post]
func (h Handlers) AccountAuthAPIKey(c *fiber.Ctx) error {
inputAPIKey := string(c.Request().Body())
inputAPIKey = inputAPIKey[1 : len(inputAPIKey)-1]
resolvedAccount, accountErr := h.Db.AccountGet("", inputAPIKey, "")
if accountErr != nil {
if accountErr.Error() == "no rows in result set" {
return c.Status(403).JSON([]ResJSONError{{Error: "Invalid credentials"}})
}
h.Log.Error("Something went wrong when trying to fetch account", "err", accountErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Something went wrong when trying to fetch account"}})
}
return h.returnTokens(resolvedAccount, c)
}
// AccountAuthPassword godoc
// @Summary Authenticate account by Password
// @Description Authenticate account by Password
// @ID auth-account-by-password
// @Accept json
// @Produce json
// @Param body body AuthInput true "Name and password to auth by"
// @Success 200 {object} ResToken
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /auth/password [post]
func (h Handlers) AccountAuthPassword(c *fiber.Ctx) error {
authInput := new(AuthInput)
if err := c.BodyParser(authInput); err != nil {
return c.Status(400).JSON([]ResJSONError{{Error: err.Error()}})
}
resolvedAccount, err := h.Db.AccountGet("", "", authInput.Name)
if err != nil {
if err.Error() == "no rows in result set" {
return c.Status(403).JSON([]ResJSONError{{Error: "Invalid name or password"}})
} else {
h.Log.Error("unknown error when resolving account", "err", err.Error())
}
return c.Status(500).JSON([]ResJSONError{{Error: err.Error()}})
}
if !utils.CheckPasswordHash(authInput.Password, resolvedAccount.Password) {
return c.Status(403).JSON([]ResJSONError{{Error: "Invalid name or password"}})
}
return h.returnTokens(resolvedAccount, c)
}
// RenewToken godoc
// @Summary Renew token
// @Description Renew token
// @ID renew-token
// @Accept json
// @Produce json
// @Param body body string true "Renewal token as a string in JSON format (just encapsulate the string with \" and you're fine)"
// @Success 200 {object} ResToken
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /renew-token [post]
func (h Handlers) RenewToken(c *fiber.Ctx) error {
inputToken := string(c.Request().Body())
inputToken = inputToken[1 : len(inputToken)-1]
foundAccountID, err := h.Db.RenewalTokenGet(inputToken)
if err != nil {
return c.Status(500).JSON([]ResJSONError{{Error: err.Error()}})
} else if foundAccountID == "" {
return c.Status(403).JSON([]ResJSONError{{Error: "Invalid token"}})
}
resolvedAccount, accountErr := h.Db.AccountGet(foundAccountID, "", "")
if accountErr != nil {
if accountErr.Error() == "no rows in result set" {
return c.Status(500).JSON([]ResJSONError{{Error: "Database missmatch. Token found, but account is missing."}})
}
h.Log.Error("Something went wrong when trying to fetch account", "err", accountErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Something went wrong when trying to fetch account"}})
}
rmErr := h.Db.RenewalTokenRm(inputToken)
if rmErr != nil {
h.Log.Error("Something went wrong when trying to fetch account", "err", rmErr.Error())
return c.Status(500).JSON([]ResJSONError{{Error: "Could not remove old token"}})
}
return h.returnTokens(resolvedAccount, c)
}

View File

@@ -1,58 +0,0 @@
package handlers
import (
"gitea.larvit.se/pwrpln/auth-api/src/db"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
// AccountUpdateFields godoc
// @Summary Update account fields
// @Description Requires Authorization-header with role "admin".
// @Description Example: Authorization: bearer xxx
// @Description Where "xxx" is a valid JWT token
// @ID account-update-fields
// @Accept json
// @Produce json
// @Param body body []db.AccountCreateInputFields true "Fields array with objects to be written to database"
// @Success 200 {object} db.Account
// @Failure 400 {object} []ResJSONError
// @Failure 401 {object} []ResJSONError
// @Failure 403 {object} []ResJSONError
// @Failure 415 {object} []ResJSONError
// @Failure 500 {object} []ResJSONError
// @Router /account/{id}/fields [put]
func (h Handlers) AccountUpdateFields(c *fiber.Ctx) error {
accountID := c.Params("accountID")
h.Log.Context = []interface{}{
"accountID", accountID,
}
_, uuidErr := uuid.Parse(accountID)
if uuidErr != nil {
h.Log.Debug("client supplied invalid uuid format")
return c.Status(400).JSON([]ResJSONError{{Error: "Invalid uuid format"}})
}
authErr := h.RequireAdminRole(c)
if authErr != nil {
h.Log.Debug("client does not have admin role")
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
}
fieldsInput := new([]db.AccountCreateInputFields)
if err := c.BodyParser(fieldsInput); err != nil {
return c.Status(400).JSON([]ResJSONError{
{Error: err.Error()},
})
}
updatedAccount, err := h.Db.AccountUpdateFields(accountID, *fieldsInput)
if err != nil {
return c.Status(500).JSON([]ResJSONError{{Error: "Internal server error"}})
}
return c.Status(200).JSON(updatedAccount)
}

View File

@@ -1,34 +0,0 @@
package handlers
import (
"gitea.larvit.se/pwrpln/auth-api/src/db"
"gitea.larvit.se/pwrpln/go_log"
jwt "github.com/dgrijalva/jwt-go"
)
// Claims is the JWT struct
type Claims struct {
AccountID string `json:"accountId"`
AccountFields map[string][]string `json:"accountFields"`
AccountName string `json:"accountName"`
jwt.StandardClaims
}
// Handlers is the overall struct for all http request handlers
type Handlers struct {
Db db.Db
JwtKey []byte
Log go_log.Log
}
// ResJSONError is an error field that is used in JSON error responses
type ResJSONError struct {
Error string `json:"error"`
Field string `json:"field,omitempty"`
}
// ResToken is a response used to return a valid token and valid renewalToken
type ResToken struct {
JWT string `json:"jwt"`
RenewalToken string `json:"renewalToken"`
}