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