Advertisement
Guest User

Untitled

a guest
Sep 17th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 5.20 KB | None | 0 0
  1. package handshake
  2.  
  3. import (
  4.     "fmt"
  5.     "io/ioutil"
  6.     "net/http"
  7.     "os"
  8.     "strconv"
  9.     "time"
  10.  
  11.     "github.com/gin-gonic/gin"
  12.     "github.com/jjeffcaii/engine.io"
  13.     "github.com/satori/go.uuid"
  14.     log "github.com/sirupsen/logrus"
  15.     "touchy.io/lib-core/database"
  16.     "touchy.io/lib-core/utils"
  17. )
  18.  
  19. const loginErrorFail string = "FAILED"
  20. const loginErrorBan string = "BAN"
  21.  
  22. // HandshakeServer .. this server handle the handshake with the client (config, login, token ..)
  23. type HandshakeServer struct {
  24.     realmDatabase *database.RealmDatabase
  25. }
  26.  
  27. // NewHandshakeServer .. create a new handshake server
  28. func NewHandshakeServer(realmDatabase *database.RealmDatabase) *HandshakeServer {
  29.     handshakeServer := &HandshakeServer{
  30.         realmDatabase: realmDatabase,
  31.     }
  32.     return handshakeServer
  33. }
  34.  
  35. // Start .. start the handshake server
  36. func (handshakeServer *HandshakeServer) Start() error {
  37.     // Read env variables
  38.     port, err := strconv.Atoi(os.Getenv("HANDSHAKE_SERVER_PORT"))
  39.     if err != nil {
  40.         return err
  41.     }
  42.  
  43.     log.Debugf("starting the handshake server on *:%d", port)
  44.  
  45.     // Start the http server
  46.     go func() {
  47.  
  48.         // Create the socket.io server
  49.         server := eio.NewEngineBuilder().Build()
  50.         server.OnConnect(handshakeServer.handleClientConnection)
  51.  
  52.         // Setup the http server
  53.         gin.SetMode(gin.ReleaseMode)
  54.         r := gin.New()
  55.         r.Use(gin.Recovery())
  56.  
  57.         // Setup routes
  58.         r.GET("/config.json", handshakeServer.handleConfig)
  59.         r.POST("/haapi/Api/CreateApiKey", handshakeServer.handleCreateHaapiKey)
  60.         r.GET("/haapi/Account/CreateToken", handshakeServer.handleCreateToken)
  61.         r.GET("/primus/", func(c *gin.Context) {
  62.             server.Router()(c.Writer, c.Request)
  63.         })
  64.         r.POST("/primus/", func(c *gin.Context) {
  65.             server.Router()(c.Writer, c.Request)
  66.         })
  67.         r.NoRoute(handshakeServer.handleReverseProxy)
  68.  
  69.         // Start the server
  70.         r.Run(fmt.Sprintf(":%d", port))
  71.     }()
  72.  
  73.     return nil
  74. }
  75.  
  76. // handleReverseProxy .. reverse proxy the official asset storage
  77. func (handshakeServer *HandshakeServer) handleReverseProxy(c *gin.Context) {
  78.     proxyAssetURL := os.Getenv("PROXY_ASSETS_URL")
  79.     resp, err := http.Get(fmt.Sprintf("%s%s", proxyAssetURL, c.Request.RequestURI))
  80.     if err != nil {
  81.         log.Error("Can't handle the proxy request: %v", err)
  82.     }
  83.     defer resp.Body.Close()
  84.     body, err := ioutil.ReadAll(resp.Body)
  85.     c.String(200, string(body))
  86. }
  87.  
  88. // handleConfig .. Get the application config
  89. func (handshakeServer *HandshakeServer) handleConfig(c *gin.Context) {
  90.     dat, err := ioutil.ReadFile("./assets/config.json")
  91.     if err != nil {
  92.         log.Error("Can't handle the proxy request: %v", err)
  93.         c.String(500, "Not available")
  94.         return
  95.     }
  96.     c.String(200, string(dat))
  97. }
  98.  
  99. // handleCreateHaapiKey .. Login for create a haapi token
  100. func (handshakeServer *HandshakeServer) handleCreateHaapiKey(c *gin.Context) {
  101.     body, _ := c.GetRawData()
  102.     values := utils.ParseEncodedBody(string(body))
  103.     login := values["login"]
  104.     password := values["password"]
  105.     account, found := handshakeServer.realmDatabase.FindAccountByUsername(login)
  106.  
  107.     // Account not found
  108.     if !found {
  109.         log.Debugf("Account not found in the database username=%s", login)
  110.         c.JSON(601, &map[string]interface{}{
  111.             "reason": loginErrorFail,
  112.         })
  113.         return
  114.     }
  115.  
  116.     // Check password
  117.     if password != account.Password {
  118.         log.Debugf("Wrong password for the account username=%s", login)
  119.         c.JSON(601, map[string]interface{}{
  120.             "reason": loginErrorFail,
  121.         })
  122.         return
  123.     }
  124.  
  125.     // Check if the account is banned
  126.     if account.IsBanned == 1 {
  127.         log.Debugf("Account is banned username=%s", login)
  128.         c.JSON(601, map[string]interface{}{
  129.             "reason": loginErrorBan,
  130.         })
  131.         return
  132.     }
  133.  
  134.     // Generate the token and the api key
  135.     accessToken := uuid.NewV4()
  136.     refreshToken := uuid.NewV4()
  137.     apiKey := uuid.NewV4()
  138.     token := &database.Token{
  139.         AccountID:    account.ID,
  140.         AccessToken:  accessToken.String(),
  141.         RefreshToken: refreshToken.String(),
  142.         APIKey:       apiKey.String(),
  143.         IsValid:      1,
  144.     }
  145.     handshakeServer.realmDatabase.SaveToken(token)
  146.  
  147.     c.JSON(200, map[string]interface{}{
  148.         "access":     map[string]interface{}{},
  149.         "account_id": account.ID,
  150.         "added_date": time.Now().UTC().Format(time.RFC3339),
  151.         "data": map[string]interface{}{
  152.             "country":  "FR",
  153.             "currency": "EUR",
  154.         },
  155.         "expiration_date": time.Now().UTC().Add(time.Hour * time.Duration(24*30)).Format(time.RFC3339),
  156.         "ip":              "0.0.0.0",
  157.         "key":             token.APIKey,
  158.         "meta":            map[string]interface{}{},
  159.         "refresh_token":   token.RefreshToken,
  160.     })
  161. }
  162.  
  163. // handleCreateToken .. create the access token for the game
  164. func (handshakeServer *HandshakeServer) handleCreateToken(c *gin.Context) {
  165.     token, found := handshakeServer.realmDatabase.FindTokenByAPIKey(c.GetHeader("apikey"))
  166.     if !found {
  167.         c.String(601, "")
  168.         return
  169.     }
  170.  
  171.     c.JSON(200, map[string]interface{}{
  172.         "token": token.AccessToken,
  173.     })
  174. }
  175.  
  176. // handleClientConnection .. handle incoming connection from primus
  177. func (handshakeServer *HandshakeServer) handleClientConnection(socket eio.Socket) {
  178.     log.Infof("incoming websocket connection id=%s", socket.ID())
  179.     socket.OnMessage(func(data []byte) {
  180.  
  181.         log.Println("recieve:", string(data))
  182.     })
  183.     socket.OnClose(func(reason string) {
  184.         log.Infof("client disconnected id=%s", socket.ID())
  185.     })
  186. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement