institution.go (2716B)
1 // Copyright 2026 Shivakumar (Certichain) 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 handlers 16 17 import ( 18 "encoding/hex" 19 "encoding/json" 20 "errors" 21 "net/http" 22 23 "certichain/api/dto" 24 "certichain/api/respond" 25 "certichain/internal/registry" 26 "certichain/internal/storage" 27 ) 28 29 // RegisterInstitution returns a handler for POST /v1/institutions. 30 func RegisterInstitution(reg *registry.Registry) http.HandlerFunc { 31 return func(w http.ResponseWriter, r *http.Request) { 32 var req dto.RegisterInstitutionRequest 33 if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 34 respond.Error(w, http.StatusBadRequest, "invalid_body", "malformed JSON body") 35 return 36 } 37 38 pubKey, err := hex.DecodeString(req.PublicKey) 39 if err != nil { 40 respond.Error(w, http.StatusBadRequest, "invalid_body", "Invalid Hex Encoding") 41 return 42 } 43 44 did, err := reg.Register(pubKey) 45 if err != nil { 46 switch { 47 case errors.Is(err, registry.ErrInvalidKey): 48 respond.Error(w, http.StatusBadRequest, "invalid_body", "Invalid Public Key") 49 case errors.Is(err, registry.ErrAlreadyExists): 50 respond.Error(w, http.StatusConflict, "already_exists", "Public Key already exists") 51 default: 52 respond.Error(w, http.StatusInternalServerError, "server_error", "Internal Server Error") 53 } 54 return 55 } 56 57 respond.JSON(w, http.StatusCreated, dto.RegisterInstitutionResponse{DID: did}) 58 } 59 } 60 61 // GetInstitution returns a handler for Get /v1/institutions/{did}. 62 func GetInstitution(reg *registry.Registry) http.HandlerFunc { 63 return func(w http.ResponseWriter, r *http.Request) { 64 did := r.PathValue("did") 65 66 _, err := reg.Get(did) 67 switch { 68 case err == nil: 69 respond.JSON(w, http.StatusOK, &dto.GetInstitutionResponse{ 70 DID: did, 71 Registered: true, 72 }) 73 return 74 case errors.Is(err, storage.ErrNotFound): 75 respond.JSON(w, http.StatusOK, &dto.GetInstitutionResponse{ 76 DID: "", 77 Registered: false, 78 }) 79 return 80 case errors.Is(err, registry.ErrInvalidDID): 81 respond.Error(w, http.StatusBadRequest, "invalid_did", "malformed DID") 82 return 83 default: 84 respond.Error(w, http.StatusInternalServerError, "server_error", "Internal Server Error") 85 return 86 } 87 } 88 }