-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
handler_user.go
84 lines (73 loc) · 2.01 KB
/
handler_user.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
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log"
"net/http"
"time"
"github.com/bootdotdev/learn-cicd-starter/internal/database"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Name string `json:"name"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
apiKey, err := generateRandomSHA256Hash()
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't gen apikey")
return
}
err = cfg.DB.CreateUser(r.Context(), database.CreateUserParams{
ID: uuid.New().String(),
CreatedAt: time.Now().UTC().Format(time.RFC3339),
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
Name: params.Name,
ApiKey: apiKey,
})
if err != nil {
log.Println(err)
respondWithError(w, http.StatusInternalServerError, "Couldn't create user")
return
}
user, err := cfg.DB.GetUser(r.Context(), apiKey)
if err != nil {
log.Println(err)
respondWithError(w, http.StatusInternalServerError, "Couldn't get user")
return
}
userResp, err := databaseUserToUser(user)
if err != nil {
log.Println(err)
respondWithError(w, http.StatusInternalServerError, "Couldn't convert user")
return
}
respondWithJSON(w, http.StatusCreated, userResp)
}
func generateRandomSHA256Hash() (string, error) {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
hash := sha256.Sum256(randomBytes)
hashString := hex.EncodeToString(hash[:])
return hashString, nil
}
func (cfg *apiConfig) handlerUsersGet(w http.ResponseWriter, r *http.Request, user database.User) {
userResp, err := databaseUserToUser(user)
if err != nil {
log.Println(err)
respondWithError(w, http.StatusInternalServerError, "Couldn't convert user")
return
}
respondWithJSON(w, http.StatusOK, userResp)
}