Reworking stuff
This commit is contained in:
256
pkgs/db/accounts.go
Normal file
256
pkgs/db/accounts.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AccountCreate writes a user to database
|
||||
func (d Db) AccountCreate(input AccountCreateInput) (CreatedAccount, error) {
|
||||
d.Log.Context = []interface{}{
|
||||
"accountName", input.Name,
|
||||
"id", input.ID,
|
||||
}
|
||||
accountSQL := "INSERT INTO accounts (id, name, \"apiKey\", password) VALUES($1,$2,$3,$4);"
|
||||
|
||||
_, err := d.DbPool.Exec(context.Background(), accountSQL, input.ID, input.Name, input.APIKey, input.Password)
|
||||
if err != nil {
|
||||
if strings.HasPrefix(err.Error(), "ERROR: duplicate key") {
|
||||
d.Log.Debug("Duplicate name in accounts database")
|
||||
} else {
|
||||
d.Log.Warn("Database error when trying to add account", "err", err.Error())
|
||||
}
|
||||
|
||||
return CreatedAccount{}, err
|
||||
}
|
||||
|
||||
d.Log.Verbose("Added account to database", "id", input.ID)
|
||||
|
||||
accountFieldsSQL := "INSERT INTO \"accountsFields\" (id, \"accountId\", name, value) VALUES($1,$2,$3,$4);"
|
||||
for _, field := range input.Fields {
|
||||
newFieldID, uuidErr := uuid.NewRandom()
|
||||
if uuidErr != nil {
|
||||
d.Log.Warn("Could not create new Uuid", "err", uuidErr.Error())
|
||||
return CreatedAccount{}, uuidErr
|
||||
}
|
||||
|
||||
_, err := d.DbPool.Exec(context.Background(), accountFieldsSQL, newFieldID, input.ID, field.Name, field.Values)
|
||||
if err != nil {
|
||||
//if strings.HasPrefix(err.Error(), "ERROR: duplicate key") {
|
||||
d.Log.Warn("Database error when trying to add account field", "err", err.Error(), "accountID", input.ID, "fieldName", field.Name, "fieldvalues", field.Values)
|
||||
// }
|
||||
}
|
||||
|
||||
d.Log.Debug("Added account field", "accountID", input.ID, "fieldName", field.Name, "fieldValues", field.Values)
|
||||
}
|
||||
|
||||
return CreatedAccount{
|
||||
ID: input.ID,
|
||||
Name: input.Name,
|
||||
APIKey: input.APIKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d Db) AccountDel(accountID string) error {
|
||||
d.Log.Context = []interface{}{
|
||||
"accountID", accountID,
|
||||
}
|
||||
d.Log.Verbose("Trying to delete account")
|
||||
|
||||
_, renewalTokensErr := d.DbPool.Exec(context.Background(), "DELETE FROM \"renewalTokens\" WHERE \"accountId\" = $1;", accountID)
|
||||
if renewalTokensErr != nil {
|
||||
d.Log.Error("Could not remove renewal tokens for account", "err", renewalTokensErr.Error())
|
||||
return renewalTokensErr
|
||||
}
|
||||
|
||||
_, fieldsErr := d.DbPool.Exec(context.Background(), "DELETE FROM \"accountsFields\" WHERE \"accountId\" = $1;", accountID)
|
||||
if fieldsErr != nil {
|
||||
d.Log.Error("Could not remove account fields", "err", fieldsErr.Error())
|
||||
return fieldsErr
|
||||
}
|
||||
|
||||
res, err := d.DbPool.Exec(context.Background(), "DELETE FROM accounts WHERE id = $1", accountID)
|
||||
if err != nil {
|
||||
d.Log.Error("Could not remove account", "err", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
if string(res) == "DELETE 0" {
|
||||
d.Log.Debug("Tried to delete account, but none exists")
|
||||
err := errors.New("no account found for given accountID")
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AccountGet fetches an account from the database
|
||||
func (d Db) AccountGet(accountID string, APIKey string, name string) (Account, error) {
|
||||
d.Log.Context = []interface{}{
|
||||
"accountID", accountID,
|
||||
"len(APIKey)", len(APIKey),
|
||||
"name", name,
|
||||
}
|
||||
d.Log.Debug("Trying to get account")
|
||||
|
||||
var account Account
|
||||
var searchParam string
|
||||
accountSQL := "SELECT id, created, name, \"password\" FROM accounts WHERE "
|
||||
if accountID != "" {
|
||||
accountSQL = accountSQL + "id = $1"
|
||||
searchParam = accountID
|
||||
} else if APIKey != "" {
|
||||
accountSQL = accountSQL + "\"apiKey\" = $1"
|
||||
searchParam = APIKey
|
||||
} else if name != "" {
|
||||
accountSQL = accountSQL + "name = $1"
|
||||
searchParam = name
|
||||
} else {
|
||||
d.Log.Debug("No get criteria entered, returning empty response without calling the database")
|
||||
|
||||
return Account{}, errors.New("no rows in result set")
|
||||
}
|
||||
|
||||
accountErr := d.DbPool.QueryRow(context.Background(), accountSQL, searchParam).Scan(&account.ID, &account.Created, &account.Name, &account.Password)
|
||||
if accountErr != nil {
|
||||
if accountErr.Error() == "no rows in result set" {
|
||||
d.Log.Debug("No account found")
|
||||
return Account{}, accountErr
|
||||
}
|
||||
|
||||
d.Log.Error("Database error when fetching account", "err", accountErr.Error())
|
||||
return Account{}, accountErr
|
||||
}
|
||||
|
||||
fieldsSQL := "SELECT name, value FROM \"accountsFields\" WHERE \"accountId\" = $1"
|
||||
rows, fieldsErr := d.DbPool.Query(context.Background(), fieldsSQL, account.ID)
|
||||
if fieldsErr != nil {
|
||||
d.Log.Error("Database error when fetching account fields", "err", accountErr.Error())
|
||||
return Account{}, fieldsErr
|
||||
}
|
||||
|
||||
account.Fields = make(map[string][]string)
|
||||
for rows.Next() {
|
||||
var name string
|
||||
var value []string
|
||||
err := rows.Scan(&name, &value)
|
||||
if err != nil {
|
||||
d.Log.Error("Could not get name or value from database row", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
account.Fields[name] = value
|
||||
}
|
||||
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// func (d Db) AccountsGet() ([]Account, error) {
|
||||
// d.Log.Debug("Trying to get accounts", "name", name)
|
||||
|
||||
// var account Account
|
||||
// var searchParam string
|
||||
// accountSQL := "SELECT id, created, name, \"password\" FROM accounts WHERE "
|
||||
// if accountID != "" {
|
||||
// accountSQL = accountSQL + "id = $1"
|
||||
// searchParam = accountID
|
||||
// } else if APIKey != "" {
|
||||
// accountSQL = accountSQL + "\"apiKey\" = $1"
|
||||
// searchParam = APIKey
|
||||
// } else if name != "" {
|
||||
// accountSQL = accountSQL + "name = $1"
|
||||
// searchParam = name
|
||||
// } else {
|
||||
// d.Log.Debug("No get criteria entered, returning empty response without calling the database")
|
||||
|
||||
// return Account{}, errors.New("no rows in result set")
|
||||
// }
|
||||
|
||||
// accountErr := d.DbPool.QueryRow(context.Background(), accountSQL, searchParam).Scan(&account.ID, &account.Created, &account.Name, &account.Password)
|
||||
// if accountErr != nil {
|
||||
// if accountErr.Error() == "no rows in result set" {
|
||||
// d.Log.Debug("No account found", "accountID", accountID, "APIKey", len(APIKey))
|
||||
// return Account{}, accountErr
|
||||
// }
|
||||
|
||||
// d.Log.Error("Database error when fetching account", "err", accountErr.Error(), "accountID", accountID, "APIKey", len(APIKey))
|
||||
// return Account{}, accountErr
|
||||
// }
|
||||
|
||||
// fieldsSQL := "SELECT name, value FROM \"accountsFields\" WHERE \"accountId\" = $1"
|
||||
// rows, fieldsErr := d.DbPool.Query(context.Background(), fieldsSQL, account.ID)
|
||||
// if fieldsErr != nil {
|
||||
// d.Log.Error("Database error when fetching account fields", "err", accountErr.Error(), "accountID", accountID, "APIKey", len(APIKey))
|
||||
// return Account{}, fieldsErr
|
||||
// }
|
||||
|
||||
// account.Fields = make(map[string][]string)
|
||||
// for rows.Next() {
|
||||
// var name string
|
||||
// var value []string
|
||||
// err := rows.Scan(&name, &value)
|
||||
// if err != nil {
|
||||
// d.Log.Error("Could not get name or value from database row", "err", err.Error(), "accountID", accountID, "APIKey", len(APIKey))
|
||||
// return Account{}, err
|
||||
// }
|
||||
// account.Fields[name] = value
|
||||
// }
|
||||
|
||||
// return account, nil
|
||||
// }
|
||||
|
||||
func (d Db) AccountUpdateFields(accountID string, fields []AccountCreateInputFields) (Account, error) {
|
||||
d.Log.Context = []interface{}{
|
||||
"accountID", accountID,
|
||||
"fields", fields,
|
||||
}
|
||||
|
||||
// Begin database transaction
|
||||
conn, err := d.DbPool.Acquire(context.Background())
|
||||
if err != nil {
|
||||
d.Log.Error("Could not acquire database connection", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
tx, err := conn.Begin(context.Background())
|
||||
if err != nil {
|
||||
d.Log.Error("Could not begin database transaction", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
// Rollback is safe to call even if the tx is already closed, so if
|
||||
// the tx commits successfully, this is a no-op
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
_, err = tx.Exec(context.Background(), "DELETE FROM \"accountsFields\" WHERE \"accountId\" = $1;", accountID)
|
||||
if err != nil {
|
||||
d.Log.Error("Could not delete previous fields", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
accountFieldsSQL := "INSERT INTO \"accountsFields\" (id, \"accountId\", name, value) VALUES($1,$2,$3,$4);"
|
||||
for _, field := range fields {
|
||||
newFieldID, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
d.Log.Error("Could not create new Uuid", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(context.Background(), accountFieldsSQL, newFieldID, accountID, field.Name, field.Values)
|
||||
if err != nil {
|
||||
d.Log.Error("Database error when trying to add account field", "err", err.Error(), "fieldName", field.Name, "fieldvalues", field.Values)
|
||||
}
|
||||
|
||||
d.Log.Debug("Added account field", "accountID", accountID, "fieldName", field.Name, "fieldValues", field.Values)
|
||||
}
|
||||
|
||||
err = tx.Commit(context.Background())
|
||||
if err != nil {
|
||||
d.Log.Error("Database error when tying to commit", "err", err.Error())
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
return d.AccountGet(accountID, "", "")
|
||||
}
|
||||
61
pkgs/db/renewalTokens.go
Normal file
61
pkgs/db/renewalTokens.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/utils"
|
||||
)
|
||||
|
||||
// RenewalTokenCreate obtain a new renewal token
|
||||
func (d Db) RenewalTokenCreate(accountID string) (string, error) {
|
||||
d.Log.Context = []interface{}{
|
||||
"accountID", accountID,
|
||||
}
|
||||
|
||||
d.Log.Debug("Creating new renewal token")
|
||||
|
||||
newToken := utils.RandString(60)
|
||||
|
||||
insertSQL := "INSERT INTO \"renewalTokens\" (\"accountId\",token) VALUES($1,$2);"
|
||||
_, insertErr := d.DbPool.Exec(context.Background(), insertSQL, accountID, newToken)
|
||||
if insertErr != nil {
|
||||
d.Log.Error("Could not insert into database table \"renewalTokens\"", "err", insertErr.Error())
|
||||
return "", insertErr
|
||||
}
|
||||
|
||||
return newToken, nil
|
||||
}
|
||||
|
||||
// RenewalTokenGet checks if a valid renewal token exists in database
|
||||
func (d Db) RenewalTokenGet(token string) (string, error) {
|
||||
d.Log.Debug("Trying to get a renewal token")
|
||||
|
||||
sql := "SELECT \"accountId\" FROM \"renewalTokens\" WHERE exp >= now() AND token = $1"
|
||||
|
||||
var foundAccountID string
|
||||
err := d.DbPool.QueryRow(context.Background(), sql, token).Scan(&foundAccountID)
|
||||
if err != nil {
|
||||
if err.Error() == "no rows in result set" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
d.Log.Error("Database error when fetching renewal token", "err", err.Error())
|
||||
return "", err
|
||||
}
|
||||
|
||||
return foundAccountID, nil
|
||||
}
|
||||
|
||||
// RenewalTokenRm removes a renewal token from the database
|
||||
func (d Db) RenewalTokenRm(token string) error {
|
||||
d.Log.Debug("Trying to remove a renewal token")
|
||||
|
||||
sql := "DELETE FROM \"renewalTokens\" WHERE token = $1"
|
||||
_, err := d.DbPool.Exec(context.Background(), sql, token)
|
||||
if err != nil {
|
||||
d.Log.Error("Database error when trying to remove token", "err", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
46
pkgs/db/types.go
Normal file
46
pkgs/db/types.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitea.larvit.se/pwrpln/go_log"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
// Account is an account as represented in the database
|
||||
type Account struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Created time.Time `json:"created"`
|
||||
Fields map[string][]string `json:"fields"`
|
||||
Name string `json:"name"`
|
||||
Password string `json:"-"`
|
||||
}
|
||||
|
||||
// CreatedAccount is a newly created account in the system
|
||||
type CreatedAccount struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKey string `json:"apiKey"`
|
||||
}
|
||||
|
||||
// AccountCreateInputFields yes
|
||||
type AccountCreateInputFields struct {
|
||||
Name string
|
||||
Values []string
|
||||
}
|
||||
|
||||
// AccountCreateInput is used as input struct for database creation of account
|
||||
type AccountCreateInput struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
APIKey string
|
||||
Fields []AccountCreateInputFields
|
||||
Password string
|
||||
}
|
||||
|
||||
// Db struct
|
||||
type Db struct {
|
||||
DbPool *pgxpool.Pool
|
||||
Log go_log.Log
|
||||
}
|
||||
48
pkgs/handlers/delete.go
Normal file
48
pkgs/handlers/delete.go
Normal file
@@ -0,0 +1,48 @@
|
||||
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 /accounts/: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)
|
||||
}
|
||||
79
pkgs/handlers/get.go
Normal file
79
pkgs/handlers/get.go
Normal file
@@ -0,0 +1,79 @@
|
||||
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 /accounts/{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)
|
||||
}
|
||||
149
pkgs/handlers/helpers.go
Normal file
149
pkgs/handlers/helpers.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/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")
|
||||
}
|
||||
27
pkgs/handlers/middlewares.go
Normal file
27
pkgs/handlers/middlewares.go
Normal file
@@ -0,0 +1,27 @@
|
||||
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
|
||||
}
|
||||
200
pkgs/handlers/post.go
Normal file
200
pkgs/handlers/post.go
Normal file
@@ -0,0 +1,200 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/db"
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/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 /accounts [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)
|
||||
}
|
||||
58
pkgs/handlers/put.go
Normal file
58
pkgs/handlers/put.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/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 /accounts/{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)
|
||||
}
|
||||
34
pkgs/handlers/types.go
Normal file
34
pkgs/handlers/types.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gitea.larvit.se/pwrpln/auth-api/pkgs/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"`
|
||||
}
|
||||
50
pkgs/utils/utils.go
Normal file
50
pkgs/utils/utils.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
const (
|
||||
letterIdxBits = 6 // 6 bits to represent a letter index
|
||||
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
|
||||
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
|
||||
)
|
||||
|
||||
var src = rand.NewSource(time.Now().UnixNano())
|
||||
|
||||
// CheckPasswordHash checks a password hash
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// HashPassword hashes a password
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
// RandString generates a random string. Taken from https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go (RandStringBytesMaskImprSrcSB())
|
||||
func RandString(n int) string {
|
||||
sb := strings.Builder{}
|
||||
sb.Grow(n)
|
||||
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
|
||||
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
|
||||
if remain == 0 {
|
||||
cache, remain = src.Int63(), letterIdxMax
|
||||
}
|
||||
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
||||
sb.WriteByte(letterBytes[idx])
|
||||
i--
|
||||
}
|
||||
cache >>= letterIdxBits
|
||||
remain--
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
Reference in New Issue
Block a user