Skip to content

Commit 9227a28

Browse files
committed
FEAT: skeleton authN middleware
1 parent 4fc4787 commit 9227a28

File tree

5 files changed

+59
-2
lines changed

5 files changed

+59
-2
lines changed

.env.example

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
HOST=localhost
22
PORT=8080
3-
ALLOWED_ORIGINS=http://localhost:8080
3+
ALLOWED_ORIGINS=http://localhost:8080
4+
AUTH_PROVIDER=none

config/config.go

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ type Config struct {
1010
Host string
1111
Port string
1212
AllowedOrigin string
13+
AuthProvider string
1314
}
1415

1516
func New() Config {
@@ -19,6 +20,7 @@ func New() Config {
1920
Host: host,
2021
Port: port,
2122
AllowedOrigin: getEnvDefault("ALLOWED_ORIGINS", fmt.Sprintf("http://%s:%s", host, port)),
23+
AuthProvider: getEnvDefault("AUTH_PROVIDER", "none"),
2224
}
2325
}
2426

server/auth.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package server
2+
3+
import (
4+
"net/http"
5+
"strings"
6+
7+
"github.com/xray-web/web-check-api/config"
8+
)
9+
10+
type User struct {
11+
ID string
12+
Email string
13+
Name string
14+
Roles []string
15+
}
16+
17+
type Auth struct {
18+
conf config.Config
19+
// connection / sdk to auth provider, to trade token for user session token
20+
}
21+
22+
func NewAuth(conf config.Config) *Auth {
23+
// TODO: reduce scope of conf when we know what auth provider we will use
24+
return &Auth{conf: conf}
25+
}
26+
27+
func (a *Auth) Authenticate(h http.Handler) http.Handler {
28+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
29+
if a.conf.AuthProvider == "none" {
30+
h.ServeHTTP(w, r)
31+
return
32+
}
33+
authHeader := r.Header.Get("Authorization")
34+
// expect "Bearer token" format
35+
parts := strings.Split(authHeader, " ")
36+
if len(parts) != 2 || parts[0] != "Bearer" {
37+
w.WriteHeader(http.StatusUnauthorized)
38+
return
39+
}
40+
// use token to get user ID from auth provider
41+
// TODO: swap token for user session token
42+
43+
})
44+
}

server/middleware.go

+7
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,10 @@ func HealthCheck() http.Handler {
4949
json.NewEncoder(w).Encode(Response{Status: "ok"})
5050
})
5151
}
52+
53+
func middlewares(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
54+
for _, m := range middlewares {
55+
h = m(h)
56+
}
57+
return h
58+
}

server/server.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,10 @@ func (s *Server) routes() {
5353
s.mux.Handle("GET /api/tls", handlers.HandleTLS(s.checks.Tls))
5454
s.mux.Handle("GET /api/trace-route", handlers.HandleTraceRoute())
5555

56-
s.srv.Handler = s.CORS(s.mux)
56+
s.srv.Handler = middlewares(s.mux,
57+
s.CORS,
58+
NewAuth(s.conf).Authenticate,
59+
)
5760
}
5861

5962
func (s *Server) Run() error {

0 commit comments

Comments
 (0)