github.com/greenpau/go-authcrunch@v1.1.4/pkg/authn/handle_http_static.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package authn 16 17 import ( 18 "context" 19 "github.com/greenpau/go-authcrunch/pkg/authn/ui" 20 "github.com/greenpau/go-authcrunch/pkg/requests" 21 "io" 22 "net/http" 23 "path" 24 "strings" 25 ) 26 27 func (p *Portal) handleHTTPStaticAssets(ctx context.Context, w http.ResponseWriter, r *http.Request, rr *requests.Request) error { 28 var assetPath string 29 switch { 30 case strings.Contains(r.URL.Path, "/favicon"): 31 assetPath = "assets/images/" + path.Base(r.URL.Path) 32 default: 33 i := strings.Index(r.URL.Path, "/assets/") 34 assetPath = r.URL.Path[i+1:] 35 } 36 37 p.logRequest("static assets", r, rr) 38 asset, err := ui.StaticAssets.GetAsset(assetPath) 39 if err != nil { 40 return p.handleHTTPError(ctx, w, r, rr, http.StatusNotFound) 41 } 42 43 if asset.Restricted && !rr.Response.Authenticated { 44 // If an asset is a protected asset and a user is not authorized, 45 // then deny access to the asset. 46 return p.handleHTTPError(ctx, w, r, rr, http.StatusUnauthorized) 47 } 48 49 w.Header().Set("Content-Type", asset.ContentType) 50 w.Header().Set("Etag", asset.Checksum) 51 w.Header().Set("Cache-Control", "max-age=7200") 52 if match := r.Header.Get("If-None-Match"); match != "" { 53 if strings.Contains(match, asset.Checksum) { 54 w.WriteHeader(http.StatusNotModified) 55 return nil 56 } 57 } 58 // TODO(greenpau): add compressed output, e.g. bzip. 59 w.WriteHeader(http.StatusOK) 60 io.WriteString(w, asset.Content) 61 return nil 62 }