Skip to content

Commit

Permalink
create user and update user modified based on middleware requirement
Browse files Browse the repository at this point in the history
  • Loading branch information
iamananya committed Jun 1, 2023
1 parent be4d332 commit 6306b4c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
Binary file modified cmd/main/main
Binary file not shown.
17 changes: 12 additions & 5 deletions pkg/controllers/gacha-controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,18 @@ func CreateUser(w http.ResponseWriter, r *http.Request) {

func UpdateUser(w http.ResponseWriter, r *http.Request) {
// Retrieve the user from the context
user := r.Context().Value("user").(*models.User)
user, ok := r.Context().Value("user").(models.User)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

var updateUser models.User
utils.ParseBody(r, &updateUser)
fmt.Print(user)
err := utils.ParseBody(r, &updateUser)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}

if updateUser.Name != "" {
user.Name = updateUser.Name
Expand All @@ -81,9 +88,9 @@ func UpdateUser(w http.ResponseWriter, r *http.Request) {
user.Token = updateUser.Token
}

err := models.UpdateUser(user)
err = models.UpdateUser(&user)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

Expand Down
4 changes: 4 additions & 0 deletions pkg/middlewares/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import (
// and adds the user to the context of the request.
func AuthenticationMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && r.URL.Path == "/user/" {
next.ServeHTTP(w, r)
return
}
token := r.Header.Get("X-Token")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
Expand Down

0 comments on commit 6306b4c

Please sign in to comment.