Exemplo n.º 1
0
// Authenticate is a function called for every client's new session.
// It manages several important tasks at the start of the session.
// 1.Ask the user for Username and twitter ID.
// 2.Search the DB to find the player if it's not a new one.
// 3.If the player is new there is a subsequence initiated:
// 3.1.Create a new sun with GenerateSun
// 3.2.Choose home planet from the newly created solar sysitem.
// 3.3.Create a reccord of the new player and start comunication.
func authenticate(ws *websocket.Conn) (*entities.Player, *anaconda.TwitterApi, error) {
	var (
		nickname  string
		twitterId string
		err       error
		request   Request
		setupData *entities.SetupData
		player    *entities.Player
		twitter   *anaconda.TwitterApi
	)

	if err = websocket.JSON.Receive(ws, &request); err != nil {
		return nil, nil, err
	}

	if len(request.Username) <= 0 || len(request.TwitterID) <= 0 {
		return nil, nil, errors.New("Incomplete credentials")
	}

	if cfg.Twitter.SecureLogin {
		var ok bool
		anaconda.SetConsumerKey(cfg.Twitter.ConsumerKey)
		anaconda.SetConsumerSecret(cfg.Twitter.ConsumerSecret)
		twitter = anaconda.NewTwitterApi(request.AccessToken, request.AccessTokenSecret)
		if ok, err = twitter.VerifyCredentials(); !ok {
			return nil, nil, err
		}
	}

	serverParamsMessage := response.NewServerParams()
	if err = websocket.JSON.Send(ws, &serverParamsMessage); err != nil {
		return nil, nil, err
	}

	nickname = request.Username
	twitterId = request.TwitterID

	entity, _ := entities.Get(fmt.Sprintf("player.%s", nickname))
	if entity == nil {
		setupData, err = FetchSetupData(ws)
		if err != nil {
			return nil, nil, err
		}
		player = register(setupData, nickname, twitterId, twitter)
	} else {
		player = entity.(*entities.Player)
	}
	return player, twitter, nil
}