Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

team 関連のAPIの実装 #20

Merged
merged 23 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,78 @@ require (
github.com/labstack/echo-contrib v0.17.2
github.com/labstack/echo/v4 v4.13.3
github.com/ogen-go/ogen v1.8.1
github.com/samber/lo v1.47.0
github.com/stephenafamo/bob v0.29.0
go.uber.org/mock v0.5.0
golang.org/x/oauth2 v0.24.0
)

require (
dario.cat/mergo v1.0.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/aarondl/json v0.0.0-20221020222930-8b0db17ef1bf // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/containerd/containerd v1.7.18 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/docker/docker v27.1.1+incompatible // indirect
github.com/docker/go-connections v0.5.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/go-jose/go-jose/v4 v4.0.2 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/patternmatcher v0.6.0 // indirect
github.com/moby/sys/sequential v0.5.0 // indirect
github.com/moby/sys/user v0.1.0 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/qdm12/reprint v0.0.0-20200326205758-722754a53494 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/shirou/gopsutil/v3 v3.23.12 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/stephenafamo/scan v0.6.1 // indirect
github.com/stretchr/testify v1.10.0 // indirect
github.com/testcontainers/testcontainers-go v0.34.0 // indirect
github.com/testcontainers/testcontainers-go/modules/mysql v0.34.0 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
go.opentelemetry.io/otel v1.32.0 // indirect
go.opentelemetry.io/otel/metric v1.32.0 // indirect
go.opentelemetry.io/otel/trace v1.32.0 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/time v0.8.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
133 changes: 133 additions & 0 deletions go.sum

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions server/domain/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@ package domain
import (
"time"

"github.com/google/uuid"
"github.com/traPtitech/piscon-portal-v2/server/utils/random"
)

type Session struct {
ID string
UserID string
UserID uuid.UUID
ExpiresAt time.Time
}

func NewSessionID() string {
return random.String(32)
}

func NewSession(id, userID string, expiresAt time.Time) Session {
func NewSession(id string, userID uuid.UUID, expiresAt time.Time) Session {
return Session{
ID: id,
UserID: userID,
Expand Down
40 changes: 40 additions & 0 deletions server/domain/team.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package domain

import (
"errors"
"slices"
"time"

"github.com/google/uuid"
)

const MaxTeamMembers = 3

type Team struct {
ID uuid.UUID
Name string
Members []User
CreatedAt time.Time
}

func NewTeam(name string) Team {
return Team{
ID: uuid.New(),
Name: name,
CreatedAt: time.Now(),
}
}

func (t *Team) AddMember(user User) error {
if slices.ContainsFunc(t.Members, func(u User) bool { return u.ID == user.ID }) {
return nil
}
if user.TeamID.Valid && user.TeamID.UUID != t.ID {
return errors.New("user is already in another team")
}
if len(t.Members) >= MaxTeamMembers {
return errors.New("team is full")
}
t.Members = append(t.Members, user)
return nil
}
8 changes: 6 additions & 2 deletions server/domain/user.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package domain

import "github.com/google/uuid"

type User struct {
ID string
ID uuid.UUID
Name string

TeamID uuid.NullUUID
}

func NewUser(id, name string) User {
func NewUser(id uuid.UUID, name string) User {
return User{
ID: id,
Name: name,
Expand Down
11 changes: 11 additions & 0 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import (
"github.com/traPtitech/piscon-portal-v2/server/handler/internal"
"github.com/traPtitech/piscon-portal-v2/server/repository"
"github.com/traPtitech/piscon-portal-v2/server/services/oauth2"
"github.com/traPtitech/piscon-portal-v2/server/usecase"
)

type Handler struct {
repo repository.Repository
sessionManager SessionManager
oauth2Service *oauth2.Service

teamUseCase *usecase.TeamUseCase
}

type Config struct {
Expand Down Expand Up @@ -44,6 +47,7 @@ func New(repo repository.Repository, config Config) (*Handler, error) {
repo: repo,
sessionManager: sessionManager,
oauth2Service: oauth2Service,
teamUseCase: usecase.NewTeamUseCase(repo),
}, nil
}

Expand All @@ -54,4 +58,11 @@ func (h *Handler) SetupRoutes(e *echo.Echo) {
api.GET("/oauth2/code", h.GetOauth2Code)
api.GET("/oauth2/callback", h.Oauth2Callback)
api.POST("/oauth2/logout", h.Logout, h.AuthMiddleware())

teams := api.Group("/teams", h.AuthMiddleware())
teams.GET("", h.GetTeams)
teams.POST("", h.CreateTeam)
teams.GET("/:teamID", h.GetTeam)
// TODO: Admins can access even if they are not members of the team.
teams.PATCH("/:teamID", h.UpdateTeam, h.TeamAuthMiddleware())
pirosiki197 marked this conversation as resolved.
Show resolved Hide resolved
}
4 changes: 2 additions & 2 deletions server/handler/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func NewClient(server *httptest.Server) *http.Client {
return client
}

func Login(t *testing.T, server *httptest.Server, client *http.Client, userID string) error {
func Login(t *testing.T, server *httptest.Server, client *http.Client, userID uuid.UUID) error {
t.Helper()

// not following redirect for the first request
Expand All @@ -117,7 +117,7 @@ func Login(t *testing.T, server *httptest.Server, client *http.Client, userID st
return err
}
q := authURL.Query()
q.Add("user", userID)
q.Add("user", userID.String())
authURL.RawQuery = q.Encode()

// from here, follow redirect
Expand Down
43 changes: 43 additions & 0 deletions server/handler/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,22 @@ package handler

import (
"errors"
"net/http"
"slices"
"time"

"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/traPtitech/piscon-portal-v2/server/domain"
"github.com/traPtitech/piscon-portal-v2/server/repository"
)

const userIDKey = "userID"

func getUserIDFromSession(c echo.Context) uuid.UUID {
return c.Get(userIDKey).(uuid.UUID)
}

func (h *Handler) AuthMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
Expand Down Expand Up @@ -36,6 +46,39 @@ func (h *Handler) AuthMiddleware() echo.MiddlewareFunc {
return unauthorizedResponse(c, "session expired")
}

c.Set(userIDKey, session.UserID)

return next(c)
}
}
}

// TeamAuthMiddleware is a middleware that checks if the user is a member of the team.
// The team ID is taken from the URL parameter.
func (h *Handler) TeamAuthMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx := c.Request().Context()

userID := getUserIDFromSession(c)
teamID, err := uuid.Parse(c.Param("teamID"))
if err != nil {
return c.NoContent(http.StatusBadRequest)
}

team, err := h.repo.FindTeam(ctx, teamID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return c.NoContent(http.StatusNotFound)
}
return internalServerErrorResponse(c, err)
}

isMember := slices.ContainsFunc(team.Members, func(m domain.User) bool { return m.ID == userID })
if !isMember {
return c.NoContent(http.StatusForbidden)
}

return next(c)
}
}
Expand Down
70 changes: 68 additions & 2 deletions server/handler/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"
"time"

"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/traPtitech/piscon-portal-v2/server/domain"
sessmock "github.com/traPtitech/piscon-portal-v2/server/handler/internal/mock"
Expand Down Expand Up @@ -37,7 +38,7 @@ func TestAuthMiddleware(t *testing.T) {
mockSessManager.EXPECT().GetSessionID(gomock.Any()).Return("sessionID", nil)
mockRepo.EXPECT().FindSession(gomock.Any(), "sessionID").Return(domain.Session{
ID: "sessionID",
UserID: "test-user-id",
UserID: uuid.New(),
ExpiresAt: time.Now().Add(time.Hour),
}, nil)
},
Expand All @@ -56,7 +57,7 @@ func TestAuthMiddleware(t *testing.T) {
mockSessManager.EXPECT().GetSessionID(gomock.Any()).Return("sessionID", nil)
mockRepo.EXPECT().FindSession(gomock.Any(), "sessionID").Return(domain.Session{
ID: "sessionID",
UserID: "test-user-id",
UserID: uuid.New(),
ExpiresAt: time.Now().Add(-time.Hour),
}, nil)
// expired session should be deleted
Expand All @@ -79,3 +80,68 @@ func TestAuthMiddleware(t *testing.T) {
})
}
}

func TestTeamAuthMiddleware(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)

mockRepo := repomock.NewMockRepository(ctrl)
mockSessManager := sessmock.NewMockSessionManager(ctrl)
handler := NewHandler(mockRepo, mockSessManager)

userID := uuid.New()
teamID := uuid.New()

needAuthorize := handler.TeamAuthMiddleware()(func(c echo.Context) error {
return c.NoContent(http.StatusOK)
})

tests := []struct {
name string
setup func()
expectStatus int
}{
{
name: "ok",
setup: func() {
mockRepo.EXPECT().FindTeam(gomock.Any(), teamID).Return(domain.Team{
ID: teamID,
Members: []domain.User{
{ID: userID},
},
}, nil)
},
expectStatus: http.StatusOK,
},
{
name: "user is not a member of the team",
setup: func() {
mockRepo.EXPECT().FindTeam(gomock.Any(), teamID).Return(domain.Team{
ID: uuid.New(),
Members: []domain.User{{ID: uuid.New()}},
}, nil)
},
expectStatus: http.StatusForbidden,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()

c := echo.New().NewContext(req, rec)
c.SetParamNames("teamID")
c.SetParamValues(teamID.String())
c.Set("userID", userID)
pirosiki197 marked this conversation as resolved.
Show resolved Hide resolved

tt.setup()

_ = needAuthorize(c)
if rec.Code != tt.expectStatus {
t.Errorf("unexpected status code: expected=%d, got=%d", tt.expectStatus, rec.Code)
}
})
}
}
Loading
Loading