Skip to content

Commit

Permalink
- zerolog added
Browse files Browse the repository at this point in the history
- log level enabled
- login & register added
- jwt auth implemented
  • Loading branch information
ferhatbostanci committed Jun 6, 2021
1 parent b739229 commit acd6f98
Show file tree
Hide file tree
Showing 19 changed files with 864 additions and 116 deletions.
1 change: 1 addition & 0 deletions config/config-docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ AppVersion: 1.1.0-alpha
Server:
Port: 3000
Development: true
LogLevel: -1

MongoDB:
URI: "mongodb://mongo:27017"
Expand Down
15 changes: 5 additions & 10 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package config

import (
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"log"
"os"
"time"
)

type Config struct {
Expand All @@ -14,13 +13,9 @@ type Config struct {
}

type Server struct {
Port string
Development bool
Timeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
MaxConnectionIdle time.Duration
MaxConnectionAge time.Duration
Port string
Development bool
LogLevel int8
}

type MongoDB struct {
Expand Down Expand Up @@ -54,7 +49,7 @@ func ParseConfig() (*Config, error) {
var c Config
err := viper.Unmarshal(&c)
if err != nil {
log.Printf("unable to decode into struct, %v", err)
log.Fatal().Err(err).Send()
return nil, err
}

Expand Down
1 change: 1 addition & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ AppVersion: 1.1.0-alpha
Server:
Port: 3000
Development: true
LogLevel: -1

MongoDB:
URI: "mongodb://localhost:27017"
Expand Down
18 changes: 9 additions & 9 deletions docker-compose.local.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
version: "3.9"

services:
server:
build: .
image: pulsey-game-server:latest
ports:
- "3000:3000"
environment:
DOCKER_ENVIRONMENT: 1
depends_on:
- mongo
# server:
# build: .
# image: pulsey-game-server:latest
# ports:
# - "3000:3000"
# environment:
# DOCKER_ENVIRONMENT: 1
# depends_on:
# - mongo

mongo:
image: mongo:4.4-bionic
Expand Down
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ module github.com/PulseyTeam/game-server
go 1.16

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/rs/zerolog v1.22.0
github.com/spf13/viper v1.7.1
github.com/stretchr/testify v1.7.0
go.mongodb.org/mongo-driver v1.5.3
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a
golang.org/x/net v0.0.0-20210505214959-0714010a04ed // indirect
golang.org/x/sys v0.0.0-20210507161434-a76c4d0a0096 // indirect
google.golang.org/genproto v0.0.0-20210506142907-4a47615972c2 // indirect
google.golang.org/grpc v1.37.0
google.golang.org/protobuf v1.26.0
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
11 changes: 9 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
Expand Down Expand Up @@ -218,6 +219,9 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
github.com/rs/zerolog v1.22.0 h1:XrVUjV4K+izZpKXZHlPrYQiDtmdGiCylnT4i43AAWxg=
github.com/rs/zerolog v1.22.0/go.mod h1:ZPhntP/xmq1nnND05hhpAh2QMhSsA4UN3MGZ6O2J3hM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
Expand Down Expand Up @@ -280,8 +284,9 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a h1:kr2P4QFmQr29mSLA43kwrOcgcReGTfbE9N577tCTuBc=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
Expand Down Expand Up @@ -319,6 +324,7 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
golang.org/x/net v0.0.0-20210505214959-0714010a04ed h1:V9kAVxLvz1lkufatrpHuUVyJ/5tR3Ms7rk951P4mI98=
golang.org/x/net v0.0.0-20210505214959-0714010a04ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
Expand Down Expand Up @@ -455,8 +461,9 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
23 changes: 18 additions & 5 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,29 @@ package handler
import (
"github.com/PulseyTeam/game-server/config"
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
mongoDB *mongo.Client
cfg *config.Config
rooms map[string]map[string]*pb.Player
jwtManager *service.JWTManager
mongoDB *mongo.Client
cfg *config.Config
}

func NewMultiplayer(cfg *config.Config, mongoDB *mongo.Client) *MultiplayerHandler {
return &MultiplayerHandler{cfg: cfg, mongoDB: mongoDB}
type AuthHandler struct {
pb.UnimplementedAuthServiceServer
jwtManager *service.JWTManager
mongoDB *mongo.Client
cfg *config.Config
}

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

func NewAuthHandler(cfg *config.Config, mongoDB *mongo.Client, jwtManager *service.JWTManager) *AuthHandler {
return &AuthHandler{cfg: cfg, mongoDB: mongoDB, jwtManager: jwtManager}
}
7 changes: 4 additions & 3 deletions handler/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import (
"context"
"github.com/PulseyTeam/game-server/model"
pb "github.com/PulseyTeam/game-server/proto"
"github.com/rs/zerolog/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"io"
"log"
"time"
)

Expand All @@ -26,7 +26,8 @@ func (h *MultiplayerHandler) RoomConnect(ctx context.Context, request *pb.RoomCo
if err == nil {
return &pb.RoomConnectResponse{RoomId: gameSession.ID.String()}, nil
} else {
log.Printf("find error: %v", err)
//Todo refactor
log.Warn().Msgf("find error: %v", err)
}

result, err := collection.InsertOne(ctx, model.GameSession{
Expand All @@ -42,7 +43,7 @@ func (h *MultiplayerHandler) RoomConnect(ctx context.Context, request *pb.RoomCo

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

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

return &pb.RoomConnectResponse{RoomId: insertedID}, nil
}
Expand Down
76 changes: 76 additions & 0 deletions handler/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package handler

import (
"context"
"github.com/PulseyTeam/game-server/model"
pb "github.com/PulseyTeam/game-server/proto"
"github.com/rs/zerolog/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"google.golang.org/grpc/codes"
"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")

findUser := &model.User{}
filter := bson.D{primitive.E{Key: "username", Value: request.GetUsername()}}

err := collection.FindOne(ctx, filter).Decode(&findUser)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "authentication failed")
}

passwordCheck := findUser.CheckPassword(request.GetPassword())

if !passwordCheck {
return nil, status.Errorf(codes.Unauthenticated, "authentication failed")
}

accessToken, err := h.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")

findUser := model.User{}
filter := bson.D{primitive.E{Key: "username", Value: request.GetUsername()}}

err := collection.FindOne(ctx, filter).Decode(&findUser)
if err == nil {
return nil, status.Errorf(codes.AlreadyExists, "user already registered")
} else if err != mongo.ErrNoDocuments {
log.Fatal().Err(err).Send()
return nil, status.Errorf(codes.Internal, "internal error")
}

newUser := &model.User{
ID: primitive.NewObjectID(),
Username: request.GetUsername(),
Password: request.GetPassword(),
}

err = newUser.HashPassword()
if err != nil {
return nil, status.Errorf(codes.Internal, "could not hash password")
}

_, err = collection.InsertOne(ctx, newUser)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create resource")
}

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

return &pb.RegisterResponse{AccessToken: accessToken}, nil
}
8 changes: 4 additions & 4 deletions model/game_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ const (

type GameSession struct {
ID primitive.ObjectID `bson:"_id"`
MapID string `bson:"map_id"`
Status string `bson:"status"`
StartedAt time.Time `bson:"started_at"`
FinishedAt *time.Time `bson:"finished_at"`
MapID string `json:"map_id"`
Status string `json:"status"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
}
35 changes: 35 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package model

import (
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/crypto/bcrypt"
)

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

func (u *User) HashPassword() error {
if len(u.Password) == 0 {
return errors.New("password should not be empty")
}

hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}

u.Password = string(hashedPassword)

return nil
}

func (u *User) CheckPassword(plain string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(plain))
return err == nil
}
Loading

0 comments on commit acd6f98

Please sign in to comment.