blob: a0065a6b859b7aed1c6005291e74bbb0ee38c797 [file] [log] [blame]
Giorgi Lekveishvilifedd0062023-12-21 10:52:49 +04001package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
Giorgi Lekveishvili83399052024-02-14 13:27:30 +04007 "io"
Giorgi Lekveishvilifedd0062023-12-21 10:52:49 +04008 "net/http"
9
10 "github.com/gorilla/mux"
11)
12
13type APIServer struct {
14 r *mux.Router
15 serv *http.Server
16 kratosAddr string
17}
18
19func 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
28func (s *APIServer) Start() error {
29 s.r.Path("/identities").Methods(http.MethodPost).HandlerFunc(s.identityCreate)
30 return s.serv.ListenAndServe()
31}
32
33const 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
50type identityCreateReq struct {
51 Username string `json:"username,omitempty"`
52 Password string `json:"password,omitempty"`
53}
54
55func (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 Lekveishvili83399052024-02-14 13:27:30 +040064 if err != nil {
Giorgi Lekveishvilifedd0062023-12-21 10:52:49 +040065 http.Error(w, "failed", http.StatusInternalServerError)
66 return
Giorgi Lekveishvili83399052024-02-14 13:27:30 +040067 } 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 Lekveishvilifedd0062023-12-21 10:52:49 +040074 }
75}
76
77func (s *APIServer) identitiesEndpoint() string {
78 return fmt.Sprintf("%s/admin/identities", s.kratosAddr)
79}