Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package handshake
- import (
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "strconv"
- "time"
- "github.com/gin-gonic/gin"
- "github.com/jjeffcaii/engine.io"
- "github.com/satori/go.uuid"
- log "github.com/sirupsen/logrus"
- "touchy.io/lib-core/database"
- "touchy.io/lib-core/utils"
- )
- const loginErrorFail string = "FAILED"
- const loginErrorBan string = "BAN"
- // HandshakeServer .. this server handle the handshake with the client (config, login, token ..)
- type HandshakeServer struct {
- realmDatabase *database.RealmDatabase
- }
- // NewHandshakeServer .. create a new handshake server
- func NewHandshakeServer(realmDatabase *database.RealmDatabase) *HandshakeServer {
- handshakeServer := &HandshakeServer{
- realmDatabase: realmDatabase,
- }
- return handshakeServer
- }
- // Start .. start the handshake server
- func (handshakeServer *HandshakeServer) Start() error {
- // Read env variables
- port, err := strconv.Atoi(os.Getenv("HANDSHAKE_SERVER_PORT"))
- if err != nil {
- return err
- }
- log.Debugf("starting the handshake server on *:%d", port)
- // Start the http server
- go func() {
- // Create the socket.io server
- server := eio.NewEngineBuilder().Build()
- server.OnConnect(handshakeServer.handleClientConnection)
- // Setup the http server
- gin.SetMode(gin.ReleaseMode)
- r := gin.New()
- r.Use(gin.Recovery())
- // Setup routes
- r.GET("/config.json", handshakeServer.handleConfig)
- r.POST("/haapi/Api/CreateApiKey", handshakeServer.handleCreateHaapiKey)
- r.GET("/haapi/Account/CreateToken", handshakeServer.handleCreateToken)
- r.GET("/primus/", func(c *gin.Context) {
- server.Router()(c.Writer, c.Request)
- })
- r.POST("/primus/", func(c *gin.Context) {
- server.Router()(c.Writer, c.Request)
- })
- r.NoRoute(handshakeServer.handleReverseProxy)
- // Start the server
- r.Run(fmt.Sprintf(":%d", port))
- }()
- return nil
- }
- // handleReverseProxy .. reverse proxy the official asset storage
- func (handshakeServer *HandshakeServer) handleReverseProxy(c *gin.Context) {
- proxyAssetURL := os.Getenv("PROXY_ASSETS_URL")
- resp, err := http.Get(fmt.Sprintf("%s%s", proxyAssetURL, c.Request.RequestURI))
- if err != nil {
- log.Error("Can't handle the proxy request: %v", err)
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- c.String(200, string(body))
- }
- // handleConfig .. Get the application config
- func (handshakeServer *HandshakeServer) handleConfig(c *gin.Context) {
- dat, err := ioutil.ReadFile("./assets/config.json")
- if err != nil {
- log.Error("Can't handle the proxy request: %v", err)
- c.String(500, "Not available")
- return
- }
- c.String(200, string(dat))
- }
- // handleCreateHaapiKey .. Login for create a haapi token
- func (handshakeServer *HandshakeServer) handleCreateHaapiKey(c *gin.Context) {
- body, _ := c.GetRawData()
- values := utils.ParseEncodedBody(string(body))
- login := values["login"]
- password := values["password"]
- account, found := handshakeServer.realmDatabase.FindAccountByUsername(login)
- // Account not found
- if !found {
- log.Debugf("Account not found in the database username=%s", login)
- c.JSON(601, &map[string]interface{}{
- "reason": loginErrorFail,
- })
- return
- }
- // Check password
- if password != account.Password {
- log.Debugf("Wrong password for the account username=%s", login)
- c.JSON(601, map[string]interface{}{
- "reason": loginErrorFail,
- })
- return
- }
- // Check if the account is banned
- if account.IsBanned == 1 {
- log.Debugf("Account is banned username=%s", login)
- c.JSON(601, map[string]interface{}{
- "reason": loginErrorBan,
- })
- return
- }
- // Generate the token and the api key
- accessToken := uuid.NewV4()
- refreshToken := uuid.NewV4()
- apiKey := uuid.NewV4()
- token := &database.Token{
- AccountID: account.ID,
- AccessToken: accessToken.String(),
- RefreshToken: refreshToken.String(),
- APIKey: apiKey.String(),
- IsValid: 1,
- }
- handshakeServer.realmDatabase.SaveToken(token)
- c.JSON(200, map[string]interface{}{
- "access": map[string]interface{}{},
- "account_id": account.ID,
- "added_date": time.Now().UTC().Format(time.RFC3339),
- "data": map[string]interface{}{
- "country": "FR",
- "currency": "EUR",
- },
- "expiration_date": time.Now().UTC().Add(time.Hour * time.Duration(24*30)).Format(time.RFC3339),
- "ip": "0.0.0.0",
- "key": token.APIKey,
- "meta": map[string]interface{}{},
- "refresh_token": token.RefreshToken,
- })
- }
- // handleCreateToken .. create the access token for the game
- func (handshakeServer *HandshakeServer) handleCreateToken(c *gin.Context) {
- token, found := handshakeServer.realmDatabase.FindTokenByAPIKey(c.GetHeader("apikey"))
- if !found {
- c.String(601, "")
- return
- }
- c.JSON(200, map[string]interface{}{
- "token": token.AccessToken,
- })
- }
- // handleClientConnection .. handle incoming connection from primus
- func (handshakeServer *HandshakeServer) handleClientConnection(socket eio.Socket) {
- log.Infof("incoming websocket connection id=%s", socket.ID())
- socket.OnMessage(func(data []byte) {
- log.Println("recieve:", string(data))
- })
- socket.OnClose(func(reason string) {
- log.Infof("client disconnected id=%s", socket.ID())
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement