You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
3.1 KiB

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