Skip to content

Commit

Permalink
:sparcles: Usersの実装
Browse files Browse the repository at this point in the history
  • Loading branch information
pikachu0310 committed Feb 1, 2024
1 parent 32738be commit 605e87c
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 108 deletions.
46 changes: 46 additions & 0 deletions internal/api/discord.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package api

import (
"encoding/json"
"io"
"net/http"

"github.com/labstack/echo/v4"
)

type DiscordUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
}

func GetDiscordUserInfo(accessToken *string) (*DiscordUserResponse, error) {
req, err := http.NewRequest("GET", "https://discordapp.com/api/users/@me", nil)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
req.Header.Set("Authorization", "Bearer "+*accessToken)

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to get Discord user: status "+resp.Status)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

var discordUser DiscordUserResponse
if err = json.Unmarshal(body, &discordUser); err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

return &discordUser, nil
}
14 changes: 7 additions & 7 deletions internal/domains/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ CREATE TABLE session
*/

type Session struct {
ID *uuid.UUID `db:"id"`
Redirect *string `db:"redirect"`
AccessToken *string `db:"access_token"`
RefreshToken *string `db:"refresh_token"`
ExpiresIn *int `db:"expires_in"`
CreatedAt *time.Time `db:"created_at"`
UpdatedAt *time.Time `db:"updated_at"`
ID *uuid.UUID
Redirect *string
AccessToken *string
RefreshToken *string
ExpiresIn *int
CreatedAt *time.Time
UpdatedAt *time.Time
}
7 changes: 5 additions & 2 deletions internal/handler/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/traPtitech/game3-back/internal/domains"
"github.com/traPtitech/game3-back/internal/repository"
"github.com/traPtitech/game3-back/openapi/models"
"io/ioutil"
"io"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -117,8 +117,11 @@ func (h *Handler) OauthCallback(c echo.Context, params models.OauthCallbackParam
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return echo.NewHTTPError(http.StatusInternalServerError, "Discord OAuth failed: status: "+resp.Status)
}

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
Expand Down
164 changes: 65 additions & 99 deletions internal/handler/user.go
Original file line number Diff line number Diff line change
@@ -1,112 +1,78 @@
package handler

import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/traPtitech/game3-back/internal/api/models"
"github.com/traPtitech/game3-back/internal/api"
"github.com/traPtitech/game3-back/openapi/models"
"net/http"
)

func (h *Handler) GetMe(ctx echo.Context) error {
panic("implement me")
type DiscordUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
}
func (h *Handler) GetMeGames(ctx echo.Context) error {
panic("implement me")

func (h *Handler) GetMe(c echo.Context) error {
cookie, err := c.Cookie("SessionToken")
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "SessionToken is not found")
}
sessionID, err := uuid.Parse(cookie.Value)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "SessionToken is invalid")
}

session, err := h.repo.GetSession(sessionID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

discordUser, err := api.GetDiscordUserInfo(session.AccessToken)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

return c.JSON(http.StatusOK, discordUser)
}
func (h *Handler) GetMeGames(c echo.Context) error {
cookie, err := c.Cookie("SessionToken")
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "SessionToken is not found")
}
sessionID, err := uuid.Parse(cookie.Value)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "SessionToken is invalid")
}

session, err := h.repo.GetSession(sessionID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

func (h *Handler) GetUser(ctx echo.Context, userId models.UserIdInPath) error {
panic("implement me")
discordUser, err := api.GetDiscordUserInfo(session.AccessToken)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

games, err := h.repo.GetGames(models.GetGamesParams{UserId: &discordUser.ID})
if err != nil {
return err
}

return c.JSON(http.StatusOK, games)
}

func (h *Handler) GetUserGames(ctx echo.Context, userId models.UserIdInPath) error {
panic("implement me")
func (h *Handler) GetUser(c echo.Context, userId models.UserIdInPath) error {
return c.JSON(http.StatusNotImplemented, nil)
}

//// スキーマ定義
//type (
// GetUsersResponse []GetUserResponse
//
// GetUserResponse struct {
// ID uuid.UUID `json:"id"`
// Name string `json:"name"`
// Email string `json:"email"`
// }
//
// CreateUserRequest struct {
// Name string `json:"name"`
// Email string `json:"email"`
// }
//
// CreateUserResponse struct {
// ID uuid.UUID `json:"id"`
// }
//)
//
//// GET /api/v1/users
//func (h *Handler) GetUsers(c echo.Context) error {
// users, err := h.repo.GetUsers(c.Request().Context())
// if err != nil {
// return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
// }
//
// res := make(GetUsersResponse, len(users))
// for i, user := range users {
// res[i] = GetUserResponse{
// ID: user.ID,
// Name: user.Name,
// Email: user.Email,
// }
// }
//
// return c.JSON(http.StatusOK, res)
//}
//
//// POST /api/v1/users
//func (h *Handler) CreateUser(c echo.Context) error {
// req := new(CreateUserRequest)
// if err := c.Bind(req); err != nil {
// return echo.NewHTTPError(http.StatusBadRequest, "invalid request body").SetInternal(err)
// }
//
// err := vd.ValidateStruct(
// req,
// vd.Field(&req.Name, vd.Required),
// vd.Field(&req.Email, vd.Required, is.Email),
// )
// if err != nil {
// return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid request body: %w", err)).SetInternal(err)
// }
//
// userID, err := h.repo.CreateUser(c.Request().Context(), repository.CreateUserParams{
// Name: req.Name,
// Email: req.Email,
// })
// if err != nil {
// return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
// }
//
// res := CreateUserResponse{
// ID: userID,
// }
//
// return c.JSON(http.StatusOK, res)
//}
//
//// GET /api/v1/users/:userID
//func (h *Handler) GetUser(c echo.Context) error {
// userID, err := uuid.Parse(c.Param("userID"))
// if err != nil {
// return echo.NewHTTPError(http.StatusBadRequest, "invalid userID").SetInternal(err)
// }
//
// user, err := h.repo.GetUser(c.Request().Context(), userID)
// if err != nil {
// return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
// }
//
// res := GetUserResponse{
// ID: user.ID,
// Name: user.Name,
// Email: user.Email,
// }
//
// return c.JSON(http.StatusOK, res)
//}
func (h *Handler) GetUserGames(c echo.Context, userId models.UserIdInPath) error {
games, err := h.repo.GetGames(models.GetGamesParams{UserId: &userId})
if err != nil {
return err
}

return c.JSON(http.StatusOK, games)
}

0 comments on commit 605e87c

Please sign in to comment.