Skip to content

Commit 059be25

Browse files
committed
added viewuseraccount, updated documentation
1 parent 001cbd3 commit 059be25

File tree

4 files changed

+51
-2
lines changed

4 files changed

+51
-2
lines changed

handlers/LogInUser.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ func (h handler) LogInUser(w http.ResponseWriter, r *http.Request) {
4747

4848
tokenString := helpers.GenerateJWT(userInput.Username)
4949

50-
// Send a 201 created response
50+
// Send a 201 response
5151
w.Header().Add("Content-Type", "application/json")
5252
w.WriteHeader(http.StatusOK)
5353
json.NewEncoder(w).Encode(tokenString)

handlers/ViewUserAccount.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

main.go

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ func main() {
2020

2121
router.HandleFunc("/createuser", h.CreateUserAccount).Methods(http.MethodPost)
2222
router.HandleFunc("/login", h.LogInUser).Methods(http.MethodPost)
23+
router.HandleFunc("/viewaccount", h.ViewUserAccount).Methods(http.MethodGet)
2324

2425
log.Println("API is running!")
2526
http.ListenAndServe(":4000", router)

models/models.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,4 @@ type Account struct {
1717
Name string
1818
Balance uint
1919
UserID uint
20-
}
20+
}

0 commit comments

Comments
 (0)