|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "gorm.io/gorm" |
| 10 | + "mangofinance.com/bank-backend/helpers" |
| 11 | + "mangofinance.com/bank-backend/models" |
| 12 | +) |
| 13 | + |
| 14 | +// Receives: response and request writers |
| 15 | +// function receives input from the user containing the access |
| 16 | +// token. We then check if the token is authorized. Retrieve |
| 17 | +// the username from it, retrieve the user id from the |
| 18 | +// username, and use that to retrieve the account detail |
| 19 | +// Returns: json containing account detail |
| 20 | +func (h handler) ViewUserAccount(w http.ResponseWriter, r *http.Request) { |
| 21 | + defer r.Body.Close() |
| 22 | + |
| 23 | + userToken := r.Header.Get("x-access-token") |
| 24 | + |
| 25 | + var user models.User |
| 26 | + var account models.Account |
| 27 | + |
| 28 | + userName := helpers.IsAuthorized(w, userToken) |
| 29 | + |
| 30 | + findUser := h.DB.Where("Username = ?", userName).First(&user) |
| 31 | + if errors.Is(findUser.Error, gorm.ErrRecordNotFound) { |
| 32 | + w.Header().Add("Content-Type", "application/json") |
| 33 | + w.WriteHeader(http.StatusNotFound) |
| 34 | + json.NewEncoder(w).Encode("User not found") |
| 35 | + } |
| 36 | + |
| 37 | + getUserAccount := h.DB.Where("user_id = ?", user.ID).First(&account) |
| 38 | + if errors.Is(getUserAccount.Error, gorm.ErrRecordNotFound) { |
| 39 | + w.Header().Add("Content-Type", "application/json") |
| 40 | + w.WriteHeader(http.StatusNotFound) |
| 41 | + json.NewEncoder(w).Encode("Account not found") |
| 42 | + } |
| 43 | + |
| 44 | + // Send a 201 retrieved response |
| 45 | + w.Header().Add("Content-Type", "application/json") |
| 46 | + w.WriteHeader(http.StatusCreated) |
| 47 | + json.NewEncoder(w).Encode(account) |
| 48 | +} |
0 commit comments