Java Code Examples for org.bukkit.event.player.PlayerLoginEvent#getPlayer()

The following examples show how to use org.bukkit.event.player.PlayerLoginEvent#getPlayer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SkinApplyListener.java    From FastLogin with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
//run this on the loginEvent to let skins plugins see the skin like in normal Minecraft behaviour
public void onPlayerLogin(PlayerLoginEvent loginEvent) {
    if (loginEvent.getResult() != Result.ALLOWED) {
        return;
    }

    Player player = loginEvent.getPlayer();

    if (plugin.getConfig().getBoolean("forwardSkin")) {
        //go through every session, because player.getAddress is null
        //loginEvent.getAddress is just a InetAddress not InetSocketAddress, so not unique enough
        for (BukkitLoginSession session : plugin.getLoginSessions().values()) {
            if (session.getUsername().equals(player.getName())) {
                session.getSkin().ifPresent(skin -> applySkin(player, skin.getValue(), skin.getSignature()));
                break;
            }
        }
    }
}
 
Example 2
Source File: LoginListener.java    From ChangeSkin with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(PlayerLoginEvent loginEvent) {
    if (loginEvent.getResult() != PlayerLoginEvent.Result.ALLOWED) {
        //in this event isCancelled option in the annotation doesn't work
        return;
    }

    Player player = loginEvent.getPlayer();

    //updates to the chosen one
    UserPreference preferences = plugin.getLoginSession(player.getUniqueId());
    if (preferences != null) {
        preferences.getTargetSkin().ifPresent(skin -> plugin.getApi().applySkin(player, skin));
    }

    plugin.endSession(player.getUniqueId());
}
 
Example 3
Source File: PlayerListener.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLogin(PlayerLoginEvent event) {
    final Player player = event.getPlayer();
    final String name = player.getName();

    try {
        onJoinVerifier.checkSingleSession(name);
    } catch (FailedVerificationException e) {
        event.setKickMessage(messages.retrieveSingle(name, e.getReason(), e.getArgs()));
        event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
        return;
    }

    if (validationService.isUnrestricted(name)) {
        return;
    }

    onJoinVerifier.refusePlayerForFullServer(event);
}
 
Example 4
Source File: VanishManagerImpl.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPreJoin(PlayerLoginEvent event) {
  Player player = event.getPlayer();
  loginSubdomains.invalidate(player.getUniqueId());
  if (player.hasPermission(Permissions.VANISH)
      && !isVanished(player.getUniqueId())
      && isVanishSubdomain(event.getHostname())) {
    loginSubdomains.put(player.getUniqueId(), event.getHostname());
  }
}
 
Example 5
Source File: OnJoinVerifier.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handles the case of a full server and verifies if the user's connection should really be refused
 * by adjusting the event object accordingly. Attempts to kick a non-VIP player to make room if the
 * joining player is a VIP.
 *
 * @param event the login event to verify
 *
 * @return true if the player's connection should be refused (i.e. the event does not need to be processed
 *         further), false if the player is not refused
 */
public boolean refusePlayerForFullServer(PlayerLoginEvent event) {
    final Player player = event.getPlayer();
    if (event.getResult() != PlayerLoginEvent.Result.KICK_FULL) {
        // Server is not full, no need to do anything
        return false;
    } else if (!permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)) {
        // Server is full and player is NOT VIP; set kick message and proceed with kick
        event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER));
        return true;
    }

    // Server is full and player is VIP; attempt to kick a non-VIP player to make room
    Collection<Player> onlinePlayers = bukkitService.getOnlinePlayers();
    if (onlinePlayers.size() < server.getMaxPlayers()) {
        event.allow();
        return false;
    }
    Player nonVipPlayer = generateKickPlayer(onlinePlayers);
    if (nonVipPlayer != null) {
        nonVipPlayer.kickPlayer(messages.retrieveSingle(player, MessageKey.KICK_FOR_VIP));
        event.allow();
        return false;
    } else {
        logger.info("VIP player " + player.getName() + " tried to join, but the server was full");
        event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER));
        return true;
    }
}
 
Example 6
Source File: PlayerLoginListener.java    From ExploitFixer with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerLogin(final PlayerLoginEvent event) {
	final Player player = event.getPlayer();
	final InetAddress address = event.getAddress();
	final String locale = VersionUtil.getLocale(player);

	if (connectionModule.isNullAddressEnabled() && address == null) {
		final String nullAddressKickMessage = messagesModule.getKickMessage("nulladdress", locale);

		event.setKickMessage(nullAddressKickMessage);
		event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
	} else {
		final UUID uuid = player.getUniqueId();
		final String playerName = player.getName();
		final ExploitPlayer exploitPlayer = exploitPlayerManager.get(player);

		if (connectionModule.isUUIDSpoofEnabled()) {
			final BukkitScheduler scheduler = plugin.getServer().getScheduler();

			scheduler.runTaskAsynchronously(plugin, () -> {
				final String originalUUID = uuid.toString().replace("-", "");
				final String offlineUUID = UUID.nameUUIDFromBytes(("OfflinePlayer:" + playerName).getBytes())
						.toString().replace("-", "");

				if (!originalUUID.contains(offlineUUID)) {
					final String onlineUUID = exploitPlayer.getOnlineUUID();

					if (onlineUUID == null || !onlineUUID.contains(originalUUID)) {
						final HamsterPlayer hamsterPlayer = HamsterAPI.getInstance().getHamsterPlayerManager()
								.get(player);
						final String uuidSpoofKickMessage = messagesModule.getKickMessage("uuidspoof", locale);

						event.setKickMessage(uuidSpoofKickMessage);
						event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
						hamsterPlayer.disconnect(uuidSpoofKickMessage);
						hamsterPlayer.closeChannel();
					}
				}

				exploitPlayer.setLogged(true);
			});
		} else {
			exploitPlayer.setLogged(true);
		}
	}

	if (player.hasPermission("exploitfixer.notifications")) {
		notificationsModule.setNotifications(player, true);
	}
}
 
Example 7
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(PlayerLoginEvent event) {
    GDTimings.PLAYER_LOGIN_EVENT.startTiming();
    final Player player = event.getPlayer();
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUID())) {
        GDTimings.PLAYER_LOGIN_EVENT.stopTiming();
        return;
    }

    final boolean checkRestore = GriefDefenderPlugin.getGlobalConfig().getConfig().economy.rentSystem && GriefDefenderPlugin.getInstance().getWorldEditProvider() != null;
    final UUID worldUniqueId = event.getPlayer().getWorld().getUID();
    final UUID playerUniqueId = player.getUniqueId();
    final GDClaimManager claimWorldManager = this.dataStore.getClaimWorldManager(worldUniqueId);
    final Instant dateNow = Instant.now();
    for (Claim claim : claimWorldManager.getWorldClaims()) {
        if (claim.getType() != ClaimTypes.ADMIN && claim.getOwnerUniqueId().equals(playerUniqueId)) {
            claim.getData().setDateLastActive(dateNow);
            for (Claim subdivision : ((GDClaim) claim).children) {
                subdivision.getData().setDateLastActive(dateNow);
            }
            ((GDClaim) claim).getInternalClaimData().setRequiresSave(true);
            ((GDClaim) claim).getInternalClaimData().save();
        } else if (checkRestore && claim.getEconomyData() != null && claim.getEconomyData().isRented()) {
            for (UUID uuid : claim.getEconomyData().getRenters()) {
                if (player.getUniqueId().equals(uuid)) {
                    // check for rent expiration
                    final PaymentType paymentType = claim.getEconomyData().getPaymentType();
                    final int rentMax = claim.getEconomyData().getRentMaxTime();
                    final Instant rentStart = claim.getEconomyData().getRentStartDate();
                    if (rentStart != null) {
                        final Instant endDate = rentStart.plus(rentMax, ChronoUnit.DAYS);
                        final Duration duration = Duration.between(rentStart, endDate);
                        if (!duration.isNegative() && duration.toDays() <= GriefDefenderPlugin.getGlobalConfig().getConfig().economy.rentRestoreDayWarning) {
                            final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ECONOMY_CLAIM_RENTED_TIME_WARNING, ImmutableMap.of(
                                    "days", duration.toDays()
                                    ));
                            GriefDefenderPlugin.sendMessage(player, message);
                        }
                    }
                }
            }
        }
    }
    GDTimings.PLAYER_LOGIN_EVENT.stopTiming();
}
 
Example 8
Source File: LoginListener.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void login(PlayerLoginEvent event) {
    try {
        final Player player = event.getPlayer();
        final UUID uuid = player.getUniqueId();

        this.logins.cleanUp();
        final LoginResponse response = this.logins.getIfPresent(uuid);
        this.logins.invalidate(uuid);

        if(response == null) {
            this.logger.warning("No login info for " + player.getName() + " " + uuid);
            event.disallow(PlayerLoginEvent.Result.KICK_OTHER, INTERNAL_SERVER_ERROR);
            return;
        }

        // TODO: Consider creating a PreUserLoginEvent that can be cancelled,
        // before things like sessions are started.

        userStore.addUser(player, response.user());

        applyPermissions(player, response.user());

        if(response.punishment() != null) {
            rejectLogin(event, punishmentFormatter.screen(response.punishment()));
        }

        if(!player.hasPermission(Permissions.LOGIN)) {
            rejectLogin(event, new TranslatableComponent("servers.notAllowed"));
        }

        if(event.getResult() == PlayerLoginEvent.Result.KICK_FULL) {
            // Allow privileged players to join when the server is full
            if(player.hasPermission("pgm.fullserver")) {
                event.allow();
            } else {
                rejectLogin(event, new TranslatableComponent("serverFull"));
            }
        }

        if(response.user().mc_locale() != null) {
            // If we have a saved locale for the player, apply it.
            // This should ensure that text displayed on join is properly
            // localized, as long as the player has connected once before.
            player.setLocale(response.user().mc_locale());
        }

        userService.update(response.user(), new UserDoc.ClientDetails() {
            @Override public String mc_client_version() {
                return MinecraftVersion.describeProtocol(player.getProtocolVersion());
            }

            @Override public String skin_blob() {
                return player.getSkin().getData();
            }
        });

        if(event.getResult() == PlayerLoginEvent.Result.KICK_OTHER) return;

        final UserLoginEvent ourEvent = new UserLoginEvent(
            player, response, event.getResult(),
            event.getKickMessage() == null || "".equals(event.getKickMessage()) ? null : new Component(event.getKickMessage())
        );

        eventBus.callEvent(ourEvent);

        event.setResult(ourEvent.getResult());
        event.setKickMessage(ourEvent.getKickMessage() == null ? "" : renderer.renderLegacy(ourEvent.getKickMessage(), player));
    }
    catch(Exception e) {
        this.logger.log(Level.SEVERE, e.toString(), e);
        event.disallow(PlayerLoginEvent.Result.KICK_OTHER, INTERNAL_SERVER_ERROR);
    }
}
 
Example 9
Source File: BukkitConnectionListener.java    From LuckPerms with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(PlayerLoginEvent e) {
    /* Called when the player starts logging into the server.
       At this point, the users data should be present and loaded. */

    final Player player = e.getPlayer();

    if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
        this.plugin.getLogger().info("Processing login for " + player.getUniqueId() + " - " + player.getName());
    }

    final User user = this.plugin.getUserManager().getIfLoaded(player.getUniqueId());

    /* User instance is null for whatever reason. Could be that it was unloaded between asyncpre and now. */
    if (user == null) {
        this.deniedLogin.add(player.getUniqueId());

        if (!getUniqueConnections().contains(player.getUniqueId())) {

            this.plugin.getLogger().warn("User " + player.getUniqueId() + " - " + player.getName() +
                    " doesn't have data pre-loaded, they have never been processed during pre-login in this session." +
                    " - denying login.");

            if (this.detectedCraftBukkitOfflineMode) {
                printCraftBukkitOfflineModeError();
                e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Message.LOADING_STATE_ERROR_CB_OFFLINE_MODE.asString(this.plugin.getLocaleManager()));
                return;
            }

        } else {
            this.plugin.getLogger().warn("User " + player.getUniqueId() + " - " + player.getName() +
                    " doesn't currently have data pre-loaded, but they have been processed before in this session." +
                    " - denying login.");
        }

        e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Message.LOADING_STATE_ERROR.asString(this.plugin.getLocaleManager()));
        return;
    }

    // User instance is there, now we can inject our custom Permissible into the player.
    // Care should be taken at this stage to ensure that async tasks which manipulate bukkit data check that the player is still online.
    try {
        // Make a new permissible for the user
        LuckPermsPermissible lpPermissible = new LuckPermsPermissible(player, user, this.plugin);

        // Inject into the player
        PermissibleInjector.inject(player, lpPermissible);

    } catch (Throwable t) {
        this.plugin.getLogger().warn("Exception thrown when setting up permissions for " +
                player.getUniqueId() + " - " + player.getName() + " - denying login.");
        t.printStackTrace();

        e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Message.LOADING_SETUP_ERROR.asString(this.plugin.getLocaleManager()));
        return;
    }

    this.plugin.getContextManager().signalContextUpdate(player);
}
 
Example 10
Source File: BukkitEventListener.java    From BungeePerms with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PlayerLoginEvent e)
{
    String playername = e.getPlayer().getName();
    UUID uuid = null;

    if (config.isUseUUIDs())
    {
        uuid = e.getPlayer().getUniqueId();
        BungeePerms.getLogger().info(Lang.translate(Lang.MessageType.LOGIN_UUID, playername, uuid));

        //update uuid player db
        pm().getUUIDPlayerDB().update(uuid, playername);
    }
    else
    {
        BungeePerms.getLogger().info(Lang.translate(Lang.MessageType.LOGIN, e.getPlayer().getName()));
    }

    //remove user from cache if present
    User oldu = config.isUseUUIDs() ? pm().getUser(uuid, false) : pm().getUser(playername, false);
    if (oldu != null)
    {
        pm().removeUserFromCache(oldu);
    }

    //load user from db
    User u = config.isUseUUIDs() ? pm().getUser(uuid) : pm().getUser(playername);
    if (u == null)
    {
        //create user and add default groups
        if (config.isUseUUIDs())
        {
            BungeePerms.getLogger().info(Lang.translate(Lang.MessageType.ADDING_DEFAULT_GROUPS_UUID, playername, uuid));
        }
        else
        {
            BungeePerms.getLogger().info(Lang.translate(Lang.MessageType.ADDING_DEFAULT_GROUPS, playername));
        }

        u = pm().createTempUser(playername, uuid);
        pm().getBackEnd().saveUser(u, true);
    }

    BukkitPlugin.getInstance().getNotifier().sendWorldUpdate(e.getPlayer());

    //inject permissible
    BPPermissible permissible = new BPPermissible(e.getPlayer(), u, Injector.getPermissible(e.getPlayer()));
    permissible.inject();

    updateAttachment(e.getPlayer(), u);
}