Skip to content

Commit 58b71cb

Browse files
feat: Adds ApiKey support
1 parent 4203c0a commit 58b71cb

File tree

5 files changed

+38
-4
lines changed

5 files changed

+38
-4
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Create a `.env` file in this directory that contains necessary environment varia
99
```
1010
USERNAME=<username>
1111
PASSWORD=<password>
12+
API_KEY=<apikey>
1213
1314
HOST=<host>
1415
PORT=<port>

authController.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,17 @@ func (a authController) getAuthToken(w http.ResponseWriter, r *http.Request) {
5454
w.Write(httpJson)
5555
}
5656

57-
func authMiddleware(jwtSecret string, next http.Handler) http.Handler {
57+
func authMiddleware(jwtSecret string, apiKey string, next http.Handler) http.Handler {
5858
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
5959
var bearerTokenString string
60+
var apiKeyString string
6061
for _, headerValue := range r.Header["Authorization"] {
6162
if strings.HasPrefix(headerValue, "Bearer ") {
6263
bearerTokenString, _ = strings.CutPrefix(headerValue, "Bearer ")
6364
}
65+
if strings.HasPrefix(headerValue, "ApiKey ") {
66+
apiKeyString, _ = strings.CutPrefix(headerValue, "ApiKey ")
67+
}
6468
}
6569

6670
if bearerTokenString != "" {
@@ -86,6 +90,12 @@ func authMiddleware(jwtSecret string, next http.Handler) http.Handler {
8690
w.WriteHeader(http.StatusUnauthorized)
8791
return
8892
}
93+
} else if apiKey != "" && apiKeyString != "" {
94+
if apiKeyString != apiKey {
95+
log.Printf("Invalid API key")
96+
w.WriteHeader(http.StatusUnauthorized)
97+
return
98+
}
8999
} else {
90100
log.Printf("Authorization scheme not supported")
91101
w.WriteHeader(http.StatusUnauthorized)

main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ func main() {
7474

7575
serverConfig := ServerConfig{
7676
authenticator: authenticator,
77+
apiKey: os.Getenv("API_KEY"),
7778
jwtSecret: os.Getenv("JWT_SECRET"),
7879
tokenDurationSeconds: 60 * 60, // 1 hour
7980

server.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
type ServerConfig struct {
1010
// Auth
1111
authenticator authenticator
12+
apiKey string
1213
jwtSecret string
1314
tokenDurationSeconds int
1415

@@ -49,9 +50,9 @@ func NewServer(serverConfig ServerConfig) (http.Handler, error) {
4950
handleFunc(tokenAuth, "DELETE /api/recs/{pointId}/history", hisController.deleteHis)
5051
handleFunc(tokenAuth, "GET /api/recs/{pointId}/current", currentController.getCurrent)
5152
handleFunc(tokenAuth, "POST /api/recs/{pointId}/current", currentController.postCurrent)
52-
server.Handle("/api/his/", authMiddleware(serverConfig.jwtSecret, tokenAuth))
53-
server.Handle("/api/recs", authMiddleware(serverConfig.jwtSecret, tokenAuth))
54-
server.Handle("/api/recs/", authMiddleware(serverConfig.jwtSecret, tokenAuth))
53+
server.Handle("/api/his/", authMiddleware(serverConfig.jwtSecret, serverConfig.apiKey, tokenAuth))
54+
server.Handle("/api/recs", authMiddleware(serverConfig.jwtSecret, serverConfig.apiKey, tokenAuth))
55+
server.Handle("/api/recs/", authMiddleware(serverConfig.jwtSecret, serverConfig.apiKey, tokenAuth))
5556

5657
// Catch all others with public files. Not found fallback is app index for browser router.
5758
server.Handle("/app/", fileServerWithFallback(http.Dir("./public"), "./public/app/index.html"))

server_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ func (suite *ServerTestSuite) SetupTest() {
4545
authenticator: authenticator,
4646
jwtSecret: "aaa",
4747
tokenDurationSeconds: 60,
48+
apiKey: "valid",
4849

4950
historyStore: historyStore,
5051
recStore: recStore,
@@ -91,6 +92,26 @@ func (suite *ServerTestSuite) TestGetAuthTokenInvalidPassword() {
9192
assert.Equal(suite.T(), response.Code, http.StatusForbidden)
9293
}
9394

95+
func (suite *ServerTestSuite) TestApiKey() {
96+
request, _ := http.NewRequest(http.MethodGet, "/api/recs", nil)
97+
request.Header.Add("Authorization", fmt.Sprintf("ApiKey %s", "valid"))
98+
response := httptest.NewRecorder()
99+
100+
suite.server.ServeHTTP(response, request)
101+
102+
assert.Equal(suite.T(), http.StatusOK, response.Code)
103+
}
104+
105+
func (suite *ServerTestSuite) TestApiKeyInvalid() {
106+
request, _ := http.NewRequest(http.MethodGet, "/api/recs", nil)
107+
request.Header.Add("Authorization", fmt.Sprintf("ApiKey %s", "invalid"))
108+
response := httptest.NewRecorder()
109+
110+
suite.server.ServeHTTP(response, request)
111+
112+
assert.Equal(suite.T(), http.StatusUnauthorized, response.Code)
113+
}
114+
94115
func (suite *ServerTestSuite) TestGetHis() {
95116
// Insert data for 2 different points with varying timestamps
96117
pointId1 := uuid.New()

0 commit comments

Comments
 (0)