| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package server |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "fmt" |
| 22 | "math/rand" |
| 23 | "net/http" |
| 24 | "strings" |
| 25 | |
| 26 | "github.com/sassoftware/relic/v7/internal/authmodel" |
| 27 | "github.com/sassoftware/relic/v7/internal/realip" |
| 28 | ) |
| 29 | |
| 30 | func (s *Server) serveDirectory(rw http.ResponseWriter, req *http.Request) error { |
| 31 | sibs := append([]string{}, s.Config.Server.Siblings...) |
| 32 | rand.Shuffle(len(sibs), func(i, j int) { sibs[i], sibs[j] = sibs[j], sibs[i] }) |
| 33 | if !strings.Contains(req.Header.Get("Accept"), "json") { |
| 34 | // legacy path |
| 35 | var buf bytes.Buffer |
| 36 | if len(sibs) == 0 { |
| 37 | u := realip.BaseURL(req) |
| 38 | sibs = []string{u.String()} |
| 39 | } |
| 40 | for _, h := range sibs { |
| 41 | _, _ = fmt.Fprintf(&buf, "%s\r\n", h) |
| 42 | } |
| 43 | var err error |
| 44 | _, err = rw.Write(buf.Bytes()) |
| 45 | return err |
| 46 | } |
| 47 | |
| 48 | md := authmodel.Metadata{ |
| 49 | Hosts: sibs, |
| 50 | Auth: []authmodel.AuthMetadata{ |
| 51 | {Type: authmodel.AuthTypeCertificate}, |
| 52 | }, |
| 53 | } |
| 54 | if _, ok := s.auth.(*authmodel.PolicyAuth); ok { |
| 55 | md.Auth = append(md.Auth, authmodel.AuthMetadata{Type: authmodel.AuthTypeBearerToken}) |
| 56 | if aad := s.Config.Server.AzureAD; aad != nil { |
| 57 | md.Auth = append(md.Auth, authmodel.AuthMetadata{ |
| 58 | Type: authmodel.AuthTypeAzureAD, |
| 59 | Authority: aad.Authority, |
| 60 | ClientID: aad.ClientID, |
| 61 | Scopes: aad.Scopes, |
| 62 | }) |
| 63 | } |
| 64 | } |
| 65 | return writeJSON(rw, md) |
| 66 | } |