-
Notifications
You must be signed in to change notification settings - Fork 8
/
middleware.go
55 lines (47 loc) · 1.27 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package organization
import (
"context"
"log"
"net/http"
d "github.com/delving/hub3/ikuzo/domain"
)
// ResolveOrgByDomain adds a domain.OrganizationID to the context by domain.
// If the domain cannot be resolved it will return a http.StatusBadRequest.
//
// GetOrganizationID can be used to retrieve the domain.OrganizationID from
// the request context.
func (s *Service) ResolveOrgByDomain(next http.Handler) http.Handler {
domains := map[string]*d.Organization{}
orgs, err := s.Filter(context.Background())
if err != nil {
log.Println("unable to get organizations")
}
var defaultOrgID *d.Organization
for _, org := range orgs {
for _, domain := range org.Config.Domains {
domains[domain] = org
if org.Config.Default {
defaultOrgID = org
}
}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
domain := r.URL.Hostname()
if domain == "" {
domain = r.Host
}
org, ok := domains[domain]
if !ok {
if defaultOrgID == nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("no organization available for this domain"))
return
}
org = defaultOrgID
}
// w.Header().Set("ORG-ID", org.RawID())
r = d.SetOrganization(r, org)
next.ServeHTTP(w, r)
})
}