Fix: API Key / JSON Fast Follow #1 (#1388)

fast follow fix #1 - imports, final loop, one last chance to skip

Co-authored-by: lunamidori5 <118759930+lunamidori5@users.noreply.github.com>
This commit is contained in:
Dave 2023-12-05 05:35:27 -05:00 committed by GitHub
parent 2b2d6673ff
commit 2eb6865a27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,10 +1,10 @@
package api package api
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"encoding/json" "os"
"io/ioutil"
"strings" "strings"
config "github.com/go-skynet/LocalAI/api/config" config "github.com/go-skynet/LocalAI/api/config"
@ -151,7 +151,7 @@ func App(opts ...options.AppOption) (*fiber.App, error) {
} }
// Check for api_keys.json file // Check for api_keys.json file
fileContent, err := ioutil.ReadFile("api_keys.json") fileContent, err := os.ReadFile("api_keys.json")
if err == nil { if err == nil {
// Parse JSON content from the file // Parse JSON content from the file
var fileKeys []string var fileKeys []string
@ -164,6 +164,10 @@ func App(opts ...options.AppOption) (*fiber.App, error) {
options.ApiKeys = append(options.ApiKeys, fileKeys...) options.ApiKeys = append(options.ApiKeys, fileKeys...)
} }
if len(options.ApiKeys) == 0 {
return c.Next()
}
authHeader := c.Get("Authorization") authHeader := c.Get("Authorization")
if authHeader == "" { if authHeader == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Authorization header missing"}) return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Authorization header missing"})
@ -174,19 +178,15 @@ func App(opts ...options.AppOption) (*fiber.App, error) {
} }
apiKey := authHeaderParts[1] apiKey := authHeaderParts[1]
validApiKey := false
for _, key := range options.ApiKeys { for _, key := range options.ApiKeys {
if apiKey == key { if apiKey == key {
validApiKey = true
}
}
if !validApiKey {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid API key"})
}
return c.Next() return c.Next()
} }
}
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid API key"})
}
if options.CORS { if options.CORS {
var c func(ctx *fiber.Ctx) error var c func(ctx *fiber.Ctx) error