-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
287 lines (206 loc) · 5.72 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/gorilla/mux"
)
type APIServer struct {
listenAddr string
store Storage
}
func NewApiServer(listenAddr string, store Storage) *APIServer {
return &APIServer{
listenAddr: listenAddr,
store: store,
}
}
func (s *APIServer) Run() {
router := mux.NewRouter()
router.HandleFunc("/login/", makeHTTPHandleFunc(s.handleLogin))
router.HandleFunc("/account/", makeHTTPHandleFunc(s.handleAccount))
router.HandleFunc("/account/{id}", withJWTAuth(makeHTTPHandleFunc(s.handleGetAccountByID), s.store))
router.HandleFunc("/transfer/", makeHTTPHandleFunc(s.handleTransfer))
log.Println("JSON API server is running on port :", s.listenAddr)
http.ListenAndServe(s.listenAddr, router)
}
func (s *APIServer) handleLogin(w http.ResponseWriter, r *http.Request) error {
if r.Method != "POST" {
return fmt.Errorf("method not allowed %s", r.Method)
}
var req LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return err
}
acc, err := s.store.GetAccountByNumber(int(req.Number))
if err != nil {
return err
}
if !acc.ValidatePassowrd(req.Password) {
return fmt.Errorf("not authenticated")
}
token, err := createJWT(acc)
if err != nil {
return nil
}
resp := LoginResponse{
Token: token,
Number: acc.Number,
}
fmt.Printf("%+v\n", acc)
return WriteJSON(w, http.StatusOK, resp)
}
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 is not allowd %s", r.Method)
}
// GET Accounts
func (s *APIServer) handleGetAccount(w http.ResponseWriter, r *http.Request) error {
account, err := s.store.GetAccounts()
if err != nil {
return err
}
return WriteJSON(w, http.StatusOK, account)
}
func (s *APIServer) handleGetAccountByID(w http.ResponseWriter, r *http.Request) error {
if r.Method == "GET" {
id, err := getID(r)
if err != nil {
return err
}
account, err := s.store.GetAccountByID(id)
if err != nil {
return err
}
return WriteJSON(w, http.StatusOK, account)
}
if r.Method == "DELETE" {
return s.handleDeleteAccount(w, r)
}
return fmt.Errorf("method is not allowed %s", r.Method)
}
func (s *APIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) error {
createAccountReq := CreateAccountRequest{}
if err := json.NewDecoder(r.Body).Decode(&createAccountReq); err != nil {
return err
}
account, err := NewAccount(createAccountReq.FirstName, createAccountReq.LastName, createAccountReq.Password)
if err != nil {
return err
}
// store in db
if err := s.store.CreateAccount(account); err != nil {
return err
}
tokenString, err := createJWT(account)
if err != nil {
return err
}
fmt.Println("JWT Token :- ", tokenString)
return WriteJSON(w, http.StatusOK, account)
}
func (s *APIServer) handleDeleteAccount(w http.ResponseWriter, r *http.Request) error {
id, err := getID(r)
if err != nil {
return err
}
if err := s.store.DeleteAccount(id); err != nil {
return err
}
return WriteJSON(w, http.StatusOK, map[string]int{"delete": id})
}
func (s *APIServer) handleTransfer(w http.ResponseWriter, r *http.Request) error {
transferRequest := new(TransferRequest)
if err := json.NewDecoder(r.Body).Decode(transferRequest); err != nil {
return err
}
defer r.Body.Close()
return WriteJSON(w, http.StatusOK, transferRequest)
}
func WriteJSON(w http.ResponseWriter, status int, v any) error {
w.Header().Add("Content-Type", "applicatioan/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
func createJWT(account *Account) (string, error) {
claims := &jwt.MapClaims{
"expiresAt": 15000,
"accountNumber": account.Number,
}
secret := os.Getenv("JWT_SECRET")
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(secret))
}
func Permissondenied(w http.ResponseWriter) {
WriteJSON(w, http.StatusForbidden, ApiError{Error: "permisson denied"})
}
// For Protect our end-points
func withJWTAuth(handerFunc http.HandlerFunc, s Storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("JWT Auth Function")
tokenString := r.Header.Get("x-jwt-token")
token, err := validateJWT(tokenString)
if err != nil {
Permissondenied(w)
return
}
if !token.Valid {
Permissondenied(w)
return
}
userID, err := getID(r)
if err != nil {
Permissondenied(w)
return
}
account, err := s.GetAccountByID(userID)
if err != nil {
Permissondenied(w)
return
}
claims := token.Claims.(jwt.MapClaims)
if account.Number != int64(claims["accountNumber"].(float64)) {
Permissondenied(w)
return
}
fmt.Println(claims)
handerFunc(w, r)
}
}
func validateJWT(tokenstring string) (*jwt.Token, error) {
secret := os.Getenv("JWT_SECRET")
return jwt.Parse(tokenstring, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v ", token.Header["alg"])
}
return []byte(secret), nil
})
}
type apiFunc func(http.ResponseWriter, *http.Request) error
type ApiError struct {
Error string `json:"error"`
}
func makeHTTPHandleFunc(f apiFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
WriteJSON(w, http.StatusBadRequest, ApiError{Error: err.Error()})
}
}
}
func getID(r *http.Request) (int, error) {
idstr := mux.Vars(r)["id"]
id, err := strconv.Atoi(idstr)
if err != nil {
return id, fmt.Errorf("Account %d not found", id)
}
return id, nil
}