Skip to content

Commit

Permalink
jwt manager updated & cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
ferhatbostanci committed Jun 6, 2021
1 parent acd6f98 commit aa71c98
Show file tree
Hide file tree
Showing 11 changed files with 127 additions and 115 deletions.
1 change: 1 addition & 0 deletions .kubernetes/comfigmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ data:
Server:
Port: 3000
Development: true
LogLevel: -1
MongoDB:
URI: "mongodb://localhost:27017"
User: "admin"
Expand Down
10 changes: 5 additions & 5 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@ package handler

import (
"github.com/PulseyTeam/game-server/config"
"github.com/PulseyTeam/game-server/jwt"
pb "github.com/PulseyTeam/game-server/proto"
"github.com/PulseyTeam/game-server/service"
"go.mongodb.org/mongo-driver/mongo"
)

type MultiplayerHandler struct {
pb.UnimplementedMultiplayerServiceServer
rooms map[string]map[string]*pb.Player
jwtManager *service.JWTManager
jwtManager *jwt.Manager
mongoDB *mongo.Client
cfg *config.Config
}

type AuthHandler struct {
pb.UnimplementedAuthServiceServer
jwtManager *service.JWTManager
jwtManager *jwt.Manager
mongoDB *mongo.Client
cfg *config.Config
}

func NewMultiplayerHandler(cfg *config.Config, mongoDB *mongo.Client, jwtManager *service.JWTManager) *MultiplayerHandler {
func NewMultiplayerHandler(cfg *config.Config, mongoDB *mongo.Client, jwtManager *jwt.Manager) *MultiplayerHandler {
return &MultiplayerHandler{cfg: cfg, mongoDB: mongoDB, jwtManager: jwtManager}
}

func NewAuthHandler(cfg *config.Config, mongoDB *mongo.Client, jwtManager *service.JWTManager) *AuthHandler {
func NewAuthHandler(cfg *config.Config, mongoDB *mongo.Client, jwtManager *jwt.Manager) *AuthHandler {
return &AuthHandler{cfg: cfg, mongoDB: mongoDB, jwtManager: jwtManager}
}
12 changes: 6 additions & 6 deletions handler/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ import (
)

func (h *MultiplayerHandler) RoomConnect(ctx context.Context, request *pb.RoomConnectRequest) (*pb.RoomConnectResponse, error) {
collection := h.mongoDB.Database(h.cfg.MongoDB.DB).Collection("game_sessions")
collection := h.mongoDB.Database(h.cfg.MongoDB.DB).Collection(model.GameSessionCollection)

gameSession := model.GameSession{}
filter := bson.D{
primitive.E{Key: "map_id", Value: request.GetMapId()},
primitive.E{Key: "status", Value: model.SessionWaiting},
primitive.E{Key: "status", Value: model.StatusWaiting},
}

err := collection.FindOne(ctx, filter).Decode(&gameSession)
if err == nil {
return &pb.RoomConnectResponse{RoomId: gameSession.ID.String()}, nil
return &pb.RoomConnectResponse{RoomId: gameSession.ID.Hex()}, nil
} else {
//Todo refactor
log.Warn().Msgf("find error: %v", err)
Expand All @@ -33,17 +33,17 @@ func (h *MultiplayerHandler) RoomConnect(ctx context.Context, request *pb.RoomCo
result, err := collection.InsertOne(ctx, model.GameSession{
ID: primitive.NewObjectID(),
MapID: request.GetMapId(),
Status: model.SessionWaiting,
Status: model.StatusWaiting,
StartedAt: time.Now(),
FinishedAt: nil,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create resource")
}

insertedID := result.InsertedID.(primitive.ObjectID).String()
insertedID := result.InsertedID.(primitive.ObjectID).Hex()

log.Trace().Msgf("game session (created): %v", insertedID)
log.Trace().Msgf("game session created: %v", insertedID)

return &pb.RoomConnectResponse{RoomId: insertedID}, nil
}
Expand Down
12 changes: 6 additions & 6 deletions handler/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
"google.golang.org/grpc/status"
)

func (h *AuthHandler) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
collection := h.mongoDB.Database(h.cfg.MongoDB.DB).Collection("users")
func (a *AuthHandler) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
collection := a.mongoDB.Database(a.cfg.MongoDB.DB).Collection(model.UserCollection)

findUser := &model.User{}
filter := bson.D{primitive.E{Key: "username", Value: request.GetUsername()}}
Expand All @@ -29,16 +29,16 @@ func (h *AuthHandler) Login(ctx context.Context, request *pb.LoginRequest) (*pb.
return nil, status.Errorf(codes.Unauthenticated, "authentication failed")
}

accessToken, err := h.jwtManager.Generate(findUser)
accessToken, err := a.jwtManager.Generate(findUser)
if err != nil {
return nil, status.Errorf(codes.Internal, "cannot generate access token")
}

return &pb.LoginResponse{AccessToken: accessToken}, nil
}

func (h *AuthHandler) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
collection := h.mongoDB.Database(h.cfg.MongoDB.DB).Collection("users")
func (a *AuthHandler) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
collection := a.mongoDB.Database(a.cfg.MongoDB.DB).Collection(model.UserCollection)

findUser := model.User{}
filter := bson.D{primitive.E{Key: "username", Value: request.GetUsername()}}
Expand Down Expand Up @@ -67,7 +67,7 @@ func (h *AuthHandler) Register(ctx context.Context, request *pb.RegisterRequest)
return nil, status.Errorf(codes.Internal, "failed to create resource")
}

accessToken, err := h.jwtManager.Generate(newUser)
accessToken, err := a.jwtManager.Generate(newUser)
if err != nil {
return nil, status.Errorf(codes.Internal, "cannot generate access token")
}
Expand Down
18 changes: 12 additions & 6 deletions service/jwt_manager.go → jwt/manager.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package service
package jwt

import (
"fmt"
Expand All @@ -7,7 +7,12 @@ import (
"time"
)

type JWTManager struct {
const (
secretKey = "0pPeA3tn0BUesH9dtjptZsZpuYHZtCDFqUFH7EdiVw4U8APE6uTNg53LXqq1EAa"
tokenDuration = 4 * time.Hour
)

type Manager struct {
secretKey string
tokenDuration time.Duration
}
Expand All @@ -17,14 +22,15 @@ type UserClaims struct {
Username string `json:"username"`
}

func NewJWTManager(secretKey string, tokenDuration time.Duration) *JWTManager {
return &JWTManager{secretKey, tokenDuration}
func NewManager() *Manager {
return &Manager{secretKey, tokenDuration}
}

func (manager *JWTManager) Generate(user *model.User) (string, error) {
func (manager *Manager) Generate(user *model.User) (string, error) {
claims := UserClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(manager.tokenDuration).Unix(),
IssuedAt: time.Now().Unix(),
Subject: user.ID.Hex(),
},
Username: user.Username,
Expand All @@ -34,7 +40,7 @@ func (manager *JWTManager) Generate(user *model.User) (string, error) {
return token.SignedString([]byte(manager.secretKey))
}

func (manager *JWTManager) Verify(accessToken string) (*UserClaims, error) {
func (manager *Manager) Verify(accessToken string) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(
accessToken,
&UserClaims{},
Expand Down
22 changes: 12 additions & 10 deletions model/game_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ import (
"time"
)

const (
SessionWaiting = "waiting"
SessionReady = "ready"
SessionPlaying = "playing"
SessionFinished = "finished"
)
const GameSessionCollection = "game_sessions"

type GameSession struct {
ID primitive.ObjectID `bson:"_id"`
MapID string `json:"map_id"`
Status string `json:"status"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
MapID string `bson:"map_id"`
Status string `bson:"status"`
StartedAt time.Time `bson:"started_at"`
FinishedAt *time.Time `bson:"finished_at"`
}

const (
StatusWaiting = "waiting"
StatusReady = "ready"
StatusPlaying = "playing"
StatusFinished = "finished"
)
10 changes: 6 additions & 4 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import (
"golang.org/x/crypto/bcrypt"
)

const UserCollection = "users"

type User struct {
ID primitive.ObjectID `bson:"_id"`
Username string `json:"username"`
Password string `json:"password"`
Settings *[]string `json:"settings"`
Cosmetics *[]string `json:"cosmetics"`
Username string `bson:"username"`
Password string `bson:"password"`
Settings *[]string `bson:"settings"`
Cosmetics *[]string `bson:"cosmetics"`
}

func (u *User) HashPassword() error {
Expand Down
Loading

0 comments on commit aa71c98

Please sign in to comment.