-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetuser.go
113 lines (91 loc) · 2.54 KB
/
getuser.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
package main
import (
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
auth "github.com/jaydee029/Verses/internal/auth"
"github.com/jaydee029/Verses/internal/database"
)
func (cfg *apiconfig) getUser(w http.ResponseWriter, r *http.Request) {
token, err := auth.BearerHeader(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
authorid, err := auth.ValidateToken(token, cfg.jwtsecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
username := chi.URLParam(r, "username")
var pgUUID pgtype.UUID
err = pgUUID.Scan(authorid)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
user, err := cfg.DB.GetUsersingle(r.Context(), database.GetUsersingleParams{
FolloweeID: pgUUID,
Username: username,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "User profile couldn't be fetched")
return
}
respondWithJson(w, http.StatusOK, User{
Name: user.Name,
Username: user.Username,
ID: user.ID,
Follower: user.Follower,
Following: user.Following,
})
}
func (cfg *apiconfig) getUsers(w http.ResponseWriter, r *http.Request) {
token, err := auth.BearerHeader(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
authorid, err := auth.ValidateToken(token, cfg.jwtsecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
after := r.URL.Query().Get("username")
var pgUUID pgtype.UUID
err = pgUUID.Scan(authorid)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
limitstr := r.URL.Query().Get("limit")
if limitstr == "" {
limitstr = "10"
}
limit, err := strconv.ParseInt(limitstr, 10, 32)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
users, err := cfg.DB.GetUsers(r.Context(), database.GetUsersParams{
FolloweeID: pgUUID,
Username: after,
Limit: int32(limit),
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Users couldn't be retrieved")
return
}
var Users []User
for _, user := range users {
Users = append(Users, User{
Name: user.Name,
Username: user.Username,
Follower: user.Follower,
Following: user.Following,
ID: user.ID,
})
}
respondWithJson(w, http.StatusOK, Users)
}