-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontroller.go
92 lines (74 loc) · 1.66 KB
/
controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"context"
"encoding/json"
"net/http"
"time"
)
type doc struct {
Id string `json:"id"`
Num string `json:"num"`
Date time.Time `json:"date"`
}
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type loginResponse struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresIn int `json:"expiresIn"`
}
type controller struct {
keycloak *keycloak
}
func newController(keycloak *keycloak) *controller {
return &controller{
keycloak: keycloak,
}
}
func (c *controller) login(w http.ResponseWriter, r *http.Request) {
rq := &loginRequest{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(rq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
jwt, err := c.keycloak.gocloak.Login(context.Background(),
c.keycloak.clientId,
c.keycloak.clientSecret,
c.keycloak.realm,
rq.Username,
rq.Password)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
rs := &loginResponse{
AccessToken: jwt.AccessToken,
RefreshToken: jwt.RefreshToken,
ExpiresIn: jwt.ExpiresIn,
}
rsJs, _ := json.Marshal(rs)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(rsJs)
}
func (c *controller) getDocs(w http.ResponseWriter, r *http.Request) {
rs := []*doc{
{
Id: "1",
Num: "ABC-123",
Date: time.Now().UTC(),
},
{
Id: "2",
Num: "ABC-456",
Date: time.Now().UTC(),
},
}
rsJs, _ := json.Marshal(rs)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(rsJs)
}