Java Code Examples for org.bukkit.event.player.AsyncPlayerPreLoginEvent

The following are top voted examples for showing how to use org.bukkit.event.player.AsyncPlayerPreLoginEvent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AntiBots   File: EventListener.java   View source code 6 votes vote down vote up
@EventHandler
public void onPlayerJoin(AsyncPlayerPreLoginEvent event){
	if(protection){
		DataProvider dp = DataProvider.getInstance();
		ApiDataProvider adp = ApiDataProvider.getInstance();
		try{
			if(dp.getWhitelist().contains(event.getName())) return;
			if(!adp.testFor(event.getName())){
				event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, DataProvider.getInstance().getFormattedMessage());
			}
		} catch(Exception e) {
			Main.instance().getLogger().log(Level.SEVERE, "An exception occured while verifying " + event.getName() + ". Usually it's caused by bad configuration. Check your configuration, or start a new issue on GitHub!");
			event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, DataProvider.getInstance().getFormattedMessage());
		}
	}
}
 
Example 2
Project: LuckPerms   File: BukkitConnectionListener.java   View source code 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerPreLoginMonitor(AsyncPlayerPreLoginEvent e) {
    /* Listen to see if the event was cancelled after we initially handled the connection
       If the connection was cancelled here, we need to do something to clean up the data that was loaded. */

    // Check to see if this connection was denied at LOW.
    if (this.deniedAsyncLogin.remove(e.getUniqueId())) {
        // their data was never loaded at LOW priority, now check to see if they have been magically allowed since then.

        // This is a problem, as they were denied at low priority, but are now being allowed.
        if (e.getLoginResult() == AsyncPlayerPreLoginEvent.Result.ALLOWED) {
            this.plugin.getLog().severe("Player connection was re-allowed for " + e.getUniqueId());
            e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "");
        }

        return;
    }
}
 
Example 3
Project: K-Security   File: TransactionAntiBot.java   View source code 6 votes vote down vote up
@EventHandler
public void onAsync(AsyncPlayerPreLoginEvent event) {
    cacher.removeAndGet(event.getAddress()).ifPresent(player -> {
        sendPacket(player, factory.createLoginPacket());
        Bukkit.getScheduler().runTask(plugin, () -> ignore.addIgnore(player, Packets.Server.LOGIN));
        holder.addPlayer(player);

        sendPacket(player, factory.createTransactionPacket(0, Short.MIN_VALUE, false));
        if (latch.await(player)) {
            holder.flush(player);
            players.add(player.getAddress().getAddress().toString());
        } else {
            event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, Lang.BOT_DETECT.withSpacingPrefix());
            counter.incrementAndGet();
        }
        holder.release(player);
        latch.release(player);
        cacher.release(player);
    });
}
 
Example 4
Project: AdvancedBan   File: BukkitMain.java   View source code 6 votes vote down vote up
public void onEnable() {
    instance = this;
    Universal.get().setup(new BukkitMethods());

    ConnectionListener connListener = new ConnectionListener();
    this.getServer().getPluginManager().registerEvents(connListener, this);
    this.getServer().getPluginManager().registerEvents(new ChatListener(), this);
    this.getServer().getPluginManager().registerEvents(new CommandListener(), this);

    for (Player op : Bukkit.getOnlinePlayers()) {
        AsyncPlayerPreLoginEvent apple = new AsyncPlayerPreLoginEvent(op.getName(), op.getAddress().getAddress(), op.getUniqueId());
        connListener.onConnect(apple);
        if (apple.getLoginResult() == AsyncPlayerPreLoginEvent.Result.KICK_BANNED) {
            op.kickPlayer(apple.getKickMessage());
        }
    }
}
 
Example 5
Project: CraftoPlugin   File: CraftoDatabase.java   View source code 6 votes vote down vote up
private void checkForNameChange(final CraftoPlayer player, final AsyncPlayerPreLoginEvent event) {
		if (player != null && event != null && player.getUniqueId().equals(event.getUniqueId())) {
			if (!player.getName().equalsIgnoreCase(event.getName())) { // If true, player has changed his name!
//				final String query = "INSERT INTO `cp_history` (`playerid`, `info`, `created_at`) "
//						+ "VALUES ("+player.getId()+", 'Changed name from "+player.getName()+" to "+event.getName()+".', "+new Timestamp(System.currentTimeMillis())
//						+ "); UPDATE `cp_players` SET `name`='"+event.getName()+"' WHERE `uuid`='"+event.getUniqueId()+"' LIMIT 1;";
//				this.executeAsync(Query.of(query));
				
				player.registerRecord(0, "Changed name from " + player.getName() + " to " + event.getName() + ".", null, null);
				
				this.plugin.getServer().getPluginManager().callEvent(new CraftoPlayerNameChangeEvent(player, player.getName(), event.getName()));
				((DatabaseCraftoPlayer) player).setName(event.getName());

				// Reinsert into name map
				if (!this.namePlayerMap.containsKey(player.getName().toLowerCase())) { this.namePlayerMap.put(player.getName().toLowerCase(), new SortedList<>(1)); }
				this.namePlayerMap.get(player.getName().toLowerCase()).add(player);
			}
		}
	}
 
Example 6
Project: CrazyLogin   File: PlayerListener.java   View source code 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
@Permission("crazylogin.warnsession")
@Localized({ "CRAZYLOGIN.KICKED.SESSION.DUPLICATE", "CRAZYLOGIN.SESSION.DUPLICATEWARN $Name$ $IP$" })
public void PlayerLoginSessionCheck(final AsyncPlayerPreLoginEvent event) {
	if (plugin.isForceSingleSessionEnabled()) {
		final Player player = Bukkit.getPlayerExact(event.getName());
		if (player != null) {
			if (plugin.isForceSingleSessionSameIPBypassEnabled()) {
				final LoginPlayerData data = plugin.getPlayerData(player);
				if (data != null) {
					if (event.getAddress().getHostAddress().equals(data.getLatestIP())) {
						return;
					}
				}
			}
			event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
			event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "KICKED.SESSION.DUPLICATE"));
			plugin.broadcastLocaleMessage(true, "crazylogin.warnsession", true, "SESSION.DUPLICATEWARN", player.getName(), event.getAddress().getHostAddress());
			plugin.sendLocaleMessage("SESSION.DUPLICATEWARN", player, event.getAddress().getHostAddress(), player.getName());
			plugin.getCrazyLogger().log("AccessDenied", "Denied access for player " + player.getName() + " @ " + event.getAddress().getHostAddress() + " because of a player with this name being already online");
			return;
		}
	}
}
 
Example 7
Project: CloudNet   File: BukkitListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void handle0(AsyncPlayerPreLoginEvent e)
{
    for(Player all : Bukkit.getOnlinePlayers())
        if(all.getUniqueId().equals(e.getUniqueId()))
            e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, "§cYou have to connect from a internal proxy server!");
}
 
Example 8
Project: Warzone   File: JoinManager.java   View source code 5 votes vote down vote up
@EventHandler
public void onPreLogin(AsyncPlayerPreLoginEvent event) {
    if (event.getLoginResult().equals(AsyncPlayerPreLoginEvent.Result.KICK_BANNED)) return;
    UserProfile userProfile = TGM.get().getTeamClient().login(new PlayerLogin(event.getName(), event.getUniqueId().toString(), event.getAddress().getHostAddress()));
    Bukkit.getLogger().info(userProfile.getName() + " " + userProfile.getId().toString());
    queuedJoins.add(new QueuedJoin(event.getUniqueId(), userProfile, System.currentTimeMillis()));
}
 
Example 9
Project: EscapeLag   File: DupeLoginPatch.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(AsyncPlayerPreLoginEvent evt) {
    if (ConfigPatch.fixDupeOnline) {
        if (AzurePlayerList.contains(evt.getName())) {
            evt.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
            evt.setKickMessage(ConfigPatch.messageKickDupeOnline);
        }
    }
}
 
Example 10
Project: ProjectAres   File: IdentityProviderImpl.java   View source code 5 votes vote down vote up
/**
 * Clear any nickname that collides with the real name of a player logging in.
 * This ensures that usernames + nicknames together contain no duplicates.
 * The user who's nickname was cleared is not notified of this, but this
 * should be an extremely rare situation, so it's not a big problem.
 */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void clearConflictingNicks(AsyncPlayerPreLoginEvent event) {
    final String name = event.getName();
    syncExecutor.execute(() -> {
        final Player player = nicknames.get(name);
        if(player != null) {
            changeIdentity(player, null);
        }
    });
}
 
Example 11
Project: Kineticraft   File: Punishments.java   View source code 5 votes vote down vote up
@EventHandler
public void onJoin(AsyncPlayerPreLoginEvent evt) {
    KCPlayer player = KCPlayer.getWrapper(evt.getUniqueId());
    if (player.isBanned())
        evt.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED,
            ChatColor.RED + "You are banned from Kineticraft!\n"
                    + ChatColor.RED + "Reason: " + ChatColor.YELLOW + player.getPunishments().last().getType().getDisplay() + "\n"
                    + ChatColor.RED + "Expiration: " + ChatColor.YELLOW + Utils.formatTimeFull(player.getPunishExpiry()) + "\n"
                    + ChatColor.RED + "Appeal on discord: http://kineticraft.net");
}
 
Example 12
Project: mopm   File: ConnectionListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPreLogin(AsyncPlayerPreLoginEvent event) {
    plugin.getLookupBoss().scheduleLookup(event.getAddress(), optBl -> optBl.ifPresent(proxyBlacklist -> {
        AsyncProxyDetectedEvent detectedEvent = new AsyncProxyDetectedEvent(proxyBlacklist, event.getAddress(), event.getUniqueId());
        plugin.getServer().getPluginManager().callEvent(detectedEvent);
        this.onJoinActions.put(detectedEvent.getUuid(), detectedEvent.getActions());
        this.finders.put(event.getUniqueId(), proxyBlacklist);
    }));
}
 
Example 13
Project: UHC   File: JoinQuitHandlers.java   View source code 5 votes vote down vote up
@EventHandler
public void prejoin(final AsyncPlayerPreLoginEvent event){
    if (!UserManager.getInstance().getUser(event.getUniqueId()).isPresent() &&
            (GameState.current() != GameState.LOBBY && GameState.current() != GameState.STARTING)
            && UHC.getInstance().getMainConfig().isRoundBanDead()) {
        event.setKickMessage(colour("&cThe round has already started!"));
        event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
    }
}
 
Example 14
Project: FlexMC   File: MessageClientLoginListener.java   View source code 5 votes vote down vote up
private String tryLogin( ConnectionHandler connectionHandler, MessageC00LoginStart message ) {
    if ( connectionHandler.getVersion() > 338 ) {
        return "Outdated Server. Please use 1.12.1";
    }
    if ( connectionHandler.getVersion() < 338 ) {
        return "Outdated Client. Please use 1.12.1";
    }
    if ( connectionHandler.getVerifySession() != null ) {
        return "Already logging in";
    }
    if ( !Flex.getServer().isRunning() || Flex.getServer().getWorld() == null || !Flex.getServer().getWorld().isGenerated() ) {
        return "Server ist still starting up";
    }
    AsyncPlayerPreLoginEvent event = EventFactory.call( new AsyncPlayerPreLoginEvent( message.getName(), connectionHandler.getSocketAddress().getAddress(), UUID.randomUUID() ) );

    if( event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED ) {
        return event.getKickMessage() == null ? "null" : event.getKickMessage();
    }

    if ( Flex.getServer().getConfig().isVerifyUsers() ) {
        VerifySession verifySession = new VerifySession( AuthHelper.nextToken(), message.getName() );
        connectionHandler.setVerifySession( verifySession );
        MessageS01EncryptionRequest encryptionRequest = new MessageS01EncryptionRequest( "", Flex.getServer().getKeyPair().getPublic().getEncoded(), verifySession.getToken() );
        connectionHandler.sendMessage( encryptionRequest );
        verifySession.getState().incrementAndGet();
    } else {
        connectionHandler.loginSuccess( message.getName(), UUID.nameUUIDFromBytes( ( "OfflinePlayer:" + message.getName() ).getBytes( Charsets.UTF_8 ) ) );
    }
    return null;
}
 
Example 15
Project: SamaGamesCore   File: JoinManagerImplement.java   View source code 5 votes vote down vote up
public void onLogin(AsyncPlayerPreLoginEvent event)
{
    UUID player = event.getUniqueId();

    if (moderatorsExpected.contains(player)) // On traite après
        return;

    if(!playersExpected.contains(player))
    {
        JoinResponse response = requestJoin(event.getUniqueId(), true);
        if (!response.isAllowed())
        {
            event.disallow(Result.KICK_OTHER, ChatColor.RED + response.getReason());
            return;
        }
    }

    playersExpected.remove(player);

    for (IJoinHandler handler : this.joiners.values())
        handler.onLogin(player, event.getName());
}
 
Example 16
Project: VoxelGamesLib   File: UserListener.java   View source code 5 votes vote down vote up
@EventHandler
public void asyncLogin(@Nonnull AsyncPlayerPreLoginEvent event) {
    AsyncUserLoginEvent e = new AsyncUserLoginEvent(event.getUniqueId(), event.getName());
    eventHandler.callEvent(e);
    if (e.isCanceled()) {
        event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
        event.setKickMessage(e.getKickMessage());
    }
}
 
Example 17
Project: DOHA-Check   File: DOHACheck.java   View source code 5 votes vote down vote up
@Override
public void onEnable() {
	saveDefaultConfig();
	loadComponent(Configuration.class);

	if (Configuration.httpProxy.enabled.get())
		Unirest.setProxy(new HttpHost(Configuration.httpProxy.host.get(), Configuration.httpProxy.port.get()));

	accountTruster = new AccountTruster(new Requester(this));

	ZLib.registerEvents(new Listener() {
		@EventHandler
		public void onLogin(final AsyncPlayerPreLoginEvent event) {
			accountTruster.isHacked(event.getUniqueId(), new Callback<Boolean>() {
				public void call(Boolean hacked) {
					if (hacked) {
						Player player = Bukkit.getPlayer(event.getUniqueId());
						if (player == null)
							return;

						player.kickPlayer(Configuration.kickReason.get());

						for (Player p : Bukkit.getOnlinePlayers())
							if (p.hasPermission(Configuration.annoucements.permission.get()))
								p.sendMessage(Configuration.annoucements.message.get()
										.replaceAll("%player_name", player.getName())
										.replaceAll("%ip_address", event.getAddress().getHostAddress()));
					}
				}
			});
		}
	});
}
 
Example 18
Project: BeeLogin   File: LoginEventHandler.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(AsyncPlayerPreLoginEvent event) {
	InetAddress playerAddress = event.getAddress();
	if ((Config.skipOnLoopbackAddress && playerAddress.isLoopbackAddress())
			|| (Config.skipOnSiteLocalAddress && playerAddress.isSiteLocalAddress())) {
		return;
	}
	if (Config.usingBeeLoginMod) {
		BeeLogin.loginStatus.put(event.getName().toLowerCase(), false);
		event.allow();
		return;
	}
	String playerName = event.getName();
	String playerIp = playerAddress.getHostAddress().replace("/", "");
	LoginResult result = new LoginResult(Config.checkUrl, Config.queryMode, Config.encodeMode, playerName, playerIp,
			Config.serverIp, Config.serverPassword);
	if (result.getResult()) {
		event.allow();
	} else if (result.isBadIp()) {
		event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
		event.setKickMessage(Config.badIpMessage.replace("%UserIp%", playerIp));
		event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER,
				Config.badIpMessage.replace("%UserIp%", playerIp));
	} else {
		event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
		event.setKickMessage(Config.kickMessage);
		event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, Config.badIpMessage);
	}
}
 
Example 19
Project: ExilePearl   File: TestBukkit.java   View source code 5 votes vote down vote up
/**
 * Creates a new player instance and adds it to the server
 * @param name The player name
 * @param uid The player UUID
 * @return The player instance
 */
public static TestPlayer createOnlinePlayer(String name, UUID uid) {    	
	TestPlayer p = TestPlayer.create(name);
	
	final InetSocketAddress address = new InetSocketAddress("localhost", 25565);
	final AsyncPlayerPreLoginEvent preLoginEvent = new AsyncPlayerPreLoginEvent(name, address.getAddress(), uid);
	getPluginManager().callEvent(preLoginEvent);
	if (preLoginEvent.getLoginResult() != Result.ALLOWED) {
		return null;
	}
	
	final PlayerLoginEvent loginEvent = new PlayerLoginEvent(p, "localhost", address.getAddress());
	getPluginManager().callEvent(loginEvent);

	if (loginEvent.getResult() != PlayerLoginEvent.Result.ALLOWED) {
		return null;
	}
	
	final PlayerJoinEvent joinEvent = new PlayerJoinEvent(p, "");
	getPluginManager().callEvent(joinEvent);
	
	p.goOnline();
	return p;
}
 
Example 20
Project: Vanguard   File: VanguardListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void preAuth(AsyncPlayerPreLoginEvent ev) {
    PlayerSettings settings = Vanguard.getPlayerSettings(ev.getUniqueId());
    if (settings.getFailedAttempts() >= Configuration.getMaxAttemptFailure()) {
        ev.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_BANNED);
        ev.setKickMessage(Configuration.getString("toomanyfailedattempts"));
    } else if (settings.getBanned() >= System.currentTimeMillis()) {
        ev.setKickMessage(Configuration.getString("vanguardauthfailure")
                .replace("$timeout$",
                        Long.toString(Configuration.getBanTimeOnFail())));

        ev.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_BANNED);
    }
}
 
Example 21
Project: BetterShards   File: BetterShardsListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void playerPreLoginCacheInv(AsyncPlayerPreLoginEvent event) {
	UUID uuid = event.getUniqueId();
	if (uuid != null) {
		plugin.getLogger().log(Level.FINER, "Preparing to pre-load player data: {0}", uuid);
	} else { 
		return;
	}
	if (st == null){ // Small race condition if someone logs on as soon as the server starts.
		event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "Please try to log in again in a moment, server is not ready to accept log-ins.");
		plugin.getLogger().log(Level.INFO, "Player {0} logged on before async process was ready, skipping.", uuid);
		return;
	}
	// caching disabled due to fail
	Future<ByteArrayInputStream> soondata = db.loadPlayerDataAsync(uuid, st.getInvIdentifier(uuid), true); // wedon't use the data, but know that it caches behind the scenes.
	
	try {
		ByteArrayInputStream after = soondata.get(); // I want to _INTENTIONALLY_ delay accepting the user's login until I know for sure I've got the data loaded asynchronously.
		if (after == null) {
			plugin.getLogger().log(Level.INFO, "Pre-load for player data {0} came back empty. New player? Error?", uuid);
		} else {
			plugin.getLogger().log(Level.FINER, "Pre-load for player data {0} complete.", uuid);
		}
		
	} catch (InterruptedException | ExecutionException e) {
		plugin.getLogger().log(Level.SEVERE, "Failed to pre-load player data: {0}", uuid);
		e.printStackTrace();
	}
	
	// We do this so it fetches the cache, then when called for real
	// by our CustomWorldNBTStorage class it doesn't have to wait and server won't lock.
}
 
Example 22
Project: BetterShards   File: BetterShardsListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void playerJoinedLobbyServer(AsyncPlayerPreLoginEvent event) {
	if (!config.get("lobby").getBool())
		return;
	UUID uuid = event.getUniqueId();
	if (st == null){ // Small race condition if someone logs on as soon as the server starts.
		plugin.getLogger().log(Level.INFO, "Player logged on before async process was ready, skipping.");
		return;
	}
	st.setInventoryIdentifier(uuid, InventoryIdentifier.IGNORE_INV);
}
 
Example 23
Project: PowerfulPerms   File: PowerfulPermissionManager.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onAsyncPlayerPreLogin(final AsyncPlayerPreLoginEvent e) {
    debug("AsyncPlayerPreLoginEvent " + e.getName());

    if (e.getLoginResult() == AsyncPlayerPreLoginEvent.Result.ALLOWED) {
        loadPlayer(e.getUniqueId(), e.getName(), true, true);
    }
}
 
Example 24
Project: Hammer   File: PlayerConnectListener.java   View source code 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onPlayerConnect(AsyncPlayerPreLoginEvent event) {
    try {
        HammerText text = eventCore.handleEvent(
                new BukkitWrappedPlayer(Bukkit.getOfflinePlayer(event.getUniqueId())),
                event.getAddress().getHostAddress());

        if (text != null) {
            event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, HammerTextConverter.constructMessage(text));
        }
    } catch (HammerException e) {
        plugin.getLogger().severe("Connection to the MySQL database failed. Falling back to the Minecraft ban list.");
        e.printStackTrace();
    }
}
 
Example 25
Project: AdvancedBan   File: ConnectionListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onConnect(AsyncPlayerPreLoginEvent event) {
    String result = Universal.get().callConnection(event.getName(), event.getAddress().getHostAddress());
    if (result != null) {
        event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, result);
    }
}
 
Example 26
Project: BGDCore   File: PlayerListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(final AsyncPlayerPreLoginEvent event) {
    // let's load it async!
    wrappers.put(event.getUniqueId(), BGDCore.loadPlayerWrapper(event.getUniqueId(), event.getName()));
    new BukkitRunnable() {
        @Override
        public void run() {
            if (wrappers.contains(event.getUniqueId())) {
                wrappers.remove(event.getUniqueId()); // aw, wasn't used
            }
        }
    }.runTaskLater(BGDCore.getPlugin(BGDCore.class), 30);
}
 
Example 27
Project: CraftoPlugin   File: PlayerListener.java   View source code 5 votes vote down vote up
void checkForNameChange(StoredPlayer player, AsyncPlayerPreLoginEvent event, PlayerStorage storage) {
	if (player == null || event == null || !player.getUniqueId().equals(event.getUniqueId())) { return; }
	
	// TODO: Register name change record as soon as RecordModule is ported to 4.0
	// TODO: Call StoredPlayerChangeNameEvent
	
	if (!player.getName().equals(event.getName())) {
		info("Player " + player.getId() + " changed name from '" + player.getName() + "' to '" + event.getName() + "'");

		((DatabaseStoredPlayer) player).setName(event.getName());
		
		// Restore into nameMap
		storage.store(player);
	}
}
 
Example 28
Project: CraftoPlugin   File: PlayerListener.java   View source code 5 votes vote down vote up
void checkForIPChange(StoredPlayer player, AsyncPlayerPreLoginEvent event, boolean firstJoin) {
	if (player == null || event == null || !player.getUniqueId().equals(event.getUniqueId())) { return; }
	String newAddress = event.getAddress().toString().replace("/", "");
	
	if (!player.getCurrentAddress().equals(newAddress) || firstJoin) {
		((DatabaseStoredPlayer) player).setCurrentAddress(newAddress);

		if (!firstJoin) {
			// TODO: Call StoredPlayerChangeIPEvent

			info("Player " +player.getId() + " changed ip from '" + player.getCurrentAddress() + "' to '" + newAddress + "'");
		}
	}
}
 
Example 29
Project: CraftoPlugin   File: CraftoDatabase.java   View source code 5 votes vote down vote up
private void checkForIPChange(final CraftoPlayer player, final AsyncPlayerPreLoginEvent event, final boolean firstJoin) {
	if (player != null && event != null && player.getUniqueId().equals(event.getUniqueId())) {
		final String newAddress = event.getAddress().toString().replace("/", "");

		if (!player.getCurrentAddress().equals(newAddress) || firstJoin) {

			((DatabaseCraftoPlayer) player).setCurrentAddress(event.getAddress().getHostAddress());

			if (!firstJoin) {
				this.plugin.getServer().getPluginManager().callEvent(new CraftoPlayerIPChangeEvent(player, player.getCurrentAddress(), event.getAddress().toString()));
			}
		}
	}
}
 
Example 30
Project: SpigotSource   File: LoginListener.java   View source code 5 votes vote down vote up
public void fireEvents() throws Exception {
            String playerName = i.getName();
            java.net.InetAddress address = ((java.net.InetSocketAddress) networkManager.getSocketAddress()).getAddress();
            java.util.UUID uniqueId = i.getId();
            final org.bukkit.craftbukkit.CraftServer server = LoginListener.this.server.server;

            AsyncPlayerPreLoginEvent asyncEvent = new AsyncPlayerPreLoginEvent(playerName, address, uniqueId);
            server.getPluginManager().callEvent(asyncEvent);

            if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0) {
                final PlayerPreLoginEvent event = new PlayerPreLoginEvent(playerName, address, uniqueId);
                if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) {
                    event.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage());
                }
                Waitable<PlayerPreLoginEvent.Result> waitable = new Waitable<PlayerPreLoginEvent.Result>() {
                    @Override
                    protected PlayerPreLoginEvent.Result evaluate() {
                        server.getPluginManager().callEvent(event);
                        return event.getResult();
                    }};

                LoginListener.this.server.processQueue.add(waitable);
                if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED) {
                    disconnect(event.getKickMessage());
                    return;
                }
            } else {
                if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
                    disconnect(asyncEvent.getKickMessage());
                    return;
                }
            }
            // CraftBukkit end
            LoginListener.c.info("UUID of player " + LoginListener.this.i.getName() + " is " + LoginListener.this.i.getId());
            LoginListener.this.g = LoginListener.EnumProtocolState.READY_TO_ACCEPT;
}
 
Example 31
Project: Bukkit-Connect   File: LoginListener.java   View source code 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onAsyncPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
	LoginPayload payload = payloadCache.getByName(event.getName());
	if (payload == null) {
		event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "LilyPad: Internal server error");
		return;
	}
}
 
Example 32
Project: ServerListPlus   File: BukkitPlugin.java   View source code 5 votes vote down vote up
@EventHandler
public void onPlayerLogin(AsyncPlayerPreLoginEvent event) {
    if (core == null) return; // Too early, we haven't finished initializing yet

    UUID uuid = null;
    try { uuid = event.getUniqueId(); } catch (NoSuchMethodError ignored) {}
    core.updateClient(event.getAddress(), uuid, event.getName());
}
 
Example 33
Project: CloudNet   File: BukkitListener.java   View source code 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void handle(AsyncPlayerPreLoginEvent e)
{
    CloudServer.getInstance().getPlayerAndCache(e.getUniqueId());
}
 
Example 34
Project: Uranium   File: ThreadPlayerLookupUUID.java   View source code 4 votes vote down vote up
private void fireLoginEvents() throws Exception
{
    // CraftBukkit start - fire PlayerPreLoginEvent
    if (!this.field_151292_a.field_147333_a.isChannelOpen())
    {
        return;
    }

    String playerName = NetHandlerLoginServer.getGameProfile(this.field_151292_a).getName();
    java.net.InetAddress address = ((java.net.InetSocketAddress) this.field_151292_a.field_147333_a.getSocketAddress()).getAddress();
    java.util.UUID uniqueId = NetHandlerLoginServer.getGameProfile(this.field_151292_a).getId();
    final org.bukkit.craftbukkit.CraftServer server = this.mcServer.server;

    AsyncPlayerPreLoginEvent asyncEvent = new AsyncPlayerPreLoginEvent(playerName, address, uniqueId);
    server.getPluginManager().callEvent(asyncEvent);

    if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0)
    {
        final PlayerPreLoginEvent event = new PlayerPreLoginEvent(playerName, address, uniqueId);

        if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED)
        {
            event.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage());
        }

        Waitable<PlayerPreLoginEvent.Result> waitable = new Waitable<PlayerPreLoginEvent.Result>()
        {
            @Override
            protected PlayerPreLoginEvent.Result evaluate()
            {
                server.getPluginManager().callEvent(event);
                return event.getResult();
            }
        };

        NetHandlerLoginServer.getMinecraftServer(this.field_151292_a).processQueue.add(waitable);

        if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED)
        {
            this.field_151292_a.func_147322_a(event.getKickMessage());
            return;
        }
    }
    else
    {
        if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED)
        {
            this.field_151292_a.func_147322_a(asyncEvent.getKickMessage());
            return;
        }
    }
    // CraftBukkit end

    NetHandlerLoginServer.getLogger().info("UUID of player " + NetHandlerLoginServer.getGameProfile(this.field_151292_a).getName() + " is " + NetHandlerLoginServer.getGameProfile(this.field_151292_a).getId());;
    NetHandlerLoginServer.setLoginState(this.field_151292_a, LoginState.READY_TO_ACCEPT);
}
 
Example 35
Project: ProjectAres   File: LoginListener.java   View source code 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void preLogin(final AsyncPlayerPreLoginEvent event) {
    this.logger.info(event.getName() + " pre-login: uuid=" + event.getUniqueId() + " ip=" + event.getAddress());

    try(Locker _ = Locker.lock(connectedLock.readLock())) {
        this.logins.invalidate(event.getUniqueId());

        if(!connected) {
            event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, SERVER_IS_RESTARTING);
            return;
        }

        LoginResponse response = this.userService.login(
            new LoginRequest(event.getName(),
                             event.getUniqueId(),
                             event.getAddress(),
                             minecraftService.getLocalServer(),
                             true)
        ).get();

        if(response.kick() != null) switch(response.kick()) {
            case "error":
                this.logger.info(event.getName() + " login error: " + response.message());
                event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, response.message());
                break;

            case "banned": // Only used for IP bans right now
                this.logger.info(event.getName() + " is banned");
                event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_BANNED, response.message());
                break;
        }

        if(event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return;

        this.logins.put(event.getUniqueId(), response);

        eventBus.callEvent(new AsyncUserLoginEvent(response));
    } catch(Exception e) {
        this.logger.log(Level.SEVERE, e.toString(), e);
        event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, INTERNAL_SERVER_ERROR);
    }
}
 
Example 36
Project: Kineticraft   File: DataHandler.java   View source code 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST) // Run first, so other things like ban checker have data.
public void onAttemptJoin(AsyncPlayerPreLoginEvent evt) {
    KCPlayer.getPlayerMap().putIfAbsent(evt.getUniqueId(), new KCPlayer(evt.getUniqueId(), evt.getName())); // Create new playerdata.
}
 
Example 37
Project: NeverLag   File: AntiDoubleLogin.java   View source code 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onLogin(AsyncPlayerPreLoginEvent e) {
	if (!cm.isAntiDoubleLogin) {
		return;
	}
	String username = e.getName();
	if (username == null) {
		return;
	}
	if (this.checkOnline(username)) {
		e.disallow(Result.KICK_OTHER, i18n.tr("antiDoubleLoginMessage"));
	}
}
 
Example 38
Project: VoxelGamesLibv2   File: UserListener.java   View source code 4 votes vote down vote up
@EventHandler
public void onAsyncLogin(@Nonnull AsyncPlayerPreLoginEvent event) {
    if (!handler.login(event.getUniqueId())) {
        // something went horribly wrong
        // we don't have a locale here since the data was not loaded :/
        event.disallow(Result.KICK_OTHER, Lang.legacyColors(Lang.string(LangKey.DATA_NOT_LOADED)));
    }
}
 
Example 39
Project: ZentrelaCore   File: PunishmentManager.java   View source code 4 votes vote down vote up
@EventHandler
public void onAsyncPrelogin(AsyncPlayerPreLoginEvent event) {
    InetAddress address = event.getAddress();
    String name = event.getName();
    String uuid = event.getUniqueId().toString();
    String ip = PunishmentManager.parseIP(address);
    PunishmentManager.registerIP(event.getUniqueId(), ip);
    /*
     * Check if user has a ban in effect matching either UUID or IP
     */
    AutoCloseable[] ac_dub = SQLManager.prepare("SELECT * FROM punishments WHERE uuid = ? OR ip = ?");
    try {
        PreparedStatement request_punishment_status = (PreparedStatement) ac_dub[0];
        request_punishment_status.setString(1, uuid);
        request_punishment_status.setString(2, ip);
        AutoCloseable[] ac_trip = SQLManager.executeQuery(request_punishment_status);
        ResultSet rs = (ResultSet) ac_trip[0];
        while (rs.next()) {
            Punishment pun = new Punishment();
            pun.load(rs);
            if (pun.isValid()) {
                if (pun.type == PunishmentType.BAN || pun.type == PunishmentType.IPBAN) {
                    System.out.println("Kicking " + name + " for active ban.");
                    event.disallow(Result.KICK_OTHER, pun.getReason());
                } else if (pun.type == PunishmentType.MUTE) {
                    muted_byUUID.put(uuid, pun);
                }
            }
        }
        SQLManager.close(ac_dub);
        SQLManager.close(ac_trip);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 40
Project: ZentrelaCore   File: LoginLogoutManager.java   View source code 4 votes vote down vote up
@EventHandler
public void onAsyncPrelogin(AsyncPlayerPreLoginEvent event) {
    if (MaintenanceCommand.maintenanceMode && !MaintenanceCommand.allowed.contains(event.getUniqueId().toString())) {
        if (MotdManager.getMotd() != null)
            event.disallow(Result.KICK_OTHER, MotdManager.getMotd());
        else
            event.disallow(Result.KICK_OTHER, ChatColor.RED + "Zentrela is down for maintenance. Please check the MOTD (server list) for details!");
    }
}