-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-create.go
More file actions
66 lines (53 loc) · 1.66 KB
/
user-create.go
File metadata and controls
66 lines (53 loc) · 1.66 KB
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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/mdmdj/bootdev-chirpy/internal/auth"
"github.com/mdmdj/bootdev-chirpy/internal/database"
)
func userCreateRoute(w http.ResponseWriter, r *http.Request) {
requestParams := userCreateRequest{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&requestParams)
if err != nil {
log.Printf("Error decoding userCreateRequest parameters: %s", err)
respondWithError(w, http.StatusBadRequest, "Something went wrong")
return
}
if requestParams.Email == "" || requestParams.Password == "" {
log.Printf("Error with userCreateRequest parameters: %s %s", requestParams.Email, requestParams.Password)
respondWithError(w, http.StatusBadRequest, "Must supply email and password")
return
}
hash, err := auth.HashPassword(requestParams.Password)
if err != nil {
log.Printf("Error with password: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
fmt.Println("Creating User")
fmt.Println(requestParams.Email)
fmt.Println(requestParams.Password)
fmt.Println(hash)
dbUser, err := cfg.db.CreateUser(
r.Context(),
database.CreateUserParams{
Email: requestParams.Email,
HashedPassword: hash})
if err != nil {
log.Printf("Error creating user: %s %s", err, requestParams.Email)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// Map database.User to main.User
user := User{
ID: dbUser.ID,
CreatedAt: dbUser.CreatedAt,
UpdatedAt: dbUser.UpdatedAt,
Email: dbUser.Email,
IsChirpyRed: dbUser.IsChirpyRed.Bool,
}
respondWithJSON(w, http.StatusCreated, user)
}