arnaucube
arnaucube/gogame-oldPublic Self-hosted repository
gogame-old/endpoint/serve.go
endpoint/serve.goRaw
  1package endpoint
  2
  3import (
  4	"log"
  5	"time"
  6
  7	jwt "github.com/appleboy/gin-jwt/v2"
  8	"github.com/arnaucube/gogame/config"
  9	"github.com/arnaucube/gogame/constants"
 10	"github.com/arnaucube/gogame/database"
 11	"github.com/arnaucube/gogame/models"
 12	"github.com/arnaucube/gogame/services/gamesrv"
 13	"github.com/arnaucube/gogame/services/usersrv"
 14	"github.com/gin-contrib/cors"
 15	"github.com/gin-gonic/gin"
 16	"gopkg.in/mgo.v2/bson"
 17)
 18
 19var serverConfig config.Config
 20var db *database.Db
 21var userservice *usersrv.Service
 22var gameservice *gamesrv.Service
 23
 24func newApiService() *gin.Engine {
 25	api := gin.Default()
 26	api.Use(cors.New(cors.Config{
 27		AllowOrigins:     []string{"http://127.0.0.1:8080"},
 28		AllowMethods:     []string{"GET", "POST"},
 29		AllowHeaders:     []string{"Authorization", "Content-Type"},
 30		AllowCredentials: true,
 31		MaxAge:           12 * time.Hour,
 32	}))
 33
 34	// the jwt middleware
 35	authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
 36		Realm:       "test zone",
 37		Key:         []byte("secret key"),
 38		Timeout:     time.Hour,
 39		MaxRefresh:  time.Hour,
 40		IdentityKey: constants.JWTIdKey,
 41		PayloadFunc: func(data interface{}) jwt.MapClaims {
 42			if v, ok := data.(*models.User); ok {
 43				return jwt.MapClaims{
 44					constants.JWTIdKey: v.Id,
 45				}
 46			}
 47			return jwt.MapClaims{}
 48		},
 49		IdentityHandler: func(c *gin.Context) interface{} {
 50			claims := jwt.ExtractClaims(c)
 51			userid := bson.ObjectIdHex(claims[constants.JWTIdKey].(string))
 52			return &models.User{
 53				Id: userid,
 54			}
 55		},
 56		Authenticator: func(c *gin.Context) (interface{}, error) {
 57			var loginMsg LoginMsg
 58			if err := c.ShouldBind(&loginMsg); err != nil {
 59				return "", jwt.ErrMissingLoginValues
 60			}
 61
 62			_, user, err := userservice.Login(loginMsg.Email, loginMsg.Password)
 63			if err != nil {
 64				fail(c, err, jwt.ErrFailedAuthentication.Error())
 65				return "", err
 66			}
 67			return user, nil
 68
 69		},
 70		Unauthorized: func(c *gin.Context, code int, message string) {
 71			c.JSON(code, gin.H{
 72				"code":    code,
 73				"message": message,
 74			})
 75		},
 76		TokenLookup: "header: Authorization",
 77
 78		// TokenHeadName is a string in the header. Default value is "Bearer"
 79		TokenHeadName: "Bearer",
 80
 81		// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
 82		TimeFunc: time.Now,
 83	})
 84	if err != nil {
 85		log.Fatal("JWT Error:" + err.Error())
 86	}
 87
 88	api.GET("/info", handleInfo)
 89	api.POST("/register", handleRegister)
 90	// api.POST("/login", handleLogin)
 91	api.POST("/login", authMiddleware.LoginHandler)
 92	api.GET("/refresh_token", authMiddleware.RefreshHandler)
 93
 94	api.Use(authMiddleware.MiddlewareFunc())
 95	{
 96		api.GET("/", handleGetUser)
 97		api.GET("/resources", handleGetResources)
 98		api.GET("/planets", handleGetUserPlanets)
 99		api.GET("/planets/:planetid", handleGetPlanet)
100		api.POST("/buildings", handlePostUpgradeBuilding)
101	}
102	return api
103}
104
105func Serve(cnfg config.Config, _db *database.Db, _userservice *usersrv.Service, _gameservice *gamesrv.Service) *gin.Engine {
106	serverConfig = cnfg
107	db = _db
108	userservice = _userservice
109	gameservice = _gameservice
110	return newApiService()
111}