| Giorgi Lekveishvili | fedd006 | 2023-12-21 10:52:49 +0400 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| Giorgi Lekveishvili | 8339905 | 2024-02-14 13:27:30 +0400 | [diff] [blame] | 7 | "io" |
| Giorgi Lekveishvili | fedd006 | 2023-12-21 10:52:49 +0400 | [diff] [blame] | 8 | "net/http" |
| 9 | |
| 10 | "github.com/gorilla/mux" |
| 11 | ) |
| 12 | |
| 13 | type APIServer struct { |
| 14 | r *mux.Router |
| 15 | serv *http.Server |
| 16 | kratosAddr string |
| 17 | } |
| 18 | |
| 19 | func NewAPIServer(port int, kratosAddr string) *APIServer { |
| 20 | r := mux.NewRouter() |
| 21 | serv := &http.Server{ |
| 22 | Addr: fmt.Sprintf(":%d", port), |
| 23 | Handler: r, |
| 24 | } |
| 25 | return &APIServer{r, serv, kratosAddr} |
| 26 | } |
| 27 | |
| 28 | func (s *APIServer) Start() error { |
| 29 | s.r.Path("/identities").Methods(http.MethodPost).HandlerFunc(s.identityCreate) |
| 30 | return s.serv.ListenAndServe() |
| 31 | } |
| 32 | |
| 33 | const identityCreateTmpl = ` |
| 34 | { |
| 35 | "credentials": { |
| 36 | "password": { |
| 37 | "config": { |
| 38 | "password": "%s" |
| 39 | } |
| 40 | } |
| 41 | }, |
| 42 | "schema_id": "user", |
| 43 | "state": "active", |
| 44 | "traits": { |
| 45 | "username": "%s" |
| 46 | } |
| 47 | } |
| 48 | ` |
| 49 | |
| 50 | type identityCreateReq struct { |
| 51 | Username string `json:"username,omitempty"` |
| 52 | Password string `json:"password,omitempty"` |
| 53 | } |
| 54 | |
| 55 | func (s *APIServer) identityCreate(w http.ResponseWriter, r *http.Request) { |
| 56 | var req identityCreateReq |
| 57 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 58 | http.Error(w, "request can not be parsed", http.StatusBadRequest) |
| 59 | return |
| 60 | } |
| 61 | var buf bytes.Buffer |
| 62 | fmt.Fprintf(&buf, identityCreateTmpl, req.Password, req.Username) |
| 63 | resp, err := http.Post(s.identitiesEndpoint(), "application/json", &buf) |
| Giorgi Lekveishvili | 8339905 | 2024-02-14 13:27:30 +0400 | [diff] [blame] | 64 | if err != nil { |
| Giorgi Lekveishvili | fedd006 | 2023-12-21 10:52:49 +0400 | [diff] [blame] | 65 | http.Error(w, "failed", http.StatusInternalServerError) |
| 66 | return |
| Giorgi Lekveishvili | 8339905 | 2024-02-14 13:27:30 +0400 | [diff] [blame] | 67 | } else if resp.StatusCode != http.StatusCreated { |
| 68 | var buf bytes.Buffer |
| 69 | if _, err := io.Copy(&buf, resp.Body); err != nil { |
| 70 | http.Error(w, "failed to copy response body", http.StatusInternalServerError) |
| 71 | } else { |
| 72 | http.Error(w, buf.String(), resp.StatusCode) |
| 73 | } |
| Giorgi Lekveishvili | fedd006 | 2023-12-21 10:52:49 +0400 | [diff] [blame] | 74 | } |
| 75 | } |
| 76 | |
| 77 | func (s *APIServer) identitiesEndpoint() string { |
| 78 | return fmt.Sprintf("%s/admin/identities", s.kratosAddr) |
| 79 | } |