github.com/greenpau/go-authcrunch@v1.0.50/pkg/authn/handle_http_settings_apikeys.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 "fmt" 20 "github.com/greenpau/go-authcrunch/pkg/authn/enums/operator" 21 "github.com/greenpau/go-authcrunch/pkg/identity" 22 "github.com/greenpau/go-authcrunch/pkg/ids" 23 "github.com/greenpau/go-authcrunch/pkg/requests" 24 "github.com/greenpau/go-authcrunch/pkg/user" 25 "net/http" 26 "strings" 27 ) 28 29 func (p *Portal) handleHTTPAPIKeysSettings( 30 ctx context.Context, r *http.Request, rr *requests.Request, 31 usr *user.User, store ids.IdentityStore, data map[string]interface{}, 32 ) error { 33 var action string 34 var status bool 35 entrypoint := "apikeys" 36 data["view"] = entrypoint 37 endpoint, err := getEndpoint(r.URL.Path, "/"+entrypoint) 38 if err != nil { 39 return err 40 } 41 switch { 42 case strings.HasPrefix(endpoint, "/add") && r.Method == "POST": 43 action = "add" 44 status = true 45 if err := validateAPIKeyInputForm(r, rr); err != nil { 46 attachFailStatus(data, "Bad Request") 47 break 48 } 49 rr.Key.Usage = "api" 50 if err = store.Request(operator.AddAPIKey, rr); err != nil { 51 attachFailStatus(data, fmt.Sprintf("%v", err)) 52 break 53 } 54 data["api_key"] = rr.Response.Payload.(string) 55 attachSuccessStatus(data, "New API key has been added") 56 case strings.HasPrefix(endpoint, "/add"): 57 action = "add" 58 case strings.HasPrefix(endpoint, "/delete"): 59 action = "delete" 60 status = true 61 keyID, err := getEndpointKeyID(endpoint, "/delete/") 62 if err != nil { 63 attachFailStatus(data, fmt.Sprintf("%v", err)) 64 break 65 } 66 rr.Key.ID = keyID 67 if err = store.Request(operator.DeleteAPIKey, rr); err != nil { 68 attachFailStatus(data, fmt.Sprintf("failed deleting key id %s: %v", keyID, err)) 69 break 70 } 71 attachSuccessStatus(data, fmt.Sprintf("key id %s deleted successfully", keyID)) 72 default: 73 // List API Keys. 74 rr.Key.Usage = "api" 75 if err = store.Request(operator.GetAPIKeys, rr); err != nil { 76 attachFailStatus(data, fmt.Sprintf("%v", err)) 77 break 78 } 79 bundle := rr.Response.Payload.(*identity.APIKeyBundle) 80 pubKeys := bundle.Get() 81 if len(pubKeys) > 0 { 82 data[entrypoint] = pubKeys 83 } 84 85 } 86 attachView(data, entrypoint, action, status) 87 return nil 88 }