/
api.go
201 lines (172 loc) · 4.86 KB
/
api.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/golang-jwt/jwt"
"github.com/gorilla/mux"
)
type APIServer struct {
ListenAddress string
Store Storage
}
func writeJson(w http.ResponseWriter, status int, v any) error {
w.Header().Add("content-type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
type apifunc func(w http.ResponseWriter, r *http.Request) error
type ApiError struct {
Error string
}
func makeHttpHandler(f apifunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
writeJson(w, 400, err.Error())
}
}
}
func newAPIServer(listen string, store Storage) *APIServer {
return &APIServer{
ListenAddress: listen,
Store: store,
}
}
func (s *APIServer) run() {
r := mux.NewRouter()
r.HandleFunc("/account", withJWTAuth(makeHttpHandler(s.handleAccount)))
r.HandleFunc("/account/{id}", makeHttpHandler(s.handleAccountByID))
r.HandleFunc("/transfer", makeHttpHandler(s.handleTransfer))
r.HandleFunc("/login", makeHttpHandler(s.handleLogin))
http.ListenAndServe(s.ListenAddress, r)
}
func (s *APIServer) handleLogin(w http.ResponseWriter, r *http.Request) error {
if r.Method != "POST" {
return fmt.Errorf("method not allowed %s", r.Method)
}
loginRequest := LoginRequest{}
err := json.NewDecoder(r.Body).Decode(&loginRequest)
if err != nil {
return fmt.Errorf("wrong")
}
accInt, err := strconv.Atoi(loginRequest.Username)
if err != nil {
return fmt.Errorf("ow")
}
acc, err := s.Store.GetAccount(accInt)
if err != nil {
return fmt.Errorf("ow")
}
token, err := generateJWT()
if err != nil {
return fmt.Errorf("oops again")
}
resp := LoginResponse{
Token: token,
UserID: fmt.Sprint(acc.Number),
}
return writeJson(w, http.StatusOK, resp)
}
func (s *APIServer) handleAccountByID(w http.ResponseWriter, r *http.Request) error {
if r.Method == "GET" {
strId := mux.Vars(r)["id"]
id, err := strconv.Atoi(strId)
if err != nil {
return fmt.Errorf("invalid id %s", strId)
}
account, err := s.Store.GetAccount(id)
if err != nil {
return err
}
return writeJson(w, http.StatusOK, account)
}
return fmt.Errorf("invalid method type %s", r.Method)
}
func (s *APIServer) handleAccount(w http.ResponseWriter, r *http.Request) error {
if r.Method == "GET" {
return s.handleGetAccount(w, r)
}
if r.Method == "POST" {
return s.handleCreateAccount(w, r)
}
return fmt.Errorf("method not supported %s", r.Method)
}
func (s *APIServer) handleGetAccount(w http.ResponseWriter, r *http.Request) error {
accounts, err := s.Store.GetAllAccounts()
if err != nil {
return fmt.Errorf("nothing found %+v", err)
}
return writeJson(w, http.StatusOK, accounts)
}
func (s *APIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) error {
accountapi := &AccountAPI{}
err := json.NewDecoder(r.Body).Decode(accountapi)
if err != nil {
return err
}
newAccount := makeAccount(accountapi.Firstname, accountapi.Lastname)
err = s.Store.CreateAccount(newAccount)
if err != nil {
return err
}
writeJson(w, http.StatusOK, accountapi)
return nil
}
func (s *APIServer) handleTransfer(w http.ResponseWriter, r *http.Request) error {
if r.Method == "POST" {
transferData := &TransferRequest{}
err := json.NewDecoder(r.Body).Decode(transferData)
if err != nil {
return err
}
return writeJson(w, http.StatusOK, transferData)
}
return nil
}
var secret = []byte("somesecretherer")
func generateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodEdDSA)
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute)
claims["auth"] = true
claims["user"] = "just"
claims["role"] = "admin"
tokenString, err := token.SignedString(secret)
if err != nil {
return "", err
}
return tokenString, nil
}
func withJWTAuth(handlefunc http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
token, err := validateJWT(tokenString)
if err != nil {
writeJson(w, http.StatusForbidden, ApiError{Error: "acces denied"})
return
}
if !token.Valid {
writeJson(w, http.StatusForbidden, ApiError{Error: "acces denied"})
return
}
// uid := r.Header
claims := token.Claims.(jwt.MapClaims)
if claims["role"] != "admin" {
writeJson(w, http.StatusForbidden, ApiError{Error: "acces denied"})
return
}
handlefunc(w, r)
}
}
func validateJWT(tokenString string) (*jwt.Token, error) {
return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(secret), nil
})
}