· 5 years ago · Mar 12, 2020, 10:28 PM
1 private ArrayList<UUID> authlocked;
2
3 @Override
4 public void onEnable() {
5 this.getServer().getPluginManager().registerEvents(this, this);
6 authlocked = new ArrayList<UUID>();
7
8 this.getConfig().options().copyDefaults(true);
9 this.saveConfig();
10 }
11
12
13 @EventHandler
14 public void onJoin(PlayerJoinEvent event) {
15 Player player = event.getPlayer();
16
17 if (!this.getConfig().contains("authcodes." + player.getUniqueId())) {
18 GoogleAuthenticator gAuth = new GoogleAuthenticator();
19 GoogleAuthenticatorKey key = gAuth.createCredentials();
20
21 player.sendMessage("§7Your §bGoogle Auth Code §7is §a" + key.getKey());
22 player.sendMessage("§7You must enter this code in the Google Authenticator App before leaving the server.");
23
24 this.getConfig().set("authcodes." + player.getUniqueId(), key.getKey());
25 this.saveConfig();
26 } else {
27 authlocked.add(player.getUniqueId());
28 player.sendMessage("§cPlease open the Google Authenticator App and provide the six digit code.");
29 }
30 }
31
32 private boolean playerInputCode(Player player, int code) {
33 String secretkey = this.getConfig().getString("authcodes." + player.getUniqueId());
34
35 GoogleAuthenticator gAuth = new GoogleAuthenticator();
36 boolean codeisvalid = gAuth.authorize(secretkey, code);
37
38
39 if (codeisvalid) {
40 authlocked.remove(player.getUniqueId());
41 return codeisvalid;
42 }
43
44 return codeisvalid;
45 }
46
47
48 @EventHandler
49 public void chat(AsyncPlayerChatEvent event) {
50 Player player = event.getPlayer();
51 String message = event.getMessage();
52
53 if (authlocked.contains(player.getUniqueId())) {
54 try {
55 Integer code = Integer.parseInt(message);
56 if (playerInputCode(player, code)) {
57 authlocked.remove(player.getUniqueId());
58 player.sendMessage("§aAccess Granted §bWelcome to the server!");
59 } else {
60 player.sendMessage("§cIncorrect or expired code ** A code will only contain numbers ");
61
62 }
63 } catch (Exception e) {
64 player.sendMessage("§cIncorrect or expired code A code will only contain numbers ");
65 }
66 event.setCancelled(true);
67 }
68 }
69 }