Skip to content

Commit

Permalink
refactor: move users logic to integrations
Browse files Browse the repository at this point in the history
  • Loading branch information
Emyr298 committed Jun 29, 2024
1 parent 1680afd commit 1f8930f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 38 deletions.
48 changes: 10 additions & 38 deletions src/handlers/auth_handler.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
package handlers

import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"os"

"pixeltactics.com/match/src/exceptions"
integration_users "pixeltactics.com/match/src/integrations/users"
"pixeltactics.com/match/src/utils"
ws_types "pixeltactics.com/match/src/websocket/types"
)
Expand Down Expand Up @@ -100,46 +97,21 @@ func (handler *AuthHandler) sendAuthRequest(playerToken string, res *ws_types.Re
}
}

host := os.Getenv("USER_MICROSERVICE_URL")
client := &http.Client{}
req, err := http.NewRequest("GET", host+"/auth/current", nil)
playerId, err := integration_users.GetUsernameFromToken(playerToken)
if err != nil {
log.Println("ERROR REQUEST MAKE")
sendError()
return
}
req.Header.Set("Authorization", "Bearer "+playerToken)
resp, err := client.Do(req)
if err != nil {
log.Println("ERROR REQUEST SEND")
sendError()
}

if resp.StatusCode == 200 {
jsonBytes, err := io.ReadAll(resp.Body)
if err != nil {
sendError()
}

var body map[string]string
json.Unmarshal(jsonBytes, &body)

playerId, ok := body["username"]
if !ok {
sendError()
}

handler.successResponses <- &ws_types.Interaction{
Request: &ws_types.Request{
Message: &ws_types.Message{
Body: map[string]interface{}{
"playerId": playerId,
},
handler.successResponses <- &ws_types.Interaction{
Request: &ws_types.Request{
Message: &ws_types.Message{
Body: map[string]interface{}{
"playerId": playerId,
},
},
Response: res,
}
} else {
sendError()
},
Response: res,
}
}()
}
Expand Down
44 changes: 44 additions & 0 deletions src/integrations/users/users_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package integration_users

import (
"encoding/json"
"errors"
"io"
"net/http"
"os"
)

func GetUsernameFromToken(playerToken string) (string, error) {
host := os.Getenv("USER_MICROSERVICE_URL")

client := &http.Client{}
req, err := http.NewRequest("GET", host+"/auth/current", nil)
if err != nil {
return "", err
}

req.Header.Set("Authorization", "Bearer "+playerToken)
resp, err := client.Do(req)
if err != nil {
return "", err
}

if resp.StatusCode != 200 {
return "", errors.New("invalid token")
}

jsonBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

var body map[string]string
json.Unmarshal(jsonBytes, &body)

playerId, ok := body["username"]
if !ok {
return "", errors.New("invalid json body")
}

return playerId, nil
}

0 comments on commit 1f8930f

Please sign in to comment.