Protected POST /account and fixed with JWT stuff in general
This commit is contained in:
115
src/handlers/helpers.go
Normal file
115
src/handlers/helpers.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gitlab.larvit.se/power-plan/auth/src/db"
|
||||
)
|
||||
|
||||
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 {
|
||||
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.RenewalTokenGet(account.ID.String())
|
||||
if renewalTokenErr != nil {
|
||||
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) {
|
||||
logContext := log.WithFields(log.Fields{"JWT": JWT})
|
||||
logContext.Trace("Parsing JWT")
|
||||
|
||||
JWT = strings.TrimPrefix(JWT, "bearer ") // Since the Authorization header should always start with "bearer "
|
||||
logContext.WithFields(log.Fields{"TrimmedJWT": JWT}).Trace("JWT trimmed")
|
||||
|
||||
claims := &Claims{}
|
||||
|
||||
token, err := jwt.ParseWithClaims(JWT, 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 {
|
||||
log.WithFields(log.Fields{"line": line}).Trace("Ignoring header 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")
|
||||
}
|
||||
@@ -5,6 +5,17 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Log all requests
|
||||
func (h Handlers) Log(c *fiber.Ctx) error {
|
||||
log.WithFields(log.Fields{
|
||||
"method": c.Method(),
|
||||
"url": c.OriginalURL(),
|
||||
}).Debug("http request")
|
||||
|
||||
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")
|
||||
|
||||
@@ -13,10 +13,15 @@ import (
|
||||
|
||||
// AccountCreate creates a new account
|
||||
func (h Handlers) AccountCreate(c *fiber.Ctx) error {
|
||||
authErr := h.RequireAdminRole(c)
|
||||
if authErr != nil {
|
||||
return c.Status(403).JSON([]ResJSONError{{Error: authErr.Error()}})
|
||||
}
|
||||
|
||||
type AccountInput struct {
|
||||
AccountName string `json:"accountName"`
|
||||
Password string `json:"password"`
|
||||
Fields []db.AccountCreateInputFields `json:"fields"`
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
Fields []db.AccountCreateInputFields `json:"fields"`
|
||||
}
|
||||
|
||||
accountInput := new(AccountInput)
|
||||
@@ -29,8 +34,8 @@ func (h Handlers) AccountCreate(c *fiber.Ctx) error {
|
||||
|
||||
var errors []ResJSONError
|
||||
|
||||
if accountInput.AccountName == "" {
|
||||
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "accountName"})
|
||||
if accountInput.Name == "" {
|
||||
errors = append(errors, ResJSONError{Error: "Can not be empty", Field: "name"})
|
||||
}
|
||||
|
||||
if len(errors) != 0 {
|
||||
@@ -47,14 +52,12 @@ func (h Handlers) AccountCreate(c *fiber.Ctx) error {
|
||||
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,
|
||||
ID: newAccountID,
|
||||
Name: accountInput.Name,
|
||||
APIKey: utils.RandString(60),
|
||||
Fields: accountInput.Fields,
|
||||
Password: hashedPwd,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -69,5 +72,17 @@ func (h Handlers) AccountCreate(c *fiber.Ctx) error {
|
||||
|
||||
// AccountAuthAPIKey auths an APIKey
|
||||
func (h Handlers) AccountAuthAPIKey(c *fiber.Ctx) error {
|
||||
return c.Status(200).JSON("key höhö")
|
||||
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"}})
|
||||
}
|
||||
log.Error("Something went wrong when trying to fetch account")
|
||||
return c.Status(500).JSON([]ResJSONError{{Error: "Something went wrong when trying to fetch account"}})
|
||||
}
|
||||
|
||||
return h.returnTokens(resolvedAccount, c)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
"gitlab.larvit.se/power-plan/auth/src/db"
|
||||
)
|
||||
|
||||
// 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
|
||||
Db db.Db
|
||||
JwtKey []byte
|
||||
}
|
||||
|
||||
// ResJSONError is an error field that is used in JSON error responses
|
||||
@@ -14,3 +24,9 @@ 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"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user