From 07e2906d0ee99ee41cc5d739d631a58d41844ab6 Mon Sep 17 00:00:00 2001 From: Colin McDonald Date: Thu, 14 Jul 2016 21:54:55 -0400 Subject: [PATCH] Test IntelliJ reformatting --- src/main/java/net/frozenorb/apiv3/APIv3.java | 467 +++---- src/main/java/net/frozenorb/apiv3/Main.java | 12 +- .../java/net/frozenorb/apiv3/actor/Actor.java | 8 +- .../net/frozenorb/apiv3/actor/ActorType.java | 2 +- .../frozenorb/apiv3/actor/SimpleActor.java | 6 +- .../frozenorb/apiv3/auditLog/AuditLog.java | 26 +- .../apiv3/auditLog/AuditLogActionType.java | 141 +- .../apiv3/dataImport/V2Importer.java | 52 +- .../dataImport/converters/GrantConverter.java | 78 +- .../dataImport/converters/IpLogConverter.java | 60 +- .../converters/PunishmentConverter.java | 70 +- .../dataImport/converters/UserConverter.java | 88 +- .../apiv3/handler/ActorAttributeHandler.java | 76 +- .../apiv3/handler/AuthorizationHandler.java | 18 +- .../handler/WebsiteUserSessionHandler.java | 2 +- .../frozenorb/apiv3/maxmind/MaxMindCity.java | 18 +- .../apiv3/maxmind/MaxMindContinent.java | 18 +- .../apiv3/maxmind/MaxMindCountry.java | 22 +- .../apiv3/maxmind/MaxMindLocation.java | 34 +- .../apiv3/maxmind/MaxMindPostal.java | 14 +- .../maxmind/MaxMindRegisteredCountry.java | 18 +- .../apiv3/maxmind/MaxMindResult.java | 46 +- .../apiv3/maxmind/MaxMindTraits.java | 30 +- .../apiv3/maxmind/MaxMindUserType.java | 40 +- .../frozenorb/apiv3/model/AccessToken.java | 76 +- .../frozenorb/apiv3/model/AuditLogEntry.java | 76 +- .../net/frozenorb/apiv3/model/BannedAsn.java | 108 +- .../apiv3/model/BannedCellCarrier.java | 108 +- .../java/net/frozenorb/apiv3/model/Grant.java | 178 +-- .../java/net/frozenorb/apiv3/model/IpBan.java | 224 +-- .../net/frozenorb/apiv3/model/IpIntel.java | 180 +-- .../net/frozenorb/apiv3/model/IpLogEntry.java | 94 +- .../apiv3/model/NotificationTemplate.java | 72 +- .../net/frozenorb/apiv3/model/PhoneIntel.java | 80 +- .../net/frozenorb/apiv3/model/Punishment.java | 264 ++-- .../java/net/frozenorb/apiv3/model/Rank.java | 110 +- .../net/frozenorb/apiv3/model/Server.java | 182 +-- .../frozenorb/apiv3/model/ServerGroup.java | 118 +- .../java/net/frozenorb/apiv3/model/User.java | 1226 ++++++++--------- .../frozenorb/apiv3/route/GETDumpsType.java | 180 +-- .../net/frozenorb/apiv3/route/GETWhoAmI.java | 16 +- .../accessTokens/DELETEAccessTokensId.java | 40 +- .../route/accessTokens/GETAccessTokens.java | 40 +- .../route/accessTokens/GETAccessTokensId.java | 18 +- .../route/accessTokens/POSTAccessTokens.java | 52 +- .../route/auditLog/DELETEAuditLogId.java | 48 +- .../apiv3/route/auditLog/GETAuditLog.java | 30 +- .../apiv3/route/auditLog/POSTAuditLog.java | 64 +- .../route/bannedAsns/DELETEBannedAsnsId.java | 40 +- .../apiv3/route/bannedAsns/GETBannedAsns.java | 6 +- .../route/bannedAsns/GETBannedAsnsId.java | 6 +- .../route/bannedAsns/POSTBannedAsns.java | 36 +- .../DELETEBannedCellCarriersId.java | 40 +- .../GETBannedCellCarriers.java | 6 +- .../GETBannedCellCarriersId.java | 6 +- .../POSTBannedCellCarriers.java | 36 +- .../route/chatFilter/DELETEChatFilterId.java | 40 +- .../apiv3/route/chatFilter/GETChatFilter.java | 18 +- .../route/chatFilter/GETChatFilterId.java | 18 +- .../route/chatFilter/POSTChatFilter.java | 36 +- .../emailTokens/GETEmailTokensIdOwner.java | 18 +- .../emailTokens/POSTEmailTokensIdConfirm.java | 66 +- .../apiv3/route/grants/DELETEGrantsId.java | 60 +- .../apiv3/route/grants/GETGrants.java | 32 +- .../apiv3/route/grants/GETGrantsId.java | 18 +- .../apiv3/route/grants/POSTGrants.java | 128 +- .../apiv3/route/ipBans/DELETEIpBansId.java | 60 +- .../apiv3/route/ipBans/GETIpBans.java | 30 +- .../apiv3/route/ipBans/GETIpBansId.java | 18 +- .../apiv3/route/ipBans/POSTIpBans.java | 74 +- .../apiv3/route/ipIntel/GETIpInteld.java | 28 +- .../apiv3/route/ipLog/GETIpLogId.java | 56 +- .../DELETENotificationTemplatesId.java | 40 +- .../GETNotificationTemplates.java | 18 +- .../GETNotificationTemplatesId.java | 18 +- .../POSTNotificationTemplates.java | 38 +- .../route/phoneIntel/GETPhoneInteld.java | 28 +- .../punishments/DELETEPunishmentsId.java | 60 +- .../DELETEUsersIdActivePunishment.java | 82 +- .../route/punishments/GETPunishments.java | 40 +- .../route/punishments/GETPunishmentsId.java | 18 +- .../route/punishments/POSTPunishments.java | 152 +- .../apiv3/route/ranks/DELETERanksId.java | 40 +- .../frozenorb/apiv3/route/ranks/GETRanks.java | 6 +- .../apiv3/route/ranks/GETRanksId.java | 6 +- .../apiv3/route/ranks/POSTRanks.java | 48 +- .../serverGroups/DELETEServerGroupsId.java | 40 +- .../route/serverGroups/GETServerGroups.java | 6 +- .../route/serverGroups/GETServerGroupsId.java | 6 +- .../route/serverGroups/POSTServerGroups.java | 36 +- .../apiv3/route/servers/DELETEServersId.java | 74 +- .../apiv3/route/servers/GETServers.java | 6 +- .../apiv3/route/servers/GETServersId.java | 6 +- .../apiv3/route/servers/POSTServers.java | 62 +- .../route/servers/POSTServersHeartbeat.java | 354 ++--- .../frozenorb/apiv3/route/users/GETStaff.java | 50 +- .../apiv3/route/users/GETUsersId.java | 18 +- .../GETUsersIdCompoundedPermissions.java | 34 +- .../apiv3/route/users/GETUsersIdDetails.java | 36 +- .../route/users/GETUsersIdRequiresTotp.java | 54 +- .../route/users/GETUsersIdVerifyPassword.java | 68 +- .../users/POSTUsersIdChangePassword.java | 104 +- .../route/users/POSTUsersIdConfirmPhone.java | 92 +- .../apiv3/route/users/POSTUsersIdLogin.java | 154 +-- .../apiv3/route/users/POSTUsersIdNotify.java | 58 +- .../route/users/POSTUsersIdPasswordReset.java | 70 +- .../route/users/POSTUsersIdRegisterEmail.java | 108 +- .../route/users/POSTUsersIdRegisterPhone.java | 110 +- .../route/users/POSTUsersIdSetupTotp.java | 58 +- .../route/users/POSTUsersIdVerifyTotp.java | 76 +- .../FollowAnnotationExclusionStrategy.java | 16 +- .../gson/InstantTypeAdapter.java | 28 +- .../jackson/InstantJsonDeserializer.java | 8 +- .../jackson/InstantJsonSerializer.java | 8 +- .../jackson/UuidJsonDeserializer.java | 8 +- .../jackson/UuidJsonSerializer.java | 8 +- .../serialization/mongodb/UuidCodec.java | 24 +- .../mongodb/UuidCodecProvider.java | 14 +- .../apiv3/unsorted/MongoToVertxCallback.java | 22 +- .../apiv3/unsorted/Notification.java | 46 +- .../frozenorb/apiv3/unsorted/Permissions.java | 6 +- .../apiv3/unsorted/RequiresTotpResult.java | 6 +- .../unsorted/TotpAuthorizationResult.java | 20 +- .../net/frozenorb/apiv3/util/EmailUtils.java | 52 +- .../net/frozenorb/apiv3/util/ErrorUtils.java | 52 +- .../net/frozenorb/apiv3/util/IpUtils.java | 16 +- .../frozenorb/apiv3/util/MandrillUtils.java | 26 +- .../frozenorb/apiv3/util/MaxMindUtils.java | 98 +- .../net/frozenorb/apiv3/util/MojangUtils.java | 38 +- .../frozenorb/apiv3/util/PermissionUtils.java | 92 +- .../net/frozenorb/apiv3/util/PhoneUtils.java | 14 +- .../net/frozenorb/apiv3/util/TimeUtils.java | 36 +- .../net/frozenorb/apiv3/util/TotpUtils.java | 110 +- .../net/frozenorb/apiv3/util/UuidUtils.java | 24 +- .../net/frozenorb/apiv3/util/ZangUtils.java | 78 +- .../net/frozenorb/apiv3/zang/ZangResult.java | 22 +- src/main/resources/log4j.xml | 8 +- 137 files changed, 4484 insertions(+), 4476 deletions(-) diff --git a/src/main/java/net/frozenorb/apiv3/APIv3.java b/src/main/java/net/frozenorb/apiv3/APIv3.java index bc71180..45f89bd 100644 --- a/src/main/java/net/frozenorb/apiv3/APIv3.java +++ b/src/main/java/net/frozenorb/apiv3/APIv3.java @@ -121,21 +121,21 @@ import java.util.concurrent.TimeUnit; @Slf4j public final class APIv3 extends AbstractVerticle { - @Getter private static Vertx vertxInstance; - @Getter private static MongoDatabase database; - @Getter private static final Properties config = new Properties(); - private static final Gson gson = new GsonBuilder() - .registerTypeAdapter(Instant.class, new InstantTypeAdapter()) - .setExclusionStrategies(new FollowAnnotationExclusionStrategy()) - .create(); + @Getter private static Vertx vertxInstance; + @Getter private static MongoDatabase database; + @Getter private static final Properties config = new Properties(); + private static final Gson gson = new GsonBuilder() + .registerTypeAdapter(Instant.class, new InstantTypeAdapter()) + .setExclusionStrategies(new FollowAnnotationExclusionStrategy()) + .create(); - @Override - public void start() { - vertxInstance = vertx; - setupConfig(); - setupDatabase(); - setupMetrics(); - setupHttpServer(); + @Override + public void start() { + vertxInstance = vertx; + setupConfig(); + setupDatabase(); + setupMetrics(); + setupHttpServer(); /*V2Importer converter = new V2Importer("mongodb://158.69.126.126", "minehq"); @@ -146,260 +146,267 @@ public final class APIv3 extends AbstractVerticle { log.info("Finished conversion!"); } });*/ - } + } - private void setupConfig() { - try (InputStream in = new FileInputStream("apiv3.properties")) { - config.load(in); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } + private void setupConfig() { + try (InputStream in = new FileInputStream("apiv3.properties")) { + config.load(in); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } - private void setupDatabase() { - List credentials = ImmutableList.of(); + private void setupDatabase() { + List credentials = ImmutableList.of(); - if (!config.getProperty("mongo.username").isEmpty()) { - credentials = ImmutableList.of( - MongoCredential.createCredential( - config.getProperty("mongo.username"), - config.getProperty("mongo.database"), - config.getProperty("mongo.password").toCharArray() - ) - ); - } + if (!config.getProperty("mongo.username").isEmpty()) { + credentials = ImmutableList.of( + MongoCredential.createCredential( + config.getProperty("mongo.username"), + config.getProperty("mongo.database"), + config.getProperty("mongo.password").toCharArray() + ) + ); + } - ConnectionString connectionString = new ConnectionString("mongodb://" + config.getProperty("mongo.address") + ":" + config.getProperty("mongo.port")); + ConnectionString connectionString = new ConnectionString("mongodb://" + config.getProperty("mongo.address") + ":" + config.getProperty("mongo.port")); - MongoClient mongoClient = MongoClients.create(MongoClientSettings - .builder() - .codecRegistry(CodecRegistries.fromProviders(ImmutableList.of( - new UuidCodecProvider(), // MHQ, fixes uuid serialization - new ValueCodecProvider(), - new DocumentCodecProvider(), - new BsonValueCodecProvider(), - new JacksonCodecProvider(createMongoJacksonMapper()) // Jackson codec, provides serialization/deserialization - ))) - .credentialList(credentials) - .clusterSettings(ClusterSettings.builder() - .applyConnectionString(connectionString) - .build() - ) - .build() - ); + MongoClient mongoClient = MongoClients.create(MongoClientSettings + .builder() + .codecRegistry(CodecRegistries.fromProviders(ImmutableList.of( + new UuidCodecProvider(), // MHQ, fixes uuid serialization + new ValueCodecProvider(), + new DocumentCodecProvider(), + new BsonValueCodecProvider(), + new JacksonCodecProvider(createMongoJacksonMapper()) // Jackson codec, provides serialization/deserialization + ))) + .credentialList(credentials) + .clusterSettings(ClusterSettings.builder() + .applyConnectionString(connectionString) + .build() + ) + .build() + ); - database = mongoClient.getDatabase(config.getProperty("mongo.database")); - database.getCollection("auditLog").createIndexes(ImmutableList.of( - new IndexModel(new Document("user", 1)), - new IndexModel(new Document("performedAt", 1)), - new IndexModel(new Document("type", 1)) - ), (a, b) -> {}); - database.getCollection("grants").createIndexes(ImmutableList.of( - new IndexModel(new Document("user", 1)), - new IndexModel(new Document("rank", 1)), - new IndexModel(new Document("addedAt", 1)) - ), (a, b) -> {}); - database.getCollection("ipLog").createIndexes(ImmutableList.of( - new IndexModel(new Document("user", 1)), - new IndexModel(new Document("user", 1).append("userIp", 1)) - ), (a, b) -> {}); - database.getCollection("ipBans").createIndexes(ImmutableList.of( - new IndexModel(new Document("userIp", 1)) - ), (a, b) -> {}); - database.getCollection("punishments").createIndexes(ImmutableList.of( - new IndexModel(new Document("user", 1)), - new IndexModel(new Document("type", 1)), - new IndexModel(new Document("addedAt", 1)), - new IndexModel(new Document("addedBy", 1)), - new IndexModel(new Document("linkedIpBanId", 1)) - ), (a, b) -> {}); - database.getCollection("users").createIndexes(ImmutableList.of( - new IndexModel(new Document("lastUsername", 1)), - new IndexModel(new Document("emailToken", 1)) - ), (a, b) -> {}); - database.getCollection("userMeta").createIndexes(ImmutableList.of( - new IndexModel(new Document("user", 1).append("serverGroup", 1)) - ), (a, b) -> {}); + database = mongoClient.getDatabase(config.getProperty("mongo.database")); + database.getCollection("auditLog").createIndexes(ImmutableList.of( + new IndexModel(new Document("user", 1)), + new IndexModel(new Document("performedAt", 1)), + new IndexModel(new Document("type", 1)) + ), (a, b) -> { + }); + database.getCollection("grants").createIndexes(ImmutableList.of( + new IndexModel(new Document("user", 1)), + new IndexModel(new Document("rank", 1)), + new IndexModel(new Document("addedAt", 1)) + ), (a, b) -> { + }); + database.getCollection("ipLog").createIndexes(ImmutableList.of( + new IndexModel(new Document("user", 1)), + new IndexModel(new Document("user", 1).append("userIp", 1)) + ), (a, b) -> { + }); + database.getCollection("ipBans").createIndexes(ImmutableList.of( + new IndexModel(new Document("userIp", 1)) + ), (a, b) -> { + }); + database.getCollection("punishments").createIndexes(ImmutableList.of( + new IndexModel(new Document("user", 1)), + new IndexModel(new Document("type", 1)), + new IndexModel(new Document("addedAt", 1)), + new IndexModel(new Document("addedBy", 1)), + new IndexModel(new Document("linkedIpBanId", 1)) + ), (a, b) -> { + }); + database.getCollection("users").createIndexes(ImmutableList.of( + new IndexModel(new Document("lastUsername", 1)), + new IndexModel(new Document("emailToken", 1)) + ), (a, b) -> { + }); + database.getCollection("userMeta").createIndexes(ImmutableList.of( + new IndexModel(new Document("user", 1).append("serverGroup", 1)) + ), (a, b) -> { + }); - BannedAsn.updateCache(); - BannedCellCarrier.updateCache(); - Rank.updateCache(); - Server.updateCache(); - ServerGroup.updateCache(); - EmailUtils.updateBannedEmailDomains(); - GETDumpsType.updateCache(); - } + BannedAsn.updateCache(); + BannedCellCarrier.updateCache(); + Rank.updateCache(); + Server.updateCache(); + ServerGroup.updateCache(); + EmailUtils.updateBannedEmailDomains(); + GETDumpsType.updateCache(); + } - private ObjectMapper createMongoJacksonMapper() { - ObjectMapper mongoJacksonMapper = ObjectMapperFactory.createObjectMapper(); - SimpleModule module = new SimpleModule(); + private ObjectMapper createMongoJacksonMapper() { + ObjectMapper mongoJacksonMapper = ObjectMapperFactory.createObjectMapper(); + SimpleModule module = new SimpleModule(); - module.addSerializer(Instant.class, new InstantJsonSerializer()); - module.addDeserializer(Instant.class, new InstantJsonDeserializer()); - module.addSerializer(UUID.class, new UuidJsonSerializer()); - module.addDeserializer(UUID.class, new UuidJsonDeserializer()); + module.addSerializer(Instant.class, new InstantJsonSerializer()); + module.addDeserializer(Instant.class, new InstantJsonDeserializer()); + module.addSerializer(UUID.class, new UuidJsonSerializer()); + module.addDeserializer(UUID.class, new UuidJsonDeserializer()); - mongoJacksonMapper.registerModule(module); - mongoJacksonMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); - mongoJacksonMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); - mongoJacksonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mongoJacksonMapper.registerModule(module); + mongoJacksonMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); + mongoJacksonMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + mongoJacksonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - return mongoJacksonMapper; - } + return mongoJacksonMapper; + } - private void setupMetrics() { - MetricRegistry registry = SharedMetricRegistries.getOrCreate("apiv3-registry"); + private void setupMetrics() { + MetricRegistry registry = SharedMetricRegistries.getOrCreate("apiv3-registry"); - LibratoReporter.enable( - LibratoReporter.builder( - registry, - config.getProperty("librato.email"), - config.getProperty("librato.apiToken"), - config.getProperty("librato.sourceIdentifier")), - 10, - TimeUnit.SECONDS); - } + LibratoReporter.enable( + LibratoReporter.builder( + registry, + config.getProperty("librato.email"), + config.getProperty("librato.apiToken"), + config.getProperty("librato.sourceIdentifier")), + 10, + TimeUnit.SECONDS); + } - private void setupHttpServer() { - HttpServerOptions httpServerOptions = new HttpServerOptions(); - httpServerOptions.setCompressionSupported(true); + private void setupHttpServer() { + HttpServerOptions httpServerOptions = new HttpServerOptions(); + httpServerOptions.setCompressionSupported(true); - if (!config.getProperty("http.keystoreFile").isEmpty()) { - httpServerOptions.setSsl(true); - httpServerOptions.setKeyStoreOptions( - new JksOptions() - .setPassword(config.getProperty("http.keystorePassword")) - .setPath(config.getProperty("http.keystoreFile")) - ); - } + if (!config.getProperty("http.keystoreFile").isEmpty()) { + httpServerOptions.setSsl(true); + httpServerOptions.setKeyStoreOptions( + new JksOptions() + .setPassword(config.getProperty("http.keystorePassword")) + .setPath(config.getProperty("http.keystoreFile")) + ); + } - HttpServer webServer = vertx.createHttpServer(httpServerOptions); - Router http = Router.router(vertx); // we just name this http to make the route declarations easier to read + HttpServer webServer = vertx.createHttpServer(httpServerOptions); + Router http = Router.router(vertx); // we just name this http to make the route declarations easier to read - http.route().handler(LoggerHandler.create(LoggerFormat.TINY)); - http.route().handler(TimeoutHandler.create(TimeUnit.SECONDS.toMillis(5))); - http.route().method(HttpMethod.PUT).method(HttpMethod.POST).method(HttpMethod.DELETE).handler(BodyHandler.create()); - http.route().handler(new ActorAttributeHandler()); - http.route().handler(new MetricsHandler()); - http.route().handler(new WebsiteUserSessionHandler()); - http.route().handler(new AuthorizationHandler()); - http.exceptionHandler(Throwable::printStackTrace); + http.route().handler(LoggerHandler.create(LoggerFormat.TINY)); + http.route().handler(TimeoutHandler.create(TimeUnit.SECONDS.toMillis(5))); + http.route().method(HttpMethod.PUT).method(HttpMethod.POST).method(HttpMethod.DELETE).handler(BodyHandler.create()); + http.route().handler(new ActorAttributeHandler()); + http.route().handler(new MetricsHandler()); + http.route().handler(new WebsiteUserSessionHandler()); + http.route().handler(new AuthorizationHandler()); + http.exceptionHandler(Throwable::printStackTrace); - // TODO: The commented out routes + // TODO: The commented out routes - http.get("/accessTokens/:accessToken").blockingHandler(new GETAccessTokensId()); - http.get("/accessTokens").blockingHandler(new GETAccessTokens()); - http.post("/accessTokens").blockingHandler(new POSTAccessTokens(), false); - //http.put("/accessTokens/:accessToken").blockingHandler(new PUTAccessTokensId(), false); - http.delete("/accessTokens/:accessToken").blockingHandler(new DELETEAccessTokensId(), false); + http.get("/accessTokens/:accessToken").blockingHandler(new GETAccessTokensId()); + http.get("/accessTokens").blockingHandler(new GETAccessTokens()); + http.post("/accessTokens").blockingHandler(new POSTAccessTokens(), false); + //http.put("/accessTokens/:accessToken").blockingHandler(new PUTAccessTokensId(), false); + http.delete("/accessTokens/:accessToken").blockingHandler(new DELETEAccessTokensId(), false); - http.get("/auditLog").handler(new GETAuditLog()); - http.post("/auditLog").handler(new POSTAuditLog()); - http.delete("/auditLog/:auditLogEntryId").blockingHandler(new DELETEAuditLogId()); + http.get("/auditLog").handler(new GETAuditLog()); + http.post("/auditLog").handler(new POSTAuditLog()); + http.delete("/auditLog/:auditLogEntryId").blockingHandler(new DELETEAuditLogId()); - http.get("/bannedAsns/:bannedAsn").handler(new GETBannedAsnsId()); - http.get("/bannedAsns").handler(new GETBannedAsns()); - http.post("/bannedAsns").blockingHandler(new POSTBannedAsns(), false); - //http.put("/bannedAsns/:bannedAsn").blockingHandler(new PUTBannedAsnsId(), false); - http.delete("/bannedAsns/:bannedAsn").blockingHandler(new DELETEBannedAsnsId(), false); + http.get("/bannedAsns/:bannedAsn").handler(new GETBannedAsnsId()); + http.get("/bannedAsns").handler(new GETBannedAsns()); + http.post("/bannedAsns").blockingHandler(new POSTBannedAsns(), false); + //http.put("/bannedAsns/:bannedAsn").blockingHandler(new PUTBannedAsnsId(), false); + http.delete("/bannedAsns/:bannedAsn").blockingHandler(new DELETEBannedAsnsId(), false); - http.get("/bannedCellCarriers/:bannedCellCarrier").handler(new GETBannedCellCarriersId()); - http.get("/bannedCellCarriers").handler(new GETBannedCellCarriers()); - http.post("/bannedCellCarriers").blockingHandler(new POSTBannedCellCarriers(), false); - //http.put("/bannedCellCarriers/:bannedCellCarrier").blockingHandler(new PUTBannedCellCarriersId(), false); - http.delete("/bannedCellCarriers/:bannedCellCarrier").blockingHandler(new DELETEBannedCellCarriersId(), false); + http.get("/bannedCellCarriers/:bannedCellCarrier").handler(new GETBannedCellCarriersId()); + http.get("/bannedCellCarriers").handler(new GETBannedCellCarriers()); + http.post("/bannedCellCarriers").blockingHandler(new POSTBannedCellCarriers(), false); + //http.put("/bannedCellCarriers/:bannedCellCarrier").blockingHandler(new PUTBannedCellCarriersId(), false); + http.delete("/bannedCellCarriers/:bannedCellCarrier").blockingHandler(new DELETEBannedCellCarriersId(), false); - http.get("/chatFilter/:chatFilterEntryId").handler(new GETChatFilterId()); - http.get("/chatFilter").handler(new GETChatFilter()); - http.post("/chatFilter").blockingHandler(new POSTChatFilter(), false); - //http.put("/chatFilter/:chatFilterEntryId").blockingHandler(new PUTChatFilterId(), false); - http.delete("/chatFilter/:chatFilterEntryId").blockingHandler(new DELETEChatFilterId(), false); + http.get("/chatFilter/:chatFilterEntryId").handler(new GETChatFilterId()); + http.get("/chatFilter").handler(new GETChatFilter()); + http.post("/chatFilter").blockingHandler(new POSTChatFilter(), false); + //http.put("/chatFilter/:chatFilterEntryId").blockingHandler(new PUTChatFilterId(), false); + http.delete("/chatFilter/:chatFilterEntryId").blockingHandler(new DELETEChatFilterId(), false); - http.post("/disposableLoginTokens").blockingHandler(new POSTDisposableLoginTokens(), false); - http.post("/disposableLoginTokens/:disposableLoginToken/use").blockingHandler(new POSTDisposableLoginTokensIdUse(), false); + http.post("/disposableLoginTokens").blockingHandler(new POSTDisposableLoginTokens(), false); + http.post("/disposableLoginTokens/:disposableLoginToken/use").blockingHandler(new POSTDisposableLoginTokensIdUse(), false); - http.get("/emailTokens/:emailToken/owner").blockingHandler(new GETEmailTokensIdOwner(), false); - http.post("/emailTokens/:emailToken/confirm").blockingHandler(new POSTEmailTokensIdConfirm(), false); + http.get("/emailTokens/:emailToken/owner").blockingHandler(new GETEmailTokensIdOwner(), false); + http.post("/emailTokens/:emailToken/confirm").blockingHandler(new POSTEmailTokensIdConfirm(), false); - http.get("/grants/:grantId").handler(new GETGrantsId()); - http.get("/grants").handler(new GETGrants()); - http.post("/grants").blockingHandler(new POSTGrants(), false); - //http.put("/grants/:grantId").blockingHandler(new PUTGrantsId(), false); - http.delete("/grants/:grantId").blockingHandler(new DELETEGrantsId(), false); + http.get("/grants/:grantId").handler(new GETGrantsId()); + http.get("/grants").handler(new GETGrants()); + http.post("/grants").blockingHandler(new POSTGrants(), false); + //http.put("/grants/:grantId").blockingHandler(new PUTGrantsId(), false); + http.delete("/grants/:grantId").blockingHandler(new DELETEGrantsId(), false); - http.get("/ipBans/:ipBanId").handler(new GETIpBansId()); - http.get("/ipBans").handler(new GETIpBans()); - http.post("/ipBans").blockingHandler(new POSTIpBans(), false); - //http.put("/ipBans/:ipBanId").blockingHandler(new PUTIpBansId(), false); - http.delete("/ipBans/:ipBanId").blockingHandler(new DELETEIpBansId(), false); + http.get("/ipBans/:ipBanId").handler(new GETIpBansId()); + http.get("/ipBans").handler(new GETIpBans()); + http.post("/ipBans").blockingHandler(new POSTIpBans(), false); + //http.put("/ipBans/:ipBanId").blockingHandler(new PUTIpBansId(), false); + http.delete("/ipBans/:ipBanId").blockingHandler(new DELETEIpBansId(), false); - http.get("/ipIntel/:userIp").handler(new GETIpInteld()); + http.get("/ipIntel/:userIp").handler(new GETIpInteld()); - http.get("/ipLog/:id").handler(new GETIpLogId()); + http.get("/ipLog/:id").handler(new GETIpLogId()); - http.get("/notificationTemplates/:notificationTemplateId").handler(new GETNotificationTemplatesId()); - http.get("/notificationTemplates").handler(new GETNotificationTemplates()); - http.post("/notificationTemplates").blockingHandler(new POSTNotificationTemplates(), false); - //http.put("/notificationTemplates/:notificationTemplateId").blockingHandler(new PUTNotificationTemplatesId(), false); - http.delete("/notificationTemplates/:notificationTemplateId").blockingHandler(new DELETENotificationTemplatesId(), false); + http.get("/notificationTemplates/:notificationTemplateId").handler(new GETNotificationTemplatesId()); + http.get("/notificationTemplates").handler(new GETNotificationTemplates()); + http.post("/notificationTemplates").blockingHandler(new POSTNotificationTemplates(), false); + //http.put("/notificationTemplates/:notificationTemplateId").blockingHandler(new PUTNotificationTemplatesId(), false); + http.delete("/notificationTemplates/:notificationTemplateId").blockingHandler(new DELETENotificationTemplatesId(), false); - http.get("/phoneIntel/:phone").handler(new GETPhoneInteld()); + http.get("/phoneIntel/:phone").handler(new GETPhoneInteld()); - http.get("/punishments/:punishmentId").handler(new GETPunishmentsId()); - http.get("/punishments").handler(new GETPunishments()); - http.post("/punishments").blockingHandler(new POSTPunishments(), false); - //http.put("/punishments/:punishmentId").blockingHandler(new PUTPunishmentsId(), false); - http.delete("/punishments/:punishmentId").blockingHandler(new DELETEPunishmentsId(), false); - http.delete("/users/:userId/activePunishment").blockingHandler(new DELETEUsersIdActivePunishment(), false); + http.get("/punishments/:punishmentId").handler(new GETPunishmentsId()); + http.get("/punishments").handler(new GETPunishments()); + http.post("/punishments").blockingHandler(new POSTPunishments(), false); + //http.put("/punishments/:punishmentId").blockingHandler(new PUTPunishmentsId(), false); + http.delete("/punishments/:punishmentId").blockingHandler(new DELETEPunishmentsId(), false); + http.delete("/users/:userId/activePunishment").blockingHandler(new DELETEUsersIdActivePunishment(), false); - http.get("/ranks/:rankId").handler(new GETRanksId()); - http.get("/ranks").handler(new GETRanks()); - http.post("/ranks").blockingHandler(new POSTRanks(), false); - //http.put("/ranks/:rankId").blockingHandler(new PUTRanksId(), false); - http.delete("/ranks/:rankId").blockingHandler(new DELETERanksId(), false); + http.get("/ranks/:rankId").handler(new GETRanksId()); + http.get("/ranks").handler(new GETRanks()); + http.post("/ranks").blockingHandler(new POSTRanks(), false); + //http.put("/ranks/:rankId").blockingHandler(new PUTRanksId(), false); + http.delete("/ranks/:rankId").blockingHandler(new DELETERanksId(), false); - http.get("/serverGroups/:serverGroupId").handler(new GETServerGroupsId()); - http.get("/serverGroups").handler(new GETServerGroups()); - http.post("/serverGroups").blockingHandler(new POSTServerGroups(), false); - //http.put("/serverGroups/:serverGroupId").blockingHandler(new PUTServerGroupsId(), false); - http.delete("/serverGroups/:serverGroupId").blockingHandler(new DELETEServerGroupsId(), false); + http.get("/serverGroups/:serverGroupId").handler(new GETServerGroupsId()); + http.get("/serverGroups").handler(new GETServerGroups()); + http.post("/serverGroups").blockingHandler(new POSTServerGroups(), false); + //http.put("/serverGroups/:serverGroupId").blockingHandler(new PUTServerGroupsId(), false); + http.delete("/serverGroups/:serverGroupId").blockingHandler(new DELETEServerGroupsId(), false); - http.get("/servers/:serverId").handler(new GETServersId()); - http.get("/servers").handler(new GETServers()); - http.post("/servers/heartbeat").handler(new POSTServersHeartbeat()); - http.post("/servers").blockingHandler(new POSTServers(), false); - //http.put("/servers/:serverId").blockingHandler(new PUTServersId(), false); - http.delete("/servers/:serverId").blockingHandler(new DELETEServersId(), false); + http.get("/servers/:serverId").handler(new GETServersId()); + http.get("/servers").handler(new GETServers()); + http.post("/servers/heartbeat").handler(new POSTServersHeartbeat()); + http.post("/servers").blockingHandler(new POSTServers(), false); + //http.put("/servers/:serverId").blockingHandler(new PUTServersId(), false); + http.delete("/servers/:serverId").blockingHandler(new DELETEServersId(), false); - http.get("/staff").blockingHandler(new GETStaff(), false); - http.get("/users/:userId").handler(new GETUsersId()); - http.get("/users/:userId/compoundedPermissions").handler(new GETUsersIdCompoundedPermissions()); - http.get("/users/:userId/details").blockingHandler(new GETUsersIdDetails(), false); - http.get("/users/:userId/requiresTotp").handler(new GETUsersIdRequiresTotp()); - http.get("/users/:userId/verifyPassword").blockingHandler(new GETUsersIdVerifyPassword(), false); - http.post("/users/:userId/changePassword").blockingHandler(new POSTUsersIdChangePassword(), false); - http.post("/users/:userId/confirmPhone").blockingHandler(new POSTUsersIdConfirmPhone(), false); - http.post("/users/:userId/login").handler(new POSTUsersIdLogin()); - http.post("/users/:userId/notify").blockingHandler(new POSTUsersIdNotify(), false); - http.post("/users/:userId/passwordReset").blockingHandler(new POSTUsersIdPasswordReset(), false); - http.post("/users/:userId/registerEmail").blockingHandler(new POSTUsersIdRegisterEmail(), false); - http.post("/users/:userId/registerPhone").blockingHandler(new POSTUsersIdRegisterPhone(), false); - http.post("/users/:userId/setupTotp").blockingHandler(new POSTUsersIdSetupTotp(), false); - http.post("/users/:userId/verifyTotp").handler(new POSTUsersIdVerifyTotp()); + http.get("/staff").blockingHandler(new GETStaff(), false); + http.get("/users/:userId").handler(new GETUsersId()); + http.get("/users/:userId/compoundedPermissions").handler(new GETUsersIdCompoundedPermissions()); + http.get("/users/:userId/details").blockingHandler(new GETUsersIdDetails(), false); + http.get("/users/:userId/requiresTotp").handler(new GETUsersIdRequiresTotp()); + http.get("/users/:userId/verifyPassword").blockingHandler(new GETUsersIdVerifyPassword(), false); + http.post("/users/:userId/changePassword").blockingHandler(new POSTUsersIdChangePassword(), false); + http.post("/users/:userId/confirmPhone").blockingHandler(new POSTUsersIdConfirmPhone(), false); + http.post("/users/:userId/login").handler(new POSTUsersIdLogin()); + http.post("/users/:userId/notify").blockingHandler(new POSTUsersIdNotify(), false); + http.post("/users/:userId/passwordReset").blockingHandler(new POSTUsersIdPasswordReset(), false); + http.post("/users/:userId/registerEmail").blockingHandler(new POSTUsersIdRegisterEmail(), false); + http.post("/users/:userId/registerPhone").blockingHandler(new POSTUsersIdRegisterPhone(), false); + http.post("/users/:userId/setupTotp").blockingHandler(new POSTUsersIdSetupTotp(), false); + http.post("/users/:userId/verifyTotp").handler(new POSTUsersIdVerifyTotp()); - http.get("/dumps/:dumpType").handler(new GETDumpsType()); - http.get("/metrics").handler(new GETMetrics()); - http.get("/whoami").handler(new GETWhoAmI()); - http.post("/logout").handler(new POSTLogout()); + http.get("/dumps/:dumpType").handler(new GETDumpsType()); + http.get("/metrics").handler(new GETMetrics()); + http.get("/whoami").handler(new GETWhoAmI()); + http.post("/logout").handler(new POSTLogout()); - int port = Integer.parseInt(config.getProperty("http.port")); - webServer.requestHandler(http::accept).listen(port); - } + int port = Integer.parseInt(config.getProperty("http.port")); + webServer.requestHandler(http::accept).listen(port); + } - public static void respondJson(RoutingContext ctx, int code, Object response) { - ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()); - ctx.response().setStatusCode(code); - ctx.response().end(gson.toJson(response)); - } + public static void respondJson(RoutingContext ctx, int code, Object response) { + ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()); + ctx.response().setStatusCode(code); + ctx.response().end(gson.toJson(response)); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/Main.java b/src/main/java/net/frozenorb/apiv3/Main.java index 90bd129..c841bfc 100644 --- a/src/main/java/net/frozenorb/apiv3/Main.java +++ b/src/main/java/net/frozenorb/apiv3/Main.java @@ -6,11 +6,11 @@ import io.vertx.ext.dropwizard.DropwizardMetricsOptions; final class Main { - public static void main(String[] args) { - System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.SLF4JLogDelegateFactory"); - Vertx.vertx(new VertxOptions().setMetricsOptions( - new DropwizardMetricsOptions().setEnabled(true).setRegistryName("apiv3-registry") - )).deployVerticle(new APIv3()); - } + public static void main(String[] args) { + System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.SLF4JLogDelegateFactory"); + Vertx.vertx(new VertxOptions().setMetricsOptions( + new DropwizardMetricsOptions().setEnabled(true).setRegistryName("apiv3-registry") + )).deployVerticle(new APIv3()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/actor/Actor.java b/src/main/java/net/frozenorb/apiv3/actor/Actor.java index d41495d..6fdaac7 100644 --- a/src/main/java/net/frozenorb/apiv3/actor/Actor.java +++ b/src/main/java/net/frozenorb/apiv3/actor/Actor.java @@ -2,8 +2,10 @@ package net.frozenorb.apiv3.actor; public interface Actor { - boolean isAuthorized(); - String getName(); - ActorType getType(); + boolean isAuthorized(); + + String getName(); + + ActorType getType(); } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/actor/ActorType.java b/src/main/java/net/frozenorb/apiv3/actor/ActorType.java index 13eb9a4..32a4aa5 100644 --- a/src/main/java/net/frozenorb/apiv3/actor/ActorType.java +++ b/src/main/java/net/frozenorb/apiv3/actor/ActorType.java @@ -2,6 +2,6 @@ package net.frozenorb.apiv3.actor; public enum ActorType { - WEBSITE, STORE, BUNGEE_CORD, SERVER, UNKNOWN + WEBSITE, STORE, BUNGEE_CORD, SERVER, UNKNOWN } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/actor/SimpleActor.java b/src/main/java/net/frozenorb/apiv3/actor/SimpleActor.java index 6fbc846..ae70268 100644 --- a/src/main/java/net/frozenorb/apiv3/actor/SimpleActor.java +++ b/src/main/java/net/frozenorb/apiv3/actor/SimpleActor.java @@ -6,8 +6,8 @@ import lombok.Getter; @AllArgsConstructor public final class SimpleActor implements Actor { - @Getter private String name; - @Getter private ActorType type; - @Getter private boolean authorized; + @Getter private String name; + @Getter private ActorType type; + @Getter private boolean authorized; } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/auditLog/AuditLog.java b/src/main/java/net/frozenorb/apiv3/auditLog/AuditLog.java index 9bc8e21..abe5185 100644 --- a/src/main/java/net/frozenorb/apiv3/auditLog/AuditLog.java +++ b/src/main/java/net/frozenorb/apiv3/auditLog/AuditLog.java @@ -12,19 +12,19 @@ import java.util.UUID; @UtilityClass public class AuditLog { - public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, SingleResultCallback callback) { - log(performedBy, performedByIp, ctx, actionType, ImmutableMap.of(), callback); - } + public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, SingleResultCallback callback) { + log(performedBy, performedByIp, ctx, actionType, ImmutableMap.of(), callback); + } - public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, Map actionData, SingleResultCallback callback) { - AuditLogEntry entry = new AuditLogEntry(performedBy, performedByIp, ctx.get("actor"), ctx.request().remoteAddress().host(), actionType, actionData); - entry.insert((ignored, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - callback.onResult(entry, null); - } - }); - } + public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, Map actionData, SingleResultCallback callback) { + AuditLogEntry entry = new AuditLogEntry(performedBy, performedByIp, ctx.get("actor"), ctx.request().remoteAddress().host(), actionType, actionData); + entry.insert((ignored, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + callback.onResult(entry, null); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/auditLog/AuditLogActionType.java b/src/main/java/net/frozenorb/apiv3/auditLog/AuditLogActionType.java index 1545584..3af7486 100644 --- a/src/main/java/net/frozenorb/apiv3/auditLog/AuditLogActionType.java +++ b/src/main/java/net/frozenorb/apiv3/auditLog/AuditLogActionType.java @@ -9,83 +9,82 @@ import java.time.Instant; public enum AuditLogActionType { - // TODO - DISPOSABLE_LOGIN_TOKEN_USE(false), - DISPOSABLE_LOGIN_TOKEN_CREATE(false), - ACCESS_TOKEN_CREATE(false), - ACCESS_TOKEN_UPDATE(false), - ACCESS_TOKEN_DELETE(false), - AUDIT_LOG_REVERT(false), - BANNED_ASN_CREATE(false), - BANNED_ASN_UPDATE(false), - BANNED_ASN_DELETE(false), - BANNED_CALL_CARRIER_CREATE(false), - BANNED_CALL_CARRIER_UPDATE(false), - BANNED_CALL_CARRIER_DELETE(false), - GRANT_CREATE(false), - GRANT_UPDATE(false), - GRANT_DELETE(false), - IP_BAN_CREATE(false), - IP_BAN_UPDATE(false), - IP_BAN_DELETE(false), - NOTIFICATION_TEMPLATE_CREATE(false), - NOTIFICATION_TEMPLATE_UPDATE(false), - NOTIFICATION_TEMPLATE_DELETE(false), - CHAT_FILTER_ENTRY_CREATE(false), - CHAT_FILTER_ENTRY_UPDATE(false), - CHAT_FILTER_ENTRY_DELETE(false), - PUNISHMENT_CREATE(true) { + // TODO + DISPOSABLE_LOGIN_TOKEN_USE(false), + DISPOSABLE_LOGIN_TOKEN_CREATE(false), + ACCESS_TOKEN_CREATE(false), + ACCESS_TOKEN_UPDATE(false), + ACCESS_TOKEN_DELETE(false), + AUDIT_LOG_REVERT(false), + BANNED_ASN_CREATE(false), + BANNED_ASN_UPDATE(false), + BANNED_ASN_DELETE(false), + BANNED_CALL_CARRIER_CREATE(false), + BANNED_CALL_CARRIER_UPDATE(false), + BANNED_CALL_CARRIER_DELETE(false), + GRANT_CREATE(false), + GRANT_UPDATE(false), + GRANT_DELETE(false), + IP_BAN_CREATE(false), + IP_BAN_UPDATE(false), + IP_BAN_DELETE(false), + NOTIFICATION_TEMPLATE_CREATE(false), + NOTIFICATION_TEMPLATE_UPDATE(false), + NOTIFICATION_TEMPLATE_DELETE(false), + CHAT_FILTER_ENTRY_CREATE(false), + CHAT_FILTER_ENTRY_UPDATE(false), + CHAT_FILTER_ENTRY_DELETE(false), + PUNISHMENT_CREATE(true) { + @Override + public void reverse(AuditLogEntry entry, SingleResultCallback callback) { + String punishmentId = (String) entry.getMetadata().get("punishmentId"); - @Override - public void reverse(AuditLogEntry entry, SingleResultCallback callback) { - String punishmentId = (String) entry.getMetadata().get("punishmentId"); + Punishment.findById(punishmentId, (punishment, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - Punishment.findById(punishmentId, (punishment, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + if (punishment == null || !punishment.isActive()) { + callback.onResult(null, null); + return; + } - if (punishment == null || !punishment.isActive()) { - callback.onResult(null, null); - return; - } + punishment.delete(null, "Removed via audit log reversal at " + Instant.now().toString() + ".", callback); + }); + } - punishment.delete(null, "Removed via audit log reversal at " + Instant.now().toString() + ".", callback); - }); - } + }, + PUNISHMENT_UPDATE(false), + PUNISHMENT_DELETE(false), + RANK_CREATE(false), + RANK_UPDATE(false), + RANK_DELETE(false), + SERVER_GROUP_CREATE(false), + SERVER_GROUP_UPDATE(false), + SERVER_GROUP_DELETE(false), + SERVER_CREATE(false), + SERVER_UPDATE(false), + SERVER_DELETE(false), + USER_LOGIN_SUCCESS(false), + USER_LOGIN_FAIL(false), + USER_CHANGE_PASSWORD(false), + USER_PASSWORD_RESET(false), + USER_REGISTER_EMAIL(false), + USER_REGISTER_PHONE(false), + USER_CONFIRM_EMAIL(false), + USER_CONFIRM_PHONE(false), + USER_SETUP_TOTP(false), + USER_VERIFY_TOTP(false); - }, - PUNISHMENT_UPDATE(false), - PUNISHMENT_DELETE(false), - RANK_CREATE(false), - RANK_UPDATE(false), - RANK_DELETE(false), - SERVER_GROUP_CREATE(false), - SERVER_GROUP_UPDATE(false), - SERVER_GROUP_DELETE(false), - SERVER_CREATE(false), - SERVER_UPDATE(false), - SERVER_DELETE(false), - USER_LOGIN_SUCCESS(false), - USER_LOGIN_FAIL(false), - USER_CHANGE_PASSWORD(false), - USER_PASSWORD_RESET(false), - USER_REGISTER_EMAIL(false), - USER_REGISTER_PHONE(false), - USER_CONFIRM_EMAIL(false), - USER_CONFIRM_PHONE(false), - USER_SETUP_TOTP(false), - USER_VERIFY_TOTP(false); + @Getter private boolean reversible; - @Getter private boolean reversible; + AuditLogActionType(boolean reversible) { + this.reversible = reversible; + } - AuditLogActionType(boolean reversible) { - this.reversible = reversible; - } - - public void reverse(AuditLogEntry entry, SingleResultCallback callback) { - callback.onResult(null, new UnsupportedOperationException()); - } + public void reverse(AuditLogEntry entry, SingleResultCallback callback) { + callback.onResult(null, new UnsupportedOperationException()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/dataImport/V2Importer.java b/src/main/java/net/frozenorb/apiv3/dataImport/V2Importer.java index f95c7bc..03d7de0 100644 --- a/src/main/java/net/frozenorb/apiv3/dataImport/V2Importer.java +++ b/src/main/java/net/frozenorb/apiv3/dataImport/V2Importer.java @@ -18,37 +18,37 @@ import java.util.UUID; public final class V2Importer { - private final MongoDatabase importFrom; + private final MongoDatabase importFrom; - public V2Importer(String mongoIp, String database) { - importFrom = MongoClients.create(mongoIp).getDatabase(database); - } + public V2Importer(String mongoIp, String database) { + importFrom = MongoClients.create(mongoIp).getDatabase(database); + } - public void startImport(SingleResultCallback callback) { - Map oidToUniqueId = new HashMap<>(); + public void startImport(SingleResultCallback callback) { + Map oidToUniqueId = new HashMap<>(); - importFrom.getCollection("user").find().forEach(new UserConverter(oidToUniqueId), (ignored, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + importFrom.getCollection("user").find().forEach(new UserConverter(oidToUniqueId), (ignored, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - Future punishmentsFuture = Future.future(); - Future grantsFuture = Future.future(); - Future ipLogFuture = Future.future(); + Future punishmentsFuture = Future.future(); + Future grantsFuture = Future.future(); + Future ipLogFuture = Future.future(); - importFrom.getCollection("punishment").find().forEach(new PunishmentConverter(oidToUniqueId), new MongoToVertxCallback<>(punishmentsFuture)); - importFrom.getCollection("grant").find().forEach(new GrantConverter(oidToUniqueId), new MongoToVertxCallback<>(grantsFuture)); - importFrom.getCollection("iplog").find().forEach(new IpLogConverter(oidToUniqueId), new MongoToVertxCallback<>(ipLogFuture)); + importFrom.getCollection("punishment").find().forEach(new PunishmentConverter(oidToUniqueId), new MongoToVertxCallback<>(punishmentsFuture)); + importFrom.getCollection("grant").find().forEach(new GrantConverter(oidToUniqueId), new MongoToVertxCallback<>(grantsFuture)); + importFrom.getCollection("iplog").find().forEach(new IpLogConverter(oidToUniqueId), new MongoToVertxCallback<>(ipLogFuture)); - CompositeFuture.all(punishmentsFuture, grantsFuture, ipLogFuture).setHandler((result) -> { - if (result.succeeded()) { - callback.onResult(null, null); - } else { - callback.onResult(null, result.cause()); - } - }); - }); - } + CompositeFuture.all(punishmentsFuture, grantsFuture, ipLogFuture).setHandler((result) -> { + if (result.succeeded()) { + callback.onResult(null, null); + } else { + callback.onResult(null, result.cause()); + } + }); + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/dataImport/converters/GrantConverter.java b/src/main/java/net/frozenorb/apiv3/dataImport/converters/GrantConverter.java index 65df424..1ddb6cd 100644 --- a/src/main/java/net/frozenorb/apiv3/dataImport/converters/GrantConverter.java +++ b/src/main/java/net/frozenorb/apiv3/dataImport/converters/GrantConverter.java @@ -16,51 +16,51 @@ import java.util.UUID; @Slf4j public final class GrantConverter implements Block { - private final Map oidToUniqueId; + private final Map oidToUniqueId; - public GrantConverter(Map oidToUniqueId) { - this.oidToUniqueId = oidToUniqueId; - } + public GrantConverter(Map oidToUniqueId) { + this.oidToUniqueId = oidToUniqueId; + } - @SuppressWarnings("unchecked") - @Override - public void apply(Document grant) { - UUID target = oidToUniqueId.get(((Map) grant.get("target")).get("$id")); + @SuppressWarnings("unchecked") + @Override + public void apply(Document grant) { + UUID target = oidToUniqueId.get(((Map) grant.get("target")).get("$id")); - if (target == null) { - return; - } + if (target == null) { + return; + } - String rank = grant.getString("role"); + String rank = grant.getString("role"); - if (rank.equalsIgnoreCase("unban") || rank.equalsIgnoreCase("pass") || rank.equalsIgnoreCase("pink") || rank.equalsIgnoreCase("jrdev")) { - return; - } else if (rank.equalsIgnoreCase("high_roller")) { - rank = "high-roller"; - } else if (rank.equalsIgnoreCase("dev")) { - rank = "developer"; - } else if (rank.equalsIgnoreCase("coowner")) { - rank = "owner"; - } + if (rank.equalsIgnoreCase("unban") || rank.equalsIgnoreCase("pass") || rank.equalsIgnoreCase("pink") || rank.equalsIgnoreCase("jrdev")) { + return; + } else if (rank.equalsIgnoreCase("high_roller")) { + rank = "high-roller"; + } else if (rank.equalsIgnoreCase("dev")) { + rank = "developer"; + } else if (rank.equalsIgnoreCase("coowner")) { + rank = "owner"; + } - Grant created = new Grant( - new ObjectId().toString(), - target, - grant.containsKey("comment") ? grant.getString("comment") : "", - grant.containsKey("scope") ? ImmutableSet.copyOf((Collection) grant.get("scope")) : ImmutableSet.of(), - rank, - grant.containsKey("expires") ? grant.getDate("expires").toInstant() : null, - grant.containsKey("addedBy") ? oidToUniqueId.get(((Map) grant.get("addedBy")).get("$id")) : null, - grant.containsKey("created") ? grant.getDate("created").toInstant() : Instant.now(), - null, - null, - null, - -1, - -1 - ); + Grant created = new Grant( + new ObjectId().toString(), + target, + grant.containsKey("comment") ? grant.getString("comment") : "", + grant.containsKey("scope") ? ImmutableSet.copyOf((Collection) grant.get("scope")) : ImmutableSet.of(), + rank, + grant.containsKey("expires") ? grant.getDate("expires").toInstant() : null, + grant.containsKey("addedBy") ? oidToUniqueId.get(((Map) grant.get("addedBy")).get("$id")) : null, + grant.containsKey("created") ? grant.getDate("created").toInstant() : Instant.now(), + null, + null, + null, + -1, + -1 + ); - SyncUtils.runBlocking(v -> created.insert(v)); - log.info("Created grant " + created.getId() + " (" + created.getRank() + ")"); - } + SyncUtils.runBlocking(v -> created.insert(v)); + log.info("Created grant " + created.getId() + " (" + created.getRank() + ")"); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/dataImport/converters/IpLogConverter.java b/src/main/java/net/frozenorb/apiv3/dataImport/converters/IpLogConverter.java index e2c97b3..092249e 100644 --- a/src/main/java/net/frozenorb/apiv3/dataImport/converters/IpLogConverter.java +++ b/src/main/java/net/frozenorb/apiv3/dataImport/converters/IpLogConverter.java @@ -15,44 +15,44 @@ import java.util.UUID; @Slf4j public final class IpLogConverter implements Block { - private final Map oidToUniqueId; + private final Map oidToUniqueId; - public IpLogConverter(Map oidToUniqueId) { - this.oidToUniqueId = oidToUniqueId; - } + public IpLogConverter(Map oidToUniqueId) { + this.oidToUniqueId = oidToUniqueId; + } - @SuppressWarnings("unchecked") - @Override - public void apply(Document ipLogEntry) { - UUID user = oidToUniqueId.get(((Map) ipLogEntry.get("user")).get("$id")); + @SuppressWarnings("unchecked") + @Override + public void apply(Document ipLogEntry) { + UUID user = oidToUniqueId.get(((Map) ipLogEntry.get("user")).get("$id")); - if (user == null || ipLogEntry.getString("ip") == null) { - return; - } + if (user == null || ipLogEntry.getString("ip") == null) { + return; + } - String ip = ipLogEntry.getString("ip").replace("/", ""); + String ip = ipLogEntry.getString("ip").replace("/", ""); - if (!IpUtils.isValidIp(ip)) { - return; - } + if (!IpUtils.isValidIp(ip)) { + return; + } - Date lastSeen = ipLogEntry.getDate("lastSeen"); + Date lastSeen = ipLogEntry.getDate("lastSeen"); - if (lastSeen == null) { - lastSeen = new Date(); - } + if (lastSeen == null) { + lastSeen = new Date(); + } - IpLogEntry created = new IpLogEntry( - new ObjectId().toString(), - user, - ip, - lastSeen.toInstant(), - lastSeen.toInstant(), - ((Number) ipLogEntry.get("uses")).intValue() - ); + IpLogEntry created = new IpLogEntry( + new ObjectId().toString(), + user, + ip, + lastSeen.toInstant(), + lastSeen.toInstant(), + ((Number) ipLogEntry.get("uses")).intValue() + ); - SyncUtils.runBlocking(v -> created.insert(v)); - log.info("Created ip log entry " + created.getId() + " (" + created.getUser() + " - " + created.getUserIp() + ")"); - } + SyncUtils.runBlocking(v -> created.insert(v)); + log.info("Created ip log entry " + created.getId() + " (" + created.getUser() + " - " + created.getUserIp() + ")"); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/dataImport/converters/PunishmentConverter.java b/src/main/java/net/frozenorb/apiv3/dataImport/converters/PunishmentConverter.java index ac83d69..e302e98 100644 --- a/src/main/java/net/frozenorb/apiv3/dataImport/converters/PunishmentConverter.java +++ b/src/main/java/net/frozenorb/apiv3/dataImport/converters/PunishmentConverter.java @@ -16,46 +16,46 @@ import java.util.UUID; @Slf4j public final class PunishmentConverter implements Block { - private final Map oidToUniqueId; + private final Map oidToUniqueId; - public PunishmentConverter(Map oidToUniqueId) { - this.oidToUniqueId = oidToUniqueId; - } + public PunishmentConverter(Map oidToUniqueId) { + this.oidToUniqueId = oidToUniqueId; + } - @SuppressWarnings("unchecked") - @Override - public void apply(Document punishment) { - UUID target = oidToUniqueId.get(((Map) punishment.get("user")).get("$id")); + @SuppressWarnings("unchecked") + @Override + public void apply(Document punishment) { + UUID target = oidToUniqueId.get(((Map) punishment.get("user")).get("$id")); - if (target == null) { - return; - } + if (target == null) { + return; + } - // Old punishments have this value set to false to indicate they're not active anymore. - if (punishment.containsKey("active") && !punishment.getBoolean("active")) { - return; - } + // Old punishments have this value set to false to indicate they're not active anymore. + if (punishment.containsKey("active") && !punishment.getBoolean("active")) { + return; + } - Punishment created = new Punishment( - new ObjectId().toString(), - target, - "Hidden (legacy punishment)", - punishment.getString("reason").toString(), - Punishment.PunishmentType.valueOf(punishment.getString("type").toUpperCase()), - punishment.containsKey("expires") ? punishment.getDate("expires").toInstant() : null, - punishment.containsKey("meta") ? (punishment.get("meta") instanceof List ? ImmutableMap.of() : (Document) punishment.get("meta")) : ImmutableMap.of(), - null, - punishment.containsKey("addedBy") ? oidToUniqueId.get(((Map) punishment.get("addedBy")).get("$id")) : null, - punishment.getDate("created").toInstant(), - punishment.containsKey("createdOn") ? String.valueOf(((Map) punishment.get("createdOn")).get("$id")) : "Old Website", - punishment.containsKey("createdOn") ? ActorType.SERVER : ActorType.WEBSITE, - punishment.containsKey("removedBy") ? (((Map) punishment.get("removedBy")).get("$ref").equals("user") ? oidToUniqueId.get(((Map) punishment.get("removedBy")).get("$id")) : null) : null, - punishment.containsKey("removedBy") ? (punishment.containsKey("removedAt") ? punishment.getDate("removedAt") : punishment.getDate("created")).toInstant() : null, - punishment.containsKey("removedBy") ? punishment.getString("removalReason").toString() : null - ); + Punishment created = new Punishment( + new ObjectId().toString(), + target, + "Hidden (legacy punishment)", + punishment.getString("reason").toString(), + Punishment.PunishmentType.valueOf(punishment.getString("type").toUpperCase()), + punishment.containsKey("expires") ? punishment.getDate("expires").toInstant() : null, + punishment.containsKey("meta") ? (punishment.get("meta") instanceof List ? ImmutableMap.of() : (Document) punishment.get("meta")) : ImmutableMap.of(), + null, + punishment.containsKey("addedBy") ? oidToUniqueId.get(((Map) punishment.get("addedBy")).get("$id")) : null, + punishment.getDate("created").toInstant(), + punishment.containsKey("createdOn") ? String.valueOf(((Map) punishment.get("createdOn")).get("$id")) : "Old Website", + punishment.containsKey("createdOn") ? ActorType.SERVER : ActorType.WEBSITE, + punishment.containsKey("removedBy") ? (((Map) punishment.get("removedBy")).get("$ref").equals("user") ? oidToUniqueId.get(((Map) punishment.get("removedBy")).get("$id")) : null) : null, + punishment.containsKey("removedBy") ? (punishment.containsKey("removedAt") ? punishment.getDate("removedAt") : punishment.getDate("created")).toInstant() : null, + punishment.containsKey("removedBy") ? punishment.getString("removalReason").toString() : null + ); - SyncUtils.runBlocking(v -> created.insert(v)); - log.info("Created punishment " + created.getId() + " (" + created.getType() + ")"); - } + SyncUtils.runBlocking(v -> created.insert(v)); + log.info("Created punishment " + created.getId() + " (" + created.getType() + ")"); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/dataImport/converters/UserConverter.java b/src/main/java/net/frozenorb/apiv3/dataImport/converters/UserConverter.java index 0e8bfc6..ed3ef9d 100644 --- a/src/main/java/net/frozenorb/apiv3/dataImport/converters/UserConverter.java +++ b/src/main/java/net/frozenorb/apiv3/dataImport/converters/UserConverter.java @@ -16,56 +16,56 @@ import java.util.UUID; @Slf4j public final class UserConverter implements Block { - private final Map oidToUniqueId; + private final Map oidToUniqueId; - public UserConverter(Map oidToUniqueId) { - this.oidToUniqueId = oidToUniqueId; - } + public UserConverter(Map oidToUniqueId) { + this.oidToUniqueId = oidToUniqueId; + } - @Override - public void apply(Document user) { - String uuidString = String.valueOf(user.get("uuid")); + @Override + public void apply(Document user) { + String uuidString = String.valueOf(user.get("uuid")); - if (uuidString == null || uuidString.length() != 32 || user.get("name") == null) { - return; - } + if (uuidString == null || uuidString.length() != 32 || user.get("name") == null) { + return; + } - UUID uuid = UuidUtils.parseUuid(uuidString); + UUID uuid = UuidUtils.parseUuid(uuidString); - if (!UuidUtils.isAcceptableUuid(uuid)) { - return; - } + if (!UuidUtils.isAcceptableUuid(uuid)) { + return; + } - oidToUniqueId.put(user.getObjectId("_id"), uuid); - - User created = new User( - uuid, - user.get("name").toString(), - ImmutableMap.of(user.get("name").toString(), user.getDate("joined").toInstant()), - null, - null, - null, - null, - user.getString("email"), - user.containsKey("email") ? Instant.EPOCH : null, - null, - null, - null, - user.getString("phone"), - user.containsKey("phone") ? Instant.EPOCH : null, - null, - null, - null, - null, - null, - "INVALID", - user.getDate("joined").toInstant(), - user.getDate("joined").toInstant(), - false - ); + oidToUniqueId.put(user.getObjectId("_id"), uuid); - SyncUtils.runBlocking(v -> created.insert(v)); - log.info("Created user " + created.getLastUsername() + " (" + created.getId() + ")"); - } + User created = new User( + uuid, + user.get("name").toString(), + ImmutableMap.of(user.get("name").toString(), user.getDate("joined").toInstant()), + null, + null, + null, + null, + user.getString("email"), + user.containsKey("email") ? Instant.EPOCH : null, + null, + null, + null, + user.getString("phone"), + user.containsKey("phone") ? Instant.EPOCH : null, + null, + null, + null, + null, + null, + "INVALID", + user.getDate("joined").toInstant(), + user.getDate("joined").toInstant(), + false + ); + + SyncUtils.runBlocking(v -> created.insert(v)); + log.info("Created user " + created.getLastUsername() + " (" + created.getId() + ")"); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/handler/ActorAttributeHandler.java b/src/main/java/net/frozenorb/apiv3/handler/ActorAttributeHandler.java index 753c875..d8a3abf 100644 --- a/src/main/java/net/frozenorb/apiv3/handler/ActorAttributeHandler.java +++ b/src/main/java/net/frozenorb/apiv3/handler/ActorAttributeHandler.java @@ -10,51 +10,51 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class ActorAttributeHandler implements Handler { - @Override - public void handle(RoutingContext ctx) { - String mhqAuthorizationHeader = ctx.request().getHeader("MHQ-Authorization"); + @Override + public void handle(RoutingContext ctx) { + String mhqAuthorizationHeader = ctx.request().getHeader("MHQ-Authorization"); - if (mhqAuthorizationHeader != null) { - processMHQAuthorization(mhqAuthorizationHeader, ctx); - } else { - processNoAuthorization(ctx); - } - } + if (mhqAuthorizationHeader != null) { + processMHQAuthorization(mhqAuthorizationHeader, ctx); + } else { + processNoAuthorization(ctx); + } + } - private void processMHQAuthorization(String accessTokenString, RoutingContext ctx) { - if (accessTokenString == null || accessTokenString.isEmpty()) { - ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeNoKey", ImmutableMap.of()); - return; - } + private void processMHQAuthorization(String accessTokenString, RoutingContext ctx) { + if (accessTokenString == null || accessTokenString.isEmpty()) { + ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeNoKey", ImmutableMap.of()); + return; + } - AccessToken.findById(accessTokenString, (accessToken, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - return; - } + AccessToken.findById(accessTokenString, (accessToken, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + return; + } - if (accessToken == null) { - ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeUnknownKey", ImmutableMap.of()); - return; - } + if (accessToken == null) { + ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeUnknownKey", ImmutableMap.of()); + return; + } - if (accessToken.getLockedIps() != null && !accessToken.getLockedIps().isEmpty()) { - boolean allowed = accessToken.getLockedIps().contains(ctx.request().remoteAddress().host()); + if (accessToken.getLockedIps() != null && !accessToken.getLockedIps().isEmpty()) { + boolean allowed = accessToken.getLockedIps().contains(ctx.request().remoteAddress().host()); - if (!allowed) { - ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeNoIpWhitelist", ImmutableMap.of()); - return; - } - } + if (!allowed) { + ErrorUtils.respondOther(ctx, 403, "Failed to authorize.", "failedToAuthorizeNoIpWhitelist", ImmutableMap.of()); + return; + } + } - ctx.put("actor", new SimpleActor(accessToken.getActorName(), accessToken.getActorType(), true)); - ctx.next(); - }); - } + ctx.put("actor", new SimpleActor(accessToken.getActorName(), accessToken.getActorType(), true)); + ctx.next(); + }); + } - private void processNoAuthorization(RoutingContext ctx) { - ctx.put("actor", new SimpleActor("UNKNOWN", ActorType.UNKNOWN, false)); - ctx.next(); - } + private void processNoAuthorization(RoutingContext ctx) { + ctx.put("actor", new SimpleActor("UNKNOWN", ActorType.UNKNOWN, false)); + ctx.next(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/handler/AuthorizationHandler.java b/src/main/java/net/frozenorb/apiv3/handler/AuthorizationHandler.java index 620109d..65f1880 100644 --- a/src/main/java/net/frozenorb/apiv3/handler/AuthorizationHandler.java +++ b/src/main/java/net/frozenorb/apiv3/handler/AuthorizationHandler.java @@ -8,15 +8,15 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class AuthorizationHandler implements Handler { - @Override - public void handle(RoutingContext ctx) { - Actor actor = ctx.get("actor"); + @Override + public void handle(RoutingContext ctx) { + Actor actor = ctx.get("actor"); - if (actor.isAuthorized()) { - ctx.next(); - } else { - ErrorUtils.respondOther(ctx, 403, "Failed to authorize as an approved actor.", "failedToAuthorizeNotApprovedActor", ImmutableMap.of()); - } - } + if (actor.isAuthorized()) { + ctx.next(); + } else { + ErrorUtils.respondOther(ctx, 403, "Failed to authorize as an approved actor.", "failedToAuthorizeNotApprovedActor", ImmutableMap.of()); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/handler/WebsiteUserSessionHandler.java b/src/main/java/net/frozenorb/apiv3/handler/WebsiteUserSessionHandler.java index 9579730..0961f20 100644 --- a/src/main/java/net/frozenorb/apiv3/handler/WebsiteUserSessionHandler.java +++ b/src/main/java/net/frozenorb/apiv3/handler/WebsiteUserSessionHandler.java @@ -49,7 +49,7 @@ public final class WebsiteUserSessionHandler implements Handler String path = ctx.request().path().toLowerCase(); /* - http.get("/emailTokens/:emailToken/owner").blockingHandler(new GETEmailTokensIdOwner(), false); + http.get("/emailTokens/:emailToken/owner").blockingHandler(new GETEmailTokensIdOwner(), false); http.get("/ranks/:rankId").handler(new GETRanksId()); http.get("/serverGroups/:serverGroupId").handler(new GETServerGroupsId()); http.get("/servers/:serverId").handler(new GETServersId()); diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCity.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCity.java index b2fb39c..10f82fe 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCity.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCity.java @@ -6,16 +6,16 @@ import net.frozenorb.apiv3.util.MaxMindUtils; public final class MaxMindCity { - @Getter private int confidence; - @Getter private int geonameId; - @Getter private String name; + @Getter private int confidence; + @Getter private int geonameId; + @Getter private String name; - private MaxMindCity() {} // For Jackson + private MaxMindCity() {} // For Jackson - public MaxMindCity(JsonObject legacy) { - this.confidence = legacy.getInteger("confidence", -1); - this.geonameId = legacy.getInteger("geoname_id", -1); - this.name = MaxMindUtils.getEnglishName(legacy); - } + public MaxMindCity(JsonObject legacy) { + this.confidence = legacy.getInteger("confidence", -1); + this.geonameId = legacy.getInteger("geoname_id", -1); + this.name = MaxMindUtils.getEnglishName(legacy); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindContinent.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindContinent.java index 8682a05..a606112 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindContinent.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindContinent.java @@ -6,16 +6,16 @@ import net.frozenorb.apiv3.util.MaxMindUtils; public final class MaxMindContinent { - @Getter private String code; - @Getter private int geonameId; - @Getter private String name; + @Getter private String code; + @Getter private int geonameId; + @Getter private String name; - private MaxMindContinent() {} // For Jackson + private MaxMindContinent() {} // For Jackson - public MaxMindContinent(JsonObject legacy) { - this.code = legacy.getString("code", ""); - this.geonameId = legacy.getInteger("geoname_id", -1); - this.name = MaxMindUtils.getEnglishName(legacy); - } + public MaxMindContinent(JsonObject legacy) { + this.code = legacy.getString("code", ""); + this.geonameId = legacy.getInteger("geoname_id", -1); + this.name = MaxMindUtils.getEnglishName(legacy); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCountry.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCountry.java index 52427b9..029c7a8 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCountry.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindCountry.java @@ -6,18 +6,18 @@ import net.frozenorb.apiv3.util.MaxMindUtils; public final class MaxMindCountry { - @Getter private String isoCode; - @Getter private int confidence; - @Getter private int geonameId; - @Getter private String name; + @Getter private String isoCode; + @Getter private int confidence; + @Getter private int geonameId; + @Getter private String name; - private MaxMindCountry() {} // For Jackson + private MaxMindCountry() {} // For Jackson - public MaxMindCountry(JsonObject legacy) { - this.isoCode = legacy.getString("iso_code", ""); - this.confidence = legacy.getInteger("confidence", -1); - this.geonameId = legacy.getInteger("geoname_id", -1); - this.name = MaxMindUtils.getEnglishName(legacy); - } + public MaxMindCountry(JsonObject legacy) { + this.isoCode = legacy.getString("iso_code", ""); + this.confidence = legacy.getInteger("confidence", -1); + this.geonameId = legacy.getInteger("geoname_id", -1); + this.name = MaxMindUtils.getEnglishName(legacy); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindLocation.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindLocation.java index 7d40c5f..f0652ad 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindLocation.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindLocation.java @@ -5,24 +5,24 @@ import lombok.Getter; public final class MaxMindLocation { - @Getter private double latitude; - @Getter private double longitude; - @Getter private int accuracyRadius; - @Getter private String timeZone; - @Getter private int populationDensity; - @Getter private int metroCode; - @Getter private int averageIncome; + @Getter private double latitude; + @Getter private double longitude; + @Getter private int accuracyRadius; + @Getter private String timeZone; + @Getter private int populationDensity; + @Getter private int metroCode; + @Getter private int averageIncome; - private MaxMindLocation() {} // For Jackson + private MaxMindLocation() {} // For Jackson - public MaxMindLocation(JsonObject legacy) { - this.latitude = legacy.getDouble("latitude", -1D); - this.longitude = legacy.getDouble("longitude", -1D); - this.accuracyRadius = legacy.getInteger("accuracy_radius", -1); - this.timeZone = legacy.getString("time_zone", ""); - this.populationDensity = legacy.getInteger("population_density", -1); - this.metroCode = legacy.getInteger("metro_code", -1); - this.averageIncome = legacy.getInteger("average_income", -1); - } + public MaxMindLocation(JsonObject legacy) { + this.latitude = legacy.getDouble("latitude", -1D); + this.longitude = legacy.getDouble("longitude", -1D); + this.accuracyRadius = legacy.getInteger("accuracy_radius", -1); + this.timeZone = legacy.getString("time_zone", ""); + this.populationDensity = legacy.getInteger("population_density", -1); + this.metroCode = legacy.getInteger("metro_code", -1); + this.averageIncome = legacy.getInteger("average_income", -1); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindPostal.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindPostal.java index da1cbfe..1577ff2 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindPostal.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindPostal.java @@ -5,14 +5,14 @@ import lombok.Getter; public final class MaxMindPostal { - @Getter private String code; - @Getter private int confidence; + @Getter private String code; + @Getter private int confidence; - private MaxMindPostal() {} // For Jackson + private MaxMindPostal() {} // For Jackson - public MaxMindPostal(JsonObject legacy) { - this.code = legacy.getString("code", ""); - this.confidence = legacy.getInteger("confidence", -1); - } + public MaxMindPostal(JsonObject legacy) { + this.code = legacy.getString("code", ""); + this.confidence = legacy.getInteger("confidence", -1); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindRegisteredCountry.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindRegisteredCountry.java index 31949a6..6e38cf0 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindRegisteredCountry.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindRegisteredCountry.java @@ -6,16 +6,16 @@ import net.frozenorb.apiv3.util.MaxMindUtils; public final class MaxMindRegisteredCountry { - @Getter private String isoCode; - @Getter private int geonameId; - @Getter private String name; + @Getter private String isoCode; + @Getter private int geonameId; + @Getter private String name; - private MaxMindRegisteredCountry() {} // For Jackson + private MaxMindRegisteredCountry() {} // For Jackson - public MaxMindRegisteredCountry(JsonObject legacy) { - this.isoCode = legacy.getString("iso_code", ""); - this.geonameId = legacy.getInteger("geoname_id", -1); - this.name = MaxMindUtils.getEnglishName(legacy); - } + public MaxMindRegisteredCountry(JsonObject legacy) { + this.isoCode = legacy.getString("iso_code", ""); + this.geonameId = legacy.getInteger("geoname_id", -1); + this.name = MaxMindUtils.getEnglishName(legacy); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindResult.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindResult.java index d42c65b..bb79a60 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindResult.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindResult.java @@ -10,33 +10,33 @@ import java.util.List; public final class MaxMindResult { - @Getter private MaxMindContinent continent; - @Getter private MaxMindCity city; - @Getter private MaxMindPostal postal; - @Getter private MaxMindTraits traits; - @Getter private MaxMindLocation location; - @Getter private List subdivisions; - @Getter private MaxMindCountry country; - @Getter private MaxMindRegisteredCountry registeredCountry; + @Getter private MaxMindContinent continent; + @Getter private MaxMindCity city; + @Getter private MaxMindPostal postal; + @Getter private MaxMindTraits traits; + @Getter private MaxMindLocation location; + @Getter private List subdivisions; + @Getter private MaxMindCountry country; + @Getter private MaxMindRegisteredCountry registeredCountry; - private MaxMindResult() {} // For Jackson + private MaxMindResult() {} // For Jackson - public MaxMindResult(JsonObject legacy) { - this.continent = new MaxMindContinent(legacy.getJsonObject("continent", new JsonObject())); - this.city = new MaxMindCity(legacy.getJsonObject("city", new JsonObject())); - this.postal = new MaxMindPostal(legacy.getJsonObject("postal", new JsonObject())); - this.traits = new MaxMindTraits(legacy.getJsonObject("traits")); - this.location = new MaxMindLocation(legacy.getJsonObject("location", new JsonObject())); - this.country = new MaxMindCountry(legacy.getJsonObject("country", new JsonObject())); - this.registeredCountry = new MaxMindRegisteredCountry(legacy.getJsonObject("registered_country", new JsonObject())); + public MaxMindResult(JsonObject legacy) { + this.continent = new MaxMindContinent(legacy.getJsonObject("continent", new JsonObject())); + this.city = new MaxMindCity(legacy.getJsonObject("city", new JsonObject())); + this.postal = new MaxMindPostal(legacy.getJsonObject("postal", new JsonObject())); + this.traits = new MaxMindTraits(legacy.getJsonObject("traits")); + this.location = new MaxMindLocation(legacy.getJsonObject("location", new JsonObject())); + this.country = new MaxMindCountry(legacy.getJsonObject("country", new JsonObject())); + this.registeredCountry = new MaxMindRegisteredCountry(legacy.getJsonObject("registered_country", new JsonObject())); - List subdivisions = new LinkedList<>(); + List subdivisions = new LinkedList<>(); - for (Object subdivision : legacy.getJsonArray("subdivisions", new JsonArray())) { - subdivisions.add(new MaxMindSubdivision((JsonObject) subdivision)); - } + for (Object subdivision : legacy.getJsonArray("subdivisions", new JsonArray())) { + subdivisions.add(new MaxMindSubdivision((JsonObject) subdivision)); + } - this.subdivisions = ImmutableList.copyOf(subdivisions); - } + this.subdivisions = ImmutableList.copyOf(subdivisions); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindTraits.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindTraits.java index a019c4f..3ade123 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindTraits.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindTraits.java @@ -5,22 +5,22 @@ import lombok.Getter; public final class MaxMindTraits { - @Getter private String isp; - @Getter private String domain; - @Getter private int asn; - @Getter private String asnOrganization; - @Getter private MaxMindUserType userType; - @Getter private String organization; + @Getter private String isp; + @Getter private String domain; + @Getter private int asn; + @Getter private String asnOrganization; + @Getter private MaxMindUserType userType; + @Getter private String organization; - private MaxMindTraits() {} // For Jackson + private MaxMindTraits() {} // For Jackson - public MaxMindTraits(JsonObject legacy) { - this.isp = legacy.getString("isp", ""); - this.domain = legacy.getString("domain", ""); - this.asn = legacy.getInteger("autonomous_system_number", -1); - this.asnOrganization = legacy.getString("autonomous_system_organization" , ""); - this.userType = legacy.containsKey("user_type") ? MaxMindUserType.valueOf(legacy.getString("user_type").toUpperCase()) : MaxMindUserType.UNKNOWN; - this.organization = legacy.getString("organization", ""); - } + public MaxMindTraits(JsonObject legacy) { + this.isp = legacy.getString("isp", ""); + this.domain = legacy.getString("domain", ""); + this.asn = legacy.getInteger("autonomous_system_number", -1); + this.asnOrganization = legacy.getString("autonomous_system_organization", ""); + this.userType = legacy.containsKey("user_type") ? MaxMindUserType.valueOf(legacy.getString("user_type").toUpperCase()) : MaxMindUserType.UNKNOWN; + this.organization = legacy.getString("organization", ""); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindUserType.java b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindUserType.java index d1706f9..d8d7645 100644 --- a/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindUserType.java +++ b/src/main/java/net/frozenorb/apiv3/maxmind/MaxMindUserType.java @@ -4,27 +4,27 @@ import lombok.Getter; public enum MaxMindUserType { - BUSINESS(true), - CAFE(true), - CELLULAR(true), - COLLEGE(true), - CONTENT_DELIVERY_NETWORK(false), - DIALUP(true), - GOVERNMENT(true), - HOSTING(false), - LIBRARY(true), - MILITARY(true), - RESIDENTIAL(true), - ROUTER(true), - SCHOOL(true), - SEARCH_ENGINE_SPIDER(false), - TRAVELER(true), - UNKNOWN(true); + BUSINESS(true), + CAFE(true), + CELLULAR(true), + COLLEGE(true), + CONTENT_DELIVERY_NETWORK(false), + DIALUP(true), + GOVERNMENT(true), + HOSTING(false), + LIBRARY(true), + MILITARY(true), + RESIDENTIAL(true), + ROUTER(true), + SCHOOL(true), + SEARCH_ENGINE_SPIDER(false), + TRAVELER(true), + UNKNOWN(true); - @Getter private final boolean allowed; + @Getter private final boolean allowed; - MaxMindUserType(boolean allowed) { - this.allowed = allowed; - } + MaxMindUserType(boolean allowed) { + this.allowed = allowed; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/AccessToken.java b/src/main/java/net/frozenorb/apiv3/model/AccessToken.java index 6fbf1be..52d5194 100644 --- a/src/main/java/net/frozenorb/apiv3/model/AccessToken.java +++ b/src/main/java/net/frozenorb/apiv3/model/AccessToken.java @@ -22,53 +22,53 @@ import java.util.UUID; @AllArgsConstructor public final class AccessToken { - private static final MongoCollection accessTokensCollection = APIv3.getDatabase().getCollection("accessTokens", AccessToken.class); + private static final MongoCollection accessTokensCollection = APIv3.getDatabase().getCollection("accessTokens", AccessToken.class); - @Getter @Id private String id; - @Getter private String actorName; - @Getter private ActorType actorType; - @Getter private List lockedIps; - @Getter private Instant createdAt; - @Getter private Instant lastUpdatedAt; + @Getter @Id private String id; + @Getter private String actorName; + @Getter private ActorType actorType; + @Getter private List lockedIps; + @Getter private Instant createdAt; + @Getter private Instant lastUpdatedAt; - public static void findAll(SingleResultCallback> callback) { - accessTokensCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + accessTokensCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - accessTokensCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + accessTokensCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByNameAndType(String actorName, ActorType actorType, SingleResultCallback callback) { - accessTokensCollection.find(new Document("actorName", actorName).append("actorType", actorType.name())).first(SyncUtils.vertxWrap(callback)); - } + public static void findByNameAndType(String actorName, ActorType actorType, SingleResultCallback callback) { + accessTokensCollection.find(new Document("actorName", actorName).append("actorType", actorType.name())).first(SyncUtils.vertxWrap(callback)); + } - private AccessToken() {} // For Jackson + private AccessToken() {} // For Jackson - public AccessToken(Server server) { - // Can't extract server host code to another line because the call to another constructor must be on the first line. - this(server.getId(), ActorType.SERVER, ImmutableList.of(server.getServerIp().split(":")[0])); - } + public AccessToken(Server server) { + // Can't extract server host code to another line because the call to another constructor must be on the first line. + this(server.getId(), ActorType.SERVER, ImmutableList.of(server.getServerIp().split(":")[0])); + } - public AccessToken(String actorName, ActorType actorType, List lockedIps) { - this.id = UUID.randomUUID().toString().replace("-", ""); - this.actorName = actorName; - this.actorType = actorType; - this.lockedIps = lockedIps; - this.createdAt = Instant.now(); - this.lastUpdatedAt = Instant.now(); - } + public AccessToken(String actorName, ActorType actorType, List lockedIps) { + this.id = UUID.randomUUID().toString().replace("-", ""); + this.actorName = actorName; + this.actorType = actorType; + this.lockedIps = lockedIps; + this.createdAt = Instant.now(); + this.lastUpdatedAt = Instant.now(); + } - public void insert(SingleResultCallback callback) { - accessTokensCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + accessTokensCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - accessTokensCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + accessTokensCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } - public void delete(SingleResultCallback callback) { - accessTokensCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + accessTokensCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/AuditLogEntry.java b/src/main/java/net/frozenorb/apiv3/model/AuditLogEntry.java index cc567ea..bec6217 100644 --- a/src/main/java/net/frozenorb/apiv3/model/AuditLogEntry.java +++ b/src/main/java/net/frozenorb/apiv3/model/AuditLogEntry.java @@ -23,50 +23,50 @@ import java.util.UUID; @Entity public final class AuditLogEntry { - private static final MongoCollection auditLogCollection = APIv3.getDatabase().getCollection("auditLog", AuditLogEntry.class); + private static final MongoCollection auditLogCollection = APIv3.getDatabase().getCollection("auditLog", AuditLogEntry.class); - @Getter @Id private String id; - @Getter private UUID user; - @Getter private String userIp; - @Getter private Instant performedAt; - @Getter private String actorName; - @Getter private ActorType actorType; - @Getter private String actorIp; - // We store 'reversible' in each object in case later on we go back and - // make something reversible (by storing more meta or such) - @Getter private boolean reversible; - @Getter private AuditLogActionType type; - @Getter private Map metadata; + @Getter @Id private String id; + @Getter private UUID user; + @Getter private String userIp; + @Getter private Instant performedAt; + @Getter private String actorName; + @Getter private ActorType actorType; + @Getter private String actorIp; + // We store 'reversible' in each object in case later on we go back and + // make something reversible (by storing more meta or such) + @Getter private boolean reversible; + @Getter private AuditLogActionType type; + @Getter private Map metadata; - public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { - auditLogCollection.find(query).sort(new Document("performedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { + auditLogCollection.find(query).sort(new Document("performedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - auditLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + auditLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void find(Document query, SingleResultCallback> callback) { - auditLogCollection.find(query).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void find(Document query, SingleResultCallback> callback) { + auditLogCollection.find(query).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - private AuditLogEntry() {} // For Jackson + private AuditLogEntry() {} // For Jackson - public AuditLogEntry(UUID user, String userIp, Actor actor, String actorIp, AuditLogActionType type, Map metadata) { - this.id = new ObjectId().toString(); - this.user = user; - this.userIp = userIp; - this.performedAt = Instant.now(); - this.actorName = actor.getName(); - this.actorType = actor.getType(); - this.actorIp = actorIp; - this.reversible = type.isReversible(); - this.type = type; - this.metadata = ImmutableMap.copyOf(metadata); - } + public AuditLogEntry(UUID user, String userIp, Actor actor, String actorIp, AuditLogActionType type, Map metadata) { + this.id = new ObjectId().toString(); + this.user = user; + this.userIp = userIp; + this.performedAt = Instant.now(); + this.actorName = actor.getName(); + this.actorType = actor.getType(); + this.actorIp = actorIp; + this.reversible = type.isReversible(); + this.type = type; + this.metadata = ImmutableMap.copyOf(metadata); + } - public void insert(SingleResultCallback callback) { - auditLogCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + auditLogCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/BannedAsn.java b/src/main/java/net/frozenorb/apiv3/model/BannedAsn.java index 4afdd30..29f92e8 100644 --- a/src/main/java/net/frozenorb/apiv3/model/BannedAsn.java +++ b/src/main/java/net/frozenorb/apiv3/model/BannedAsn.java @@ -22,74 +22,74 @@ import java.util.concurrent.TimeUnit; @Entity public final class BannedAsn { - private static final MongoCollection bannedAsnsCollection = APIv3.getDatabase().getCollection("bannedAsns", BannedAsn.class); + private static final MongoCollection bannedAsnsCollection = APIv3.getDatabase().getCollection("bannedAsns", BannedAsn.class); - private static Map bannedAsnIdCache = null; - private static List bannedAsnCache = null; + private static Map bannedAsnIdCache = null; + private static List bannedAsnCache = null; - @Getter @Id private int id; - @Getter @Setter String note; - @Getter private Instant bannedAt; - @Getter private Instant lastUpdatedAt; + @Getter @Id private int id; + @Getter @Setter String note; + @Getter private Instant bannedAt; + @Getter private Instant lastUpdatedAt; - public static List findAll() { - return ImmutableList.copyOf(bannedAsnCache); - } + public static List findAll() { + return ImmutableList.copyOf(bannedAsnCache); + } - public static BannedAsn findById(int id) { - return bannedAsnIdCache.get(id); - } + public static BannedAsn findById(int id) { + return bannedAsnIdCache.get(id); + } - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); + } - public static void updateCache() { - bannedAsnsCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((bannedAsns, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + bannedAsnsCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((bannedAsns, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map working = new HashMap<>(); + Map working = new HashMap<>(); - for (BannedAsn bannedAsn : bannedAsns) { - working.put(bannedAsn.getId(), bannedAsn); - } + for (BannedAsn bannedAsn : bannedAsns) { + working.put(bannedAsn.getId(), bannedAsn); + } - bannedAsnIdCache = working; - bannedAsnCache = bannedAsns; - })); - } + bannedAsnIdCache = working; + bannedAsnCache = bannedAsns; + })); + } - private BannedAsn() {} // For Jackson + private BannedAsn() {} // For Jackson - public BannedAsn(int id, String note) { - this.id = id; - this.note = note; - this.bannedAt = Instant.now(); - this.lastUpdatedAt = Instant.now(); - } + public BannedAsn(int id, String note) { + this.id = id; + this.note = note; + this.bannedAt = Instant.now(); + this.lastUpdatedAt = Instant.now(); + } - public void updateNote(String newNote) { - this.note = newNote; - this.lastUpdatedAt = Instant.now(); - } + public void updateNote(String newNote) { + this.note = newNote; + this.lastUpdatedAt = Instant.now(); + } - public void insert(SingleResultCallback callback) { - bannedAsnCache.add(this); - bannedAsnIdCache.put(id, this); - bannedAsnsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + bannedAsnCache.add(this); + bannedAsnIdCache.put(id, this); + bannedAsnsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - bannedAsnsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + bannedAsnsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } - public void delete(SingleResultCallback callback) { - bannedAsnCache.remove(this); - bannedAsnIdCache.remove(id); - bannedAsnsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + bannedAsnCache.remove(this); + bannedAsnIdCache.remove(id); + bannedAsnsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/BannedCellCarrier.java b/src/main/java/net/frozenorb/apiv3/model/BannedCellCarrier.java index 1dde0c8..3c1f760 100644 --- a/src/main/java/net/frozenorb/apiv3/model/BannedCellCarrier.java +++ b/src/main/java/net/frozenorb/apiv3/model/BannedCellCarrier.java @@ -23,74 +23,74 @@ import java.util.concurrent.TimeUnit; @Entity public final class BannedCellCarrier { - private static final MongoCollection bannedCellCarriersCollection = APIv3.getDatabase().getCollection("bannedCellCarriers", BannedCellCarrier.class); + private static final MongoCollection bannedCellCarriersCollection = APIv3.getDatabase().getCollection("bannedCellCarriers", BannedCellCarrier.class); - private static Map bannedCellCarrierIdCache = null; - private static List bannedCellCarrierCache = null; + private static Map bannedCellCarrierIdCache = null; + private static List bannedCellCarrierCache = null; - @Getter @Id private int id; - @Getter @Setter String note; - @Getter private Instant bannedAt; - @Getter private Instant lastUpdatedAt; + @Getter @Id private int id; + @Getter @Setter String note; + @Getter private Instant bannedAt; + @Getter private Instant lastUpdatedAt; - public static List findAll() { - return ImmutableList.copyOf(bannedCellCarrierCache); - } + public static List findAll() { + return ImmutableList.copyOf(bannedCellCarrierCache); + } - public static BannedCellCarrier findById(int id) { - return bannedCellCarrierIdCache.get(id); - } + public static BannedCellCarrier findById(int id) { + return bannedCellCarrierIdCache.get(id); + } - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); + } - public static void updateCache() { - bannedCellCarriersCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((bannedCellCarriers, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + bannedCellCarriersCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((bannedCellCarriers, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map working = new HashMap<>(); + Map working = new HashMap<>(); - for (BannedCellCarrier bannedCellCarrier : bannedCellCarriers) { - working.put(bannedCellCarrier.getId(), bannedCellCarrier); - } + for (BannedCellCarrier bannedCellCarrier : bannedCellCarriers) { + working.put(bannedCellCarrier.getId(), bannedCellCarrier); + } - bannedCellCarrierIdCache = working; - bannedCellCarrierCache = bannedCellCarriers; - })); - } + bannedCellCarrierIdCache = working; + bannedCellCarrierCache = bannedCellCarriers; + })); + } - private BannedCellCarrier() {} // For Jackson + private BannedCellCarrier() {} // For Jackson - public BannedCellCarrier(int id, String note) { - this.id = id; - this.note = note; - this.bannedAt = Instant.now(); - this.lastUpdatedAt = Instant.now(); - } + public BannedCellCarrier(int id, String note) { + this.id = id; + this.note = note; + this.bannedAt = Instant.now(); + this.lastUpdatedAt = Instant.now(); + } - public void updateNote(String newNote) { - this.note = newNote; - this.lastUpdatedAt = Instant.now(); - } + public void updateNote(String newNote) { + this.note = newNote; + this.lastUpdatedAt = Instant.now(); + } - public void insert(SingleResultCallback callback) { - bannedCellCarrierCache.add(this); - bannedCellCarrierIdCache.put(id, this); - bannedCellCarriersCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + bannedCellCarrierCache.add(this); + bannedCellCarrierIdCache.put(id, this); + bannedCellCarriersCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - bannedCellCarriersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + bannedCellCarriersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } - public void delete(SingleResultCallback callback) { - bannedCellCarrierCache.remove(this); - bannedCellCarrierIdCache.remove(id); - bannedCellCarriersCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + bannedCellCarrierCache.remove(this); + bannedCellCarrierIdCache.remove(id); + bannedCellCarriersCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/Grant.java b/src/main/java/net/frozenorb/apiv3/model/Grant.java index 0051328..6ff6786 100644 --- a/src/main/java/net/frozenorb/apiv3/model/Grant.java +++ b/src/main/java/net/frozenorb/apiv3/model/Grant.java @@ -21,119 +21,119 @@ import java.util.stream.Collectors; @AllArgsConstructor public final class Grant { - private static final MongoCollection grantsCollection = APIv3.getDatabase().getCollection("grants", Grant.class); + private static final MongoCollection grantsCollection = APIv3.getDatabase().getCollection("grants", Grant.class); - @Getter @Id private String id; - @Getter private UUID user; - @Getter private String reason; - @Getter private Set scopes; - @Getter private String rank; - @Getter private Instant expiresAt; + @Getter @Id private String id; + @Getter private UUID user; + @Getter private String reason; + @Getter private Set scopes; + @Getter private String rank; + @Getter private Instant expiresAt; - @Getter private UUID addedBy; - @Getter private Instant addedAt; + @Getter private UUID addedBy; + @Getter private Instant addedAt; - @Getter private UUID removedBy; - @Getter private Instant removedAt; - @Getter private String removalReason; + @Getter private UUID removedBy; + @Getter private Instant removedAt; + @Getter private String removalReason; - @Getter private int storeItemId; - @Getter private int storeOrderId; + @Getter private int storeItemId; + @Getter private int storeOrderId; - public static void findAll(SingleResultCallback> callback) { - grantsCollection.find().sort(new Document("addedAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + grantsCollection.find().sort(new Document("addedAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByRank(Collection ranks, SingleResultCallback> callback) { - Collection convertedRanks = ranks.stream().map(Rank::getId).collect(Collectors.toList()); - grantsCollection.find(new Document("rank", new Document("$in", convertedRanks))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByRank(Collection ranks, SingleResultCallback> callback) { + Collection convertedRanks = ranks.stream().map(Rank::getId).collect(Collectors.toList()); + grantsCollection.find(new Document("rank", new Document("$in", convertedRanks))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { - grantsCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { + grantsCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - grantsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + grantsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByUser(User user, SingleResultCallback> callback) { - findByUser(user.getId(), callback); - } + public static void findByUser(User user, SingleResultCallback> callback) { + findByUser(user.getId(), callback); + } - public static void findByUser(UUID user, SingleResultCallback> callback) { - grantsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByUser(UUID user, SingleResultCallback> callback) { + grantsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByUserGrouped(Iterable users, SingleResultCallback>> callback) { - grantsCollection.find(new Document("user", new Document("$in", users))).into(new LinkedList<>(), SyncUtils.vertxWrap((grants, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - Map> result = new HashMap<>(); + public static void findByUserGrouped(Iterable users, SingleResultCallback>> callback) { + grantsCollection.find(new Document("user", new Document("$in", users))).into(new LinkedList<>(), SyncUtils.vertxWrap((grants, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + Map> result = new HashMap<>(); - for (UUID user : users) { - result.put(user, new LinkedList<>()); - } + for (UUID user : users) { + result.put(user, new LinkedList<>()); + } - for (Grant grant : grants) { - result.get(grant.getUser()).add(grant); - } + for (Grant grant : grants) { + result.get(grant.getUser()).add(grant); + } - callback.onResult(result, null); - } - })); - } + callback.onResult(result, null); + } + })); + } - private Grant() {} // For Jackson + private Grant() {} // For Jackson - public Grant(User user, String reason, Set scopes, Rank rank, Instant expiresAt, User addedBy) { - this(user, reason, scopes, rank, expiresAt, addedBy, -1, -1); - } + public Grant(User user, String reason, Set scopes, Rank rank, Instant expiresAt, User addedBy) { + this(user, reason, scopes, rank, expiresAt, addedBy, -1, -1); + } - public Grant(User user, String reason, Set scopes, Rank rank, Instant expiresAt, User addedBy, int storeItemId, int storeOrderId) { - this.id = new ObjectId().toString(); - this.user = user.getId(); - this.reason = reason; - this.scopes = new HashSet<>(Collections2.transform(scopes, ServerGroup::getId)); - this.rank = rank.getId(); - this.expiresAt = expiresAt; - this.addedBy = addedBy == null ? null : addedBy.getId(); - this.addedAt = Instant.now(); - this.storeItemId = storeItemId; - this.storeOrderId = storeOrderId; - } + public Grant(User user, String reason, Set scopes, Rank rank, Instant expiresAt, User addedBy, int storeItemId, int storeOrderId) { + this.id = new ObjectId().toString(); + this.user = user.getId(); + this.reason = reason; + this.scopes = new HashSet<>(Collections2.transform(scopes, ServerGroup::getId)); + this.rank = rank.getId(); + this.expiresAt = expiresAt; + this.addedBy = addedBy == null ? null : addedBy.getId(); + this.addedAt = Instant.now(); + this.storeItemId = storeItemId; + this.storeOrderId = storeOrderId; + } - public boolean isActive() { - return !(isExpired() || isRemoved()); - } + public boolean isActive() { + return !(isExpired() || isRemoved()); + } - public boolean isExpired() { - return expiresAt != null && expiresAt.isBefore(Instant.now()); - } + public boolean isExpired() { + return expiresAt != null && expiresAt.isBefore(Instant.now()); + } - public boolean isRemoved() { - return removedAt != null; - } + public boolean isRemoved() { + return removedAt != null; + } - public boolean appliesOn(ServerGroup serverGroup) { - return isGlobal() || scopes.contains(serverGroup.getId()); - } + public boolean appliesOn(ServerGroup serverGroup) { + return isGlobal() || scopes.contains(serverGroup.getId()); + } - public boolean isGlobal() { - return scopes.isEmpty(); - } + public boolean isGlobal() { + return scopes.isEmpty(); + } - public void insert(SingleResultCallback callback) { - grantsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + grantsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void delete(User removedBy, String reason, SingleResultCallback callback) { - this.removedBy = removedBy == null ? null : removedBy.getId(); - this.removedAt = Instant.now(); - this.removalReason = reason; + public void delete(User removedBy, String reason, SingleResultCallback callback) { + this.removedBy = removedBy == null ? null : removedBy.getId(); + this.removedAt = Instant.now(); + this.removalReason = reason; - grantsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + grantsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/IpBan.java b/src/main/java/net/frozenorb/apiv3/model/IpBan.java index 3104282..0ecd8e7 100644 --- a/src/main/java/net/frozenorb/apiv3/model/IpBan.java +++ b/src/main/java/net/frozenorb/apiv3/model/IpBan.java @@ -22,143 +22,143 @@ import java.util.*; @AllArgsConstructor public final class IpBan { - private static final MongoCollection ipBansCollection = APIv3.getDatabase().getCollection("ipBans", IpBan.class); + private static final MongoCollection ipBansCollection = APIv3.getDatabase().getCollection("ipBans", IpBan.class); - @Getter @Id private String id; - @Getter private String userIp; - @Getter private String reason; - @Getter private Instant expiresAt; + @Getter @Id private String id; + @Getter private String userIp; + @Getter private String reason; + @Getter private Instant expiresAt; - @Getter private UUID addedBy; - @Getter private Instant addedAt; - @Getter private String actorName; - @Getter private ActorType actorType; + @Getter private UUID addedBy; + @Getter private Instant addedAt; + @Getter private String actorName; + @Getter private ActorType actorType; - @Getter private UUID removedBy; - @Getter private Instant removedAt; - @Getter private String removalReason; + @Getter private UUID removedBy; + @Getter private Instant removedAt; + @Getter private String removalReason; - public static void find(SingleResultCallback> callback) { - ipBansCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void find(SingleResultCallback> callback) { + ipBansCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { - ipBansCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { + ipBansCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - ipBansCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + ipBansCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByIp(String userIp, SingleResultCallback> callback) { - ipBansCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByIp(String userIp, SingleResultCallback> callback) { + ipBansCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByIpGrouped(Iterable userIps, SingleResultCallback>> callback) { - ipBansCollection.find(new Document("userIp", new Document("$in", userIps))).into(new LinkedList<>(), SyncUtils.vertxWrap((ipBans, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - Map> result = new HashMap<>(); + public static void findByIpGrouped(Iterable userIps, SingleResultCallback>> callback) { + ipBansCollection.find(new Document("userIp", new Document("$in", userIps))).into(new LinkedList<>(), SyncUtils.vertxWrap((ipBans, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + Map> result = new HashMap<>(); - for (String userIp : userIps) { - result.put(userIp, new LinkedList<>()); - } + for (String userIp : userIps) { + result.put(userIp, new LinkedList<>()); + } - for (IpBan ipBan : ipBans) { - result.get(ipBan.getUserIp()).add(ipBan); - } + for (IpBan ipBan : ipBans) { + result.get(ipBan.getUserIp()).add(ipBan); + } - callback.onResult(result, null); - } - })); - } + callback.onResult(result, null); + } + })); + } - private IpBan() {} // For Jackson + private IpBan() {} // For Jackson - public IpBan(String userIp, Punishment linked) { - this.id = new ObjectId().toString(); - this.userIp = userIp; - this.reason = linked.getPublicReason(); - this.expiresAt = linked.getExpiresAt(); - this.addedBy = linked.getAddedBy(); - this.addedAt = Instant.now(); - this.actorName = linked.getActorName(); - this.actorType = linked.getActorType(); - } + public IpBan(String userIp, Punishment linked) { + this.id = new ObjectId().toString(); + this.userIp = userIp; + this.reason = linked.getPublicReason(); + this.expiresAt = linked.getExpiresAt(); + this.addedBy = linked.getAddedBy(); + this.addedAt = Instant.now(); + this.actorName = linked.getActorName(); + this.actorType = linked.getActorType(); + } - public IpBan(String userIp, String reason, Instant expiresAt, User addedBy, Actor actor) { - this.id = new ObjectId().toString(); - this.userIp = userIp; - this.reason = reason; - this.expiresAt = expiresAt; - this.addedBy = addedBy == null ? null : addedBy.getId(); - this.addedAt = Instant.now(); - this.actorName = actor.getName(); - this.actorType = actor.getType(); - } + public IpBan(String userIp, String reason, Instant expiresAt, User addedBy, Actor actor) { + this.id = new ObjectId().toString(); + this.userIp = userIp; + this.reason = reason; + this.expiresAt = expiresAt; + this.addedBy = addedBy == null ? null : addedBy.getId(); + this.addedAt = Instant.now(); + this.actorName = actor.getName(); + this.actorType = actor.getType(); + } - public boolean isActive() { - return !(isExpired() || isRemoved()); - } + public boolean isActive() { + return !(isExpired() || isRemoved()); + } - public boolean isExpired() { - return expiresAt != null && expiresAt.isBefore(Instant.now()); - } + public boolean isExpired() { + return expiresAt != null && expiresAt.isBefore(Instant.now()); + } - public boolean isRemoved() { - return removedAt != null; - } + public boolean isRemoved() { + return removedAt != null; + } - public void getAccessDenialReason(SingleResultCallback callback) { - Punishment.findByLinkedIpBanId(id, (punishment, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + public void getAccessDenialReason(SingleResultCallback callback) { + Punishment.findByLinkedIpBanId(id, (punishment, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - if (punishment != null) { - User.findById(punishment.getUser(), (user, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - } else { - callback.onResult(buildDenialReason(user), null); - } - }); - } else { - callback.onResult(buildDenialReason(null), null); - } - }); - } + if (punishment != null) { + User.findById(punishment.getUser(), (user, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + } else { + callback.onResult(buildDenialReason(user), null); + } + }); + } else { + callback.onResult(buildDenialReason(null), null); + } + }); + } - private String buildDenialReason(User linkedIpBanUser) { - String accessDenialReason; + private String buildDenialReason(User linkedIpBanUser) { + String accessDenialReason; - if (linkedIpBanUser != null) { - accessDenialReason = "Your IP address has been suspended from the MineHQ Network for a punishment related to " + linkedIpBanUser.getLastUsername() + ". \n\n"; - } else { - accessDenialReason = "Your IP address has been suspended from the MineHQ Network. \n\n"; - } + if (linkedIpBanUser != null) { + accessDenialReason = "Your IP address has been suspended from the MineHQ Network for a punishment related to " + linkedIpBanUser.getLastUsername() + ". \n\n"; + } else { + accessDenialReason = "Your IP address has been suspended from the MineHQ Network. \n\n"; + } - if (getExpiresAt() != null) { - accessDenialReason += "Expires in " + TimeUtils.formatIntoDetailedString(TimeUtils.getSecondsBetween(getExpiresAt(), Instant.now())); - } else { - accessDenialReason += "Appeal at MineHQ.com/appeal"; - } + if (getExpiresAt() != null) { + accessDenialReason += "Expires in " + TimeUtils.formatIntoDetailedString(TimeUtils.getSecondsBetween(getExpiresAt(), Instant.now())); + } else { + accessDenialReason += "Appeal at MineHQ.com/appeal"; + } - return accessDenialReason; - } + return accessDenialReason; + } - public void insert(SingleResultCallback callback) { - ipBansCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + ipBansCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void delete(User removedBy, String reason, SingleResultCallback callback) { - this.removedBy = removedBy == null ? null : removedBy.getId(); - this.removedAt = Instant.now(); - this.removalReason = reason; + public void delete(User removedBy, String reason, SingleResultCallback callback) { + this.removedBy = removedBy == null ? null : removedBy.getId(); + this.removedAt = Instant.now(); + this.removalReason = reason; - ipBansCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + ipBansCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/IpIntel.java b/src/main/java/net/frozenorb/apiv3/model/IpIntel.java index 88650ab..c315ca0 100644 --- a/src/main/java/net/frozenorb/apiv3/model/IpIntel.java +++ b/src/main/java/net/frozenorb/apiv3/model/IpIntel.java @@ -22,113 +22,113 @@ import java.util.concurrent.ConcurrentHashMap; @AllArgsConstructor public final class IpIntel { - private static final MongoCollection ipIntelCollection = APIv3.getDatabase().getCollection("ipIntel", IpIntel.class); + private static final MongoCollection ipIntelCollection = APIv3.getDatabase().getCollection("ipIntel", IpIntel.class); - @Getter @Id private String id; - @Getter private Instant lastUpdatedAt; - @Getter private MaxMindResult result; + @Getter @Id private String id; + @Getter private Instant lastUpdatedAt; + @Getter private MaxMindResult result; - public static void findAll(SingleResultCallback> callback) { - ipIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + ipIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - ipIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + ipIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findOrCreateById(String id, SingleResultCallback callback) { - findById(id, (existingIpIntel, error) -> { - if (error != null) { - callback.onResult(null, error); - } else if (existingIpIntel != null) { - callback.onResult(existingIpIntel, null); - } else { - MaxMindUtils.getInsights(id, (maxMindResult, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - } else if (maxMindResult != null) { - IpIntel newIpIntel = new IpIntel(id, maxMindResult); + public static void findOrCreateById(String id, SingleResultCallback callback) { + findById(id, (existingIpIntel, error) -> { + if (error != null) { + callback.onResult(null, error); + } else if (existingIpIntel != null) { + callback.onResult(existingIpIntel, null); + } else { + MaxMindUtils.getInsights(id, (maxMindResult, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + } else if (maxMindResult != null) { + IpIntel newIpIntel = new IpIntel(id, maxMindResult); - ipIntelCollection.insertOne(newIpIntel, (ignored, error3) -> { - if (error3 != null) { - callback.onResult(null, error3); - } else { - callback.onResult(newIpIntel, null); - } - }); - } else { - // MaxMind failed to return result - callback.onResult(null, null); - } - }); - } - }); - } + ipIntelCollection.insertOne(newIpIntel, (ignored, error3) -> { + if (error3 != null) { + callback.onResult(null, error3); + } else { + callback.onResult(newIpIntel, null); + } + }); + } else { + // MaxMind failed to return result + callback.onResult(null, null); + } + }); + } + }); + } - public static void findOrCreateByIdGrouped(Collection search, SingleResultCallback> callback) { - ipIntelCollection.find(new Document("_id", new Document("$in", search))).into(new LinkedList<>(), SyncUtils.vertxWrap((existingIntel, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + public static void findOrCreateByIdGrouped(Collection search, SingleResultCallback> callback) { + ipIntelCollection.find(new Document("_id", new Document("$in", search))).into(new LinkedList<>(), SyncUtils.vertxWrap((existingIntel, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - Map result = new ConcurrentHashMap<>(); + Map result = new ConcurrentHashMap<>(); - for (IpIntel ipIntel : existingIntel) { - result.put(ipIntel.getId(), ipIntel); - } + for (IpIntel ipIntel : existingIntel) { + result.put(ipIntel.getId(), ipIntel); + } - List createNewIntelFutures = new ArrayList<>(); + List createNewIntelFutures = new ArrayList<>(); - search.forEach((ip) -> { - if (result.containsKey(ip)) { - return; - } + search.forEach((ip) -> { + if (result.containsKey(ip)) { + return; + } - Future createNewIntelFuture = Future.future(); - createNewIntelFutures.add(createNewIntelFuture); + Future createNewIntelFuture = Future.future(); + createNewIntelFutures.add(createNewIntelFuture); - MaxMindUtils.getInsights(ip, (maxMindResult, error2) -> { - if (error2 != null) { - createNewIntelFuture.fail(error2); - return; - } + MaxMindUtils.getInsights(ip, (maxMindResult, error2) -> { + if (error2 != null) { + createNewIntelFuture.fail(error2); + return; + } - // MaxMind failed to return result - if (maxMindResult == null) { - createNewIntelFuture.complete(); - return; - } + // MaxMind failed to return result + if (maxMindResult == null) { + createNewIntelFuture.complete(); + return; + } - IpIntel newIpIntel = new IpIntel(ip, maxMindResult); + IpIntel newIpIntel = new IpIntel(ip, maxMindResult); - ipIntelCollection.insertOne(newIpIntel, SyncUtils.vertxWrap((ignored, error3) -> { - if (error3 != null) { - createNewIntelFuture.fail(error3); - } else { - result.put(ip, newIpIntel); - createNewIntelFuture.complete(); - } - })); - }); - }); + ipIntelCollection.insertOne(newIpIntel, SyncUtils.vertxWrap((ignored, error3) -> { + if (error3 != null) { + createNewIntelFuture.fail(error3); + } else { + result.put(ip, newIpIntel); + createNewIntelFuture.complete(); + } + })); + }); + }); - CompositeFuture.all(createNewIntelFutures).setHandler((creationStatus) -> { - if (creationStatus.failed()) { - callback.onResult(null, creationStatus.cause()); - } else { - callback.onResult(result, null); - } - }); - })); - } + CompositeFuture.all(createNewIntelFutures).setHandler((creationStatus) -> { + if (creationStatus.failed()) { + callback.onResult(null, creationStatus.cause()); + } else { + callback.onResult(result, null); + } + }); + })); + } - private IpIntel() {} // For Jackson + private IpIntel() {} // For Jackson - private IpIntel(String ip, MaxMindResult result) { - this.id = ip; - this.lastUpdatedAt = Instant.now(); - this.result = result; - } + private IpIntel(String ip, MaxMindResult result) { + this.id = ip; + this.lastUpdatedAt = Instant.now(); + this.result = result; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/IpLogEntry.java b/src/main/java/net/frozenorb/apiv3/model/IpLogEntry.java index c80af2b..a746fe8 100644 --- a/src/main/java/net/frozenorb/apiv3/model/IpLogEntry.java +++ b/src/main/java/net/frozenorb/apiv3/model/IpLogEntry.java @@ -21,65 +21,65 @@ import java.util.UUID; @AllArgsConstructor public final class IpLogEntry { - private static final MongoCollection ipLogCollection = APIv3.getDatabase().getCollection("ipLog", IpLogEntry.class); + private static final MongoCollection ipLogCollection = APIv3.getDatabase().getCollection("ipLog", IpLogEntry.class); - @Getter @Id private String id; - @Getter private UUID user; - @Getter private String userIp; - @Getter private Instant firstSeenAt; - @Getter private Instant lastSeenAt; - @Getter private int uses; + @Getter @Id private String id; + @Getter private UUID user; + @Getter private String userIp; + @Getter private Instant firstSeenAt; + @Getter private Instant lastSeenAt; + @Getter private int uses; - public static void findAll(SingleResultCallback> callback) { - ipLogCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + ipLogCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - ipLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + ipLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByUser(User user, SingleResultCallback> callback) { - findByUser(user.getId(), callback); - } + public static void findByUser(User user, SingleResultCallback> callback) { + findByUser(user.getId(), callback); + } - public static void findByUser(UUID user, SingleResultCallback> callback) { - ipLogCollection.find(new Document("user", user)).sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByUser(UUID user, SingleResultCallback> callback) { + ipLogCollection.find(new Document("user", user)).sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByIp(String userIp, SingleResultCallback> callback) { - ipLogCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByIp(String userIp, SingleResultCallback> callback) { + ipLogCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByUserAndIp(User user, String userIp, SingleResultCallback callback) { - findByUserAndIp(user.getId(), userIp, callback); - } + public static void findByUserAndIp(User user, String userIp, SingleResultCallback callback) { + findByUserAndIp(user.getId(), userIp, callback); + } - public static void findByUserAndIp(UUID user, String userIp, SingleResultCallback callback) { - ipLogCollection.find(new Document("user", user).append("userIp", userIp)).first(SyncUtils.vertxWrap(callback)); - } + public static void findByUserAndIp(UUID user, String userIp, SingleResultCallback callback) { + ipLogCollection.find(new Document("user", user).append("userIp", userIp)).first(SyncUtils.vertxWrap(callback)); + } - private IpLogEntry() {} // For Jackson + private IpLogEntry() {} // For Jackson - public IpLogEntry(User user, String userIp) { - this.id = new ObjectId().toString(); - this.user = user.getId(); - this.userIp = userIp; - this.firstSeenAt = Instant.now(); - this.lastSeenAt = Instant.now(); - this.uses = 0; - } + public IpLogEntry(User user, String userIp) { + this.id = new ObjectId().toString(); + this.user = user.getId(); + this.userIp = userIp; + this.firstSeenAt = Instant.now(); + this.lastSeenAt = Instant.now(); + this.uses = 0; + } - public void used() { - this.lastSeenAt = Instant.now(); - this.uses++; - } + public void used() { + this.lastSeenAt = Instant.now(); + this.uses++; + } - public void insert(SingleResultCallback callback) { - ipLogCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + ipLogCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - ipLogCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + ipLogCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/NotificationTemplate.java b/src/main/java/net/frozenorb/apiv3/model/NotificationTemplate.java index 27eb982..2886378 100644 --- a/src/main/java/net/frozenorb/apiv3/model/NotificationTemplate.java +++ b/src/main/java/net/frozenorb/apiv3/model/NotificationTemplate.java @@ -18,53 +18,53 @@ import java.util.Map; @Entity public final class NotificationTemplate { - private static final MongoCollection notificationTemplatesCollection = APIv3.getDatabase().getCollection("notificationTemplates", NotificationTemplate.class); + private static final MongoCollection notificationTemplatesCollection = APIv3.getDatabase().getCollection("notificationTemplates", NotificationTemplate.class); - @Getter @Id private String id; - @Getter @Setter private String subject; - @Getter @Setter private String body; + @Getter @Id private String id; + @Getter @Setter private String subject; + @Getter @Setter private String body; - public static void findAll(SingleResultCallback> callback) { - notificationTemplatesCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + notificationTemplatesCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - notificationTemplatesCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + notificationTemplatesCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - private NotificationTemplate() {} // For Jackson + private NotificationTemplate() {} // For Jackson - public NotificationTemplate(String id, String subject, String body) { - this.id = id; - this.subject = subject; - this.body = body; - } + public NotificationTemplate(String id, String subject, String body) { + this.id = id; + this.subject = subject; + this.body = body; + } - public String fillSubject(Map replacements) { - return fill(subject, replacements); - } + public String fillSubject(Map replacements) { + return fill(subject, replacements); + } - public String fillBody(Map replacements) { - return fill(body, replacements); - } + public String fillBody(Map replacements) { + return fill(body, replacements); + } - private String fill(String working, Map replacements) { - for (Map.Entry replacement : replacements.entrySet()) { - String key = replacement.getKey(); - String value = String.valueOf(replacement.getValue()); + private String fill(String working, Map replacements) { + for (Map.Entry replacement : replacements.entrySet()) { + String key = replacement.getKey(); + String value = String.valueOf(replacement.getValue()); - working = working.replace("%" + key + "%", value); - } + working = working.replace("%" + key + "%", value); + } - return working; - } + return working; + } - public void insert(SingleResultCallback callback) { - notificationTemplatesCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + notificationTemplatesCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void delete(SingleResultCallback callback) { - notificationTemplatesCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + notificationTemplatesCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/PhoneIntel.java b/src/main/java/net/frozenorb/apiv3/model/PhoneIntel.java index f974b5d..980fe94 100644 --- a/src/main/java/net/frozenorb/apiv3/model/PhoneIntel.java +++ b/src/main/java/net/frozenorb/apiv3/model/PhoneIntel.java @@ -20,52 +20,52 @@ import java.util.List; @AllArgsConstructor public final class PhoneIntel { - private static final MongoCollection phoneIntelCollection = APIv3.getDatabase().getCollection("phoneIntel", PhoneIntel.class); + private static final MongoCollection phoneIntelCollection = APIv3.getDatabase().getCollection("phoneIntel", PhoneIntel.class); - @Getter @Id private String id; - @Getter private Instant lastUpdatedAt; - @Getter private ZangResult result; + @Getter @Id private String id; + @Getter private Instant lastUpdatedAt; + @Getter private ZangResult result; - public static void findAll(SingleResultCallback> callback) { - phoneIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findAll(SingleResultCallback> callback) { + phoneIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - phoneIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + phoneIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findOrCreateById(String id, SingleResultCallback callback) { - findById(id, (existingPhoneIntel, error) -> { - if (error != null) { - callback.onResult(null, error); - } else if (existingPhoneIntel != null) { - callback.onResult(existingPhoneIntel, null); - } else { - ZangUtils.getCarrierInfo(id, (zangResult, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - } else { - PhoneIntel newPhoneIntel = new PhoneIntel(id, zangResult); + public static void findOrCreateById(String id, SingleResultCallback callback) { + findById(id, (existingPhoneIntel, error) -> { + if (error != null) { + callback.onResult(null, error); + } else if (existingPhoneIntel != null) { + callback.onResult(existingPhoneIntel, null); + } else { + ZangUtils.getCarrierInfo(id, (zangResult, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + } else { + PhoneIntel newPhoneIntel = new PhoneIntel(id, zangResult); - phoneIntelCollection.insertOne(newPhoneIntel, SyncUtils.vertxWrap((ignored, error3) -> { - if (error3 != null) { - callback.onResult(null, error3); - } else { - callback.onResult(newPhoneIntel, null); - } - })); - } - }); - } - }); - } + phoneIntelCollection.insertOne(newPhoneIntel, SyncUtils.vertxWrap((ignored, error3) -> { + if (error3 != null) { + callback.onResult(null, error3); + } else { + callback.onResult(newPhoneIntel, null); + } + })); + } + }); + } + }); + } - private PhoneIntel() {} // For Jackson + private PhoneIntel() {} // For Jackson - private PhoneIntel(String phoneNumber, ZangResult result) { - this.id = phoneNumber; - this.lastUpdatedAt = Instant.now(); - this.result = result; - } + private PhoneIntel(String phoneNumber, ZangResult result) { + this.id = phoneNumber; + this.lastUpdatedAt = Instant.now(); + this.result = result; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/Punishment.java b/src/main/java/net/frozenorb/apiv3/model/Punishment.java index 9ec0089..7737dd0 100644 --- a/src/main/java/net/frozenorb/apiv3/model/Punishment.java +++ b/src/main/java/net/frozenorb/apiv3/model/Punishment.java @@ -23,169 +23,169 @@ import java.util.stream.Collectors; @AllArgsConstructor public final class Punishment { - private static final MongoCollection punishmentsCollection = APIv3.getDatabase().getCollection("punishments", Punishment.class); + private static final MongoCollection punishmentsCollection = APIv3.getDatabase().getCollection("punishments", Punishment.class); - @Getter @Id private String id; - @Getter private UUID user; - @Getter private String publicReason; - @Getter private String privateReason; - @Getter private PunishmentType type; - @Getter private Instant expiresAt; - @Getter private Map metadata; - @Getter private String linkedIpBanId; + @Getter @Id private String id; + @Getter private UUID user; + @Getter private String publicReason; + @Getter private String privateReason; + @Getter private PunishmentType type; + @Getter private Instant expiresAt; + @Getter private Map metadata; + @Getter private String linkedIpBanId; - @Getter private UUID addedBy; - @Getter private Instant addedAt; - @Getter private String actorName; - @Getter private ActorType actorType; + @Getter private UUID addedBy; + @Getter private Instant addedAt; + @Getter private String actorName; + @Getter private ActorType actorType; - @Getter private UUID removedBy; - @Getter private Instant removedAt; - @Getter private String removalReason; + @Getter private UUID removedBy; + @Getter private Instant removedAt; + @Getter private String removalReason; - public static void findByType(Collection types, SingleResultCallback> callback) { - Collection convertedTypes = types.stream().map(PunishmentType::name).collect(Collectors.toList()); - punishmentsCollection.find(new Document("type", new Document("$in", convertedTypes))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByType(Collection types, SingleResultCallback> callback) { + Collection convertedTypes = types.stream().map(PunishmentType::name).collect(Collectors.toList()); + punishmentsCollection.find(new Document("type", new Document("$in", convertedTypes))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { - punishmentsCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback> callback) { + punishmentsCollection.find(query).sort(new Document("addedAt", -1)).skip(skip).limit(pageSize).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findById(String id, SingleResultCallback callback) { - punishmentsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findById(String id, SingleResultCallback callback) { + punishmentsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByLinkedIpBanId(String id, SingleResultCallback callback) { - punishmentsCollection.find(new Document("linkedIpBanId", id)).first(SyncUtils.vertxWrap(callback)); - } + public static void findByLinkedIpBanId(String id, SingleResultCallback callback) { + punishmentsCollection.find(new Document("linkedIpBanId", id)).first(SyncUtils.vertxWrap(callback)); + } - public static void findByUser(User user, SingleResultCallback> callback) { - findByUser(user.getId(), callback); - } + public static void findByUser(User user, SingleResultCallback> callback) { + findByUser(user.getId(), callback); + } - public static void findByUser(UUID user, SingleResultCallback> callback) { - punishmentsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByUser(UUID user, SingleResultCallback> callback) { + punishmentsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - public static void findByUserGrouped(Iterable users, SingleResultCallback>> callback) { - punishmentsCollection.find(new Document("user", new Document("$in", users))).into(new LinkedList<>(), SyncUtils.vertxWrap((punishments, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - Map> result = new HashMap<>(); + public static void findByUserGrouped(Iterable users, SingleResultCallback>> callback) { + punishmentsCollection.find(new Document("user", new Document("$in", users))).into(new LinkedList<>(), SyncUtils.vertxWrap((punishments, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + Map> result = new HashMap<>(); - for (UUID user : users) { - result.put(user, new LinkedList<>()); - } + for (UUID user : users) { + result.put(user, new LinkedList<>()); + } - for (Punishment punishment : punishments) { - result.get(punishment.getUser()).add(punishment); - } + for (Punishment punishment : punishments) { + result.get(punishment.getUser()).add(punishment); + } - callback.onResult(result, null); - } - })); - } + callback.onResult(result, null); + } + })); + } - public static void findByUserAndType(User user, Collection types, SingleResultCallback> callback) { - findByUserAndType(user.getId(), types, callback); - } + public static void findByUserAndType(User user, Collection types, SingleResultCallback> callback) { + findByUserAndType(user.getId(), types, callback); + } - public static void findByUserAndType(UUID user, Collection types, SingleResultCallback> callback) { - Collection convertedTypes = types.stream().map(PunishmentType::name).collect(Collectors.toList()); - punishmentsCollection.find(new Document("user", user).append("type", new Document("$in", convertedTypes))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); - } + public static void findByUserAndType(UUID user, Collection types, SingleResultCallback> callback) { + Collection convertedTypes = types.stream().map(PunishmentType::name).collect(Collectors.toList()); + punishmentsCollection.find(new Document("user", user).append("type", new Document("$in", convertedTypes))).into(new LinkedList<>(), SyncUtils.vertxWrap(callback)); + } - private Punishment() {} // For Jackson + private Punishment() {} // For Jackson - public Punishment(User user, String publicReason, String privateReason, PunishmentType type, Instant expiresAt, User addedBy, Actor actor, Map metadata) { - this.id = new ObjectId().toString(); - this.user = user.getId(); - this.publicReason = publicReason; - this.privateReason = privateReason; - this.type = type; - this.expiresAt = expiresAt; - this.addedBy = addedBy == null ? null : addedBy.getId(); - this.addedAt = Instant.now(); - this.actorName = actor.getName(); - this.actorType = actor.getType(); - this.metadata = metadata; - } + public Punishment(User user, String publicReason, String privateReason, PunishmentType type, Instant expiresAt, User addedBy, Actor actor, Map metadata) { + this.id = new ObjectId().toString(); + this.user = user.getId(); + this.publicReason = publicReason; + this.privateReason = privateReason; + this.type = type; + this.expiresAt = expiresAt; + this.addedBy = addedBy == null ? null : addedBy.getId(); + this.addedAt = Instant.now(); + this.actorName = actor.getName(); + this.actorType = actor.getType(); + this.metadata = metadata; + } - public boolean isActive() { - return !(isExpired() || isRemoved()); - } + public boolean isActive() { + return !(isExpired() || isRemoved()); + } - public boolean isExpired() { - return expiresAt != null && expiresAt.isBefore(Instant.now()); - } + public boolean isExpired() { + return expiresAt != null && expiresAt.isBefore(Instant.now()); + } - public boolean isRemoved() { - return removedAt != null; - } + public boolean isRemoved() { + return removedAt != null; + } - public String getAccessDenialReason() { - switch (type) { - case BLACKLIST: - return "Your account has been blacklisted from the MineHQ Network. \n\nThis type of punishment cannot be appealed."; - case BAN: - String accessDenialReason = "Your account has been suspended from the MineHQ Network. \n\n"; + public String getAccessDenialReason() { + switch (type) { + case BLACKLIST: + return "Your account has been blacklisted from the MineHQ Network. \n\nThis type of punishment cannot be appealed."; + case BAN: + String accessDenialReason = "Your account has been suspended from the MineHQ Network. \n\n"; - if (getExpiresAt() != null) { - accessDenialReason += "Expires in " + TimeUtils.formatIntoDetailedString(TimeUtils.getSecondsBetween(getExpiresAt(), Instant.now())); - } else { - accessDenialReason += "Appeal at MineHQ.com/appeal"; - } + if (getExpiresAt() != null) { + accessDenialReason += "Expires in " + TimeUtils.formatIntoDetailedString(TimeUtils.getSecondsBetween(getExpiresAt(), Instant.now())); + } else { + accessDenialReason += "Appeal at MineHQ.com/appeal"; + } - return accessDenialReason; - default: - return null; - } - } + return accessDenialReason; + default: + return null; + } + } - public void linkIpBan(IpBan ipBan) { - this.linkedIpBanId = ipBan.getId(); - } + public void linkIpBan(IpBan ipBan) { + this.linkedIpBanId = ipBan.getId(); + } - public void insert(SingleResultCallback callback) { - punishmentsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + punishmentsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void delete(User removedBy, String reason, SingleResultCallback callback) { - this.removedBy = removedBy == null ? null : removedBy.getId(); - this.removedAt = Instant.now(); - this.removalReason = reason; + public void delete(User removedBy, String reason, SingleResultCallback callback) { + this.removedBy = removedBy == null ? null : removedBy.getId(); + this.removedAt = Instant.now(); + this.removalReason = reason; - if (linkedIpBanId == null) { - punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - return; - } + if (linkedIpBanId == null) { + punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + return; + } - IpBan.findById(linkedIpBanId, (ipBan, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + IpBan.findById(linkedIpBanId, (ipBan, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - if (ipBan != null && ipBan.isActive()) { - ipBan.delete(removedBy, "Linked punishment removed: " + reason, (ignored, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - } else { - punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } - }); - } else { - punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } - }); - } + if (ipBan != null && ipBan.isActive()) { + ipBan.delete(removedBy, "Linked punishment removed: " + reason, (ignored, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + } else { + punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } + }); + } else { + punishmentsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } + }); + } - public enum PunishmentType { + public enum PunishmentType { - BLACKLIST, BAN, MUTE, WARN + BLACKLIST, BAN, MUTE, WARN - } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/Rank.java b/src/main/java/net/frozenorb/apiv3/model/Rank.java index 8703fd2..9574918 100644 --- a/src/main/java/net/frozenorb/apiv3/model/Rank.java +++ b/src/main/java/net/frozenorb/apiv3/model/Rank.java @@ -20,73 +20,73 @@ import java.util.concurrent.TimeUnit; @Entity public final class Rank { - private static final MongoCollection ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class); + private static final MongoCollection ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class); - private static Map rankIdCache = null; - private static List rankCache = null; + private static Map rankIdCache = null; + private static List rankCache = null; - @Getter @Id private String id; - @Getter private String inheritsFromId; - @Getter private int weight; - @Getter private String displayName; - @Getter private String gameColor; - @Getter private String websiteColor; - @Getter private boolean staffRank; - @Getter private boolean higherStaffRank; + @Getter @Id private String id; + @Getter private String inheritsFromId; + @Getter private int weight; + @Getter private String displayName; + @Getter private String gameColor; + @Getter private String websiteColor; + @Getter private boolean staffRank; + @Getter private boolean higherStaffRank; - public static List findAll() { - return ImmutableList.copyOf(rankCache); - } + public static List findAll() { + return ImmutableList.copyOf(rankCache); + } - public static Rank findById(String id) { - return rankIdCache.get(id); - } + public static Rank findById(String id) { + return rankIdCache.get(id); + } - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); + } - public static void updateCache() { - ranksCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((ranks, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + ranksCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((ranks, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map working = new HashMap<>(); + Map working = new HashMap<>(); - for (Rank rank : ranks) { - working.put(rank.getId(), rank); - } + for (Rank rank : ranks) { + working.put(rank.getId(), rank); + } - rankIdCache = working; - rankCache = ranks; - })); - } + rankIdCache = working; + rankCache = ranks; + })); + } - private Rank() {} // For Jackson + private Rank() {} // For Jackson - public Rank(String id, String inheritsFromId, int weight, String displayName, String gameColor, String websiteColor, boolean staffRank, boolean higherStaffRank) { - this.id = id; - this.inheritsFromId = inheritsFromId; - this.weight = weight; - this.displayName = displayName; - this.gameColor = gameColor; - this.websiteColor = websiteColor; - this.staffRank = staffRank; - this.higherStaffRank = higherStaffRank; - } + public Rank(String id, String inheritsFromId, int weight, String displayName, String gameColor, String websiteColor, boolean staffRank, boolean higherStaffRank) { + this.id = id; + this.inheritsFromId = inheritsFromId; + this.weight = weight; + this.displayName = displayName; + this.gameColor = gameColor; + this.websiteColor = websiteColor; + this.staffRank = staffRank; + this.higherStaffRank = higherStaffRank; + } - public void insert(SingleResultCallback callback) { - rankCache.add(this); - rankIdCache.put(id, this); - ranksCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + rankCache.add(this); + rankIdCache.put(id, this); + ranksCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void delete(SingleResultCallback callback) { - rankCache.remove(this); - rankIdCache.remove(id); - ranksCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + rankCache.remove(this); + rankIdCache.remove(id); + ranksCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/Server.java b/src/main/java/net/frozenorb/apiv3/model/Server.java index 43d44ea..09ad250 100644 --- a/src/main/java/net/frozenorb/apiv3/model/Server.java +++ b/src/main/java/net/frozenorb/apiv3/model/Server.java @@ -21,116 +21,116 @@ import java.util.concurrent.TimeUnit; @Entity public final class Server { - private static final MongoCollection serversCollection = APIv3.getDatabase().getCollection("servers", Server.class); + private static final MongoCollection serversCollection = APIv3.getDatabase().getCollection("servers", Server.class); - private static Map serverIdCache = null; - private static List serverCache = null; + private static Map serverIdCache = null; + private static List serverCache = null; - @Getter @Id private String id; - @Getter private String displayName; - @Getter private String serverGroup; - @Getter private String serverIp; - @Getter private Instant lastUpdatedAt; - @Getter private double lastTps; - @Getter @ExcludeFromReplies private Set players; + @Getter @Id private String id; + @Getter private String displayName; + @Getter private String serverGroup; + @Getter private String serverIp; + @Getter private Instant lastUpdatedAt; + @Getter private double lastTps; + @Getter @ExcludeFromReplies private Set players; - public static List findAll() { - return ImmutableList.copyOf(serverCache); - } + public static List findAll() { + return ImmutableList.copyOf(serverCache); + } - public static Server findById(String id) { - return serverIdCache.get(id); - } + public static Server findById(String id) { + return serverIdCache.get(id); + } - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateTimedOutServers()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateTimedOutServers()); + } - public static void updateCache() { - serversCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((servers, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + serversCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((servers, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map working = new HashMap<>(); + Map working = new HashMap<>(); - for (Server server : servers) { - working.put(server.getId(), server); - } + for (Server server : servers) { + working.put(server.getId(), server); + } - serverIdCache = working; - serverCache = servers; - })); - } + serverIdCache = working; + serverCache = servers; + })); + } - private static void updateTimedOutServers() { - for (Server server : serverCache) { - int lastUpdatedAgo = TimeUtils.getSecondsBetween(server.getLastUpdatedAt(), Instant.now()); + private static void updateTimedOutServers() { + for (Server server : serverCache) { + int lastUpdatedAgo = TimeUtils.getSecondsBetween(server.getLastUpdatedAt(), Instant.now()); - if (lastUpdatedAgo < 60 || lastUpdatedAgo > 30 * 5) { - return; - } + if (lastUpdatedAgo < 60 || lastUpdatedAgo > 30 * 5) { + return; + } - for (UUID online : server.getPlayers()) { - User.findById(online, (user, findUserError) -> { - if (findUserError != null) { - findUserError.printStackTrace(); - return; - } + for (UUID online : server.getPlayers()) { + User.findById(online, (user, findUserError) -> { + if (findUserError != null) { + findUserError.printStackTrace(); + return; + } - if (user.leftServer(server)) { - user.save((ignored, saveUserError) -> { - if (saveUserError != null) { - saveUserError.printStackTrace(); - } - }); - } - }); - } + if (user.leftServer(server)) { + user.save((ignored, saveUserError) -> { + if (saveUserError != null) { + saveUserError.printStackTrace(); + } + }); + } + }); + } - server.players = new HashSet<>(); - server.save((ignored, error) -> { - if (error != null) { - error.printStackTrace(); - } - }); - } - } + server.players = new HashSet<>(); + server.save((ignored, error) -> { + if (error != null) { + error.printStackTrace(); + } + }); + } + } - private Server() {} // For Jackson + private Server() {} // For Jackson - public Server(String id, String displayName, ServerGroup serverGroup, String serverIp) { - this.id = id; - this.displayName = displayName; - this.serverGroup = serverGroup.getId(); - this.serverIp = serverIp; - this.lastUpdatedAt = Instant.now(); - this.lastTps = 0; - this.players = new HashSet<>(); - } + public Server(String id, String displayName, ServerGroup serverGroup, String serverIp) { + this.id = id; + this.displayName = displayName; + this.serverGroup = serverGroup.getId(); + this.serverIp = serverIp; + this.lastUpdatedAt = Instant.now(); + this.lastTps = 0; + this.players = new HashSet<>(); + } - public void receivedHeartbeat(double tps, Iterable players) { - this.lastUpdatedAt = Instant.now(); - this.lastTps = tps; - this.players = ImmutableSet.copyOf(players); - } + public void receivedHeartbeat(double tps, Iterable players) { + this.lastUpdatedAt = Instant.now(); + this.lastTps = tps; + this.players = ImmutableSet.copyOf(players); + } - public void insert(SingleResultCallback callback) { - serverCache.add(this); - serverIdCache.put(id, this); - serversCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + serverCache.add(this); + serverIdCache.put(id, this); + serversCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - serversCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + serversCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } - public void delete(SingleResultCallback callback) { - serverCache.remove(this); - serverIdCache.remove(id); - serversCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + serverCache.remove(this); + serverIdCache.remove(id); + serversCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/ServerGroup.java b/src/main/java/net/frozenorb/apiv3/model/ServerGroup.java index 0271a60..c4d0467 100644 --- a/src/main/java/net/frozenorb/apiv3/model/ServerGroup.java +++ b/src/main/java/net/frozenorb/apiv3/model/ServerGroup.java @@ -21,80 +21,80 @@ import java.util.concurrent.TimeUnit; @Entity public final class ServerGroup { - public static final String DEFAULT_GROUP_ID = "default"; - private static final MongoCollection serverGroupsCollection = APIv3.getDatabase().getCollection("serverGroups", ServerGroup.class); + public static final String DEFAULT_GROUP_ID = "default"; + private static final MongoCollection serverGroupsCollection = APIv3.getDatabase().getCollection("serverGroups", ServerGroup.class); - private static Map serverGroupIdCache = null; - private static List serverGroupCache = null; + private static Map serverGroupIdCache = null; + private static List serverGroupCache = null; - @Getter @Id private String id; - @Getter private String image; - @Getter @Setter private Set announcements; - @Getter @Setter @ExcludeFromReplies private Map> permissions; + @Getter @Id private String id; + @Getter private String image; + @Getter @Setter private Set announcements; + @Getter @Setter @ExcludeFromReplies private Map> permissions; - public static List findAll() { - return ImmutableList.copyOf(serverGroupCache); - } + public static List findAll() { + return ImmutableList.copyOf(serverGroupCache); + } - public static ServerGroup findById(String id) { - return serverGroupIdCache.get(id); - } + public static ServerGroup findById(String id) { + return serverGroupIdCache.get(id); + } - public static ServerGroup findDefault() { - return findById(DEFAULT_GROUP_ID); - } + public static ServerGroup findDefault() { + return findById(DEFAULT_GROUP_ID); + } - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); + } - public static void updateCache() { - serverGroupsCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((serverGroups, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + serverGroupsCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap((serverGroups, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map working = new HashMap<>(); + Map working = new HashMap<>(); - for (ServerGroup serverGroup : serverGroups) { - working.put(serverGroup.getId(), serverGroup); - } + for (ServerGroup serverGroup : serverGroups) { + working.put(serverGroup.getId(), serverGroup); + } - serverGroupIdCache = working; - serverGroupCache = serverGroups; - })); - } + serverGroupIdCache = working; + serverGroupCache = serverGroups; + })); + } - private ServerGroup() {} // For Jackson + private ServerGroup() {} // For Jackson - public ServerGroup(String id, String image) { - this.id = id; - this.image = image; - } + public ServerGroup(String id, String image) { + this.id = id; + this.image = image; + } - public Map calculatePermissions(Rank rank) { - if (permissions == null) { - return ImmutableMap.of(); - } else { - return PermissionUtils.mergeUpTo(permissions, rank); - } - } + public Map calculatePermissions(Rank rank) { + if (permissions == null) { + return ImmutableMap.of(); + } else { + return PermissionUtils.mergeUpTo(permissions, rank); + } + } - public void insert(SingleResultCallback callback) { - serverGroupCache.add(this); - serverGroupIdCache.put(id, this); - serverGroupsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } + public void insert(SingleResultCallback callback) { + serverGroupCache.add(this); + serverGroupIdCache.put(id, this); + serverGroupsCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } - public void save(SingleResultCallback callback) { - serverGroupsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void save(SingleResultCallback callback) { + serverGroupsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } - public void delete(SingleResultCallback callback) { - serverGroupCache.remove(this); - serverGroupIdCache.remove(id); - serverGroupsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + public void delete(SingleResultCallback callback) { + serverGroupCache.remove(this); + serverGroupIdCache.remove(id); + serverGroupsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/model/User.java b/src/main/java/net/frozenorb/apiv3/model/User.java index 33794fd..88612cd 100644 --- a/src/main/java/net/frozenorb/apiv3/model/User.java +++ b/src/main/java/net/frozenorb/apiv3/model/User.java @@ -37,618 +37,618 @@ import java.util.stream.Collectors; @AllArgsConstructor public final class User { - private static final MongoCollection usersCollection = APIv3.getDatabase().getCollection("users", User.class); - - @Getter @Id @JsonSerialize(using=UuidJsonSerializer.class) @JsonDeserialize(using=UuidJsonDeserializer.class) private UUID id; - @Getter private String lastUsername; - @Getter @ExcludeFromReplies private Map aliases = new HashMap<>(); - @Getter @ExcludeFromReplies @Setter private String totpSecret; - @Getter @ExcludeFromReplies private String password; - @Getter @ExcludeFromReplies private String passwordResetToken; - @Getter @ExcludeFromReplies private Instant passwordResetTokenSetAt; - @Getter private String email; - @Getter private Instant registeredAt; - @Getter @ExcludeFromReplies private String pendingEmail; - @Getter @ExcludeFromReplies private String pendingEmailToken; - @Getter @ExcludeFromReplies private Instant pendingEmailTokenSetAt; - @Getter private String phone; - @Getter private Instant phoneRegisteredAt; - @Getter @ExcludeFromReplies private String pendingPhone; - @Getter @ExcludeFromReplies private String pendingPhoneToken; - @Getter @ExcludeFromReplies private Instant pendingPhoneTokenSetAt; - @Getter @ExcludeFromReplies private Instant pendingPhoneTokenVerificationAttemptedAt; - @Getter @ExcludeFromReplies private Set phoneVerificationFailedAttempts; - @Getter private String lastSeenOn; - @Getter private Instant lastSeenAt; - @Getter private Instant firstSeenAt; - @Getter private boolean online; - - public static void findById(String id, SingleResultCallback callback) { - try { - findById(UuidUtils.parseUuid(id), callback); - } catch (NullPointerException | IllegalArgumentException ignored) { // from UUID parsing - callback.onResult(null, null); // We don't pass in the exception, we just pretend we couldn't find them. - } - } - - public static void findById(UUID id, SingleResultCallback callback) { - if (UuidUtils.isAcceptableUuid(id)) { - usersCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); - } else { - callback.onResult(null, null); - } - } - - - public static void findOrCreateById(UUID id, String username, SingleResultCallback callback) { - if (!UuidUtils.isAcceptableUuid(id)) { - callback.onResult(null, null); - return; - } - - usersCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap((user, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } - - if (user != null) { - callback.onResult(user, null); - return; - } - - User created = new User(id, username); - - created.checkNameCollisions((ignored, nameCollisionsError) -> { - if (nameCollisionsError != null) { - callback.onResult(null, nameCollisionsError); - return; - } - - created.insert((ignored2, insertUserError) -> { - if (insertUserError != null) { - callback.onResult(null, insertUserError); - } else { - callback.onResult(created, null); - } - }); - }); - })); - } - - public static void findByPhone(String phoneNumber, SingleResultCallback callback) { - usersCollection.find(new Document("$or", ImmutableList.of( - new Document("phone", phoneNumber), - new Document("pendingPhone", phoneNumber) - ))).first(SyncUtils.vertxWrap(callback)); - } - - public static void findByEmail(String email, SingleResultCallback callback) { - usersCollection.find(new Document("email", email)).first(SyncUtils.vertxWrap(callback)); - } - - public static void findByEmailToken(String emailToken, SingleResultCallback callback) { - usersCollection.find(new Document("emailToken", emailToken)).first(SyncUtils.vertxWrap(callback)); - } - - public static void findByLastUsername(String lastUsername, SingleResultCallback callback) { - usersCollection.find(new Document("lastUsername", lastUsername)).first(SyncUtils.vertxWrap(callback)); - } - - public static void findOrCreateByIdGrouped(Map search, SingleResultCallback> callback) { - usersCollection.find(new Document("_id", new Document("$in", search.keySet()))).into(new LinkedList<>(), SyncUtils.vertxWrap((users, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } - - Map result = new ConcurrentHashMap<>(); - - for (User user : users) { - result.put(user.getId(), user); - } - - List createNewUserFutures = new ArrayList<>(); - - search.forEach((uuid, username) -> { - if (result.containsKey(uuid) || !UuidUtils.isAcceptableUuid(uuid)) { - return; - } - - Future createNewUserFuture = Future.future(); - createNewUserFutures.add(createNewUserFuture); - - User created = new User(uuid, username); - created.checkNameCollisions((ignored, error2) -> { - if (error2 != null) { - createNewUserFuture.fail(error2); - return; - } - - created.insert((ignored2, error3) -> { - if (error3 != null) { - createNewUserFuture.fail(error3); - return; - } - - result.put(uuid, created); - createNewUserFuture.complete(); - }); - }); - }); - - CompositeFuture.all(createNewUserFutures).setHandler((creationStatus) -> { - if (creationStatus.failed()) { - callback.onResult(null, creationStatus.cause()); - } else { - callback.onResult(result, null); - } - }); - })); - } - - private User() {} // For Jackson - - public User(UUID id, String lastUsername) { - this.id = id; - this.lastUsername = lastUsername; - this.aliases = new HashMap<>(); - this.lastSeenAt = Instant.now(); - this.firstSeenAt = Instant.now(); - - this.aliases.put(lastUsername, Instant.now()); - } - - public void updateUsername(String newUsername) { - this.aliases.put(newUsername, Instant.now()); - this.lastUsername = newUsername; - } - - public void checkNameCollisions(SingleResultCallback callback) { - User.findByLastUsername(lastUsername, (collision, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } - - if (collision == null) { - callback.onResult(null, null); - return; - } - - MojangUtils.getName(collision.getId(), (collisionNewUsername, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - return; - } - - collision.updateUsername(collisionNewUsername); - collision.checkNameCollisions((ignored, error3) -> { - if (error3 != null) { - callback.onResult(null, error3); - return; - } - - collision.save((ignored2, error4) -> { - if (error4 != null) { - callback.onResult(null, error4); - } else { - callback.onResult(null, null); - } - }); - }); - }); - }); - } - - public void getLoginInfo(Server server, String userIp, SingleResultCallback> callback) { - Future> punishmentsFuture = Future.future(); - Future ipIntelFuture = Future.future(); - Future> ipBansFuture = Future.future(); - Future> grantsFuture = Future.future(); - - Punishment.findByUserAndType(this, ImmutableSet.of( - Punishment.PunishmentType.BLACKLIST, - Punishment.PunishmentType.BAN, - Punishment.PunishmentType.MUTE - ), new MongoToVertxCallback<>(punishmentsFuture)); - - if (userIp != null) { - IpIntel.findOrCreateById(userIp, new MongoToVertxCallback<>(ipIntelFuture)); - IpBan.findByIp(userIp, new MongoToVertxCallback<>(ipBansFuture)); - } else { - ipIntelFuture.complete(null); - ipBansFuture.complete(ImmutableList.of()); - } - - Grant.findByUser(this, new MongoToVertxCallback<>(grantsFuture)); - - CompositeFuture.all(punishmentsFuture, ipIntelFuture, ipBansFuture, grantsFuture).setHandler((result) -> { - if (result.failed()) { - callback.onResult(null, result.cause()); - return; - } - - Iterable punishments = result.result().result(0); - IpIntel ipIntel = result.result().result(1); - Iterable ipBans = result.result().result(2); - Iterable grants = result.result().result(3); - - getLoginInfo(server, ipIntel, punishments, ipBans, grants, (loginInfo, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - callback.onResult(loginInfo, null); - } - }); - }); - } - - // This is only used to help batch requests to mongo - public void getLoginInfo(Server server, IpIntel ipIntel, Iterable punishments, Iterable ipBans, Iterable grants, SingleResultCallback> callback) { - getAccessInfo(ipIntel, punishments, ipBans, (accessInfo, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } - - ServerGroup serverGroup = ServerGroup.findById(server.getServerGroup()); - Punishment activeMute = null; - - for (Punishment punishment : punishments) { - if (punishment.isActive() && punishment.getType() == Punishment.PunishmentType.MUTE) { - activeMute = punishment; - break; - } - } - - Map result = new HashMap<>(); - List ranks = getRanksScoped(serverGroup, grants); - - // Currently, we exclude this from login info. We do still do the relevant - // db query, but we don't include the result because it's not used in - // Hydrogen at all (bnut probably will be later on) - // result.put("user", this); - result.put("ranks", ranks.stream().map(Rank::getId).collect(Collectors.toList())); - - if (activeMute != null) { - result.put("mute", activeMute); - } - - if (accessInfo != null) { - result.put("access", accessInfo); - } - - callback.onResult(result, null); - }); - } - - private void getAccessInfo(IpIntel ipIntel, Iterable punishments, Iterable ipBans, SingleResultCallback> callback) { - Punishment activeBan = null; - IpBan activeIpBan = null; - - for (Punishment punishment : punishments) { - if (punishment.isActive() && (punishment.getType() == Punishment.PunishmentType.BAN || punishment.getType() == Punishment.PunishmentType.BLACKLIST)) { - activeBan = punishment; - break; - } - } - - for (IpBan ipBan : ipBans) { - if (ipBan.isActive()) { - activeIpBan = ipBan; - break; - } - } - - if (activeBan != null) { - callback.onResult(ImmutableMap.of( - "allowed", false, - "message", activeBan.getAccessDenialReason() - ), null); - } else if (activeIpBan != null) { - activeIpBan.getAccessDenialReason((denialReason, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - callback.onResult(ImmutableMap.of( - "allowed", false, - "message", denialReason - ), null); - } - }); - } else if (ipIntel != null) { - MaxMindResult maxMindResult = ipIntel.getResult(); - MaxMindUserType userType = maxMindResult.getTraits().getUserType(); - Map proposedAccess = null; - - if (!userType.isAllowed()) { - proposedAccess = ImmutableMap.of( - "allowed", false, - "message", "You cannot join MineHQ from a VPN." - ); - } else if (BannedAsn.findById(maxMindResult.getTraits().getAsn()) != null) { - proposedAccess = ImmutableMap.of( - "allowed", false, - "message", "You cannot join MineHQ from this ISP." - ); - } - - Map finalProposedAccess = proposedAccess; - - if (proposedAccess != null) { - hasPermissionAnywhere(Permissions.BYPASS_VPN_CHECK, (bypass, error) -> { - if (error != null) { - callback.onResult(null, error); - } else if (bypass) { - callback.onResult(null, null); - } else { - callback.onResult(finalProposedAccess, null); - } - }); - } else { - callback.onResult(null, null); - } - } else { - callback.onResult(null, null); - } - } - - public boolean seenOnServer(Server server) { - if (online && server.getId().equals(lastSeenOn)) { - return false; - } - - this.lastSeenOn = server.getId(); - this.lastSeenAt = Instant.now(); - this.online = true; - return true; - } - - // Returns if any change was actually made. - public boolean leftServer(Server server) { - // We have this check to prevent issues where one server's - // leave is processed after another server's login. - if (server.getId().equals(lastSeenOn)) { - this.lastSeenAt = Instant.now(); - this.online = false; - return true; - } else { - return false; - } - } - - public void startPasswordReset() { - this.passwordResetToken = UUID.randomUUID().toString().replaceAll("-", ""); - this.passwordResetTokenSetAt = Instant.now(); - } - - public void updatePassword(String password) { - this.passwordResetToken = null; - this.passwordResetTokenSetAt = null; - this.password = Hashing - .sha256() - .hashString(password + "$" + id.toString(), Charsets.UTF_8) - .toString(); - } - - public boolean checkPassword(String input) { - String hashed = Hashing - .sha256() - .hashString(input + "$" + id.toString(), Charsets.UTF_8) - .toString(); - - return password != null && hashed.equals(password); - } - - public void requiresTotpAuthorization(String ip, SingleResultCallback callback) { - if (totpSecret == null) { - callback.onResult(RequiresTotpResult.NOT_REQUIRED_NOT_SET, null); - return; - } - - if (!IpUtils.isValidIp(ip)) { - callback.onResult(RequiresTotpResult.REQUIRED_NO_EXEMPTIONS, null); - return; - } - - TotpUtils.isPreAuthorized(this, ip, (ipPreAuth, error) -> { - if (error != null) { - callback.onResult(null, error); - } else if (ipPreAuth) { - callback.onResult(RequiresTotpResult.NOT_REQUIRED_IP_PRE_AUTHORIZED, null); - } else { - callback.onResult(RequiresTotpResult.REQUIRED_NO_EXEMPTIONS, null); - } - }); - } - - public void checkTotpAuthorization(int code, String ip, SingleResultCallback callback) { - if (totpSecret == null) { - hasPermissionAnywhere(Permissions.REQUIRE_TOTP_CODE, (totpRequired, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - TotpAuthorizationResult result = totpRequired ? TotpAuthorizationResult.NOT_AUTHORIZED_NOT_SET : TotpAuthorizationResult.AUTHORIZED_NOT_SET; - callback.onResult(result, null); - } - }); - - return; - } - - TotpUtils.isPreAuthorized(this, ip, (preAuthorized, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } - - if (preAuthorized) { - callback.onResult(TotpAuthorizationResult.AUTHORIZED_IP_PRE_AUTH, null); - return; - } - - TotpUtils.wasRecentlyUsed(this, code, (recentlyUsed, error2) -> { - if (error2 != null) { - callback.onResult(null, error2); - return; - } - - if (recentlyUsed) { - callback.onResult(TotpAuthorizationResult.NOT_AUTHORIZED_RECENTLY_USED, null); - return; - } - - if (!TotpUtils.authorizeUser(totpSecret, code)) { - callback.onResult(TotpAuthorizationResult.NOT_AUTHORIZED_BAD_CODE, null); - return; - } - - Future markPreAuthFuture = Future.future(); - Future markRecentlyUsedFuture = Future.future(); - - TotpUtils.markPreAuthorized(this, ip, 3, TimeUnit.DAYS, new MongoToVertxCallback<>(markPreAuthFuture)); - TotpUtils.markRecentlyUsed(this, code, new MongoToVertxCallback<>(markRecentlyUsedFuture)); - - CompositeFuture.all(markPreAuthFuture, markRecentlyUsedFuture).setHandler((result) -> { - if (result.failed()) { - callback.onResult(null, result.cause()); - } else { - callback.onResult(TotpAuthorizationResult.AUTHORIZED_GOOD_CODE, null); - } - }); - }); - }); - } - - public void startEmailRegistration(String pendingEmail) { - this.pendingEmail = pendingEmail; - this.pendingEmailToken = UUID.randomUUID().toString().replace("-", ""); - this.pendingEmailTokenSetAt = Instant.now(); - } - - public void completeEmailRegistration(String email) { - this.email = email; - this.registeredAt = Instant.now(); - this.pendingEmail = null; - this.pendingEmailToken = null; - this.pendingEmailTokenSetAt = null; - } - - public void startPhoneRegistration(String phoneNumber) { - this.pendingPhone = phoneNumber; - this.pendingPhoneToken = String.valueOf(new Random().nextInt(999999 - 100000) + 100000); - this.pendingPhoneTokenSetAt = Instant.now(); - } - - public void failedPhoneRegistration() { - this.pendingPhoneTokenVerificationAttemptedAt = Instant.now(); - this.phoneVerificationFailedAttempts.add(Instant.now()); - } - - public void completePhoneRegistration(String phoneNumber) { - this.phone = phoneNumber; - this.phoneRegisteredAt = Instant.now(); - this.pendingPhone = null; - this.pendingPhoneToken = null; - this.pendingPhoneTokenSetAt = null; - this.pendingPhoneTokenVerificationAttemptedAt = null; - this.phoneVerificationFailedAttempts = null; - } - - public void hasPermissionAnywhere(String permission, SingleResultCallback callback) { - getCompoundedPermissions((permissions, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - boolean hasPermission = permissions.containsKey(permission) && permissions.get(permission); - callback.onResult(hasPermission, null); - } - }); - } - - public void getCompoundedPermissions(SingleResultCallback> callback) { - Grant.findByUser(this, (grants, error) -> { - if (error != null) { - callback.onResult(null, error); - } else { - Map compoundedPermissions = new HashMap<>(); - - for (Rank globalRank : getRanksScoped(null, grants)) { - compoundedPermissions = PermissionUtils.mergePermissions( - compoundedPermissions, - ServerGroup.findDefault().calculatePermissions(globalRank) - ); - } - - for (ServerGroup serverGroup : ServerGroup.findAll()) { - for (Rank scopedRank : getRanksScoped(serverGroup, grants)) { - compoundedPermissions = PermissionUtils.mergePermissions( - compoundedPermissions, - serverGroup.calculatePermissions(scopedRank) - ); - } - } - - callback.onResult(ImmutableMap.copyOf(compoundedPermissions), null); - } - }); - } - - private List getRanksScoped(ServerGroup serverGroup, Iterable grants) { - Set grantedRanks = new HashSet<>(); - - for (Grant grant : grants) { - if (!grant.isActive() || (serverGroup != null && !grant.appliesOn(serverGroup))) { - continue; - } - - Rank grantedRank = Rank.findById(grant.getRank()); - grantedRanks.add(grantedRank); - } - - if (grantedRanks.isEmpty()) { - return ImmutableList.of(Rank.findById("default")); - } - - Iterator iterator = grantedRanks.iterator(); - Set copiedRanks = ImmutableSet.copyOf(grantedRanks); - - // This is to remove redundant ranks. Say they have mod, mod-plus, admin, and youtuber, - // we should remove mod and mod-plus as it'll be made redundant by the higher ranked admin. - while (iterator.hasNext()) { - Rank rank = iterator.next(); - - // Check all other ranks for inherited collision - for (Rank otherRank : copiedRanks) { - if (otherRank == rank) { - continue; - } - - Rank parent = otherRank; - - // Iterate up the inheritance tree to detect rank redundancies. - while (parent.getInheritsFromId() != null) { - if (parent == rank) { - iterator.remove(); - } - - parent = Rank.findById(parent.getInheritsFromId()); - } - } - } - - List grantedRanksList = new ArrayList<>(grantedRanks); - grantedRanksList.sort((a, b) -> Ints.compare(b.getWeight(), a.getWeight())); - return ImmutableList.copyOf(grantedRanksList); - } - - public void insert(SingleResultCallback callback) { - usersCollection.insertOne(this, SyncUtils.vertxWrap(callback)); - } - - public void save(SingleResultCallback callback) { - usersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); - } + private static final MongoCollection usersCollection = APIv3.getDatabase().getCollection("users", User.class); + + @Getter @Id @JsonSerialize(using = UuidJsonSerializer.class) @JsonDeserialize(using = UuidJsonDeserializer.class) private UUID id; + @Getter private String lastUsername; + @Getter @ExcludeFromReplies private Map aliases = new HashMap<>(); + @Getter @ExcludeFromReplies @Setter private String totpSecret; + @Getter @ExcludeFromReplies private String password; + @Getter @ExcludeFromReplies private String passwordResetToken; + @Getter @ExcludeFromReplies private Instant passwordResetTokenSetAt; + @Getter private String email; + @Getter private Instant registeredAt; + @Getter @ExcludeFromReplies private String pendingEmail; + @Getter @ExcludeFromReplies private String pendingEmailToken; + @Getter @ExcludeFromReplies private Instant pendingEmailTokenSetAt; + @Getter private String phone; + @Getter private Instant phoneRegisteredAt; + @Getter @ExcludeFromReplies private String pendingPhone; + @Getter @ExcludeFromReplies private String pendingPhoneToken; + @Getter @ExcludeFromReplies private Instant pendingPhoneTokenSetAt; + @Getter @ExcludeFromReplies private Instant pendingPhoneTokenVerificationAttemptedAt; + @Getter @ExcludeFromReplies private Set phoneVerificationFailedAttempts; + @Getter private String lastSeenOn; + @Getter private Instant lastSeenAt; + @Getter private Instant firstSeenAt; + @Getter private boolean online; + + public static void findById(String id, SingleResultCallback callback) { + try { + findById(UuidUtils.parseUuid(id), callback); + } catch (NullPointerException | IllegalArgumentException ignored) { // from UUID parsing + callback.onResult(null, null); // We don't pass in the exception, we just pretend we couldn't find them. + } + } + + public static void findById(UUID id, SingleResultCallback callback) { + if (UuidUtils.isAcceptableUuid(id)) { + usersCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback)); + } else { + callback.onResult(null, null); + } + } + + + public static void findOrCreateById(UUID id, String username, SingleResultCallback callback) { + if (!UuidUtils.isAcceptableUuid(id)) { + callback.onResult(null, null); + return; + } + + usersCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap((user, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } + + if (user != null) { + callback.onResult(user, null); + return; + } + + User created = new User(id, username); + + created.checkNameCollisions((ignored, nameCollisionsError) -> { + if (nameCollisionsError != null) { + callback.onResult(null, nameCollisionsError); + return; + } + + created.insert((ignored2, insertUserError) -> { + if (insertUserError != null) { + callback.onResult(null, insertUserError); + } else { + callback.onResult(created, null); + } + }); + }); + })); + } + + public static void findByPhone(String phoneNumber, SingleResultCallback callback) { + usersCollection.find(new Document("$or", ImmutableList.of( + new Document("phone", phoneNumber), + new Document("pendingPhone", phoneNumber) + ))).first(SyncUtils.vertxWrap(callback)); + } + + public static void findByEmail(String email, SingleResultCallback callback) { + usersCollection.find(new Document("email", email)).first(SyncUtils.vertxWrap(callback)); + } + + public static void findByEmailToken(String emailToken, SingleResultCallback callback) { + usersCollection.find(new Document("emailToken", emailToken)).first(SyncUtils.vertxWrap(callback)); + } + + public static void findByLastUsername(String lastUsername, SingleResultCallback callback) { + usersCollection.find(new Document("lastUsername", lastUsername)).first(SyncUtils.vertxWrap(callback)); + } + + public static void findOrCreateByIdGrouped(Map search, SingleResultCallback> callback) { + usersCollection.find(new Document("_id", new Document("$in", search.keySet()))).into(new LinkedList<>(), SyncUtils.vertxWrap((users, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } + + Map result = new ConcurrentHashMap<>(); + + for (User user : users) { + result.put(user.getId(), user); + } + + List createNewUserFutures = new ArrayList<>(); + + search.forEach((uuid, username) -> { + if (result.containsKey(uuid) || !UuidUtils.isAcceptableUuid(uuid)) { + return; + } + + Future createNewUserFuture = Future.future(); + createNewUserFutures.add(createNewUserFuture); + + User created = new User(uuid, username); + created.checkNameCollisions((ignored, error2) -> { + if (error2 != null) { + createNewUserFuture.fail(error2); + return; + } + + created.insert((ignored2, error3) -> { + if (error3 != null) { + createNewUserFuture.fail(error3); + return; + } + + result.put(uuid, created); + createNewUserFuture.complete(); + }); + }); + }); + + CompositeFuture.all(createNewUserFutures).setHandler((creationStatus) -> { + if (creationStatus.failed()) { + callback.onResult(null, creationStatus.cause()); + } else { + callback.onResult(result, null); + } + }); + })); + } + + private User() {} // For Jackson + + public User(UUID id, String lastUsername) { + this.id = id; + this.lastUsername = lastUsername; + this.aliases = new HashMap<>(); + this.lastSeenAt = Instant.now(); + this.firstSeenAt = Instant.now(); + + this.aliases.put(lastUsername, Instant.now()); + } + + public void updateUsername(String newUsername) { + this.aliases.put(newUsername, Instant.now()); + this.lastUsername = newUsername; + } + + public void checkNameCollisions(SingleResultCallback callback) { + User.findByLastUsername(lastUsername, (collision, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } + + if (collision == null) { + callback.onResult(null, null); + return; + } + + MojangUtils.getName(collision.getId(), (collisionNewUsername, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + return; + } + + collision.updateUsername(collisionNewUsername); + collision.checkNameCollisions((ignored, error3) -> { + if (error3 != null) { + callback.onResult(null, error3); + return; + } + + collision.save((ignored2, error4) -> { + if (error4 != null) { + callback.onResult(null, error4); + } else { + callback.onResult(null, null); + } + }); + }); + }); + }); + } + + public void getLoginInfo(Server server, String userIp, SingleResultCallback> callback) { + Future> punishmentsFuture = Future.future(); + Future ipIntelFuture = Future.future(); + Future> ipBansFuture = Future.future(); + Future> grantsFuture = Future.future(); + + Punishment.findByUserAndType(this, ImmutableSet.of( + Punishment.PunishmentType.BLACKLIST, + Punishment.PunishmentType.BAN, + Punishment.PunishmentType.MUTE + ), new MongoToVertxCallback<>(punishmentsFuture)); + + if (userIp != null) { + IpIntel.findOrCreateById(userIp, new MongoToVertxCallback<>(ipIntelFuture)); + IpBan.findByIp(userIp, new MongoToVertxCallback<>(ipBansFuture)); + } else { + ipIntelFuture.complete(null); + ipBansFuture.complete(ImmutableList.of()); + } + + Grant.findByUser(this, new MongoToVertxCallback<>(grantsFuture)); + + CompositeFuture.all(punishmentsFuture, ipIntelFuture, ipBansFuture, grantsFuture).setHandler((result) -> { + if (result.failed()) { + callback.onResult(null, result.cause()); + return; + } + + Iterable punishments = result.result().result(0); + IpIntel ipIntel = result.result().result(1); + Iterable ipBans = result.result().result(2); + Iterable grants = result.result().result(3); + + getLoginInfo(server, ipIntel, punishments, ipBans, grants, (loginInfo, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + callback.onResult(loginInfo, null); + } + }); + }); + } + + // This is only used to help batch requests to mongo + public void getLoginInfo(Server server, IpIntel ipIntel, Iterable punishments, Iterable ipBans, Iterable grants, SingleResultCallback> callback) { + getAccessInfo(ipIntel, punishments, ipBans, (accessInfo, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } + + ServerGroup serverGroup = ServerGroup.findById(server.getServerGroup()); + Punishment activeMute = null; + + for (Punishment punishment : punishments) { + if (punishment.isActive() && punishment.getType() == Punishment.PunishmentType.MUTE) { + activeMute = punishment; + break; + } + } + + Map result = new HashMap<>(); + List ranks = getRanksScoped(serverGroup, grants); + + // Currently, we exclude this from login info. We do still do the relevant + // db query, but we don't include the result because it's not used in + // Hydrogen at all (bnut probably will be later on) + // result.put("user", this); + result.put("ranks", ranks.stream().map(Rank::getId).collect(Collectors.toList())); + + if (activeMute != null) { + result.put("mute", activeMute); + } + + if (accessInfo != null) { + result.put("access", accessInfo); + } + + callback.onResult(result, null); + }); + } + + private void getAccessInfo(IpIntel ipIntel, Iterable punishments, Iterable ipBans, SingleResultCallback> callback) { + Punishment activeBan = null; + IpBan activeIpBan = null; + + for (Punishment punishment : punishments) { + if (punishment.isActive() && (punishment.getType() == Punishment.PunishmentType.BAN || punishment.getType() == Punishment.PunishmentType.BLACKLIST)) { + activeBan = punishment; + break; + } + } + + for (IpBan ipBan : ipBans) { + if (ipBan.isActive()) { + activeIpBan = ipBan; + break; + } + } + + if (activeBan != null) { + callback.onResult(ImmutableMap.of( + "allowed", false, + "message", activeBan.getAccessDenialReason() + ), null); + } else if (activeIpBan != null) { + activeIpBan.getAccessDenialReason((denialReason, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + callback.onResult(ImmutableMap.of( + "allowed", false, + "message", denialReason + ), null); + } + }); + } else if (ipIntel != null) { + MaxMindResult maxMindResult = ipIntel.getResult(); + MaxMindUserType userType = maxMindResult.getTraits().getUserType(); + Map proposedAccess = null; + + if (!userType.isAllowed()) { + proposedAccess = ImmutableMap.of( + "allowed", false, + "message", "You cannot join MineHQ from a VPN." + ); + } else if (BannedAsn.findById(maxMindResult.getTraits().getAsn()) != null) { + proposedAccess = ImmutableMap.of( + "allowed", false, + "message", "You cannot join MineHQ from this ISP." + ); + } + + Map finalProposedAccess = proposedAccess; + + if (proposedAccess != null) { + hasPermissionAnywhere(Permissions.BYPASS_VPN_CHECK, (bypass, error) -> { + if (error != null) { + callback.onResult(null, error); + } else if (bypass) { + callback.onResult(null, null); + } else { + callback.onResult(finalProposedAccess, null); + } + }); + } else { + callback.onResult(null, null); + } + } else { + callback.onResult(null, null); + } + } + + public boolean seenOnServer(Server server) { + if (online && server.getId().equals(lastSeenOn)) { + return false; + } + + this.lastSeenOn = server.getId(); + this.lastSeenAt = Instant.now(); + this.online = true; + return true; + } + + // Returns if any change was actually made. + public boolean leftServer(Server server) { + // We have this check to prevent issues where one server's + // leave is processed after another server's login. + if (server.getId().equals(lastSeenOn)) { + this.lastSeenAt = Instant.now(); + this.online = false; + return true; + } else { + return false; + } + } + + public void startPasswordReset() { + this.passwordResetToken = UUID.randomUUID().toString().replaceAll("-", ""); + this.passwordResetTokenSetAt = Instant.now(); + } + + public void updatePassword(String password) { + this.passwordResetToken = null; + this.passwordResetTokenSetAt = null; + this.password = Hashing + .sha256() + .hashString(password + "$" + id.toString(), Charsets.UTF_8) + .toString(); + } + + public boolean checkPassword(String input) { + String hashed = Hashing + .sha256() + .hashString(input + "$" + id.toString(), Charsets.UTF_8) + .toString(); + + return password != null && hashed.equals(password); + } + + public void requiresTotpAuthorization(String ip, SingleResultCallback callback) { + if (totpSecret == null) { + callback.onResult(RequiresTotpResult.NOT_REQUIRED_NOT_SET, null); + return; + } + + if (!IpUtils.isValidIp(ip)) { + callback.onResult(RequiresTotpResult.REQUIRED_NO_EXEMPTIONS, null); + return; + } + + TotpUtils.isPreAuthorized(this, ip, (ipPreAuth, error) -> { + if (error != null) { + callback.onResult(null, error); + } else if (ipPreAuth) { + callback.onResult(RequiresTotpResult.NOT_REQUIRED_IP_PRE_AUTHORIZED, null); + } else { + callback.onResult(RequiresTotpResult.REQUIRED_NO_EXEMPTIONS, null); + } + }); + } + + public void checkTotpAuthorization(int code, String ip, SingleResultCallback callback) { + if (totpSecret == null) { + hasPermissionAnywhere(Permissions.REQUIRE_TOTP_CODE, (totpRequired, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + TotpAuthorizationResult result = totpRequired ? TotpAuthorizationResult.NOT_AUTHORIZED_NOT_SET : TotpAuthorizationResult.AUTHORIZED_NOT_SET; + callback.onResult(result, null); + } + }); + + return; + } + + TotpUtils.isPreAuthorized(this, ip, (preAuthorized, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } + + if (preAuthorized) { + callback.onResult(TotpAuthorizationResult.AUTHORIZED_IP_PRE_AUTH, null); + return; + } + + TotpUtils.wasRecentlyUsed(this, code, (recentlyUsed, error2) -> { + if (error2 != null) { + callback.onResult(null, error2); + return; + } + + if (recentlyUsed) { + callback.onResult(TotpAuthorizationResult.NOT_AUTHORIZED_RECENTLY_USED, null); + return; + } + + if (!TotpUtils.authorizeUser(totpSecret, code)) { + callback.onResult(TotpAuthorizationResult.NOT_AUTHORIZED_BAD_CODE, null); + return; + } + + Future markPreAuthFuture = Future.future(); + Future markRecentlyUsedFuture = Future.future(); + + TotpUtils.markPreAuthorized(this, ip, 3, TimeUnit.DAYS, new MongoToVertxCallback<>(markPreAuthFuture)); + TotpUtils.markRecentlyUsed(this, code, new MongoToVertxCallback<>(markRecentlyUsedFuture)); + + CompositeFuture.all(markPreAuthFuture, markRecentlyUsedFuture).setHandler((result) -> { + if (result.failed()) { + callback.onResult(null, result.cause()); + } else { + callback.onResult(TotpAuthorizationResult.AUTHORIZED_GOOD_CODE, null); + } + }); + }); + }); + } + + public void startEmailRegistration(String pendingEmail) { + this.pendingEmail = pendingEmail; + this.pendingEmailToken = UUID.randomUUID().toString().replace("-", ""); + this.pendingEmailTokenSetAt = Instant.now(); + } + + public void completeEmailRegistration(String email) { + this.email = email; + this.registeredAt = Instant.now(); + this.pendingEmail = null; + this.pendingEmailToken = null; + this.pendingEmailTokenSetAt = null; + } + + public void startPhoneRegistration(String phoneNumber) { + this.pendingPhone = phoneNumber; + this.pendingPhoneToken = String.valueOf(new Random().nextInt(999999 - 100000) + 100000); + this.pendingPhoneTokenSetAt = Instant.now(); + } + + public void failedPhoneRegistration() { + this.pendingPhoneTokenVerificationAttemptedAt = Instant.now(); + this.phoneVerificationFailedAttempts.add(Instant.now()); + } + + public void completePhoneRegistration(String phoneNumber) { + this.phone = phoneNumber; + this.phoneRegisteredAt = Instant.now(); + this.pendingPhone = null; + this.pendingPhoneToken = null; + this.pendingPhoneTokenSetAt = null; + this.pendingPhoneTokenVerificationAttemptedAt = null; + this.phoneVerificationFailedAttempts = null; + } + + public void hasPermissionAnywhere(String permission, SingleResultCallback callback) { + getCompoundedPermissions((permissions, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + boolean hasPermission = permissions.containsKey(permission) && permissions.get(permission); + callback.onResult(hasPermission, null); + } + }); + } + + public void getCompoundedPermissions(SingleResultCallback> callback) { + Grant.findByUser(this, (grants, error) -> { + if (error != null) { + callback.onResult(null, error); + } else { + Map compoundedPermissions = new HashMap<>(); + + for (Rank globalRank : getRanksScoped(null, grants)) { + compoundedPermissions = PermissionUtils.mergePermissions( + compoundedPermissions, + ServerGroup.findDefault().calculatePermissions(globalRank) + ); + } + + for (ServerGroup serverGroup : ServerGroup.findAll()) { + for (Rank scopedRank : getRanksScoped(serverGroup, grants)) { + compoundedPermissions = PermissionUtils.mergePermissions( + compoundedPermissions, + serverGroup.calculatePermissions(scopedRank) + ); + } + } + + callback.onResult(ImmutableMap.copyOf(compoundedPermissions), null); + } + }); + } + + private List getRanksScoped(ServerGroup serverGroup, Iterable grants) { + Set grantedRanks = new HashSet<>(); + + for (Grant grant : grants) { + if (!grant.isActive() || (serverGroup != null && !grant.appliesOn(serverGroup))) { + continue; + } + + Rank grantedRank = Rank.findById(grant.getRank()); + grantedRanks.add(grantedRank); + } + + if (grantedRanks.isEmpty()) { + return ImmutableList.of(Rank.findById("default")); + } + + Iterator iterator = grantedRanks.iterator(); + Set copiedRanks = ImmutableSet.copyOf(grantedRanks); + + // This is to remove redundant ranks. Say they have mod, mod-plus, admin, and youtuber, + // we should remove mod and mod-plus as it'll be made redundant by the higher ranked admin. + while (iterator.hasNext()) { + Rank rank = iterator.next(); + + // Check all other ranks for inherited collision + for (Rank otherRank : copiedRanks) { + if (otherRank == rank) { + continue; + } + + Rank parent = otherRank; + + // Iterate up the inheritance tree to detect rank redundancies. + while (parent.getInheritsFromId() != null) { + if (parent == rank) { + iterator.remove(); + } + + parent = Rank.findById(parent.getInheritsFromId()); + } + } + } + + List grantedRanksList = new ArrayList<>(grantedRanks); + grantedRanksList.sort((a, b) -> Ints.compare(b.getWeight(), a.getWeight())); + return ImmutableList.copyOf(grantedRanksList); + } + + public void insert(SingleResultCallback callback) { + usersCollection.insertOne(this, SyncUtils.vertxWrap(callback)); + } + + public void save(SingleResultCallback callback) { + usersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/GETDumpsType.java b/src/main/java/net/frozenorb/apiv3/route/GETDumpsType.java index 06ab752..eb863ef 100644 --- a/src/main/java/net/frozenorb/apiv3/route/GETDumpsType.java +++ b/src/main/java/net/frozenorb/apiv3/route/GETDumpsType.java @@ -16,117 +16,117 @@ import java.util.concurrent.TimeUnit; public final class GETDumpsType implements Handler { - private static List banCache = ImmutableList.of(); - private static List blacklistCache = ImmutableList.of(); - private static List ipBanCache = ImmutableList.of(); - private static Map> grantCache = ImmutableMap.of(); + private static List banCache = ImmutableList.of(); + private static List blacklistCache = ImmutableList.of(); + private static List ipBanCache = ImmutableList.of(); + private static Map> grantCache = ImmutableMap.of(); - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(5), (id) -> updateCache()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(5), (id) -> updateCache()); + } - public static void updateCache() { - Punishment.findByType(ImmutableSet.of( - Punishment.PunishmentType.BAN, - Punishment.PunishmentType.BLACKLIST - ), (punishments, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + public static void updateCache() { + Punishment.findByType(ImmutableSet.of( + Punishment.PunishmentType.BAN, + Punishment.PunishmentType.BLACKLIST + ), (punishments, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - List banCache = new LinkedList<>(); - List blacklistCache = new LinkedList<>(); + List banCache = new LinkedList<>(); + List blacklistCache = new LinkedList<>(); - for (Punishment punishment : punishments) { - if (!punishment.isActive()) { - continue; - } + for (Punishment punishment : punishments) { + if (!punishment.isActive()) { + continue; + } - if (punishment.getType() == Punishment.PunishmentType.BAN) { - banCache.add(punishment.getUser()); - } else if (punishment.getType() == Punishment.PunishmentType.BLACKLIST) { - blacklistCache.add(punishment.getUser()); - } - } + if (punishment.getType() == Punishment.PunishmentType.BAN) { + banCache.add(punishment.getUser()); + } else if (punishment.getType() == Punishment.PunishmentType.BLACKLIST) { + blacklistCache.add(punishment.getUser()); + } + } - GETDumpsType.banCache = banCache; - GETDumpsType.blacklistCache = blacklistCache; - }); + GETDumpsType.banCache = banCache; + GETDumpsType.blacklistCache = blacklistCache; + }); - Grant.findAll((grants, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + Grant.findAll((grants, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - Map> grantCache = new HashMap<>(); + Map> grantCache = new HashMap<>(); - for (Grant grant : grants) { - if (!grant.isActive()) { - continue; - } + for (Grant grant : grants) { + if (!grant.isActive()) { + continue; + } - List users = grantCache.get(grant.getRank()); + List users = grantCache.get(grant.getRank()); - if (users == null) { - users = new LinkedList<>(); - grantCache.put(grant.getRank(), users); - } + if (users == null) { + users = new LinkedList<>(); + grantCache.put(grant.getRank(), users); + } - users.add(grant.getUser()); - } + users.add(grant.getUser()); + } - GETDumpsType.grantCache = grantCache; - }); + GETDumpsType.grantCache = grantCache; + }); - IpBan.find((ipBans, error) -> { - if (error != null) { - error.printStackTrace(); - return; - } + IpBan.find((ipBans, error) -> { + if (error != null) { + error.printStackTrace(); + return; + } - List ipBanCache = new LinkedList<>(); + List ipBanCache = new LinkedList<>(); - for (IpBan ipBan : ipBans) { - if (!ipBan.isActive()) { - continue; - } + for (IpBan ipBan : ipBans) { + if (!ipBan.isActive()) { + continue; + } - ipBanCache.add(ipBan.getUserIp()); - } + ipBanCache.add(ipBan.getUserIp()); + } - GETDumpsType.ipBanCache = ipBanCache; - }); - } + GETDumpsType.ipBanCache = ipBanCache; + }); + } - public void handle(RoutingContext ctx) { - String dumpType = ctx.request().getParam("dumpType"); + public void handle(RoutingContext ctx) { + String dumpType = ctx.request().getParam("dumpType"); - switch (dumpType.toLowerCase()) { - case "ban": - APIv3.respondJson(ctx, 200, banCache); - return; - case "blacklist": - APIv3.respondJson(ctx, 200, blacklistCache); - return; - case "accessdeniable": // Lowercase d because we convert to lowercase above - List result = new LinkedList<>(); + switch (dumpType.toLowerCase()) { + case "ban": + APIv3.respondJson(ctx, 200, banCache); + return; + case "blacklist": + APIv3.respondJson(ctx, 200, blacklistCache); + return; + case "accessdeniable": // Lowercase d because we convert to lowercase above + List result = new LinkedList<>(); - result.addAll(banCache); - result.addAll(blacklistCache); + result.addAll(banCache); + result.addAll(blacklistCache); - APIv3.respondJson(ctx, 200, result); - return; - case "ipban": - APIv3.respondJson(ctx, 200, ipBanCache); - return; - case "grant": - APIv3.respondJson(ctx, 200, grantCache); - return; - default: - ErrorUtils.respondInvalidInput(ctx, dumpType + " is not a valid type. Not in [ban, blacklist, accessDeniable, ipBan, grant]"); - } - } + APIv3.respondJson(ctx, 200, result); + return; + case "ipban": + APIv3.respondJson(ctx, 200, ipBanCache); + return; + case "grant": + APIv3.respondJson(ctx, 200, grantCache); + return; + default: + ErrorUtils.respondInvalidInput(ctx, dumpType + " is not a valid type. Not in [ban, blacklist, accessDeniable, ipBan, grant]"); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/GETWhoAmI.java b/src/main/java/net/frozenorb/apiv3/route/GETWhoAmI.java index 9d9530c..5a054b3 100644 --- a/src/main/java/net/frozenorb/apiv3/route/GETWhoAmI.java +++ b/src/main/java/net/frozenorb/apiv3/route/GETWhoAmI.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.actor.Actor; public final class GETWhoAmI implements Handler { - public void handle(RoutingContext ctx) { - Actor actor = ctx.get("actor"); + public void handle(RoutingContext ctx) { + Actor actor = ctx.get("actor"); - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "name", actor.getName(), - "type", actor.getType(), - "authorized", actor.isAuthorized() - )); - } + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "name", actor.getName(), + "type", actor.getType(), + "authorized", actor.isAuthorized() + )); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/accessTokens/DELETEAccessTokensId.java b/src/main/java/net/frozenorb/apiv3/route/accessTokens/DELETEAccessTokensId.java index c839456..b0a8c65 100644 --- a/src/main/java/net/frozenorb/apiv3/route/accessTokens/DELETEAccessTokensId.java +++ b/src/main/java/net/frozenorb/apiv3/route/accessTokens/DELETEAccessTokensId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEAccessTokensId implements Handler { - public void handle(RoutingContext ctx) { - AccessToken accessToken = SyncUtils.runBlocking(v -> AccessToken.findById(ctx.request().getParam("accessToken"), v)); + public void handle(RoutingContext ctx) { + AccessToken accessToken = SyncUtils.runBlocking(v -> AccessToken.findById(ctx.request().getParam("accessToken"), v)); - if (accessToken == null) { - ErrorUtils.respondNotFound(ctx, "Access token", ctx.request().getParam("accessToken")); - return; - } + if (accessToken == null) { + ErrorUtils.respondNotFound(ctx, "Access token", ctx.request().getParam("accessToken")); + return; + } - SyncUtils.runBlocking(v -> accessToken.delete(v)); + SyncUtils.runBlocking(v -> accessToken.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.ACCESS_TOKEN_DELETE, ImmutableMap.of("accessTokenId", accessToken.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, accessToken); - } - }); - } else { - APIv3.respondJson(ctx, 200, accessToken); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.ACCESS_TOKEN_DELETE, ImmutableMap.of("accessTokenId", accessToken.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, accessToken); + } + }); + } else { + APIv3.respondJson(ctx, 200, accessToken); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokens.java b/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokens.java index ada68bd..439e377 100644 --- a/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokens.java +++ b/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokens.java @@ -11,29 +11,29 @@ import net.frozenorb.apiv3.util.SyncUtils; public final class GETAccessTokens implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("user"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("user"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("user")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("user")); + return; + } - int code = Integer.parseInt(ctx.request().getParam("totpCode")); - TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> user.checkTotpAuthorization(code, null, v)); + int code = Integer.parseInt(ctx.request().getParam("totpCode")); + TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> user.checkTotpAuthorization(code, null, v)); - if (!totpAuthorizationResult.isAuthorized()) { - ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); - return; - } + if (!totpAuthorizationResult.isAuthorized()) { + ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); + return; + } - AccessToken.findAll((accessTokens, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, accessTokens); - } - }); - } + AccessToken.findAll((accessTokens, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, accessTokens); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokensId.java b/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokensId.java index 4c6d7b3..46a415f 100644 --- a/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokensId.java +++ b/src/main/java/net/frozenorb/apiv3/route/accessTokens/GETAccessTokensId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETAccessTokensId implements Handler { - public void handle(RoutingContext ctx) { - AccessToken.findById(ctx.request().getParam("accessToken"), (accessToken, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, accessToken); - } - }); - } + public void handle(RoutingContext ctx) { + AccessToken.findById(ctx.request().getParam("accessToken"), (accessToken, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, accessToken); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/accessTokens/POSTAccessTokens.java b/src/main/java/net/frozenorb/apiv3/route/accessTokens/POSTAccessTokens.java index f7457c0..a51b9a4 100644 --- a/src/main/java/net/frozenorb/apiv3/route/accessTokens/POSTAccessTokens.java +++ b/src/main/java/net/frozenorb/apiv3/route/accessTokens/POSTAccessTokens.java @@ -18,36 +18,36 @@ import java.util.List; public final class POSTAccessTokens implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String actorName = requestBody.getString("actorName"); - ActorType actorType = ActorType.valueOf(requestBody.getString("actorType").toUpperCase()); - List lockedIps = (List) requestBody.getJsonArray("lockedIps").getList(); - User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String actorName = requestBody.getString("actorName"); + ActorType actorType = ActorType.valueOf(requestBody.getString("actorType").toUpperCase()); + List lockedIps = (List) requestBody.getJsonArray("lockedIps").getList(); + User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); - if (addedBy == null) { - ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("addedBy")); - return; - } + if (addedBy == null) { + ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("addedBy")); + return; + } - int code = requestBody.getInteger("totpCode"); - TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> addedBy.checkTotpAuthorization(code, null, v)); + int code = requestBody.getInteger("totpCode"); + TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> addedBy.checkTotpAuthorization(code, null, v)); - if (!totpAuthorizationResult.isAuthorized()) { - ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); - return; - } + if (!totpAuthorizationResult.isAuthorized()) { + ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); + return; + } - AccessToken accessToken = new AccessToken(actorName, actorType, lockedIps); - SyncUtils.runBlocking(v -> accessToken.insert(v)); + AccessToken accessToken = new AccessToken(actorName, actorType, lockedIps); + SyncUtils.runBlocking(v -> accessToken.insert(v)); - AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.ACCESS_TOKEN_CREATE, ImmutableMap.of("accessTokenActorName", actorName), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, accessToken); - } - }); - } + AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.ACCESS_TOKEN_CREATE, ImmutableMap.of("accessTokenActorName", actorName), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, accessToken); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/auditLog/DELETEAuditLogId.java b/src/main/java/net/frozenorb/apiv3/route/auditLog/DELETEAuditLogId.java index 099d18f..662be3d 100644 --- a/src/main/java/net/frozenorb/apiv3/route/auditLog/DELETEAuditLogId.java +++ b/src/main/java/net/frozenorb/apiv3/route/auditLog/DELETEAuditLogId.java @@ -14,34 +14,34 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEAuditLogId implements Handler { - public void handle(RoutingContext ctx) { - AuditLogEntry auditLogEntry = SyncUtils.runBlocking(v -> AuditLogEntry.findById(ctx.request().getParam("auditLogEntryId"), v)); + public void handle(RoutingContext ctx) { + AuditLogEntry auditLogEntry = SyncUtils.runBlocking(v -> AuditLogEntry.findById(ctx.request().getParam("auditLogEntryId"), v)); - if (auditLogEntry == null) { - ErrorUtils.respondNotFound(ctx, "Audit log entry", ctx.request().getParam("auditLogEntryId")); - return; - } + if (auditLogEntry == null) { + ErrorUtils.respondNotFound(ctx, "Audit log entry", ctx.request().getParam("auditLogEntryId")); + return; + } - if (!auditLogEntry.isReversible()) { - ErrorUtils.respondInvalidInput(ctx, "Audit log entry referenced is not reversible."); - return; - } + if (!auditLogEntry.isReversible()) { + ErrorUtils.respondInvalidInput(ctx, "Audit log entry referenced is not reversible."); + return; + } - SyncUtils.runBlocking(v -> auditLogEntry.getType().reverse(auditLogEntry, v)); + SyncUtils.runBlocking(v -> auditLogEntry.getType().reverse(auditLogEntry, v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("revertedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("revertedBy")), requestBody.getString("revertedByIp"), ctx, AuditLogActionType.AUDIT_LOG_REVERT, ImmutableMap.of("auditLogEntryId", auditLogEntry.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, auditLogEntry); - } - }); - } else { - APIv3.respondJson(ctx, 200, auditLogEntry); - } - } + if (requestBody.containsKey("revertedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("revertedBy")), requestBody.getString("revertedByIp"), ctx, AuditLogActionType.AUDIT_LOG_REVERT, ImmutableMap.of("auditLogEntryId", auditLogEntry.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, auditLogEntry); + } + }); + } else { + APIv3.respondJson(ctx, 200, auditLogEntry); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/auditLog/GETAuditLog.java b/src/main/java/net/frozenorb/apiv3/route/auditLog/GETAuditLog.java index 1e9cb7d..26c9b85 100644 --- a/src/main/java/net/frozenorb/apiv3/route/auditLog/GETAuditLog.java +++ b/src/main/java/net/frozenorb/apiv3/route/auditLog/GETAuditLog.java @@ -10,21 +10,21 @@ import org.bson.Document; public final class GETAuditLog implements Handler { - public void handle(RoutingContext ctx) { - try { - int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); - int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); + public void handle(RoutingContext ctx) { + try { + int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); + int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); - AuditLogEntry.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (auditLog, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, auditLog); - } - }); - } catch (NumberFormatException ignored) { - ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); - } - } + AuditLogEntry.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (auditLog, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, auditLog); + } + }); + } catch (NumberFormatException ignored) { + ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/auditLog/POSTAuditLog.java b/src/main/java/net/frozenorb/apiv3/route/auditLog/POSTAuditLog.java index 0cb4997..d2437da 100644 --- a/src/main/java/net/frozenorb/apiv3/route/auditLog/POSTAuditLog.java +++ b/src/main/java/net/frozenorb/apiv3/route/auditLog/POSTAuditLog.java @@ -12,44 +12,44 @@ import net.frozenorb.apiv3.util.IpUtils; public final class POSTAuditLog implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); - User.findById(requestBody.getString("user"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - return; - } + User.findById(requestBody.getString("user"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + return; + } - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); + return; + } - String userIp = requestBody.getString("userIp"); + String userIp = requestBody.getString("userIp"); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); + return; + } - AuditLogActionType type; + AuditLogActionType type; - try { - type = AuditLogActionType.valueOf(requestBody.getString("type")); - } catch (IllegalArgumentException ignored) { - ErrorUtils.respondNotFound(ctx, "Audit log action type", requestBody.getString("type")); - return; - } + try { + type = AuditLogActionType.valueOf(requestBody.getString("type")); + } catch (IllegalArgumentException ignored) { + ErrorUtils.respondNotFound(ctx, "Audit log action type", requestBody.getString("type")); + return; + } - AuditLog.log(user.getId(), userIp, ctx, type, requestBody.getJsonObject("metadata").getMap(), (auditLogEntry, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, auditLogEntry); - } - }); - }); - } + AuditLog.log(user.getId(), userIp, ctx, type, requestBody.getJsonObject("metadata").getMap(), (auditLogEntry, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, auditLogEntry); + } + }); + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/DELETEBannedAsnsId.java b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/DELETEBannedAsnsId.java index b77f0ed..2cdece5 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/DELETEBannedAsnsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/DELETEBannedAsnsId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEBannedAsnsId implements Handler { - public void handle(RoutingContext ctx) { - BannedAsn bannedAsn = BannedAsn.findById(Integer.parseInt(ctx.request().getParam("bannedAsn"))); + public void handle(RoutingContext ctx) { + BannedAsn bannedAsn = BannedAsn.findById(Integer.parseInt(ctx.request().getParam("bannedAsn"))); - if (bannedAsn == null) { - ErrorUtils.respondNotFound(ctx, "Banned asn", ctx.request().getParam("bannedAsn")); - return; - } + if (bannedAsn == null) { + ErrorUtils.respondNotFound(ctx, "Banned asn", ctx.request().getParam("bannedAsn")); + return; + } - SyncUtils.runBlocking(v -> bannedAsn.delete(v)); + SyncUtils.runBlocking(v -> bannedAsn.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.BANNED_ASN_DELETE, ImmutableMap.of("bannedAsnId", bannedAsn.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, bannedAsn); - } - }); - } else { - APIv3.respondJson(ctx, 200, bannedAsn); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.BANNED_ASN_DELETE, ImmutableMap.of("bannedAsnId", bannedAsn.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, bannedAsn); + } + }); + } else { + APIv3.respondJson(ctx, 200, bannedAsn); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsns.java b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsns.java index d92edbe..6149813 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsns.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsns.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedAsn; public final class GETBannedAsns implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, BannedAsn.findAll()); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, BannedAsn.findAll()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsnsId.java b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsnsId.java index f6e90a4..08b0bd4 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsnsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/GETBannedAsnsId.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedAsn; public final class GETBannedAsnsId implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, BannedAsn.findById(Integer.parseInt(ctx.request().getParam("bannedAsn")))); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, BannedAsn.findById(Integer.parseInt(ctx.request().getParam("bannedAsn")))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/POSTBannedAsns.java b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/POSTBannedAsns.java index 79900d5..fbdb9e7 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedAsns/POSTBannedAsns.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedAsns/POSTBannedAsns.java @@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTBannedAsns implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - int id = requestBody.getInteger("id"); - String note = requestBody.getString("note"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + int id = requestBody.getInteger("id"); + String note = requestBody.getString("note"); - BannedAsn bannedAsn = new BannedAsn(id, note); - SyncUtils.runBlocking(v -> bannedAsn.insert(v)); + BannedAsn bannedAsn = new BannedAsn(id, note); + SyncUtils.runBlocking(v -> bannedAsn.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.BANNED_ASN_CREATE, ImmutableMap.of("bannedAsnId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, bannedAsn); - } - }); - } else { - APIv3.respondJson(ctx, 200, bannedAsn); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.BANNED_ASN_CREATE, ImmutableMap.of("bannedAsnId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, bannedAsn); + } + }); + } else { + APIv3.respondJson(ctx, 200, bannedAsn); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/DELETEBannedCellCarriersId.java b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/DELETEBannedCellCarriersId.java index abd14cf..fcd2771 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/DELETEBannedCellCarriersId.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/DELETEBannedCellCarriersId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEBannedCellCarriersId implements Handler { - public void handle(RoutingContext ctx) { - BannedCellCarrier bannedCellCarrier = BannedCellCarrier.findById(Integer.parseInt(ctx.request().getParam("bannedCellCarrier"))); + public void handle(RoutingContext ctx) { + BannedCellCarrier bannedCellCarrier = BannedCellCarrier.findById(Integer.parseInt(ctx.request().getParam("bannedCellCarrier"))); - if (bannedCellCarrier == null) { - ErrorUtils.respondNotFound(ctx, "Banned cell carrier", ctx.request().getParam("bannedCellCarrier")); - return; - } + if (bannedCellCarrier == null) { + ErrorUtils.respondNotFound(ctx, "Banned cell carrier", ctx.request().getParam("bannedCellCarrier")); + return; + } - SyncUtils.runBlocking(v -> bannedCellCarrier.delete(v)); + SyncUtils.runBlocking(v -> bannedCellCarrier.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.BANNED_CALL_CARRIER_DELETE, ImmutableMap.of("bannedCellCarrierId", bannedCellCarrier.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, bannedCellCarrier); - } - }); - } else { - APIv3.respondJson(ctx, 200, bannedCellCarrier); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.BANNED_CALL_CARRIER_DELETE, ImmutableMap.of("bannedCellCarrierId", bannedCellCarrier.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, bannedCellCarrier); + } + }); + } else { + APIv3.respondJson(ctx, 200, bannedCellCarrier); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriers.java b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriers.java index 23643c6..5f49e80 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriers.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriers.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedCellCarrier; public final class GETBannedCellCarriers implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, BannedCellCarrier.findAll()); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, BannedCellCarrier.findAll()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriersId.java b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriersId.java index 9379186..b025c40 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriersId.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/GETBannedCellCarriersId.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedCellCarrier; public final class GETBannedCellCarriersId implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, BannedCellCarrier.findById(Integer.parseInt(ctx.request().getParam("bannedCellCarrier")))); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, BannedCellCarrier.findById(Integer.parseInt(ctx.request().getParam("bannedCellCarrier")))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/POSTBannedCellCarriers.java b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/POSTBannedCellCarriers.java index bbf0023..1f02d37 100644 --- a/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/POSTBannedCellCarriers.java +++ b/src/main/java/net/frozenorb/apiv3/route/bannedCellCarriers/POSTBannedCellCarriers.java @@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTBannedCellCarriers implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - int id = requestBody.getInteger("id"); - String note = requestBody.getString("note"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + int id = requestBody.getInteger("id"); + String note = requestBody.getString("note"); - BannedCellCarrier bannedCellCarrier = new BannedCellCarrier(id, note); - SyncUtils.runBlocking(v -> bannedCellCarrier.insert(v)); + BannedCellCarrier bannedCellCarrier = new BannedCellCarrier(id, note); + SyncUtils.runBlocking(v -> bannedCellCarrier.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.BANNED_CALL_CARRIER_CREATE, ImmutableMap.of("bannedCellCarrierId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, bannedCellCarrier); - } - }); - } else { - APIv3.respondJson(ctx, 200, bannedCellCarrier); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.BANNED_CALL_CARRIER_CREATE, ImmutableMap.of("bannedCellCarrierId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, bannedCellCarrier); + } + }); + } else { + APIv3.respondJson(ctx, 200, bannedCellCarrier); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/chatFilter/DELETEChatFilterId.java b/src/main/java/net/frozenorb/apiv3/route/chatFilter/DELETEChatFilterId.java index fad690a..b1150eb 100644 --- a/src/main/java/net/frozenorb/apiv3/route/chatFilter/DELETEChatFilterId.java +++ b/src/main/java/net/frozenorb/apiv3/route/chatFilter/DELETEChatFilterId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEChatFilterId implements Handler { - public void handle(RoutingContext ctx) { - ChatFilterEntry chatFilterEntry = SyncUtils.runBlocking(v -> ChatFilterEntry.findById(ctx.request().getParam("chatFilterEntryId"), v)); + public void handle(RoutingContext ctx) { + ChatFilterEntry chatFilterEntry = SyncUtils.runBlocking(v -> ChatFilterEntry.findById(ctx.request().getParam("chatFilterEntryId"), v)); - if (chatFilterEntry == null) { - ErrorUtils.respondNotFound(ctx, "Chat filter entry", ctx.request().getParam("chatFilterEntryId")); - return; - } + if (chatFilterEntry == null) { + ErrorUtils.respondNotFound(ctx, "Chat filter entry", ctx.request().getParam("chatFilterEntryId")); + return; + } - SyncUtils.runBlocking(v -> chatFilterEntry.delete(v)); + SyncUtils.runBlocking(v -> chatFilterEntry.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.CHAT_FILTER_ENTRY_DELETE, ImmutableMap.of("chatFilterEntryId", chatFilterEntry.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, chatFilterEntry); - } - }); - } else { - APIv3.respondJson(ctx, 200, chatFilterEntry); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.CHAT_FILTER_ENTRY_DELETE, ImmutableMap.of("chatFilterEntryId", chatFilterEntry.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, chatFilterEntry); + } + }); + } else { + APIv3.respondJson(ctx, 200, chatFilterEntry); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilter.java b/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilter.java index ade5335..906017a 100644 --- a/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilter.java +++ b/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilter.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETChatFilter implements Handler { - public void handle(RoutingContext ctx) { - ChatFilterEntry.findAll((chatFilterEntries, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, chatFilterEntries); - } - }); - } + public void handle(RoutingContext ctx) { + ChatFilterEntry.findAll((chatFilterEntries, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, chatFilterEntries); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilterId.java b/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilterId.java index aee2950..3613bc8 100644 --- a/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilterId.java +++ b/src/main/java/net/frozenorb/apiv3/route/chatFilter/GETChatFilterId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETChatFilterId implements Handler { - public void handle(RoutingContext ctx) { - ChatFilterEntry.findById(ctx.request().getParam("chatFilterEntryId"), (notificationTemplate, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - }); - } + public void handle(RoutingContext ctx) { + ChatFilterEntry.findById(ctx.request().getParam("chatFilterEntryId"), (notificationTemplate, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/chatFilter/POSTChatFilter.java b/src/main/java/net/frozenorb/apiv3/route/chatFilter/POSTChatFilter.java index 8592846..af80dff 100644 --- a/src/main/java/net/frozenorb/apiv3/route/chatFilter/POSTChatFilter.java +++ b/src/main/java/net/frozenorb/apiv3/route/chatFilter/POSTChatFilter.java @@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTChatFilter implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String id = requestBody.getString("id"); - String regex = requestBody.getString("regex"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String id = requestBody.getString("id"); + String regex = requestBody.getString("regex"); - ChatFilterEntry chatFilterEntry = new ChatFilterEntry(id, regex); - SyncUtils.runBlocking(v -> chatFilterEntry.insert(v)); + ChatFilterEntry chatFilterEntry = new ChatFilterEntry(id, regex); + SyncUtils.runBlocking(v -> chatFilterEntry.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.CHAT_FILTER_ENTRY_CREATE, ImmutableMap.of("chatFilterEntryId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, chatFilterEntry); - } - }); - } else { - APIv3.respondJson(ctx, 200, chatFilterEntry); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.CHAT_FILTER_ENTRY_CREATE, ImmutableMap.of("chatFilterEntryId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, chatFilterEntry); + } + }); + } else { + APIv3.respondJson(ctx, 200, chatFilterEntry); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/emailTokens/GETEmailTokensIdOwner.java b/src/main/java/net/frozenorb/apiv3/route/emailTokens/GETEmailTokensIdOwner.java index 00d10dd..3a36756 100644 --- a/src/main/java/net/frozenorb/apiv3/route/emailTokens/GETEmailTokensIdOwner.java +++ b/src/main/java/net/frozenorb/apiv3/route/emailTokens/GETEmailTokensIdOwner.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETEmailTokensIdOwner implements Handler { - public void handle(RoutingContext ctx) { - User.findByEmailToken(ctx.request().getParam("emailToken"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, user); - } - }); - } + public void handle(RoutingContext ctx) { + User.findByEmailToken(ctx.request().getParam("emailToken"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, user); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/emailTokens/POSTEmailTokensIdConfirm.java b/src/main/java/net/frozenorb/apiv3/route/emailTokens/POSTEmailTokensIdConfirm.java index 1953d45..08e82e1 100644 --- a/src/main/java/net/frozenorb/apiv3/route/emailTokens/POSTEmailTokensIdConfirm.java +++ b/src/main/java/net/frozenorb/apiv3/route/emailTokens/POSTEmailTokensIdConfirm.java @@ -15,45 +15,45 @@ import java.util.concurrent.TimeUnit; public final class POSTEmailTokensIdConfirm implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findByEmailToken(ctx.request().getParam("emailToken"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findByEmailToken(ctx.request().getParam("emailToken"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "Email token", ctx.request().getParam("emailToken")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "Email token", ctx.request().getParam("emailToken")); + return; + } - if (user.getEmail() != null) { - ErrorUtils.respondOther(ctx, 409, "User provided already has email set.", "emailAlreadySet", ImmutableMap.of()); - return; - } + if (user.getEmail() != null) { + ErrorUtils.respondOther(ctx, 409, "User provided already has email set.", "emailAlreadySet", ImmutableMap.of()); + return; + } - if ((System.currentTimeMillis() - user.getPendingEmailTokenSetAt().toEpochMilli()) > TimeUnit.DAYS.toMillis(2)) { - ErrorUtils.respondInvalidInput(ctx, "Email token is expired"); - return; - } + if ((System.currentTimeMillis() - user.getPendingEmailTokenSetAt().toEpochMilli()) > TimeUnit.DAYS.toMillis(2)) { + ErrorUtils.respondInvalidInput(ctx, "Email token is expired"); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String password = requestBody.getString("password"); + JsonObject requestBody = ctx.getBodyAsJson(); + String password = requestBody.getString("password"); - if (password.length() < 8) { - ErrorUtils.respondInvalidInput(ctx, "Your password is too short."); - return; - } + if (password.length() < 8) { + ErrorUtils.respondInvalidInput(ctx, "Your password is too short."); + return; + } - user.completeEmailRegistration(user.getPendingEmail()); - user.updatePassword(password); - SyncUtils.runBlocking(v -> user.save(v)); + user.completeEmailRegistration(user.getPendingEmail()); + user.updatePassword(password); + SyncUtils.runBlocking(v -> user.save(v)); - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CONFIRM_EMAIL, (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CONFIRM_EMAIL, (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/grants/DELETEGrantsId.java b/src/main/java/net/frozenorb/apiv3/route/grants/DELETEGrantsId.java index 3e62b63..9214fcf 100644 --- a/src/main/java/net/frozenorb/apiv3/route/grants/DELETEGrantsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/grants/DELETEGrantsId.java @@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils; public final class DELETEGrantsId implements Handler { - public void handle(RoutingContext ctx) { - Grant grant = SyncUtils.runBlocking(v -> Grant.findById(ctx.request().getParam("grantId"), v)); + public void handle(RoutingContext ctx) { + Grant grant = SyncUtils.runBlocking(v -> Grant.findById(ctx.request().getParam("grantId"), v)); - if (grant == null) { - ErrorUtils.respondNotFound(ctx, "Grant", ctx.request().getParam("grantId")); - return; - } else if (!grant.isActive()) { - ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive grant."); - return; - } + if (grant == null) { + ErrorUtils.respondNotFound(ctx, "Grant", ctx.request().getParam("grantId")); + return; + } else if (!grant.isActive()) { + ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive grant."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - // We purposely don't do a null check, grant removals don't have to have a user/ip. - User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); - String reason = requestBody.getString("reason"); + JsonObject requestBody = ctx.getBodyAsJson(); + // We purposely don't do a null check, grant removals don't have to have a user/ip. + User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - SyncUtils.runBlocking(v -> grant.delete(removedBy, reason, v)); + SyncUtils.runBlocking(v -> grant.delete(removedBy, reason, v)); - if (removedBy != null) { - AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.GRANT_DELETE, ImmutableMap.of("grantId", grant.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, grant); - } - }); - } else { - APIv3.respondJson(ctx, 200, grant); - } - } + if (removedBy != null) { + AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.GRANT_DELETE, ImmutableMap.of("grantId", grant.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, grant); + } + }); + } else { + APIv3.respondJson(ctx, 200, grant); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/grants/GETGrants.java b/src/main/java/net/frozenorb/apiv3/route/grants/GETGrants.java index d507f6f..9492355 100644 --- a/src/main/java/net/frozenorb/apiv3/route/grants/GETGrants.java +++ b/src/main/java/net/frozenorb/apiv3/route/grants/GETGrants.java @@ -12,22 +12,22 @@ import java.util.stream.Collectors; public final class GETGrants implements Handler { - public void handle(RoutingContext ctx) { - try { - int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); - int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); + public void handle(RoutingContext ctx) { + try { + int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); + int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); - Grant.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (grants, error) -> { - if (ctx.request().getParam("active") != null) { - boolean requireActive = Boolean.parseBoolean(ctx.request().getParam("active")); - APIv3.respondJson(ctx, 200, grants.stream().filter(grant -> grant.isActive() == requireActive).collect(Collectors.toList())); - } else { - APIv3.respondJson(ctx, 200, grants); - } - }); - } catch (NumberFormatException ignored) { - ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); - } - } + Grant.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (grants, error) -> { + if (ctx.request().getParam("active") != null) { + boolean requireActive = Boolean.parseBoolean(ctx.request().getParam("active")); + APIv3.respondJson(ctx, 200, grants.stream().filter(grant -> grant.isActive() == requireActive).collect(Collectors.toList())); + } else { + APIv3.respondJson(ctx, 200, grants); + } + }); + } catch (NumberFormatException ignored) { + ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/grants/GETGrantsId.java b/src/main/java/net/frozenorb/apiv3/route/grants/GETGrantsId.java index 024f756..0cff261 100644 --- a/src/main/java/net/frozenorb/apiv3/route/grants/GETGrantsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/grants/GETGrantsId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETGrantsId implements Handler { - public void handle(RoutingContext ctx) { - Grant.findById(ctx.request().getParam("grantId"), (grant, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, grant); - } - }); - } + public void handle(RoutingContext ctx) { + Grant.findById(ctx.request().getParam("grantId"), (grant, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, grant); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/grants/POSTGrants.java b/src/main/java/net/frozenorb/apiv3/route/grants/POSTGrants.java index 6e12494..6d510ea 100644 --- a/src/main/java/net/frozenorb/apiv3/route/grants/POSTGrants.java +++ b/src/main/java/net/frozenorb/apiv3/route/grants/POSTGrants.java @@ -22,87 +22,87 @@ import java.util.Set; public final class POSTGrants implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - User target = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("user"), v)); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + User target = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("user"), v)); - if (target == null) { - ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); - return; - } + if (target == null) { + ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); + return; + } - String reason = requestBody.getString("reason"); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - Set scopes = new HashSet<>(); - List scopeIds = (List) requestBody.getJsonArray("scopes").getList(); + Set scopes = new HashSet<>(); + List scopeIds = (List) requestBody.getJsonArray("scopes").getList(); - if (!scopeIds.isEmpty()) { - for (String serverGroupId : scopeIds) { - ServerGroup serverGroup = ServerGroup.findById(serverGroupId); + if (!scopeIds.isEmpty()) { + for (String serverGroupId : scopeIds) { + ServerGroup serverGroup = ServerGroup.findById(serverGroupId); - if (serverGroup == null) { - ErrorUtils.respondNotFound(ctx, "Server group", serverGroupId); - return; - } + if (serverGroup == null) { + ErrorUtils.respondNotFound(ctx, "Server group", serverGroupId); + return; + } - scopes.add(serverGroup); - } - } + scopes.add(serverGroup); + } + } - Rank rank = Rank.findById(requestBody.getString("rank")); + Rank rank = Rank.findById(requestBody.getString("rank")); - if (rank == null) { - ErrorUtils.respondNotFound(ctx, "Rank", requestBody.getString("rank")); - return; - } + if (rank == null) { + ErrorUtils.respondNotFound(ctx, "Rank", requestBody.getString("rank")); + return; + } - Instant expiresAt = null; + Instant expiresAt = null; - if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { - long expiresInMillis = requestBody.getLong("expiresIn") * 1000; - expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); - } + if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { + long expiresInMillis = requestBody.getLong("expiresIn") * 1000; + expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); + } - if (expiresAt != null && expiresAt.isBefore(Instant.now())) { - ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); - return; - } + if (expiresAt != null && expiresAt.isBefore(Instant.now())) { + ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); + return; + } - // We purposely don't fail on a null check, grants don't have to have a source. - User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); + // We purposely don't fail on a null check, grants don't have to have a source. + User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); - if (addedBy != null && rank.isHigherStaffRank()) { - int code = requestBody.getInteger("totpCode"); - TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> addedBy.checkTotpAuthorization(code, null, v)); + if (addedBy != null && rank.isHigherStaffRank()) { + int code = requestBody.getInteger("totpCode"); + TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> addedBy.checkTotpAuthorization(code, null, v)); - if (!totpAuthorizationResult.isAuthorized()) { - ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); - return; - } - } + if (!totpAuthorizationResult.isAuthorized()) { + ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); + return; + } + } - int storeItemId = requestBody.getInteger("storeItemId", -1); - int storeOrderId = requestBody.getInteger("storeOrderId", -1); + int storeItemId = requestBody.getInteger("storeItemId", -1); + int storeOrderId = requestBody.getInteger("storeOrderId", -1); - Grant grant = new Grant(target, reason, scopes, rank, expiresAt, addedBy, storeItemId, storeOrderId); - SyncUtils.runBlocking(v -> grant.insert(v)); + Grant grant = new Grant(target, reason, scopes, rank, expiresAt, addedBy, storeItemId, storeOrderId); + SyncUtils.runBlocking(v -> grant.insert(v)); - if (addedBy != null) { - AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.GRANT_CREATE, ImmutableMap.of("grantId", grant.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, grant); - } - }); - } else { - APIv3.respondJson(ctx, 200, grant); - } - } + if (addedBy != null) { + AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.GRANT_CREATE, ImmutableMap.of("grantId", grant.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, grant); + } + }); + } else { + APIv3.respondJson(ctx, 200, grant); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipBans/DELETEIpBansId.java b/src/main/java/net/frozenorb/apiv3/route/ipBans/DELETEIpBansId.java index 04c7bb4..5ac18cf 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipBans/DELETEIpBansId.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipBans/DELETEIpBansId.java @@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils; public final class DELETEIpBansId implements Handler { - public void handle(RoutingContext ctx) { - IpBan ipBan = SyncUtils.runBlocking(v -> IpBan.findById(ctx.request().getParam("ipBanId"), v)); + public void handle(RoutingContext ctx) { + IpBan ipBan = SyncUtils.runBlocking(v -> IpBan.findById(ctx.request().getParam("ipBanId"), v)); - if (ipBan == null) { - ErrorUtils.respondNotFound(ctx, "IpBan", ctx.request().getParam("ipBanId")); - return; - } else if (!ipBan.isActive()) { - ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive ip ban."); - return; - } + if (ipBan == null) { + ErrorUtils.respondNotFound(ctx, "IpBan", ctx.request().getParam("ipBanId")); + return; + } else if (!ipBan.isActive()) { + ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive ip ban."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - // We purposely don't do a null check, ip ban removals don't have to have a user/ip. - User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); - String reason = requestBody.getString("reason"); + JsonObject requestBody = ctx.getBodyAsJson(); + // We purposely don't do a null check, ip ban removals don't have to have a user/ip. + User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - SyncUtils.runBlocking(v -> ipBan.delete(removedBy, reason, v)); + SyncUtils.runBlocking(v -> ipBan.delete(removedBy, reason, v)); - if (removedBy != null) { - AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.IP_BAN_DELETE, ImmutableMap.of("punishmentId", ipBan.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipBan); - } - }); - } else { - APIv3.respondJson(ctx, 200, ipBan); - } - } + if (removedBy != null) { + AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.IP_BAN_DELETE, ImmutableMap.of("punishmentId", ipBan.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipBan); + } + }); + } else { + APIv3.respondJson(ctx, 200, ipBan); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBans.java b/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBans.java index 3431310..4a72242 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBans.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBans.java @@ -10,21 +10,21 @@ import org.bson.Document; public final class GETIpBans implements Handler { - public void handle(RoutingContext ctx) { - try { - int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); - int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); + public void handle(RoutingContext ctx) { + try { + int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); + int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); - IpBan.findPaginated(ctx.request().getParam("userIp") == null ? new Document() : new Document("userIp", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (grants, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, grants); - } - }); - } catch (NumberFormatException ignored) { - ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); - } - } + IpBan.findPaginated(ctx.request().getParam("userIp") == null ? new Document() : new Document("userIp", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (grants, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, grants); + } + }); + } catch (NumberFormatException ignored) { + ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBansId.java b/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBansId.java index 09a1a2b..c2c0889 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBansId.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipBans/GETIpBansId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETIpBansId implements Handler { - public void handle(RoutingContext ctx) { - IpBan.findById(ctx.request().getParam("ipBanId"), (ipBan, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipBan); - } - }); - } + public void handle(RoutingContext ctx) { + IpBan.findById(ctx.request().getParam("ipBanId"), (ipBan, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipBan); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipBans/POSTIpBans.java b/src/main/java/net/frozenorb/apiv3/route/ipBans/POSTIpBans.java index 15dc7b8..32ab057 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipBans/POSTIpBans.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipBans/POSTIpBans.java @@ -17,51 +17,51 @@ import java.time.Instant; public final class POSTIpBans implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String userIp = requestBody.getString("userIp"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String userIp = requestBody.getString("userIp"); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); + return; + } - String reason = requestBody.getString("reason"); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - Instant expiresAt = null; + Instant expiresAt = null; - if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { - long expiresInMillis = requestBody.getLong("expiresIn") * 1000; - expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); - } + if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { + long expiresInMillis = requestBody.getLong("expiresIn") * 1000; + expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); + } - if (expiresAt != null && expiresAt.isBefore(Instant.now())) { - ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); - return; - } + if (expiresAt != null && expiresAt.isBefore(Instant.now())) { + ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); + return; + } - // We purposely don't do a null check, ip bans don't have to have a source. - User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); + // We purposely don't do a null check, ip bans don't have to have a source. + User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); - IpBan ipBan = new IpBan(userIp, reason, expiresAt, addedBy, ctx.get("actor")); - SyncUtils.runBlocking(v -> ipBan.insert(v)); + IpBan ipBan = new IpBan(userIp, reason, expiresAt, addedBy, ctx.get("actor")); + SyncUtils.runBlocking(v -> ipBan.insert(v)); - if (addedBy != null) { - AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.IP_BAN_CREATE, ImmutableMap.of("ipBanId", ipBan.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipBan); - } - }); - } else { - APIv3.respondJson(ctx, 200, ipBan); - } - } + if (addedBy != null) { + AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.IP_BAN_CREATE, ImmutableMap.of("ipBanId", ipBan.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipBan); + } + }); + } else { + APIv3.respondJson(ctx, 200, ipBan); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipIntel/GETIpInteld.java b/src/main/java/net/frozenorb/apiv3/route/ipIntel/GETIpInteld.java index a70bad3..e5f4e0d 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipIntel/GETIpInteld.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipIntel/GETIpInteld.java @@ -9,21 +9,21 @@ import net.frozenorb.apiv3.util.IpUtils; public final class GETIpInteld implements Handler { - public void handle(RoutingContext ctx) { - String userIp = ctx.request().getParam("userIp"); + public void handle(RoutingContext ctx) { + String userIp = ctx.request().getParam("userIp"); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); + return; + } - IpIntel.findOrCreateById(userIp, (ipIntel, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipIntel); - } - }); - } + IpIntel.findOrCreateById(userIp, (ipIntel, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipIntel); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ipLog/GETIpLogId.java b/src/main/java/net/frozenorb/apiv3/route/ipLog/GETIpLogId.java index 8d4278d..b374406 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ipLog/GETIpLogId.java +++ b/src/main/java/net/frozenorb/apiv3/route/ipLog/GETIpLogId.java @@ -9,34 +9,34 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETIpLogId implements Handler { - public void handle(RoutingContext ctx) { - String search = ctx.request().getParam("id"); + public void handle(RoutingContext ctx) { + String search = ctx.request().getParam("id"); - if (search.length() >= 32) { - User.findById(search, (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", search); - } else { - IpLogEntry.findByUser(user, (ipLog, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, ipLog); - } - }); - } - }); - } else { - IpLogEntry.findByIp(search, (ipLogs, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipLogs); - } - }); - } - } + if (search.length() >= 32) { + User.findById(search, (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", search); + } else { + IpLogEntry.findByUser(user, (ipLog, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, ipLog); + } + }); + } + }); + } else { + IpLogEntry.findByIp(search, (ipLogs, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipLogs); + } + }); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/DELETENotificationTemplatesId.java b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/DELETENotificationTemplatesId.java index 758f847..2a538dc 100644 --- a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/DELETENotificationTemplatesId.java +++ b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/DELETENotificationTemplatesId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETENotificationTemplatesId implements Handler { - public void handle(RoutingContext ctx) { - NotificationTemplate notificationTemplate = SyncUtils.runBlocking(v -> NotificationTemplate.findById(ctx.request().getParam("notificationTemplateId"), v)); + public void handle(RoutingContext ctx) { + NotificationTemplate notificationTemplate = SyncUtils.runBlocking(v -> NotificationTemplate.findById(ctx.request().getParam("notificationTemplateId"), v)); - if (notificationTemplate == null) { - ErrorUtils.respondNotFound(ctx, "Notification template", ctx.request().getParam("notificationTemplateId")); - return; - } + if (notificationTemplate == null) { + ErrorUtils.respondNotFound(ctx, "Notification template", ctx.request().getParam("notificationTemplateId")); + return; + } - SyncUtils.runBlocking(v -> notificationTemplate.delete(v)); + SyncUtils.runBlocking(v -> notificationTemplate.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.NOTIFICATION_TEMPLATE_DELETE, ImmutableMap.of("notificationTemplateId", notificationTemplate.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - }); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.NOTIFICATION_TEMPLATE_DELETE, ImmutableMap.of("notificationTemplateId", notificationTemplate.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + }); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplates.java b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplates.java index 108a3a7..978278f 100644 --- a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplates.java +++ b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplates.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETNotificationTemplates implements Handler { - public void handle(RoutingContext ctx) { - NotificationTemplate.findAll((notificationTemplates, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, notificationTemplates); - } - }); - } + public void handle(RoutingContext ctx) { + NotificationTemplate.findAll((notificationTemplates, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, notificationTemplates); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplatesId.java b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplatesId.java index e0c6bf7..66084ab 100644 --- a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplatesId.java +++ b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/GETNotificationTemplatesId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETNotificationTemplatesId implements Handler { - public void handle(RoutingContext ctx) { - NotificationTemplate.findById(ctx.request().getParam("notificationTemplateId"), (notificationTemplate, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - }); - } + public void handle(RoutingContext ctx) { + NotificationTemplate.findById(ctx.request().getParam("notificationTemplateId"), (notificationTemplate, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/POSTNotificationTemplates.java b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/POSTNotificationTemplates.java index 1040446..2889da6 100644 --- a/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/POSTNotificationTemplates.java +++ b/src/main/java/net/frozenorb/apiv3/route/notificationTemplates/POSTNotificationTemplates.java @@ -14,26 +14,26 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTNotificationTemplates implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String id = requestBody.getString("id"); - String subject = requestBody.getString("subject"); - String body = requestBody.getString("body"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String id = requestBody.getString("id"); + String subject = requestBody.getString("subject"); + String body = requestBody.getString("body"); - NotificationTemplate notificationTemplate = new NotificationTemplate(id, subject, body); - SyncUtils.runBlocking(v -> notificationTemplate.insert(v)); + NotificationTemplate notificationTemplate = new NotificationTemplate(id, subject, body); + SyncUtils.runBlocking(v -> notificationTemplate.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.NOTIFICATION_TEMPLATE_CREATE, ImmutableMap.of("notificationTemplateId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - }); - } else { - APIv3.respondJson(ctx, 200, notificationTemplate); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.NOTIFICATION_TEMPLATE_CREATE, ImmutableMap.of("notificationTemplateId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + }); + } else { + APIv3.respondJson(ctx, 200, notificationTemplate); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/phoneIntel/GETPhoneInteld.java b/src/main/java/net/frozenorb/apiv3/route/phoneIntel/GETPhoneInteld.java index 363183c..72ef811 100644 --- a/src/main/java/net/frozenorb/apiv3/route/phoneIntel/GETPhoneInteld.java +++ b/src/main/java/net/frozenorb/apiv3/route/phoneIntel/GETPhoneInteld.java @@ -9,21 +9,21 @@ import net.frozenorb.apiv3.util.PhoneUtils; public final class GETPhoneInteld implements Handler { - public void handle(RoutingContext ctx) { - String phoneNumber = ctx.request().getParam("phone"); + public void handle(RoutingContext ctx) { + String phoneNumber = ctx.request().getParam("phone"); - if (!PhoneUtils.isValidPhone(phoneNumber)) { - ErrorUtils.respondInvalidInput(ctx, "Phone number \"" + phoneNumber + "\" is not valid."); - return; - } + if (!PhoneUtils.isValidPhone(phoneNumber)) { + ErrorUtils.respondInvalidInput(ctx, "Phone number \"" + phoneNumber + "\" is not valid."); + return; + } - PhoneIntel.findOrCreateById(phoneNumber, (ipIntel, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ipIntel); - } - }); - } + PhoneIntel.findOrCreateById(phoneNumber, (ipIntel, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ipIntel); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEPunishmentsId.java b/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEPunishmentsId.java index 17a1661..598362c 100644 --- a/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEPunishmentsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEPunishmentsId.java @@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils; public final class DELETEPunishmentsId implements Handler { - public void handle(RoutingContext ctx) { - Punishment punishment = SyncUtils.runBlocking(v -> Punishment.findById(ctx.request().getParam("punishmentId"), v)); + public void handle(RoutingContext ctx) { + Punishment punishment = SyncUtils.runBlocking(v -> Punishment.findById(ctx.request().getParam("punishmentId"), v)); - if (punishment == null) { - ErrorUtils.respondNotFound(ctx, "Punishment", ctx.request().getParam("punishmentId")); - return; - } else if (!punishment.isActive()) { - ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive punishment."); - return; - } + if (punishment == null) { + ErrorUtils.respondNotFound(ctx, "Punishment", ctx.request().getParam("punishmentId")); + return; + } else if (!punishment.isActive()) { + ErrorUtils.respondInvalidInput(ctx, "Cannot remove an inactive punishment."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - // We purposely don't do a null check, punishment removals don't have to have a user/ip. - User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); - String reason = requestBody.getString("reason"); + JsonObject requestBody = ctx.getBodyAsJson(); + // We purposely don't do a null check, punishment removals don't have to have a user/ip. + User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - SyncUtils.runBlocking(v -> punishment.delete(removedBy, reason, v)); + SyncUtils.runBlocking(v -> punishment.delete(removedBy, reason, v)); - if (removedBy != null) { - AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.PUNISHMENT_DELETE, ImmutableMap.of("punishmentId", punishment.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, punishment); - } - }); - } else { - APIv3.respondJson(ctx, 200, punishment); - } - } + if (removedBy != null) { + AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.PUNISHMENT_DELETE, ImmutableMap.of("punishmentId", punishment.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, punishment); + } + }); + } else { + APIv3.respondJson(ctx, 200, punishment); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEUsersIdActivePunishment.java b/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEUsersIdActivePunishment.java index b705702..53a642e 100644 --- a/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEUsersIdActivePunishment.java +++ b/src/main/java/net/frozenorb/apiv3/route/punishments/DELETEUsersIdActivePunishment.java @@ -17,54 +17,54 @@ import java.util.List; public final class DELETEUsersIdActivePunishment implements Handler { - public void handle(RoutingContext ctx) { - User target = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User target = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (target == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (target == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - Punishment.PunishmentType type = Punishment.PunishmentType.valueOf(requestBody.getString("type").toUpperCase()); - // We purposely don't do a null check, punishment removals don't have to have a user/ip. - User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); - String reason = requestBody.getString("reason"); + JsonObject requestBody = ctx.getBodyAsJson(); + Punishment.PunishmentType type = Punishment.PunishmentType.valueOf(requestBody.getString("type").toUpperCase()); + // We purposely don't do a null check, punishment removals don't have to have a user/ip. + User removedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("removedBy"), v)); + String reason = requestBody.getString("reason"); - if (reason == null || reason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "reason"); - return; - } + if (reason == null || reason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "reason"); + return; + } - List punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v)); - Punishment activePunishment = null; + List punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v)); + Punishment activePunishment = null; - for (Punishment punishment : punishments) { - if (punishment.isActive()) { - activePunishment = punishment; - break; - } - } + for (Punishment punishment : punishments) { + if (punishment.isActive()) { + activePunishment = punishment; + break; + } + } - if (activePunishment == null) { - ErrorUtils.respondOther(ctx, 409, "User provided has no active punishments.", "noActivePunishments", ImmutableMap.of()); - return; - } + if (activePunishment == null) { + ErrorUtils.respondOther(ctx, 409, "User provided has no active punishments.", "noActivePunishments", ImmutableMap.of()); + return; + } - Punishment finalActivePunishment = activePunishment; - SyncUtils.runBlocking(v -> finalActivePunishment.delete(removedBy, reason, v)); + Punishment finalActivePunishment = activePunishment; + SyncUtils.runBlocking(v -> finalActivePunishment.delete(removedBy, reason, v)); - if (removedBy != null) { - AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.PUNISHMENT_DELETE, ImmutableMap.of("punishmentId", activePunishment.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, finalActivePunishment); - } - }); - } else { - APIv3.respondJson(ctx, 200, finalActivePunishment); - } - } + if (removedBy != null) { + AuditLog.log(removedBy.getId(), requestBody.getString("removedByIp"), ctx, AuditLogActionType.PUNISHMENT_DELETE, ImmutableMap.of("punishmentId", activePunishment.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, finalActivePunishment); + } + }); + } else { + APIv3.respondJson(ctx, 200, finalActivePunishment); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishments.java b/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishments.java index 1fd1f30..68d28e6 100644 --- a/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishments.java +++ b/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishments.java @@ -12,26 +12,26 @@ import java.util.stream.Collectors; public final class GETPunishments implements Handler { - public void handle(RoutingContext ctx) { - try { - int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); - int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); + public void handle(RoutingContext ctx) { + try { + int skip = ctx.request().getParam("skip") == null ? 0 : Integer.parseInt(ctx.request().getParam("skip")); + int pageSize = ctx.request().getParam("pageSize") == null ? 100 : Integer.parseInt(ctx.request().getParam("pageSize")); - Punishment.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (punishments, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - if (ctx.request().getParam("active") != null) { - boolean requireActive = Boolean.parseBoolean(ctx.request().getParam("active")); - APIv3.respondJson(ctx, 200, punishments.stream().filter(punishment -> punishment.isActive() == requireActive).collect(Collectors.toList())); - } else { - APIv3.respondJson(ctx, 200, punishments); - } - } - }); - } catch (NumberFormatException ignored) { - ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); - } - } + Punishment.findPaginated(ctx.request().getParam("user") == null ? new Document() : new Document("user", UuidUtils.parseUuid(ctx.request().getParam("user"))), skip, pageSize, (punishments, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + if (ctx.request().getParam("active") != null) { + boolean requireActive = Boolean.parseBoolean(ctx.request().getParam("active")); + APIv3.respondJson(ctx, 200, punishments.stream().filter(punishment -> punishment.isActive() == requireActive).collect(Collectors.toList())); + } else { + APIv3.respondJson(ctx, 200, punishments); + } + } + }); + } catch (NumberFormatException ignored) { + ErrorUtils.respondInvalidInput(ctx, "skip and pageSize must be numerical inputs."); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishmentsId.java b/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishmentsId.java index c0baeed..b1b212a 100644 --- a/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishmentsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/punishments/GETPunishmentsId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETPunishmentsId implements Handler { - public void handle(RoutingContext ctx) { - Punishment.findById(ctx.request().getParam("punishmentId"), (punishment, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, punishment); - } - }); - } + public void handle(RoutingContext ctx) { + Punishment.findById(ctx.request().getParam("punishmentId"), (punishment, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, punishment); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/punishments/POSTPunishments.java b/src/main/java/net/frozenorb/apiv3/route/punishments/POSTPunishments.java index 616f820..a024cc4 100644 --- a/src/main/java/net/frozenorb/apiv3/route/punishments/POSTPunishments.java +++ b/src/main/java/net/frozenorb/apiv3/route/punishments/POSTPunishments.java @@ -21,100 +21,100 @@ import java.util.Map; public final class POSTPunishments implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - User target = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("user"), v)); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + User target = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("user"), v)); - if (target == null) { - ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); - return; - } + if (target == null) { + ErrorUtils.respondNotFound(ctx, "User", requestBody.getString("user")); + return; + } - String publicReason = requestBody.getString("publicReason"); - String privateReason = requestBody.getString("privateReason"); + String publicReason = requestBody.getString("publicReason"); + String privateReason = requestBody.getString("privateReason"); - if (publicReason == null || publicReason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "publicReason"); - return; - } + if (publicReason == null || publicReason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "publicReason"); + return; + } - if (privateReason == null || privateReason.trim().isEmpty()) { - ErrorUtils.respondRequiredInput(ctx, "privateReason"); - return; - } + if (privateReason == null || privateReason.trim().isEmpty()) { + ErrorUtils.respondRequiredInput(ctx, "privateReason"); + return; + } - Punishment.PunishmentType type = Punishment.PunishmentType.valueOf(requestBody.getString("type")); + Punishment.PunishmentType type = Punishment.PunishmentType.valueOf(requestBody.getString("type")); - if (type != Punishment.PunishmentType.WARN) { - List punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v)); + if (type != Punishment.PunishmentType.WARN) { + List punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v)); - for (Punishment alternatePunishment : punishments) { - if (alternatePunishment.isActive()) { - User user = SyncUtils.runBlocking(v -> User.findById(alternatePunishment.getAddedBy(), v)); - ErrorUtils.respondOther(ctx, 409, "User already covered by alternate punishment.", "alreadyCoveredByAlternatePunishment", ImmutableMap.of("alternatePunishmentBy", user.getLastUsername())); - return; - } - } - } + for (Punishment alternatePunishment : punishments) { + if (alternatePunishment.isActive()) { + User user = SyncUtils.runBlocking(v -> User.findById(alternatePunishment.getAddedBy(), v)); + ErrorUtils.respondOther(ctx, 409, "User already covered by alternate punishment.", "alreadyCoveredByAlternatePunishment", ImmutableMap.of("alternatePunishmentBy", user.getLastUsername())); + return; + } + } + } - Instant expiresAt = null; + Instant expiresAt = null; - if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { - long expiresInMillis = requestBody.getLong("expiresIn") * 1000; - expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); - } + if (requestBody.containsKey("expiresIn") && requestBody.getLong("expiresIn") != -1) { + long expiresInMillis = requestBody.getLong("expiresIn") * 1000; + expiresAt = Instant.ofEpochMilli(System.currentTimeMillis() + expiresInMillis); + } - if (expiresAt != null && expiresAt.isBefore(Instant.now())) { - ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); - return; - } + if (expiresAt != null && expiresAt.isBefore(Instant.now())) { + ErrorUtils.respondInvalidInput(ctx, "Expiration time cannot be in the past."); + return; + } - Map meta = requestBody.getJsonObject("metadata").getMap(); + Map meta = requestBody.getJsonObject("metadata").getMap(); - if (meta == null) { - ErrorUtils.respondRequiredInput(ctx, "request body meta"); - return; - } + if (meta == null) { + ErrorUtils.respondRequiredInput(ctx, "request body meta"); + return; + } - // We purposely don't do a null check, punishments don't have to have a source. - User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); - boolean isProtected = SyncUtils.runBlocking(v -> target.hasPermissionAnywhere(Permissions.PROTECTED_PUNISHMENT, v)); + // We purposely don't do a null check, punishments don't have to have a source. + User addedBy = SyncUtils.runBlocking(v -> User.findById(requestBody.getString("addedBy"), v)); + boolean isProtected = SyncUtils.runBlocking(v -> target.hasPermissionAnywhere(Permissions.PROTECTED_PUNISHMENT, v)); - if (isProtected) { - ErrorUtils.respondOther(ctx, 409, "User is protected from punishments.", "protectedFromPunishments", ImmutableMap.of()); - return; - } + if (isProtected) { + ErrorUtils.respondOther(ctx, 409, "User is protected from punishments.", "protectedFromPunishments", ImmutableMap.of()); + return; + } - Punishment punishment = new Punishment(target, publicReason, privateReason, type, expiresAt, addedBy, ctx.get("actor"), meta); - String accessDenialReason = punishment.getAccessDenialReason(); - String userIp = requestBody.getString("userIp"); + Punishment punishment = new Punishment(target, publicReason, privateReason, type, expiresAt, addedBy, ctx.get("actor"), meta); + String accessDenialReason = punishment.getAccessDenialReason(); + String userIp = requestBody.getString("userIp"); - if ((type == Punishment.PunishmentType.BAN || type == Punishment.PunishmentType.BLACKLIST) && userIp != null) { - IpBan ipBan = new IpBan(userIp, punishment); - SyncUtils.runBlocking(v -> ipBan.insert(v)); + if ((type == Punishment.PunishmentType.BAN || type == Punishment.PunishmentType.BLACKLIST) && userIp != null) { + IpBan ipBan = new IpBan(userIp, punishment); + SyncUtils.runBlocking(v -> ipBan.insert(v)); - punishment.linkIpBan(ipBan); - } + punishment.linkIpBan(ipBan); + } - SyncUtils.runBlocking(v -> punishment.insert(v)); + SyncUtils.runBlocking(v -> punishment.insert(v)); - if (addedBy != null) { - AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.PUNISHMENT_CREATE, ImmutableMap.of("punishmentId", punishment.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "punishment", punishment, - "accessDenialReason", accessDenialReason == null ? "" : accessDenialReason - )); - } - }); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "punishment", punishment, - "accessDenialReason", accessDenialReason == null ? "" : accessDenialReason - )); - } - } + if (addedBy != null) { + AuditLog.log(addedBy.getId(), requestBody.getString("addedByIp"), ctx, AuditLogActionType.PUNISHMENT_CREATE, ImmutableMap.of("punishmentId", punishment.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "punishment", punishment, + "accessDenialReason", accessDenialReason == null ? "" : accessDenialReason + )); + } + }); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "punishment", punishment, + "accessDenialReason", accessDenialReason == null ? "" : accessDenialReason + )); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ranks/DELETERanksId.java b/src/main/java/net/frozenorb/apiv3/route/ranks/DELETERanksId.java index aaab43e..d8c87f8 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ranks/DELETERanksId.java +++ b/src/main/java/net/frozenorb/apiv3/route/ranks/DELETERanksId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETERanksId implements Handler { - public void handle(RoutingContext ctx) { - Rank rank = Rank.findById(ctx.request().getParam("rankId")); + public void handle(RoutingContext ctx) { + Rank rank = Rank.findById(ctx.request().getParam("rankId")); - if (rank == null) { - ErrorUtils.respondNotFound(ctx, "Rank", ctx.request().getParam("rankId")); - return; - } + if (rank == null) { + ErrorUtils.respondNotFound(ctx, "Rank", ctx.request().getParam("rankId")); + return; + } - SyncUtils.runBlocking(v -> rank.delete(v)); + SyncUtils.runBlocking(v -> rank.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.RANK_DELETE, ImmutableMap.of("rankId", rank.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, rank); - } - }); - } else { - APIv3.respondJson(ctx, 200, rank); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.RANK_DELETE, ImmutableMap.of("rankId", rank.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, rank); + } + }); + } else { + APIv3.respondJson(ctx, 200, rank); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanks.java b/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanks.java index 94c75d3..c1204b7 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanks.java +++ b/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanks.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Rank; public final class GETRanks implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, Rank.findAll()); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, Rank.findAll()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanksId.java b/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanksId.java index f57515f..b66e347 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanksId.java +++ b/src/main/java/net/frozenorb/apiv3/route/ranks/GETRanksId.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Rank; public final class GETRanksId implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, Rank.findById(ctx.request().getParam("rankId"))); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, Rank.findById(ctx.request().getParam("rankId"))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/ranks/POSTRanks.java b/src/main/java/net/frozenorb/apiv3/route/ranks/POSTRanks.java index 32364c2..69e904a 100644 --- a/src/main/java/net/frozenorb/apiv3/route/ranks/POSTRanks.java +++ b/src/main/java/net/frozenorb/apiv3/route/ranks/POSTRanks.java @@ -14,31 +14,31 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTRanks implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String id = requestBody.getString("id"); - String inheritsFromId = requestBody.getString("inheritsFromId"); - int weight = requestBody.getInteger("weight"); - String displayName = requestBody.getString("displayName"); - String gameColor = requestBody.getString("gameColor"); - String websiteColor = requestBody.getString("websiteColor"); - boolean staffRank = requestBody.getBoolean("staffRank"); - boolean higherStaffRank = requestBody.getBoolean("higherStaffRank"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String id = requestBody.getString("id"); + String inheritsFromId = requestBody.getString("inheritsFromId"); + int weight = requestBody.getInteger("weight"); + String displayName = requestBody.getString("displayName"); + String gameColor = requestBody.getString("gameColor"); + String websiteColor = requestBody.getString("websiteColor"); + boolean staffRank = requestBody.getBoolean("staffRank"); + boolean higherStaffRank = requestBody.getBoolean("higherStaffRank"); - Rank rank = new Rank(id, inheritsFromId, weight, displayName, gameColor, websiteColor, staffRank, higherStaffRank); - SyncUtils.runBlocking(v -> rank.insert(v)); + Rank rank = new Rank(id, inheritsFromId, weight, displayName, gameColor, websiteColor, staffRank, higherStaffRank); + SyncUtils.runBlocking(v -> rank.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.RANK_CREATE, ImmutableMap.of("rankId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, rank); - } - }); - } else { - APIv3.respondJson(ctx, 200, rank); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.RANK_CREATE, ImmutableMap.of("rankId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, rank); + } + }); + } else { + APIv3.respondJson(ctx, 200, rank); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/serverGroups/DELETEServerGroupsId.java b/src/main/java/net/frozenorb/apiv3/route/serverGroups/DELETEServerGroupsId.java index c4e9d35..8623c00 100644 --- a/src/main/java/net/frozenorb/apiv3/route/serverGroups/DELETEServerGroupsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/serverGroups/DELETEServerGroupsId.java @@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEServerGroupsId implements Handler { - public void handle(RoutingContext ctx) { - ServerGroup serverGroup = ServerGroup.findById(ctx.request().getParam("serverGroupId")); + public void handle(RoutingContext ctx) { + ServerGroup serverGroup = ServerGroup.findById(ctx.request().getParam("serverGroupId")); - if (serverGroup == null) { - ErrorUtils.respondNotFound(ctx, "Server group", ctx.request().getParam("serverGroupId")); - return; - } + if (serverGroup == null) { + ErrorUtils.respondNotFound(ctx, "Server group", ctx.request().getParam("serverGroupId")); + return; + } - SyncUtils.runBlocking(v -> serverGroup.delete(v)); + SyncUtils.runBlocking(v -> serverGroup.delete(v)); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("emovedBy")), requestBody.getString("emovedByIp"), ctx, AuditLogActionType.SERVER_GROUP_DELETE, ImmutableMap.of("serverGroupId", serverGroup.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, serverGroup); - } - }); - } else { - APIv3.respondJson(ctx, 200, serverGroup); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("emovedBy")), requestBody.getString("emovedByIp"), ctx, AuditLogActionType.SERVER_GROUP_DELETE, ImmutableMap.of("serverGroupId", serverGroup.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, serverGroup); + } + }); + } else { + APIv3.respondJson(ctx, 200, serverGroup); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroups.java b/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroups.java index 28452b1..bd36ad3 100644 --- a/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroups.java +++ b/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroups.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.ServerGroup; public final class GETServerGroups implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, ServerGroup.findAll()); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, ServerGroup.findAll()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroupsId.java b/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroupsId.java index ac22424..ef23bdc 100644 --- a/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroupsId.java +++ b/src/main/java/net/frozenorb/apiv3/route/serverGroups/GETServerGroupsId.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.ServerGroup; public final class GETServerGroupsId implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, ServerGroup.findById(ctx.request().getParam("serverGroupId"))); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, ServerGroup.findById(ctx.request().getParam("serverGroupId"))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/serverGroups/POSTServerGroups.java b/src/main/java/net/frozenorb/apiv3/route/serverGroups/POSTServerGroups.java index 8895668..998f53d 100644 --- a/src/main/java/net/frozenorb/apiv3/route/serverGroups/POSTServerGroups.java +++ b/src/main/java/net/frozenorb/apiv3/route/serverGroups/POSTServerGroups.java @@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTServerGroups implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String id = requestBody.getString("id"); - String image = requestBody.getString("image"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String id = requestBody.getString("id"); + String image = requestBody.getString("image"); - ServerGroup serverGroup = new ServerGroup(id, image); - SyncUtils.runBlocking(v -> serverGroup.insert(v)); + ServerGroup serverGroup = new ServerGroup(id, image); + SyncUtils.runBlocking(v -> serverGroup.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.SERVER_GROUP_CREATE, ImmutableMap.of("serverGroupId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, serverGroup); - } - }); - } else { - APIv3.respondJson(ctx, 200, serverGroup); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.SERVER_GROUP_CREATE, ImmutableMap.of("serverGroupId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, serverGroup); + } + }); + } else { + APIv3.respondJson(ctx, 200, serverGroup); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/servers/DELETEServersId.java b/src/main/java/net/frozenorb/apiv3/route/servers/DELETEServersId.java index 6b49a77..70e36ef 100644 --- a/src/main/java/net/frozenorb/apiv3/route/servers/DELETEServersId.java +++ b/src/main/java/net/frozenorb/apiv3/route/servers/DELETEServersId.java @@ -16,47 +16,47 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class DELETEServersId implements Handler { - public void handle(RoutingContext ctx) { - Server server = Server.findById(ctx.request().getParam("serverId")); + public void handle(RoutingContext ctx) { + Server server = Server.findById(ctx.request().getParam("serverId")); - if (server == null) { - ErrorUtils.respondNotFound(ctx, "Server", ctx.request().getParam("serverId")); - return; - } + if (server == null) { + ErrorUtils.respondNotFound(ctx, "Server", ctx.request().getParam("serverId")); + return; + } - SyncUtils.runBlocking(v -> server.insert(v)); + SyncUtils.runBlocking(v -> server.insert(v)); - SyncUtils.runBlocking(v -> { - AccessToken.findByNameAndType(server.getId(), ActorType.SERVER, (accessToken, error) -> { - if (error != null) { - v.onResult(null, error); - } else if (accessToken != null) { - accessToken.delete((ignored, error2) -> { - if (error2 != null) { - v.onResult(null, error2); - } else { - v.onResult(null, null); - } - }); - } else { - v.onResult(null, new NullPointerException("Access token not found.")); - } - }); - }); + SyncUtils.runBlocking(v -> { + AccessToken.findByNameAndType(server.getId(), ActorType.SERVER, (accessToken, error) -> { + if (error != null) { + v.onResult(null, error); + } else if (accessToken != null) { + accessToken.delete((ignored, error2) -> { + if (error2 != null) { + v.onResult(null, error2); + } else { + v.onResult(null, null); + } + }); + } else { + v.onResult(null, new NullPointerException("Access token not found.")); + } + }); + }); - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (requestBody.containsKey("removedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.SERVER_DELETE, ImmutableMap.of("serverId", server.getId()), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, server); - } - }); - } else { - APIv3.respondJson(ctx, 200, server); - } - } + if (requestBody.containsKey("removedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("removedBy")), requestBody.getString("removedByIp"), ctx, AuditLogActionType.SERVER_DELETE, ImmutableMap.of("serverId", server.getId()), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, server); + } + }); + } else { + APIv3.respondJson(ctx, 200, server); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/servers/GETServers.java b/src/main/java/net/frozenorb/apiv3/route/servers/GETServers.java index df5f752..df20de0 100644 --- a/src/main/java/net/frozenorb/apiv3/route/servers/GETServers.java +++ b/src/main/java/net/frozenorb/apiv3/route/servers/GETServers.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Server; public final class GETServers implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, Server.findAll()); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, Server.findAll()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/servers/GETServersId.java b/src/main/java/net/frozenorb/apiv3/route/servers/GETServersId.java index db9d2e6..5b11f89 100644 --- a/src/main/java/net/frozenorb/apiv3/route/servers/GETServersId.java +++ b/src/main/java/net/frozenorb/apiv3/route/servers/GETServersId.java @@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Server; public final class GETServersId implements Handler { - public void handle(RoutingContext ctx) { - APIv3.respondJson(ctx, 200, Server.findById(ctx.request().getParam("serverId"))); - } + public void handle(RoutingContext ctx) { + APIv3.respondJson(ctx, 200, Server.findById(ctx.request().getParam("serverId"))); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/servers/POSTServers.java b/src/main/java/net/frozenorb/apiv3/route/servers/POSTServers.java index fe65b56..df60094 100644 --- a/src/main/java/net/frozenorb/apiv3/route/servers/POSTServers.java +++ b/src/main/java/net/frozenorb/apiv3/route/servers/POSTServers.java @@ -17,42 +17,42 @@ import net.frozenorb.apiv3.util.UuidUtils; public final class POSTServers implements Handler { - public void handle(RoutingContext ctx) { - JsonObject requestBody = ctx.getBodyAsJson(); - String id = requestBody.getString("id"); - String displayName = requestBody.getString("displayName"); - ServerGroup group = ServerGroup.findById(requestBody.getString("group")); - String ip = requestBody.getString("ip"); + public void handle(RoutingContext ctx) { + JsonObject requestBody = ctx.getBodyAsJson(); + String id = requestBody.getString("id"); + String displayName = requestBody.getString("displayName"); + ServerGroup group = ServerGroup.findById(requestBody.getString("group")); + String ip = requestBody.getString("ip"); - if (group == null) { - ErrorUtils.respondNotFound(ctx, "Server group", requestBody.getString("group")); - return; - } + if (group == null) { + ErrorUtils.respondNotFound(ctx, "Server group", requestBody.getString("group")); + return; + } - String ipHost = ip.split(":")[0]; + String ipHost = ip.split(":")[0]; - if (!IpUtils.isValidIp(ipHost)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + ip + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(ipHost)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + ip + "\" is not valid."); + return; + } - Server server = new Server(id, displayName, group, ip); - SyncUtils.runBlocking(v -> server.insert(v)); + Server server = new Server(id, displayName, group, ip); + SyncUtils.runBlocking(v -> server.insert(v)); - AccessToken accessToken = new AccessToken(server); - SyncUtils.runBlocking(v -> accessToken.insert(v)); + AccessToken accessToken = new AccessToken(server); + SyncUtils.runBlocking(v -> accessToken.insert(v)); - if (requestBody.containsKey("addedBy")) { - AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.SERVER_CREATE, ImmutableMap.of("serverId", id), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, server); - } - }); - } else { - APIv3.respondJson(ctx, 200, server); - } - } + if (requestBody.containsKey("addedBy")) { + AuditLog.log(UuidUtils.parseUuid(requestBody.getString("addedBy")), requestBody.getString("addedByIp"), ctx, AuditLogActionType.SERVER_CREATE, ImmutableMap.of("serverId", id), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, server); + } + }); + } else { + APIv3.respondJson(ctx, 200, server); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/servers/POSTServersHeartbeat.java b/src/main/java/net/frozenorb/apiv3/route/servers/POSTServersHeartbeat.java index 8412e06..d003da0 100644 --- a/src/main/java/net/frozenorb/apiv3/route/servers/POSTServersHeartbeat.java +++ b/src/main/java/net/frozenorb/apiv3/route/servers/POSTServersHeartbeat.java @@ -23,221 +23,221 @@ import java.util.*; @Slf4j public final class POSTServersHeartbeat implements Handler { - public void handle(RoutingContext ctx) { - Actor actor = ctx.get("actor"); + public void handle(RoutingContext ctx) { + Actor actor = ctx.get("actor"); - if (actor.getType() != ActorType.SERVER) { - ErrorUtils.respondOther(ctx, 403, "This action can only be performed when requested by a server.", "serverOnly", ImmutableMap.of()); - return; - } + if (actor.getType() != ActorType.SERVER) { + ErrorUtils.respondOther(ctx, 403, "This action can only be performed when requested by a server.", "serverOnly", ImmutableMap.of()); + return; + } - Server actorServer = Server.findById(actor.getName()); - JsonObject requestBody = ctx.getBodyAsJson(); - JsonObject players = requestBody.getJsonObject("players"); - Map playerNames = extractPlayerNames(players); - Map playerIps = extractPlayerIps(players); + Server actorServer = Server.findById(actor.getName()); + JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject players = requestBody.getJsonObject("players"); + Map playerNames = extractPlayerNames(players); + Map playerIps = extractPlayerIps(players); - CompositeFuture.all( - createInfoResponse(actorServer, requestBody.getDouble("lastTps"), playerNames), - createPlayerResponse(actorServer, playerNames, playerIps), - createPermissionsResponse(ServerGroup.findById(actorServer.getServerGroup())), - createEventsResponse(actorServer, requestBody.getJsonArray("events")) - ).setHandler((result) -> { - if (result.succeeded()) { - // We don't do anything with the info callback, as - // it's just to update our database. - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "players", result.result().result(1), - "permissions", result.result().result(2), - "events", result.result().result(3) - )); - } else { - ErrorUtils.respondInternalError(ctx, result.cause()); - } - }); - } + CompositeFuture.all( + createInfoResponse(actorServer, requestBody.getDouble("lastTps"), playerNames), + createPlayerResponse(actorServer, playerNames, playerIps), + createPermissionsResponse(ServerGroup.findById(actorServer.getServerGroup())), + createEventsResponse(actorServer, requestBody.getJsonArray("events")) + ).setHandler((result) -> { + if (result.succeeded()) { + // We don't do anything with the info callback, as + // it's just to update our database. + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "players", result.result().result(1), + "permissions", result.result().result(2), + "events", result.result().result(3) + )); + } else { + ErrorUtils.respondInternalError(ctx, result.cause()); + } + }); + } - private Future createInfoResponse(Server server, double tps, Map playerNames) { - Future callback = Future.future(); + private Future createInfoResponse(Server server, double tps, Map playerNames) { + Future callback = Future.future(); - server.receivedHeartbeat(tps, playerNames.keySet()); - server.save((ignored, error) -> { - if (error != null) { - callback.fail(error); - } else { - callback.complete(); - } - }); + server.receivedHeartbeat(tps, playerNames.keySet()); + server.save((ignored, error) -> { + if (error != null) { + callback.fail(error); + } else { + callback.complete(); + } + }); - return callback; - } + return callback; + } - private Future> createPlayerResponse(Server server, Map playerNames, Map playerIps) { - Future> callback = Future.future(); + private Future> createPlayerResponse(Server server, Map playerNames, Map playerIps) { + Future> callback = Future.future(); - Future> userLookupCallback = Future.future(); - Future> ipIntelCallback = Future.future(); - Future>> grantLookupCallback = Future.future(); - Future>> punishmentLookupCallback = Future.future(); + Future> userLookupCallback = Future.future(); + Future> ipIntelCallback = Future.future(); + Future>> grantLookupCallback = Future.future(); + Future>> punishmentLookupCallback = Future.future(); - User.findOrCreateByIdGrouped(playerNames, new MongoToVertxCallback<>(userLookupCallback)); - IpIntel.findOrCreateByIdGrouped(playerIps.values(), new MongoToVertxCallback<>(ipIntelCallback)); - Grant.findByUserGrouped(playerNames.keySet(), new MongoToVertxCallback<>(grantLookupCallback)); - Punishment.findByUserGrouped(playerNames.keySet(), new MongoToVertxCallback<>(punishmentLookupCallback)); + User.findOrCreateByIdGrouped(playerNames, new MongoToVertxCallback<>(userLookupCallback)); + IpIntel.findOrCreateByIdGrouped(playerIps.values(), new MongoToVertxCallback<>(ipIntelCallback)); + Grant.findByUserGrouped(playerNames.keySet(), new MongoToVertxCallback<>(grantLookupCallback)); + Punishment.findByUserGrouped(playerNames.keySet(), new MongoToVertxCallback<>(punishmentLookupCallback)); - CompositeFuture.all( - userLookupCallback, - ipIntelCallback, - grantLookupCallback, - punishmentLookupCallback - ).setHandler((batchLookupInfo) -> { - if (batchLookupInfo.failed()) { - callback.fail(batchLookupInfo.cause()); - return; - } + CompositeFuture.all( + userLookupCallback, + ipIntelCallback, + grantLookupCallback, + punishmentLookupCallback + ).setHandler((batchLookupInfo) -> { + if (batchLookupInfo.failed()) { + callback.fail(batchLookupInfo.cause()); + return; + } - Map users = batchLookupInfo.result().result(0); - Map ipIntel = batchLookupInfo.result().result(1); - Map> grants = batchLookupInfo.result().result(2); - Map> punishments = batchLookupInfo.result().result(3); - Map loginInfoFutures = new HashMap<>(); + Map users = batchLookupInfo.result().result(0); + Map ipIntel = batchLookupInfo.result().result(1); + Map> grants = batchLookupInfo.result().result(2); + Map> punishments = batchLookupInfo.result().result(3); + Map loginInfoFutures = new HashMap<>(); - users.forEach((uuid, user) -> { - Future> loginInfoFuture = Future.future(); - createLoginInfo(user, server, ipIntel.get(playerIps.get(uuid)), grants.get(uuid), punishments.get(uuid), loginInfoFuture); - loginInfoFutures.put(uuid, loginInfoFuture); - }); + users.forEach((uuid, user) -> { + Future> loginInfoFuture = Future.future(); + createLoginInfo(user, server, ipIntel.get(playerIps.get(uuid)), grants.get(uuid), punishments.get(uuid), loginInfoFuture); + loginInfoFutures.put(uuid, loginInfoFuture); + }); - CompositeFuture.all(ImmutableList.copyOf(loginInfoFutures.values())).setHandler((allLoginInfo) -> { - if (allLoginInfo.failed()) { - callback.fail(allLoginInfo.cause()); - return; - } + CompositeFuture.all(ImmutableList.copyOf(loginInfoFutures.values())).setHandler((allLoginInfo) -> { + if (allLoginInfo.failed()) { + callback.fail(allLoginInfo.cause()); + return; + } - Map response = new HashMap<>(); - loginInfoFutures.forEach((uuid, loginInfo) -> response.put(uuid.toString(), loginInfo.result())); - callback.complete(response); - }); - }); + Map response = new HashMap<>(); + loginInfoFutures.forEach((uuid, loginInfo) -> response.put(uuid.toString(), loginInfo.result())); + callback.complete(response); + }); + }); - return callback; - } + return callback; + } - private Future> createPermissionsResponse(ServerGroup serverGroup) { - Future> callback = Future.future(); - Map permissionsResponse = new HashMap<>(); + private Future> createPermissionsResponse(ServerGroup serverGroup) { + Future> callback = Future.future(); + Map permissionsResponse = new HashMap<>(); - for (Rank rank : Rank.findAll()) { - Map scopedPermissions = PermissionUtils.mergePermissions( - ServerGroup.findDefault().calculatePermissions(rank), - serverGroup.calculatePermissions(rank) - ); + for (Rank rank : Rank.findAll()) { + Map scopedPermissions = PermissionUtils.mergePermissions( + ServerGroup.findDefault().calculatePermissions(rank), + serverGroup.calculatePermissions(rank) + ); - permissionsResponse.put(rank.getId(), PermissionUtils.convertToList(scopedPermissions)); - } + permissionsResponse.put(rank.getId(), PermissionUtils.convertToList(scopedPermissions)); + } - callback.complete(permissionsResponse); - return callback; - } + callback.complete(permissionsResponse); + return callback; + } - private Future> createEventsResponse(Server server, JsonArray events) { - Future> callback = Future.future(); - List eventFutures = new ArrayList<>(); + private Future> createEventsResponse(Server server, JsonArray events) { + Future> callback = Future.future(); + List eventFutures = new ArrayList<>(); - for (Object event : events) { - JsonObject eventJson = (JsonObject) event; - String type = eventJson.getString("type"); + for (Object event : events) { + JsonObject eventJson = (JsonObject) event; + String type = eventJson.getString("type"); - switch (type) { - case "leave": - Future eventFuture = Future.future(); - eventFutures.add(eventFuture); + switch (type) { + case "leave": + Future eventFuture = Future.future(); + eventFutures.add(eventFuture); - User.findById(eventJson.getString("user"), ((user, error) -> { - if (error != null) { - eventFuture.fail(error); - return; - } + User.findById(eventJson.getString("user"), ((user, error) -> { + if (error != null) { + eventFuture.fail(error); + return; + } - if (user == null) { - eventFuture.complete(); - return; - } + if (user == null) { + eventFuture.complete(); + return; + } - if (!user.leftServer(server)) { - eventFuture.complete(); - return; - } + if (!user.leftServer(server)) { + eventFuture.complete(); + return; + } - user.save((ignored, saveError) -> { - if (saveError != null) { - eventFuture.fail(saveError); - } else { - eventFuture.complete(); - } - }); - })); + user.save((ignored, saveError) -> { + if (saveError != null) { + eventFuture.fail(saveError); + } else { + eventFuture.complete(); + } + }); + })); - break; - default: - log.warn("Recieved event with unknown type " + type + "."); - } - } + break; + default: + log.warn("Recieved event with unknown type " + type + "."); + } + } - CompositeFuture.all(eventFutures).setHandler((allEvents) -> { - if (allEvents.failed()) { - callback.fail(allEvents.cause()); - } else { - callback.complete(ImmutableMap.of()); - } - }); + CompositeFuture.all(eventFutures).setHandler((allEvents) -> { + if (allEvents.failed()) { + callback.fail(allEvents.cause()); + } else { + callback.complete(ImmutableMap.of()); + } + }); - return callback; - } + return callback; + } - private Map extractPlayerNames(JsonObject players) { - Map result = new HashMap<>(); + private Map extractPlayerNames(JsonObject players) { + Map result = new HashMap<>(); - players.forEach((entry) -> { - UUID uuid = UuidUtils.parseUuid(entry.getKey()); - JsonObject data = (JsonObject) entry.getValue(); + players.forEach((entry) -> { + UUID uuid = UuidUtils.parseUuid(entry.getKey()); + JsonObject data = (JsonObject) entry.getValue(); - if (UuidUtils.isAcceptableUuid(uuid)) { - result.put(uuid, data.getString("username")); - } - }); + if (UuidUtils.isAcceptableUuid(uuid)) { + result.put(uuid, data.getString("username")); + } + }); - return result; - } + return result; + } - private Map extractPlayerIps(JsonObject players) { - Map result = new HashMap<>(); + private Map extractPlayerIps(JsonObject players) { + Map result = new HashMap<>(); - players.forEach((entry) -> { - UUID uuid = UuidUtils.parseUuid(entry.getKey()); - JsonObject data = (JsonObject) entry.getValue(); + players.forEach((entry) -> { + UUID uuid = UuidUtils.parseUuid(entry.getKey()); + JsonObject data = (JsonObject) entry.getValue(); - if (UuidUtils.isAcceptableUuid(uuid)) { - result.put(uuid, data.getString("userIp")); - } - }); + if (UuidUtils.isAcceptableUuid(uuid)) { + result.put(uuid, data.getString("userIp")); + } + }); - return result; - } + return result; + } - private void createLoginInfo(User user, Server server, IpIntel ipIntel, List grants, List punishments, Future> callback) { - if (user.seenOnServer(server)) { - user.save((ignored, error) -> { - if (error != null) { - callback.fail(error); - return; - } + private void createLoginInfo(User user, Server server, IpIntel ipIntel, List grants, List punishments, Future> callback) { + if (user.seenOnServer(server)) { + user.save((ignored, error) -> { + if (error != null) { + callback.fail(error); + return; + } - user.getLoginInfo(server, ipIntel, punishments, ImmutableList.of(), grants, new MongoToVertxCallback<>(callback)); - }); - } else { - user.getLoginInfo(server, ipIntel, punishments, ImmutableList.of(), grants, new MongoToVertxCallback<>(callback)); - } - } + user.getLoginInfo(server, ipIntel, punishments, ImmutableList.of(), grants, new MongoToVertxCallback<>(callback)); + }); + } else { + user.getLoginInfo(server, ipIntel, punishments, ImmutableList.of(), grants, new MongoToVertxCallback<>(callback)); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETStaff.java b/src/main/java/net/frozenorb/apiv3/route/users/GETStaff.java index 429d1e5..034d982 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETStaff.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETStaff.java @@ -12,38 +12,38 @@ import java.util.*; public final class GETStaff implements Handler { - public void handle(RoutingContext ctx) { - Map staffRanks = new HashMap<>(); + public void handle(RoutingContext ctx) { + Map staffRanks = new HashMap<>(); - Rank.findAll().forEach(rank -> { - if (rank.isStaffRank()) { - staffRanks.put(rank.getId(), rank); - } - }); + Rank.findAll().forEach(rank -> { + if (rank.isStaffRank()) { + staffRanks.put(rank.getId(), rank); + } + }); - Map> result = new TreeMap<>((first, second) -> { - Rank firstRank = staffRanks.get(first); - Rank secondRank = staffRanks.get(second); + Map> result = new TreeMap<>((first, second) -> { + Rank firstRank = staffRanks.get(first); + Rank secondRank = staffRanks.get(second); - return Integer.compare(firstRank.getWeight(), secondRank.getWeight()); - }); + return Integer.compare(firstRank.getWeight(), secondRank.getWeight()); + }); - List staffGrants = SyncUtils.runBlocking(v -> Grant.findByRank(staffRanks.values(), v)); + List staffGrants = SyncUtils.runBlocking(v -> Grant.findByRank(staffRanks.values(), v)); - for (Grant staffGrant : staffGrants) { - if (staffGrant.isActive()) { - User user = SyncUtils.runBlocking(v -> User.findById(staffGrant.getId(), v)); - Rank rank = staffRanks.get(staffGrant.getRank()); + for (Grant staffGrant : staffGrants) { + if (staffGrant.isActive()) { + User user = SyncUtils.runBlocking(v -> User.findById(staffGrant.getId(), v)); + Rank rank = staffRanks.get(staffGrant.getRank()); - if (!result.containsKey(rank.getId())) { - result.put(rank.getId(), new HashSet<>()); - } + if (!result.containsKey(rank.getId())) { + result.put(rank.getId(), new HashSet<>()); + } - result.get(rank.getId()).add(user); - } - } + result.get(rank.getId()).add(user); + } + } - APIv3.respondJson(ctx, 200, result); - } + APIv3.respondJson(ctx, 200, result); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersId.java b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersId.java index 5cbccdb..136f4ad 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersId.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersId.java @@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils; public final class GETUsersId implements Handler { - public void handle(RoutingContext ctx) { - User.findById(ctx.request().getParam("userId"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, user); - } - }); - } + public void handle(RoutingContext ctx) { + User.findById(ctx.request().getParam("userId"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, user); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdCompoundedPermissions.java b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdCompoundedPermissions.java index ef4e52c..62b9075 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdCompoundedPermissions.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdCompoundedPermissions.java @@ -9,22 +9,22 @@ import net.frozenorb.apiv3.util.PermissionUtils; public final class GETUsersIdCompoundedPermissions implements Handler { - public void handle(RoutingContext ctx) { - User.findById(ctx.request().getParam("userId"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - } else { - user.getCompoundedPermissions((permissions, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, PermissionUtils.convertToList(permissions)); - } - }); - } - }); - } + public void handle(RoutingContext ctx) { + User.findById(ctx.request().getParam("userId"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + } else { + user.getCompoundedPermissions((permissions, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, PermissionUtils.convertToList(permissions)); + } + }); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdDetails.java b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdDetails.java index f58c8e4..cfaadd4 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdDetails.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdDetails.java @@ -16,27 +16,27 @@ import java.util.Map; public final class GETUsersIdDetails implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - List grants = SyncUtils.runBlocking(v -> Grant.findByUser(user, v)); - List ipLog = SyncUtils.runBlocking(v -> IpLogEntry.findByUser(user, v)); - List punishments = SyncUtils.runBlocking(v -> Punishment.findByUser(user, v)); - Map result = new HashMap<>(); + List grants = SyncUtils.runBlocking(v -> Grant.findByUser(user, v)); + List ipLog = SyncUtils.runBlocking(v -> IpLogEntry.findByUser(user, v)); + List punishments = SyncUtils.runBlocking(v -> Punishment.findByUser(user, v)); + Map result = new HashMap<>(); - result.put("user", user); - result.put("grants", grants); - result.put("ipLog", ipLog); - result.put("punishments", punishments); - result.put("aliases", user.getAliases()); - result.put("totpSetup", user.getTotpSecret() != null); + result.put("user", user); + result.put("grants", grants); + result.put("ipLog", ipLog); + result.put("punishments", punishments); + result.put("aliases", user.getAliases()); + result.put("totpSetup", user.getTotpSecret() != null); - APIv3.respondJson(ctx, 200, result); - } + APIv3.respondJson(ctx, 200, result); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdRequiresTotp.java b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdRequiresTotp.java index c1342c2..cde0ace 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdRequiresTotp.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdRequiresTotp.java @@ -11,36 +11,36 @@ import net.frozenorb.apiv3.util.IpUtils; public final class GETUsersIdRequiresTotp implements Handler { - public void handle(RoutingContext ctx) { - User.findById(ctx.request().getParam("userId"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - return; - } + public void handle(RoutingContext ctx) { + User.findById(ctx.request().getParam("userId"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + return; + } - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - String userIp = ctx.request().getParam("userIp"); + String userIp = ctx.request().getParam("userIp"); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); + return; + } - user.requiresTotpAuthorization(userIp, (requiresTotpResult, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "required", (requiresTotpResult == RequiresTotpResult.REQUIRED_NO_EXEMPTIONS), - "message", requiresTotpResult.name() - )); - } - }); - }); - } + user.requiresTotpAuthorization(userIp, (requiresTotpResult, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "required", (requiresTotpResult == RequiresTotpResult.REQUIRED_NO_EXEMPTIONS), + "message", requiresTotpResult.name() + )); + } + }); + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdVerifyPassword.java b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdVerifyPassword.java index 47a4562..4f5545a 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdVerifyPassword.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/GETUsersIdVerifyPassword.java @@ -16,48 +16,48 @@ import java.util.UUID; public final class GETUsersIdVerifyPassword implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - user = SyncUtils.runBlocking(v -> User.findByLastUsername(ctx.request().getParam("userId"), v)); - } + if (user == null) { + user = SyncUtils.runBlocking(v -> User.findByLastUsername(ctx.request().getParam("userId"), v)); + } - if (user == null) { - user = SyncUtils.runBlocking(v -> User.findByEmail(ctx.request().getParam("userId"), v)); - } + if (user == null) { + user = SyncUtils.runBlocking(v -> User.findByEmail(ctx.request().getParam("userId"), v)); + } - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getPassword() == null) { - ErrorUtils.respondInvalidInput(ctx, "User provided does not have password set."); - return; - } + if (user.getPassword() == null) { + ErrorUtils.respondInvalidInput(ctx, "User provided does not have password set."); + return; + } - final UUID finalUuid = user.getId(); - boolean authorized = user.checkPassword(ctx.request().getParam("password")); - String userIp = ctx.request().getParam("userIp"); + final UUID finalUuid = user.getId(); + boolean authorized = user.checkPassword(ctx.request().getParam("password")); + String userIp = ctx.request().getParam("userIp"); - AuditLog.log(user.getId(), userIp, ctx, authorized ? AuditLogActionType.USER_LOGIN_SUCCESS : AuditLogActionType.USER_LOGIN_FAIL, (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - Map result = new HashMap<>(); + AuditLog.log(user.getId(), userIp, ctx, authorized ? AuditLogActionType.USER_LOGIN_SUCCESS : AuditLogActionType.USER_LOGIN_FAIL, (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + Map result = new HashMap<>(); - result.put("authorized", authorized); - result.put("uuid", finalUuid); + result.put("authorized", authorized); + result.put("uuid", finalUuid); - if (authorized) { - String session = SyncUtils.runBlocking(v -> UserSessionUtils.createSession(finalUuid, userIp, v)); - result.put("session", session); - } + if (authorized) { + String session = SyncUtils.runBlocking(v -> UserSessionUtils.createSession(finalUuid, userIp, v)); + result.put("session", session); + } - APIv3.respondJson(ctx, 200, result); - } - }); - } + APIv3.respondJson(ctx, 200, result); + } + }); + } } diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdChangePassword.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdChangePassword.java index 2d9edae..0dc22b1 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdChangePassword.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdChangePassword.java @@ -18,71 +18,71 @@ import java.util.concurrent.TimeUnit; public final class POSTUsersIdChangePassword implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); + JsonObject requestBody = ctx.getBodyAsJson(); - if (user.getPassword() == null) { - ErrorUtils.respondInvalidInput(ctx, "User provided does not have password set."); - return; - } + if (user.getPassword() == null) { + ErrorUtils.respondInvalidInput(ctx, "User provided does not have password set."); + return; + } - boolean authorized = false; + boolean authorized = false; - if (user.checkPassword(requestBody.getString("currentPassword"))) { - RequiresTotpResult requiresTotp = SyncUtils.runBlocking(v -> user.requiresTotpAuthorization(null, v)); + if (user.checkPassword(requestBody.getString("currentPassword"))) { + RequiresTotpResult requiresTotp = SyncUtils.runBlocking(v -> user.requiresTotpAuthorization(null, v)); - if (requiresTotp == RequiresTotpResult.REQUIRED_NO_EXEMPTIONS) { - int code = requestBody.getInteger("totpCode"); - TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> user.checkTotpAuthorization(code, null, v)); + if (requiresTotp == RequiresTotpResult.REQUIRED_NO_EXEMPTIONS) { + int code = requestBody.getInteger("totpCode"); + TotpAuthorizationResult totpAuthorizationResult = SyncUtils.runBlocking(v -> user.checkTotpAuthorization(code, null, v)); - if (!totpAuthorizationResult.isAuthorized()) { - ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); - return; - } - } + if (!totpAuthorizationResult.isAuthorized()) { + ErrorUtils.respondInvalidInput(ctx, "Totp authorization failed: " + totpAuthorizationResult.name()); + return; + } + } - authorized = true; - } else if (user.getPasswordResetToken() != null && user.getPasswordResetToken().equals(requestBody.getString("passwordResetToken"))) { - if ((System.currentTimeMillis() - user.getPasswordResetTokenSetAt().toEpochMilli()) > TimeUnit.DAYS.toMillis(2)) { - ErrorUtils.respondOther(ctx, 409, "Password reset token is expired.", "passwordTokenExpired", ImmutableMap.of()); - return; - } + authorized = true; + } else if (user.getPasswordResetToken() != null && user.getPasswordResetToken().equals(requestBody.getString("passwordResetToken"))) { + if ((System.currentTimeMillis() - user.getPasswordResetTokenSetAt().toEpochMilli()) > TimeUnit.DAYS.toMillis(2)) { + ErrorUtils.respondOther(ctx, 409, "Password reset token is expired.", "passwordTokenExpired", ImmutableMap.of()); + return; + } - authorized = true; - } + authorized = true; + } - if (!authorized) { - ErrorUtils.respondInvalidInput(ctx, "Could not authorize password change."); - return; - } + if (!authorized) { + ErrorUtils.respondInvalidInput(ctx, "Could not authorize password change."); + return; + } - String newPassword = requestBody.getString("newPassword"); + String newPassword = requestBody.getString("newPassword"); - if (newPassword.length() < 8) { - ErrorUtils.respondInvalidInput(ctx, "Password is too short."); - return; - } + if (newPassword.length() < 8) { + ErrorUtils.respondInvalidInput(ctx, "Password is too short."); + return; + } - user.updatePassword(newPassword); - SyncUtils.runBlocking(v -> user.save(v)); - SyncUtils.runBlocking(v -> UserSessionUtils.invalidateAllSessions(user.getId(), v)); + user.updatePassword(newPassword); + SyncUtils.runBlocking(v -> user.save(v)); + SyncUtils.runBlocking(v -> UserSessionUtils.invalidateAllSessions(user.getId(), v)); - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CHANGE_PASSWORD, (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CHANGE_PASSWORD, (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } } diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdConfirmPhone.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdConfirmPhone.java index c232a2a..8d3b26c 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdConfirmPhone.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdConfirmPhone.java @@ -15,62 +15,62 @@ import java.util.concurrent.TimeUnit; public final class POSTUsersIdConfirmPhone implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getPhone() != null) { - ErrorUtils.respondOther(ctx, 409, "User provided already has a confirmed phone number", "phoneNumberAlreadyConfirmed", ImmutableMap.of()); - return; - } + if (user.getPhone() != null) { + ErrorUtils.respondOther(ctx, 409, "User provided already has a confirmed phone number", "phoneNumberAlreadyConfirmed", ImmutableMap.of()); + return; + } - if (user.getPendingPhoneToken() == null) { - ErrorUtils.respondOther(ctx, 409, "User provided already hasn't started confirming a phone number.", "phoneConfirmationNotStarted", ImmutableMap.of()); - return; - } + if (user.getPendingPhoneToken() == null) { + ErrorUtils.respondOther(ctx, 409, "User provided already hasn't started confirming a phone number.", "phoneConfirmationNotStarted", ImmutableMap.of()); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - int phoneCode = requestBody.getInteger("phoneCode"); + JsonObject requestBody = ctx.getBodyAsJson(); + int phoneCode = requestBody.getInteger("phoneCode"); - if ((System.currentTimeMillis() - user.getPendingPhoneTokenSetAt().toEpochMilli()) > TimeUnit.HOURS.toMillis(6)) { - ErrorUtils.respondOther(ctx, 409, "Phone token is expired", "phoneTokenExpired", ImmutableMap.of()); - return; - } + if ((System.currentTimeMillis() - user.getPendingPhoneTokenSetAt().toEpochMilli()) > TimeUnit.HOURS.toMillis(6)) { + ErrorUtils.respondOther(ctx, 409, "Phone token is expired", "phoneTokenExpired", ImmutableMap.of()); + return; + } - if ((System.currentTimeMillis() - user.getPendingPhoneTokenVerificationAttemptedAt().toEpochMilli()) < TimeUnit.MINUTES.toMillis(20)) { - ErrorUtils.respondOther(ctx, 409, "Wait before attempting phone verification again.", "waitBeforeAttemptingPhoneVerificationAgain", ImmutableMap.of()); - return; - } + if ((System.currentTimeMillis() - user.getPendingPhoneTokenVerificationAttemptedAt().toEpochMilli()) < TimeUnit.MINUTES.toMillis(20)) { + ErrorUtils.respondOther(ctx, 409, "Wait before attempting phone verification again.", "waitBeforeAttemptingPhoneVerificationAgain", ImmutableMap.of()); + return; + } - if (user.getPhoneVerificationFailedAttempts().size() >= 5) { - ErrorUtils.respondOther(ctx, 409, "Too many failed verification attempts", "tooManyFailedPhoneVerifications", ImmutableMap.of()); - return; - } + if (user.getPhoneVerificationFailedAttempts().size() >= 5) { + ErrorUtils.respondOther(ctx, 409, "Too many failed verification attempts", "tooManyFailedPhoneVerifications", ImmutableMap.of()); + return; + } - if (!String.valueOf(phoneCode).equals(user.getPendingPhoneToken())) { - user.failedPhoneRegistration(); - SyncUtils.runBlocking(v -> user.save(v)); + if (!String.valueOf(phoneCode).equals(user.getPendingPhoneToken())) { + user.failedPhoneRegistration(); + SyncUtils.runBlocking(v -> user.save(v)); - ErrorUtils.respondOther(ctx, 409, "Phone token doesn't match", "phoneTokenNoMatch", ImmutableMap.of()); - return; - } + ErrorUtils.respondOther(ctx, 409, "Phone token doesn't match", "phoneTokenNoMatch", ImmutableMap.of()); + return; + } - user.completePhoneRegistration(user.getPendingPhone()); - SyncUtils.runBlocking(v -> user.save(v)); + user.completePhoneRegistration(user.getPendingPhone()); + SyncUtils.runBlocking(v -> user.save(v)); - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CONFIRM_PHONE, (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_CONFIRM_PHONE, (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdLogin.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdLogin.java index 567a249..3d8bcfd 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdLogin.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdLogin.java @@ -19,97 +19,97 @@ import java.util.UUID; public final class POSTUsersIdLogin implements Handler { - public void handle(RoutingContext ctx) { - UUID uuid = UuidUtils.parseUuid(ctx.request().getParam("userId")); + public void handle(RoutingContext ctx) { + UUID uuid = UuidUtils.parseUuid(ctx.request().getParam("userId")); - if (!UuidUtils.isAcceptableUuid(uuid)) { - ErrorUtils.respondInvalidInput(ctx, "Uuid \"" + uuid + "\" is not valid."); - return; - } + if (!UuidUtils.isAcceptableUuid(uuid)) { + ErrorUtils.respondInvalidInput(ctx, "Uuid \"" + uuid + "\" is not valid."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String currentUsername = requestBody.getString("username"); - String userIp = requestBody.getString("userIp"); - Actor actor = ctx.get("actor"); + JsonObject requestBody = ctx.getBodyAsJson(); + String currentUsername = requestBody.getString("username"); + String userIp = requestBody.getString("userIp"); + Actor actor = ctx.get("actor"); - if (actor.getType() != ActorType.SERVER) { - ErrorUtils.respondOther(ctx, 403, "This action can only be performed when requested by a server.", "serverOnly", ImmutableMap.of()); - return; - } + if (actor.getType() != ActorType.SERVER) { + ErrorUtils.respondOther(ctx, 403, "This action can only be performed when requested by a server.", "serverOnly", ImmutableMap.of()); + return; + } - Server actorServer = Server.findById(actor.getName()); + Server actorServer = Server.findById(actor.getName()); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "IP address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "IP address \"" + userIp + "\" is not valid."); + return; + } - User.findOrCreateById(uuid, currentUsername, (user, findUserError) -> { - if (findUserError != null) { - ErrorUtils.respondInternalError(ctx, findUserError); - return; - } + User.findOrCreateById(uuid, currentUsername, (user, findUserError) -> { + if (findUserError != null) { + ErrorUtils.respondInternalError(ctx, findUserError); + return; + } - incrementIpLog(user, userIp, (ignored, ipLogError) -> { - if (ipLogError != null) { - ErrorUtils.respondInternalError(ctx, ipLogError); - return; - } + incrementIpLog(user, userIp, (ignored, ipLogError) -> { + if (ipLogError != null) { + ErrorUtils.respondInternalError(ctx, ipLogError); + return; + } - updateUsername(user, currentUsername, (ignored2, updateUsernameError) -> { - if (updateUsernameError != null) { - ErrorUtils.respondInternalError(ctx, updateUsernameError); - return; - } + updateUsername(user, currentUsername, (ignored2, updateUsernameError) -> { + if (updateUsernameError != null) { + ErrorUtils.respondInternalError(ctx, updateUsernameError); + return; + } - user.seenOnServer(actorServer); - user.save((ignored3, saveUserError) -> { - if (saveUserError != null) { - ErrorUtils.respondInternalError(ctx, saveUserError); - return; - } + user.seenOnServer(actorServer); + user.save((ignored3, saveUserError) -> { + if (saveUserError != null) { + ErrorUtils.respondInternalError(ctx, saveUserError); + return; + } - user.getLoginInfo(actorServer, userIp, (loginInfo, loginInfoError) -> { - if (loginInfoError != null) { - ErrorUtils.respondInternalError(ctx, loginInfoError); - } else { - APIv3.respondJson(ctx, 200, loginInfo); - } - }); - }); - }); - }); - }); - } + user.getLoginInfo(actorServer, userIp, (loginInfo, loginInfoError) -> { + if (loginInfoError != null) { + ErrorUtils.respondInternalError(ctx, loginInfoError); + } else { + APIv3.respondJson(ctx, 200, loginInfo); + } + }); + }); + }); + }); + }); + } - public void incrementIpLog(User user, String userIp, SingleResultCallback callback) { - IpLogEntry.findByUserAndIp(user, userIp, (existingEntry, error) -> { - if (error != null) { - callback.onResult(null, error); - return; - } + public void incrementIpLog(User user, String userIp, SingleResultCallback callback) { + IpLogEntry.findByUserAndIp(user, userIp, (existingEntry, error) -> { + if (error != null) { + callback.onResult(null, error); + return; + } - if (existingEntry != null) { - existingEntry.used(); - existingEntry.save(callback); - return; - } + if (existingEntry != null) { + existingEntry.used(); + existingEntry.save(callback); + return; + } - IpLogEntry inserted = new IpLogEntry(user, userIp); - inserted.used(); - inserted.insert(callback); - }); - } + IpLogEntry inserted = new IpLogEntry(user, userIp); + inserted.used(); + inserted.insert(callback); + }); + } - public void updateUsername(User user, String currentUsername, SingleResultCallback callback) { - String lastUsername = user.getLastUsername(); - user.updateUsername(currentUsername); + public void updateUsername(User user, String currentUsername, SingleResultCallback callback) { + String lastUsername = user.getLastUsername(); + user.updateUsername(currentUsername); - if (!currentUsername.equals(lastUsername)) { - user.checkNameCollisions(callback); - } else { - callback.onResult(null, null); - } - } + if (!currentUsername.equals(lastUsername)) { + user.checkNameCollisions(callback); + } else { + callback.onResult(null, null); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdNotify.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdNotify.java index 01b927f..7a95425 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdNotify.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdNotify.java @@ -15,41 +15,41 @@ import java.util.Map; public final class POSTUsersIdNotify implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getEmail() == null) { - ErrorUtils.respondInvalidInput(ctx, "User provided does not have email set."); - return; - } + if (user.getEmail() == null) { + ErrorUtils.respondInvalidInput(ctx, "User provided does not have email set."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById(requestBody.getString("template"), v)); + JsonObject requestBody = ctx.getBodyAsJson(); + NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById(requestBody.getString("template"), v)); - if (template == null) { - ErrorUtils.respondNotFound(ctx, "Notification template", requestBody.getString("template")); - return; - } + if (template == null) { + ErrorUtils.respondNotFound(ctx, "Notification template", requestBody.getString("template")); + return; + } - Map subjectReplacements = requestBody.getJsonObject("subjectReplacements").getMap(); - Map bodyReplacements = requestBody.getJsonObject("subjectReplacements").getMap(); + Map subjectReplacements = requestBody.getJsonObject("subjectReplacements").getMap(); + Map bodyReplacements = requestBody.getJsonObject("subjectReplacements").getMap(); - Notification notification = new Notification(template, subjectReplacements, bodyReplacements); + Notification notification = new Notification(template, subjectReplacements, bodyReplacements); - notification.sendAsEmail(user.getEmail(), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } + notification.sendAsEmail(user.getEmail(), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdPasswordReset.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdPasswordReset.java index 4bc9274..8bf8f0d 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdPasswordReset.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdPasswordReset.java @@ -18,47 +18,47 @@ import java.util.concurrent.TimeUnit; public final class POSTUsersIdPasswordReset implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getPasswordResetToken() != null && (System.currentTimeMillis() - user.getPasswordResetTokenSetAt().toEpochMilli()) < TimeUnit.DAYS.toMillis(2)) { - ErrorUtils.respondInvalidInput(ctx, "User provided already has password reset token set."); - return; - } + if (user.getPasswordResetToken() != null && (System.currentTimeMillis() - user.getPasswordResetTokenSetAt().toEpochMilli()) < TimeUnit.DAYS.toMillis(2)) { + ErrorUtils.respondInvalidInput(ctx, "User provided already has password reset token set."); + return; + } - user.startPasswordReset(); - SyncUtils.runBlocking(v -> user.save(v)); + user.startPasswordReset(); + SyncUtils.runBlocking(v -> user.save(v)); - Map replacements = ImmutableMap.of( - "username", user.getLastUsername(), - "passwordResetToken", user.getPasswordResetToken() - ); + Map replacements = ImmutableMap.of( + "username", user.getLastUsername(), + "passwordResetToken", user.getPasswordResetToken() + ); - NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("password-reset", v)); - Notification notification = new Notification(template, replacements, replacements); + NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("password-reset", v)); + Notification notification = new Notification(template, replacements, replacements); - notification.sendAsEmail(user.getEmail(), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - JsonObject requestBody = ctx.getBodyAsJson(); + notification.sendAsEmail(user.getEmail(), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + JsonObject requestBody = ctx.getBodyAsJson(); - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_PASSWORD_RESET, (ignored2, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } - }); - } + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_PASSWORD_RESET, (ignored2, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterEmail.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterEmail.java index 0d1ab5a..d1cc28c 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterEmail.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterEmail.java @@ -19,71 +19,71 @@ import java.util.concurrent.TimeUnit; public final class POSTUsersIdRegisterEmail implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getEmail() != null) { - ErrorUtils.respondInvalidInput(ctx, "User provided already has email set."); - return; - } + if (user.getEmail() != null) { + ErrorUtils.respondInvalidInput(ctx, "User provided already has email set."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String email = requestBody.getString("email"); + JsonObject requestBody = ctx.getBodyAsJson(); + String email = requestBody.getString("email"); - if (!EmailUtils.isValidEmail(email)) { - ErrorUtils.respondInvalidInput(ctx, email + " is not a valid email."); - return; - } + if (!EmailUtils.isValidEmail(email)) { + ErrorUtils.respondInvalidInput(ctx, email + " is not a valid email."); + return; + } - if (EmailUtils.isBannedEmailDomain(email)) { - ErrorUtils.respondInvalidInput(ctx, email + " is from a blacklisted domain."); - return; - } + if (EmailUtils.isBannedEmailDomain(email)) { + ErrorUtils.respondInvalidInput(ctx, email + " is from a blacklisted domain."); + return; + } - if (user.getPendingEmailToken() != null && (System.currentTimeMillis() - user.getPendingEmailTokenSetAt().toEpochMilli()) < TimeUnit.DAYS.toMillis(2)) { - ErrorUtils.respondOther(ctx, 409, "Confirmation email recently sent.", "confirmationEmailRecentlySent", ImmutableMap.of()); - return; - } + if (user.getPendingEmailToken() != null && (System.currentTimeMillis() - user.getPendingEmailTokenSetAt().toEpochMilli()) < TimeUnit.DAYS.toMillis(2)) { + ErrorUtils.respondOther(ctx, 409, "Confirmation email recently sent.", "confirmationEmailRecentlySent", ImmutableMap.of()); + return; + } - User sameEmail = SyncUtils.runBlocking(v -> User.findByEmail(email, v)); + User sameEmail = SyncUtils.runBlocking(v -> User.findByEmail(email, v)); - if (sameEmail != null) { - ErrorUtils.respondInvalidInput(ctx, email + " is already in use."); - return; - } + if (sameEmail != null) { + ErrorUtils.respondInvalidInput(ctx, email + " is already in use."); + return; + } - user.startEmailRegistration(email); - SyncUtils.runBlocking(v -> user.save(v)); + user.startEmailRegistration(email); + SyncUtils.runBlocking(v -> user.save(v)); - Map replacements = ImmutableMap.of( - "username", user.getLastUsername(), - "email", user.getPendingEmail(), - "emailToken", user.getPendingEmailToken() - ); + Map replacements = ImmutableMap.of( + "username", user.getLastUsername(), + "email", user.getPendingEmail(), + "emailToken", user.getPendingEmailToken() + ); - NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("email-confirmation", v)); - Notification notification = new Notification(template, replacements, replacements); + NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("email-confirmation", v)); + Notification notification = new Notification(template, replacements, replacements); - notification.sendAsEmail(user.getEmail(), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_REGISTER_EMAIL, (ignored2, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } - }); - } + notification.sendAsEmail(user.getEmail(), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_REGISTER_EMAIL, (ignored2, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterPhone.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterPhone.java index 8335992..50ff1e6 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterPhone.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdRegisterPhone.java @@ -21,73 +21,73 @@ import java.util.concurrent.TimeUnit; public final class POSTUsersIdRegisterPhone implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getPhone() != null) { - ErrorUtils.respondInvalidInput(ctx, "User provided already has phone set."); - return; - } + if (user.getPhone() != null) { + ErrorUtils.respondInvalidInput(ctx, "User provided already has phone set."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String phone = requestBody.getString("phone"); + JsonObject requestBody = ctx.getBodyAsJson(); + String phone = requestBody.getString("phone"); - if (!PhoneUtils.isValidPhone(phone)) { - ErrorUtils.respondInvalidInput(ctx, phone + " is not a valid phone number."); - return; - } + if (!PhoneUtils.isValidPhone(phone)) { + ErrorUtils.respondInvalidInput(ctx, phone + " is not a valid phone number."); + return; + } - if (user.getPendingPhoneToken() != null && (System.currentTimeMillis() - user.getPendingPhoneTokenSetAt().toEpochMilli()) < TimeUnit.HOURS.toMillis(6)) { - ErrorUtils.respondOther(ctx, 409, "Confirmation code recently sent.", "confirmationCodeRecentlySent", ImmutableMap.of()); - return; - } + if (user.getPendingPhoneToken() != null && (System.currentTimeMillis() - user.getPendingPhoneTokenSetAt().toEpochMilli()) < TimeUnit.HOURS.toMillis(6)) { + ErrorUtils.respondOther(ctx, 409, "Confirmation code recently sent.", "confirmationCodeRecentlySent", ImmutableMap.of()); + return; + } - User samePhone = SyncUtils.runBlocking(v -> User.findByPhone(phone, v)); + User samePhone = SyncUtils.runBlocking(v -> User.findByPhone(phone, v)); - if (samePhone != null) { - ErrorUtils.respondInvalidInput(ctx, phone + " is already in use."); - return; - } + if (samePhone != null) { + ErrorUtils.respondInvalidInput(ctx, phone + " is already in use."); + return; + } - PhoneIntel phoneIntel = SyncUtils.runBlocking(v -> PhoneIntel.findOrCreateById(phone, v)); + PhoneIntel phoneIntel = SyncUtils.runBlocking(v -> PhoneIntel.findOrCreateById(phone, v)); - if (BannedCellCarrier.findById(phoneIntel.getResult().getCarrierId()) != null) { - ErrorUtils.respondInvalidInput(ctx, phone + " is from a banned cell provider."); - return; - } + if (BannedCellCarrier.findById(phoneIntel.getResult().getCarrierId()) != null) { + ErrorUtils.respondInvalidInput(ctx, phone + " is from a banned cell provider."); + return; + } - user.startPhoneRegistration(phone); - SyncUtils.runBlocking(v -> user.save(v)); + user.startPhoneRegistration(phone); + SyncUtils.runBlocking(v -> user.save(v)); - Map replacements = ImmutableMap.of( - "username", user.getLastUsername(), - "phone", user.getPendingPhone(), - "phoneToken", user.getPendingPhoneToken() - ); + Map replacements = ImmutableMap.of( + "username", user.getLastUsername(), + "phone", user.getPendingPhone(), + "phoneToken", user.getPendingPhoneToken() + ); - NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("phone-confirmation", v)); - Notification notification = new Notification(template, replacements, replacements); + NotificationTemplate template = SyncUtils.runBlocking(v -> NotificationTemplate.findById("phone-confirmation", v)); + Notification notification = new Notification(template, replacements, replacements); - notification.sendAsText(user.getPendingPhone(), (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_REGISTER_PHONE, (ignored2, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } - }); - } + notification.sendAsText(user.getPendingPhone(), (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_REGISTER_PHONE, (ignored2, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdSetupTotp.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdSetupTotp.java index bcc160b..1f5bd12 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdSetupTotp.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdSetupTotp.java @@ -14,39 +14,39 @@ import net.frozenorb.apiv3.util.TotpUtils; public final class POSTUsersIdSetupTotp implements Handler { - public void handle(RoutingContext ctx) { - User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); + public void handle(RoutingContext ctx) { + User user = SyncUtils.runBlocking(v -> User.findById(ctx.request().getParam("userId"), v)); - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getTotpSecret() != null) { - ErrorUtils.respondInvalidInput(ctx, "User provided already has totp setup."); - return; - } + if (user.getTotpSecret() != null) { + ErrorUtils.respondInvalidInput(ctx, "User provided already has totp setup."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String secret = requestBody.getString("secret"); - int totpCode = requestBody.getInteger("totpCode"); + JsonObject requestBody = ctx.getBodyAsJson(); + String secret = requestBody.getString("secret"); + int totpCode = requestBody.getInteger("totpCode"); - if (TotpUtils.authorizeUser(secret, totpCode)) { - user.setTotpSecret(secret); - SyncUtils.runBlocking(v -> user.save(v)); + if (TotpUtils.authorizeUser(secret, totpCode)) { + user.setTotpSecret(secret); + SyncUtils.runBlocking(v -> user.save(v)); - AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_SETUP_TOTP, (ignored, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "success", true - )); - } - }); - } else { - ErrorUtils.respondOther(ctx, 400, "Confirmation code provided did not match.", "badConfirmationCode", ImmutableMap.of()); - } - } + AuditLog.log(user.getId(), requestBody.getString("userIp"), ctx, AuditLogActionType.USER_SETUP_TOTP, (ignored, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "success", true + )); + } + }); + } else { + ErrorUtils.respondOther(ctx, 400, "Confirmation code provided did not match.", "badConfirmationCode", ImmutableMap.of()); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdVerifyTotp.java b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdVerifyTotp.java index 1ba7714..e088978 100644 --- a/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdVerifyTotp.java +++ b/src/main/java/net/frozenorb/apiv3/route/users/POSTUsersIdVerifyTotp.java @@ -13,49 +13,49 @@ import net.frozenorb.apiv3.util.IpUtils; public final class POSTUsersIdVerifyTotp implements Handler { - public void handle(RoutingContext ctx) { - User.findById(ctx.request().getParam("userId"), (user, error) -> { - if (error != null) { - ErrorUtils.respondInternalError(ctx, error); - return; - } + public void handle(RoutingContext ctx) { + User.findById(ctx.request().getParam("userId"), (user, error) -> { + if (error != null) { + ErrorUtils.respondInternalError(ctx, error); + return; + } - if (user == null) { - ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); - return; - } + if (user == null) { + ErrorUtils.respondNotFound(ctx, "User", ctx.request().getParam("userId")); + return; + } - if (user.getTotpSecret() == null) { - ErrorUtils.respondInvalidInput(ctx, "User provided does not have totp code set."); - return; - } + if (user.getTotpSecret() == null) { + ErrorUtils.respondInvalidInput(ctx, "User provided does not have totp code set."); + return; + } - JsonObject requestBody = ctx.getBodyAsJson(); - String userIp = requestBody.getString("userIp"); + JsonObject requestBody = ctx.getBodyAsJson(); + String userIp = requestBody.getString("userIp"); - if (!IpUtils.isValidIp(userIp)) { - ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); - return; - } + if (!IpUtils.isValidIp(userIp)) { + ErrorUtils.respondInvalidInput(ctx, "Ip address \"" + userIp + "\" is not valid."); + return; + } - user.checkTotpAuthorization(requestBody.getInteger("totpCode"), userIp, (totpAuthorizationResult, error2) -> { - if (error2 != null) { - ErrorUtils.respondInternalError(ctx, error2); - return; - } + user.checkTotpAuthorization(requestBody.getInteger("totpCode"), userIp, (totpAuthorizationResult, error2) -> { + if (error2 != null) { + ErrorUtils.respondInternalError(ctx, error2); + return; + } - AuditLog.log(user.getId(), userIp, ctx, AuditLogActionType.USER_VERIFY_TOTP, (ignored, error3) -> { - if (error3 != null) { - ErrorUtils.respondInternalError(ctx, error3); - } else { - APIv3.respondJson(ctx, 200, ImmutableMap.of( - "authorized", totpAuthorizationResult.isAuthorized(), - "message", totpAuthorizationResult.name() - )); - } - }); - }); - }); - } + AuditLog.log(user.getId(), userIp, ctx, AuditLogActionType.USER_VERIFY_TOTP, (ignored, error3) -> { + if (error3 != null) { + ErrorUtils.respondInternalError(ctx, error3); + } else { + APIv3.respondJson(ctx, 200, ImmutableMap.of( + "authorized", totpAuthorizationResult.isAuthorized(), + "message", totpAuthorizationResult.name() + )); + } + }); + }); + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/gson/FollowAnnotationExclusionStrategy.java b/src/main/java/net/frozenorb/apiv3/serialization/gson/FollowAnnotationExclusionStrategy.java index 6deee9b..f41789f 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/gson/FollowAnnotationExclusionStrategy.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/gson/FollowAnnotationExclusionStrategy.java @@ -5,14 +5,14 @@ import com.google.gson.FieldAttributes; public final class FollowAnnotationExclusionStrategy implements ExclusionStrategy { - @Override - public boolean shouldSkipField(FieldAttributes fieldAttributes) { - return fieldAttributes.getAnnotation(ExcludeFromReplies.class) != null; - } + @Override + public boolean shouldSkipField(FieldAttributes fieldAttributes) { + return fieldAttributes.getAnnotation(ExcludeFromReplies.class) != null; + } - @Override - public boolean shouldSkipClass(Class aClass) { - return false; - } + @Override + public boolean shouldSkipClass(Class aClass) { + return false; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/gson/InstantTypeAdapter.java b/src/main/java/net/frozenorb/apiv3/serialization/gson/InstantTypeAdapter.java index 4a7ef24..4db3f0e 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/gson/InstantTypeAdapter.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/gson/InstantTypeAdapter.java @@ -9,20 +9,20 @@ import java.time.Instant; public final class InstantTypeAdapter extends TypeAdapter { - public void write(JsonWriter writer, Instant write) throws IOException { - if (write == null) { - writer.nullValue(); - } else { - //writer.value(write.toEpochMilli() - System.currentTimeMillis()); - writer.value(write.toEpochMilli()); - } - } + public void write(JsonWriter writer, Instant write) throws IOException { + if (write == null) { + writer.nullValue(); + } else { + //writer.value(write.toEpochMilli() - System.currentTimeMillis()); + writer.value(write.toEpochMilli()); + } + } - // This is used with Gson, which is only used - // to serialize outgoing responses, thus we - // don't need to have a read method. - public Instant read(JsonReader reader) { - throw new IllegalArgumentException(); - } + // This is used with Gson, which is only used + // to serialize outgoing responses, thus we + // don't need to have a read method. + public Instant read(JsonReader reader) { + throw new IllegalArgumentException(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonDeserializer.java b/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonDeserializer.java index ec32ed2..7f71b5c 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonDeserializer.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonDeserializer.java @@ -9,9 +9,9 @@ import java.time.Instant; public final class InstantJsonDeserializer extends JsonDeserializer { - @Override - public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { - return Instant.ofEpochMilli(jsonParser.getValueAsLong()); - } + @Override + public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { + return Instant.ofEpochMilli(jsonParser.getValueAsLong()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonSerializer.java b/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonSerializer.java index e6477e5..c726b46 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonSerializer.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/jackson/InstantJsonSerializer.java @@ -9,9 +9,9 @@ import java.time.Instant; public final class InstantJsonSerializer extends JsonSerializer { - @Override - public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - jsonGenerator.writeNumber(instant.toEpochMilli()); - } + @Override + public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeNumber(instant.toEpochMilli()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonDeserializer.java b/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonDeserializer.java index 58d1fe5..edf6a9a 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonDeserializer.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonDeserializer.java @@ -9,9 +9,9 @@ import java.util.UUID; public final class UuidJsonDeserializer extends JsonDeserializer { - @Override - public UUID deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { - return UUID.fromString(jsonParser.getValueAsString()); - } + @Override + public UUID deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { + return UUID.fromString(jsonParser.getValueAsString()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonSerializer.java b/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonSerializer.java index 86977ad..1b84edf 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonSerializer.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/jackson/UuidJsonSerializer.java @@ -9,9 +9,9 @@ import java.util.UUID; public final class UuidJsonSerializer extends JsonSerializer { - @Override - public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - jsonGenerator.writeString(uuid.toString()); - } + @Override + public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeString(uuid.toString()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodec.java b/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodec.java index 4622cf9..d1db6f4 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodec.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodec.java @@ -10,19 +10,19 @@ import java.util.UUID; final class UuidCodec implements Codec { - @Override - public UUID decode(BsonReader bsonReader, DecoderContext decoderContext) { - return UUID.fromString(bsonReader.readString()); - } + @Override + public UUID decode(BsonReader bsonReader, DecoderContext decoderContext) { + return UUID.fromString(bsonReader.readString()); + } - @Override - public void encode(BsonWriter bsonWriter, UUID uuid, EncoderContext encoderContext) { - bsonWriter.writeString(uuid == null ? null : uuid.toString()); - } + @Override + public void encode(BsonWriter bsonWriter, UUID uuid, EncoderContext encoderContext) { + bsonWriter.writeString(uuid == null ? null : uuid.toString()); + } - @Override - public Class getEncoderClass() { - return UUID.class; - } + @Override + public Class getEncoderClass() { + return UUID.class; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodecProvider.java b/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodecProvider.java index afd0e9a..f40102b 100644 --- a/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodecProvider.java +++ b/src/main/java/net/frozenorb/apiv3/serialization/mongodb/UuidCodecProvider.java @@ -8,12 +8,12 @@ import java.util.UUID; public final class UuidCodecProvider implements CodecProvider { - public Codec get(Class clazz, CodecRegistry codecRegistry) { - if (clazz == UUID.class) { - return (Codec) new UuidCodec(); - } else { - return null; - } - } + public Codec get(Class clazz, CodecRegistry codecRegistry) { + if (clazz == UUID.class) { + return (Codec) new UuidCodec(); + } else { + return null; + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/unsorted/MongoToVertxCallback.java b/src/main/java/net/frozenorb/apiv3/unsorted/MongoToVertxCallback.java index 9527a35..b1f1b69 100644 --- a/src/main/java/net/frozenorb/apiv3/unsorted/MongoToVertxCallback.java +++ b/src/main/java/net/frozenorb/apiv3/unsorted/MongoToVertxCallback.java @@ -5,18 +5,18 @@ import io.vertx.core.Future; public final class MongoToVertxCallback implements SingleResultCallback { - private final Future future; + private final Future future; - public MongoToVertxCallback(Future future) { - this.future = future; - } + public MongoToVertxCallback(Future future) { + this.future = future; + } - public void onResult(T val, Throwable error) { - if (error != null) { - future.fail(error); - } else { - future.complete(val); - } - } + public void onResult(T val, Throwable error) { + if (error != null) { + future.fail(error); + } else { + future.complete(val); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/unsorted/Notification.java b/src/main/java/net/frozenorb/apiv3/unsorted/Notification.java index 1fe3204..d23b42d 100644 --- a/src/main/java/net/frozenorb/apiv3/unsorted/Notification.java +++ b/src/main/java/net/frozenorb/apiv3/unsorted/Notification.java @@ -11,33 +11,33 @@ import java.util.Map; public final class Notification { - private final String subject; - private final String body; + private final String subject; + private final String body; - public Notification(NotificationTemplate template, Map subjectReplacements, Map bodyReplacements) { - this.subject = template.fillSubject(subjectReplacements); - this.body = template.fillBody(bodyReplacements); - } + public Notification(NotificationTemplate template, Map subjectReplacements, Map bodyReplacements) { + this.subject = template.fillSubject(subjectReplacements); + this.body = template.fillBody(bodyReplacements); + } - public void sendAsEmail(String email, SingleResultCallback callback) { - JsonObject message = new JsonObject(); + public void sendAsEmail(String email, SingleResultCallback callback) { + JsonObject message = new JsonObject(); - message.put("html", body); - message.put("subject", subject); - message.put("from_email", "no-reply@minehq.com"); - message.put("from_name", "MineHQ Network"); - message.put("to", new JsonArray().add( - new JsonObject() - .put("email", email) - .putNull("name") - .put("type", "to") - )); + message.put("html", body); + message.put("subject", subject); + message.put("from_email", "no-reply@minehq.com"); + message.put("from_name", "MineHQ Network"); + message.put("to", new JsonArray().add( + new JsonObject() + .put("email", email) + .putNull("name") + .put("type", "to") + )); - MandrillUtils.sendEmail(message, callback); - } + MandrillUtils.sendEmail(message, callback); + } - public void sendAsText(String phoneNumber, SingleResultCallback callback) { - ZangUtils.sendText(phoneNumber, body, callback); - } + public void sendAsText(String phoneNumber, SingleResultCallback callback) { + ZangUtils.sendText(phoneNumber, body, callback); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/unsorted/Permissions.java b/src/main/java/net/frozenorb/apiv3/unsorted/Permissions.java index 0a502a7..71ad3eb 100644 --- a/src/main/java/net/frozenorb/apiv3/unsorted/Permissions.java +++ b/src/main/java/net/frozenorb/apiv3/unsorted/Permissions.java @@ -5,8 +5,8 @@ import lombok.experimental.UtilityClass; @UtilityClass public class Permissions { - public static final String PROTECTED_PUNISHMENT = "minehq.punishment.protected"; - public static final String BYPASS_VPN_CHECK = "minehq.vpn.bypass"; - public static final String REQUIRE_TOTP_CODE = "minehq.totp.require"; + public static final String PROTECTED_PUNISHMENT = "minehq.punishment.protected"; + public static final String BYPASS_VPN_CHECK = "minehq.vpn.bypass"; + public static final String REQUIRE_TOTP_CODE = "minehq.totp.require"; } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/unsorted/RequiresTotpResult.java b/src/main/java/net/frozenorb/apiv3/unsorted/RequiresTotpResult.java index 6df2d24..905d685 100644 --- a/src/main/java/net/frozenorb/apiv3/unsorted/RequiresTotpResult.java +++ b/src/main/java/net/frozenorb/apiv3/unsorted/RequiresTotpResult.java @@ -2,8 +2,8 @@ package net.frozenorb.apiv3.unsorted; public enum RequiresTotpResult { - NOT_REQUIRED_NOT_SET, - NOT_REQUIRED_IP_PRE_AUTHORIZED, - REQUIRED_NO_EXEMPTIONS + NOT_REQUIRED_NOT_SET, + NOT_REQUIRED_IP_PRE_AUTHORIZED, + REQUIRED_NO_EXEMPTIONS } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/unsorted/TotpAuthorizationResult.java b/src/main/java/net/frozenorb/apiv3/unsorted/TotpAuthorizationResult.java index 84b7a75..5593c95 100644 --- a/src/main/java/net/frozenorb/apiv3/unsorted/TotpAuthorizationResult.java +++ b/src/main/java/net/frozenorb/apiv3/unsorted/TotpAuthorizationResult.java @@ -4,17 +4,17 @@ import lombok.Getter; public enum TotpAuthorizationResult { - AUTHORIZED_NOT_SET(true), - AUTHORIZED_IP_PRE_AUTH(true), - AUTHORIZED_GOOD_CODE(true), - NOT_AUTHORIZED_NOT_SET(false), - NOT_AUTHORIZED_RECENTLY_USED(false), - NOT_AUTHORIZED_BAD_CODE(false); + AUTHORIZED_NOT_SET(true), + AUTHORIZED_IP_PRE_AUTH(true), + AUTHORIZED_GOOD_CODE(true), + NOT_AUTHORIZED_NOT_SET(false), + NOT_AUTHORIZED_RECENTLY_USED(false), + NOT_AUTHORIZED_BAD_CODE(false); - @Getter private final boolean authorized; + @Getter private final boolean authorized; - TotpAuthorizationResult(boolean authorized) { - this.authorized = authorized; - } + TotpAuthorizationResult(boolean authorized) { + this.authorized = authorized; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/EmailUtils.java b/src/main/java/net/frozenorb/apiv3/util/EmailUtils.java index 0cac3b3..6d4aee1 100644 --- a/src/main/java/net/frozenorb/apiv3/util/EmailUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/EmailUtils.java @@ -13,36 +13,36 @@ import java.util.regex.Pattern; @UtilityClass public class EmailUtils { - private static final Pattern VALID_EMAIL_PATTERN = Pattern.compile( - "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", - Pattern.CASE_INSENSITIVE - ); - private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); - private static Set bannedEmailDomains = ImmutableSet.of(); + private static final Pattern VALID_EMAIL_PATTERN = Pattern.compile( + "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", + Pattern.CASE_INSENSITIVE + ); + private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); + private static Set bannedEmailDomains = ImmutableSet.of(); - static { - APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(10), (id) -> updateBannedEmailDomains()); - } + static { + APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(10), (id) -> updateBannedEmailDomains()); + } - public static void updateBannedEmailDomains() { - httpsClient.get(443, "raw.githubusercontent.com", "/martenson/disposable-email-domains/master/disposable_email_blacklist.conf", (response) -> { - response.bodyHandler((body) -> bannedEmailDomains = ImmutableSet.copyOf(body.toString().split("\n"))); - response.exceptionHandler(Throwable::printStackTrace); - }).end(); - } + public static void updateBannedEmailDomains() { + httpsClient.get(443, "raw.githubusercontent.com", "/martenson/disposable-email-domains/master/disposable_email_blacklist.conf", (response) -> { + response.bodyHandler((body) -> bannedEmailDomains = ImmutableSet.copyOf(body.toString().split("\n"))); + response.exceptionHandler(Throwable::printStackTrace); + }).end(); + } - public static boolean isBannedEmailDomain(String email) { - if (!isValidEmail(email)) { - return false; - } + public static boolean isBannedEmailDomain(String email) { + if (!isValidEmail(email)) { + return false; + } - String[] split = email.split("@"); - String domain = split[1]; - return split.length == 2 && bannedEmailDomains.contains(domain.toLowerCase()); - } + String[] split = email.split("@"); + String domain = split[1]; + return split.length == 2 && bannedEmailDomains.contains(domain.toLowerCase()); + } - public static boolean isValidEmail(String email) { - return email != null && VALID_EMAIL_PATTERN.matcher(email).matches(); - } + public static boolean isValidEmail(String email) { + return email != null && VALID_EMAIL_PATTERN.matcher(email).matches(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/ErrorUtils.java b/src/main/java/net/frozenorb/apiv3/util/ErrorUtils.java index a1aeaa5..d384f14 100644 --- a/src/main/java/net/frozenorb/apiv3/util/ErrorUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/ErrorUtils.java @@ -12,39 +12,39 @@ import java.util.Map; @UtilityClass public class ErrorUtils { - public static void respondNotFound(RoutingContext ctx, String itemType, String id) { - respond(ctx, 404, "Not found: " + itemType + " with id " + id + " cannot be found.", null, null); - } + public static void respondNotFound(RoutingContext ctx, String itemType, String id) { + respond(ctx, 404, "Not found: " + itemType + " with id " + id + " cannot be found.", null, null); + } - public static void respondInvalidInput(RoutingContext ctx, String message) { - respond(ctx, 400, "Invalid input: " + message, null, null); - } + public static void respondInvalidInput(RoutingContext ctx, String message) { + respond(ctx, 400, "Invalid input: " + message, null, null); + } - public static void respondRequiredInput(RoutingContext ctx, String field) { - respond(ctx, 400, "Required input: " + field + " is required.", null, null); - } + public static void respondRequiredInput(RoutingContext ctx, String field) { + respond(ctx, 400, "Required input: " + field + " is required.", null, null); + } - public static void respondInternalError(RoutingContext ctx, Throwable error) { - log.error("Request \"" + ctx.request().method().name() + " " + ctx.request().path() + "\" failed.", error); - respond(ctx, 500, "Internal error: " + error.getClass().getSimpleName(), null, null); - } + public static void respondInternalError(RoutingContext ctx, Throwable error) { + log.error("Request \"" + ctx.request().method().name() + " " + ctx.request().path() + "\" failed.", error); + respond(ctx, 500, "Internal error: " + error.getClass().getSimpleName(), null, null); + } - public static void respondOther(RoutingContext ctx, int code, String message, String translationId, Map translationParams) { - respond(ctx, code, message, translationId, translationParams); - } + public static void respondOther(RoutingContext ctx, int code, String message, String translationId, Map translationParams) { + respond(ctx, code, message, translationId, translationParams); + } - private static void respond(RoutingContext ctx, int code, String message, String translationId, Map translationParams) { - ImmutableMap.Builder builder = ImmutableMap.builder(); + private static void respond(RoutingContext ctx, int code, String message, String translationId, Map translationParams) { + ImmutableMap.Builder builder = ImmutableMap.builder(); - builder.put("success", false); - builder.put("message", message); + builder.put("success", false); + builder.put("message", message); - if (translationId != null) { - builder.put("translationId", translationId); - builder.put("translationParams", translationParams); - } + if (translationId != null) { + builder.put("translationId", translationId); + builder.put("translationParams", translationParams); + } - APIv3.respondJson(ctx, code, builder.build()); - } + APIv3.respondJson(ctx, code, builder.build()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/IpUtils.java b/src/main/java/net/frozenorb/apiv3/util/IpUtils.java index b834862..c772319 100644 --- a/src/main/java/net/frozenorb/apiv3/util/IpUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/IpUtils.java @@ -7,14 +7,14 @@ import java.util.regex.Pattern; @UtilityClass public class IpUtils { - private static final Pattern VALID_IP_PATTERN = Pattern.compile( - "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + - "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + - "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + - "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + private static final Pattern VALID_IP_PATTERN = Pattern.compile( + "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); - public static boolean isValidIp(String ip) { - return ip != null && VALID_IP_PATTERN.matcher(ip).matches(); - } + public static boolean isValidIp(String ip) { + return ip != null && VALID_IP_PATTERN.matcher(ip).matches(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/MandrillUtils.java b/src/main/java/net/frozenorb/apiv3/util/MandrillUtils.java index aa0bb86..e63b01b 100644 --- a/src/main/java/net/frozenorb/apiv3/util/MandrillUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/MandrillUtils.java @@ -11,20 +11,20 @@ import net.frozenorb.apiv3.APIv3; @UtilityClass public class MandrillUtils { - private static final String mandrillApiKey = APIv3.getConfig().getProperty("mandrill.apiKey"); - private static final HttpClient httpClient = APIv3.getVertxInstance().createHttpClient(); + private static final String mandrillApiKey = APIv3.getConfig().getProperty("mandrill.apiKey"); + private static final HttpClient httpClient = APIv3.getVertxInstance().createHttpClient(); - public static void sendEmail(JsonObject message, SingleResultCallback callback) { - JsonObject body = new JsonObject() - .put("key", mandrillApiKey) - .put("message", message); + public static void sendEmail(JsonObject message, SingleResultCallback callback) { + JsonObject body = new JsonObject() + .put("key", mandrillApiKey) + .put("message", message); - httpClient.post("mandrillapp.com", "/api/1.0/messages/send.json", (response) -> { - response.bodyHandler((ignored) -> callback.onResult(null, null)); - response.exceptionHandler((error) -> callback.onResult(null, error)); - }) - .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) - .end(body.encode()); - } + httpClient.post("mandrillapp.com", "/api/1.0/messages/send.json", (response) -> { + response.bodyHandler((ignored) -> callback.onResult(null, null)); + response.exceptionHandler((error) -> callback.onResult(null, error)); + }) + .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) + .end(body.encode()); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/MaxMindUtils.java b/src/main/java/net/frozenorb/apiv3/util/MaxMindUtils.java index b13e339..fe6fb97 100644 --- a/src/main/java/net/frozenorb/apiv3/util/MaxMindUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/MaxMindUtils.java @@ -16,60 +16,60 @@ import java.util.Base64; @UtilityClass public class MaxMindUtils { - private static final String maxMindUserId = APIv3.getConfig().getProperty("maxMind.userId"); - private static final String maxMindLicenseKey = APIv3.getConfig().getProperty("maxMind.maxMindLicenseKey"); - private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); - private static final CircuitBreaker breaker; + private static final String maxMindUserId = APIv3.getConfig().getProperty("maxMind.userId"); + private static final String maxMindLicenseKey = APIv3.getConfig().getProperty("maxMind.maxMindLicenseKey"); + private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); + private static final CircuitBreaker breaker; - // MaxMind likes to randomly not respond, so we take advantage of the circuit breaker pattern to only - // check MaxMind periodically (while it's in a non-responsive state) to keep our average response times - // nice and low. - static { - breaker = CircuitBreaker.create("maxmind-circuit-breaker", APIv3.getVertxInstance(), - new CircuitBreakerOptions() - .setMaxFailures(5) - .setTimeout(1000) // 1 second - .setFallbackOnFailure(true) - .setResetTimeout(120_000) // 2 minutes - ); - } + // MaxMind likes to randomly not respond, so we take advantage of the circuit breaker pattern to only + // check MaxMind periodically (while it's in a non-responsive state) to keep our average response times + // nice and low. + static { + breaker = CircuitBreaker.create("maxmind-circuit-breaker", APIv3.getVertxInstance(), + new CircuitBreakerOptions() + .setMaxFailures(5) + .setTimeout(1000) // 1 second + .setFallbackOnFailure(true) + .setResetTimeout(120_000) // 2 minutes + ); + } - public static void getInsights(String ip, SingleResultCallback callback) { - breaker.executeWithFallback((future) -> { - String authHeader = "Basic " + Base64.getEncoder().encodeToString((maxMindUserId + ":" + maxMindLicenseKey).getBytes(Charsets.UTF_8)); + public static void getInsights(String ip, SingleResultCallback callback) { + breaker.executeWithFallback((future) -> { + String authHeader = "Basic " + Base64.getEncoder().encodeToString((maxMindUserId + ":" + maxMindLicenseKey).getBytes(Charsets.UTF_8)); - httpsClient.get(443, "geoip.maxmind.com", "/geoip/v2.1/insights/" + ip, (response) -> { - response.bodyHandler((body) -> { - JsonObject bodyJson = new JsonObject(body.toString()); + httpsClient.get(443, "geoip.maxmind.com", "/geoip/v2.1/insights/" + ip, (response) -> { + response.bodyHandler((body) -> { + JsonObject bodyJson = new JsonObject(body.toString()); - try { - MaxMindResult maxMindResult = new MaxMindResult(bodyJson); - future.complete(maxMindResult); - } catch (Exception ignored) { - future.complete(null); - } - }); + try { + MaxMindResult maxMindResult = new MaxMindResult(bodyJson); + future.complete(maxMindResult); + } catch (Exception ignored) { + future.complete(null); + } + }); - response.exceptionHandler((error) -> { - // we have to check !failed because the circuit breaker's timeout will mark us as failed already - if (!future.failed()) { - future.fail(error); - } - }); - }) - .putHeader("Authorization", authHeader) - .end(); - }, (ignored) -> null).setHandler((result) -> { // The (ignored) -> null section is our fallback, which just returns null (when the breaker is open) - if (result.failed()) { - callback.onResult(null, result.cause()); - } else { - callback.onResult((MaxMindResult) result.result(), null); - } - }); - } + response.exceptionHandler((error) -> { + // we have to check !failed because the circuit breaker's timeout will mark us as failed already + if (!future.failed()) { + future.fail(error); + } + }); + }) + .putHeader("Authorization", authHeader) + .end(); + }, (ignored) -> null).setHandler((result) -> { // The (ignored) -> null section is our fallback, which just returns null (when the breaker is open) + if (result.failed()) { + callback.onResult(null, result.cause()); + } else { + callback.onResult((MaxMindResult) result.result(), null); + } + }); + } - public static String getEnglishName(JsonObject source) { - return source.getJsonObject("names", new JsonObject()).getString("en", "INVALID"); - } + public static String getEnglishName(JsonObject source) { + return source.getJsonObject("names", new JsonObject()).getString("en", "INVALID"); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/MojangUtils.java b/src/main/java/net/frozenorb/apiv3/util/MojangUtils.java index 57d5b39..a8fe16d 100644 --- a/src/main/java/net/frozenorb/apiv3/util/MojangUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/MojangUtils.java @@ -14,27 +14,27 @@ import java.util.UUID; @UtilityClass public class MojangUtils { - private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); + private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); - public static void getName(UUID id, SingleResultCallback callback) { - httpsClient.get(443, "sessionserver.mojang.com", "/session/minecraft/profile/" + id.toString().replace("-", ""), (response) -> { - response.bodyHandler((body) -> { - try { - JsonObject bodyJson = new JsonObject(body.toString()); - String name = bodyJson.getString("name"); + public static void getName(UUID id, SingleResultCallback callback) { + httpsClient.get(443, "sessionserver.mojang.com", "/session/minecraft/profile/" + id.toString().replace("-", ""), (response) -> { + response.bodyHandler((body) -> { + try { + JsonObject bodyJson = new JsonObject(body.toString()); + String name = bodyJson.getString("name"); - if (name == null) { - callback.onResult(null, new IOException("Hit Mojang API rate limit: " + bodyJson.encode())); - } else { - callback.onResult(name, null); - } - } catch (DecodeException ex) { - callback.onResult(null, ex); - } - }); + if (name == null) { + callback.onResult(null, new IOException("Hit Mojang API rate limit: " + bodyJson.encode())); + } else { + callback.onResult(name, null); + } + } catch (DecodeException ex) { + callback.onResult(null, ex); + } + }); - response.exceptionHandler((error) -> callback.onResult(null, error)); - }).end(); - } + response.exceptionHandler((error) -> callback.onResult(null, error)); + }).end(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/PermissionUtils.java b/src/main/java/net/frozenorb/apiv3/util/PermissionUtils.java index 8ddc16b..588953c 100644 --- a/src/main/java/net/frozenorb/apiv3/util/PermissionUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/PermissionUtils.java @@ -13,66 +13,66 @@ import java.util.Map; @UtilityClass public class PermissionUtils { - public static Map mergePermissions(Map current, Map merge) { - Map result = new HashMap<>(current); + public static Map mergePermissions(Map current, Map merge) { + Map result = new HashMap<>(current); - result.putAll(merge); + result.putAll(merge); - return result; - } + return result; + } - public static Map mergeUpTo(Map> raw, Rank upTo) { - Map result = new HashMap<>(); - List mergeQueue = new LinkedList<>(); - Rank merge = upTo; + public static Map mergeUpTo(Map> raw, Rank upTo) { + Map result = new HashMap<>(); + List mergeQueue = new LinkedList<>(); + Rank merge = upTo; - while (merge != null) { - mergeQueue.add(0, merge); - merge = Rank.findById(merge.getInheritsFromId()); - } + while (merge != null) { + mergeQueue.add(0, merge); + merge = Rank.findById(merge.getInheritsFromId()); + } - for (Rank rank : mergeQueue) { - Map rankPermissions = convertFromList(raw.get(rank.getId())); + for (Rank rank : mergeQueue) { + Map rankPermissions = convertFromList(raw.get(rank.getId())); - // If there's no permissions defined for this rank just skip it. - if (!rankPermissions.isEmpty()) { - result = mergePermissions(result, rankPermissions); - } - } + // If there's no permissions defined for this rank just skip it. + if (!rankPermissions.isEmpty()) { + result = mergePermissions(result, rankPermissions); + } + } - return result; - } + return result; + } - private static Map convertFromList(List permissionsList) { - if (permissionsList == null) { - return ImmutableMap.of(); - } + private static Map convertFromList(List permissionsList) { + if (permissionsList == null) { + return ImmutableMap.of(); + } - Map permissionsMap = new HashMap<>(); + Map permissionsMap = new HashMap<>(); - permissionsList.forEach((permission) -> { - if (permission.startsWith("-")) { - permissionsMap.put(permission.substring(1), false); - } else { - permissionsMap.put(permission, true); - } - }); + permissionsList.forEach((permission) -> { + if (permission.startsWith("-")) { + permissionsMap.put(permission.substring(1), false); + } else { + permissionsMap.put(permission, true); + } + }); - return permissionsMap; - } + return permissionsMap; + } - public static List convertToList(Map permissionsMap) { - if (permissionsMap == null) { - return ImmutableList.of(); - } + public static List convertToList(Map permissionsMap) { + if (permissionsMap == null) { + return ImmutableList.of(); + } - List permissionsList = new LinkedList<>(); + List permissionsList = new LinkedList<>(); - permissionsMap.forEach((permission, granted) -> { - permissionsList.add((granted ? "" : "-") + permission); - }); + permissionsMap.forEach((permission, granted) -> { + permissionsList.add((granted ? "" : "-") + permission); + }); - return permissionsList; - } + return permissionsList; + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/PhoneUtils.java b/src/main/java/net/frozenorb/apiv3/util/PhoneUtils.java index 443655b..dbbb78e 100644 --- a/src/main/java/net/frozenorb/apiv3/util/PhoneUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/PhoneUtils.java @@ -7,13 +7,13 @@ import java.util.regex.Pattern; @UtilityClass public class PhoneUtils { - private static final Pattern VALID_PHONE_PATTERN = Pattern.compile( - "^\\+?[1-9]\\d{1,14}$", - Pattern.CASE_INSENSITIVE - ); + private static final Pattern VALID_PHONE_PATTERN = Pattern.compile( + "^\\+?[1-9]\\d{1,14}$", + Pattern.CASE_INSENSITIVE + ); - public static boolean isValidPhone(String phoneNumber) { - return phoneNumber != null && VALID_PHONE_PATTERN.matcher(phoneNumber).matches(); - } + public static boolean isValidPhone(String phoneNumber) { + return phoneNumber != null && VALID_PHONE_PATTERN.matcher(phoneNumber).matches(); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/TimeUtils.java b/src/main/java/net/frozenorb/apiv3/util/TimeUtils.java index 0ce40de..fb1e741 100644 --- a/src/main/java/net/frozenorb/apiv3/util/TimeUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/TimeUtils.java @@ -7,28 +7,28 @@ import java.time.Instant; @UtilityClass public class TimeUtils { - public static String formatIntoDetailedString(int secs) { - if (secs == 0) { - return "0 seconds"; - } + public static String formatIntoDetailedString(int secs) { + if (secs == 0) { + return "0 seconds"; + } - int remainder = secs % 86400; + int remainder = secs % 86400; - int days = secs / 86400; - int hours = remainder / 3600; - int minutes = (remainder / 60) - (hours * 60); - int seconds = (remainder % 3600) - (minutes * 60); + int days = secs / 86400; + int hours = remainder / 3600; + int minutes = (remainder / 60) - (hours * 60); + int seconds = (remainder % 3600) - (minutes * 60); - String fDays = (days > 0 ? " " + days + " day" + (days > 1 ? "s" : "") : ""); - String fHours = (hours > 0 ? " " + hours + " hour" + (hours > 1 ? "s" : "") : ""); - String fMinutes = (minutes > 0 ? " " + minutes + " minute" + (minutes > 1 ? "s" : "") : ""); - String fSeconds = (seconds > 0 ? " " + seconds + " second" + (seconds > 1 ? "s" : "") : ""); + String fDays = (days > 0 ? " " + days + " day" + (days > 1 ? "s" : "") : ""); + String fHours = (hours > 0 ? " " + hours + " hour" + (hours > 1 ? "s" : "") : ""); + String fMinutes = (minutes > 0 ? " " + minutes + " minute" + (minutes > 1 ? "s" : "") : ""); + String fSeconds = (seconds > 0 ? " " + seconds + " second" + (seconds > 1 ? "s" : "") : ""); - return (fDays + fHours + fMinutes + fSeconds).trim(); - } + return (fDays + fHours + fMinutes + fSeconds).trim(); + } - public static int getSecondsBetween(Instant a, Instant b) { - return (Math.abs((int) (a.toEpochMilli() - b.toEpochMilli()) / 1000)); - } + public static int getSecondsBetween(Instant a, Instant b) { + return (Math.abs((int) (a.toEpochMilli() - b.toEpochMilli()) / 1000)); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/TotpUtils.java b/src/main/java/net/frozenorb/apiv3/util/TotpUtils.java index 3e1f7fe..76302b1 100644 --- a/src/main/java/net/frozenorb/apiv3/util/TotpUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/TotpUtils.java @@ -14,69 +14,69 @@ import java.util.concurrent.TimeUnit; @UtilityClass public class TotpUtils { - private static final GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator(new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder().setWindowSize(10).build()); - private static final RedisClient redisClient = RedisClient.create(APIv3.getVertxInstance(), - new RedisOptions() - .setAddress(APIv3.getConfig().getProperty("redis.address")) - .setPort(Integer.parseInt(APIv3.getConfig().getProperty("redis.port"))) - ); + private static final GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator(new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder().setWindowSize(10).build()); + private static final RedisClient redisClient = RedisClient.create(APIv3.getVertxInstance(), + new RedisOptions() + .setAddress(APIv3.getConfig().getProperty("redis.address")) + .setPort(Integer.parseInt(APIv3.getConfig().getProperty("redis.port"))) + ); - public static boolean authorizeUser(String secret, int code) { - return googleAuthenticator.authorize(secret, code); - } + public static boolean authorizeUser(String secret, int code) { + return googleAuthenticator.authorize(secret, code); + } - public static void isPreAuthorized(User user, String ip, SingleResultCallback callback) { - if (!IpUtils.isValidIp(ip)) { - callback.onResult(false, null); - return; - } + public static void isPreAuthorized(User user, String ip, SingleResultCallback callback) { + if (!IpUtils.isValidIp(ip)) { + callback.onResult(false, null); + return; + } - redisClient.exists(user.getId() + ":preAuthorizedIp:" + ip.toLowerCase(), (result) -> { - if (result.succeeded()) { - callback.onResult(result.result() == 1, null); - } else { - callback.onResult(null, result.cause()); - } - }); - } + redisClient.exists(user.getId() + ":preAuthorizedIp:" + ip.toLowerCase(), (result) -> { + if (result.succeeded()) { + callback.onResult(result.result() == 1, null); + } else { + callback.onResult(null, result.cause()); + } + }); + } - public static void markPreAuthorized(User user, String ip, long duration, TimeUnit unit, SingleResultCallback callback) { - if (!IpUtils.isValidIp(ip)) { - callback.onResult(null, null); - return; - } + public static void markPreAuthorized(User user, String ip, long duration, TimeUnit unit, SingleResultCallback callback) { + if (!IpUtils.isValidIp(ip)) { + callback.onResult(null, null); + return; + } - String key = user.getId() + ":preAuthorizedIp:" + ip.toLowerCase(); + String key = user.getId() + ":preAuthorizedIp:" + ip.toLowerCase(); - redisClient.setex(key, unit.toSeconds(duration), "", (result) -> { - if (result.succeeded()) { - callback.onResult(null, null); - } else { - callback.onResult(null, result.cause()); - } - }); - } + redisClient.setex(key, unit.toSeconds(duration), "", (result) -> { + if (result.succeeded()) { + callback.onResult(null, null); + } else { + callback.onResult(null, result.cause()); + } + }); + } - public static void wasRecentlyUsed(User user, int code, SingleResultCallback callback) { - redisClient.exists(user.getId() + ":recentTotpCodes:" + code, (result) -> { - if (result.succeeded()) { - callback.onResult(result.result() == 1 , null); - } else { - callback.onResult(null, result.cause()); - } - }); - } + public static void wasRecentlyUsed(User user, int code, SingleResultCallback callback) { + redisClient.exists(user.getId() + ":recentTotpCodes:" + code, (result) -> { + if (result.succeeded()) { + callback.onResult(result.result() == 1, null); + } else { + callback.onResult(null, result.cause()); + } + }); + } - public static void markRecentlyUsed(User user, int code, SingleResultCallback callback) { - String key = user.getId() + ":recentTotpCodes:" + code; + public static void markRecentlyUsed(User user, int code, SingleResultCallback callback) { + String key = user.getId() + ":recentTotpCodes:" + code; - redisClient.setex(key, TimeUnit.MINUTES.toSeconds(5), "", (result) -> { - if (result.succeeded()) { - callback.onResult(null, null); - } else { - callback.onResult(null, result.cause()); - } - }); - } + redisClient.setex(key, TimeUnit.MINUTES.toSeconds(5), "", (result) -> { + if (result.succeeded()) { + callback.onResult(null, null); + } else { + callback.onResult(null, result.cause()); + } + }); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/UuidUtils.java b/src/main/java/net/frozenorb/apiv3/util/UuidUtils.java index 1bc5b54..a4bc9d2 100644 --- a/src/main/java/net/frozenorb/apiv3/util/UuidUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/UuidUtils.java @@ -7,18 +7,18 @@ import java.util.UUID; @UtilityClass public class UuidUtils { - public static boolean isAcceptableUuid(UUID uuid) { - return uuid.version() == 4; - } + public static boolean isAcceptableUuid(UUID uuid) { + return uuid.version() == 4; + } - public static UUID parseUuid(String input) { - if (input.length() == 36) { - return UUID.fromString(input); - } else if (input.length() == 32) { - return UUID.fromString(input.replaceFirst("([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5")); - } else { - throw new IllegalArgumentException("Invalid UUID string: " + input); - } - } + public static UUID parseUuid(String input) { + if (input.length() == 36) { + return UUID.fromString(input); + } else if (input.length() == 32) { + return UUID.fromString(input.replaceFirst("([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5")); + } else { + throw new IllegalArgumentException("Invalid UUID string: " + input); + } + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/util/ZangUtils.java b/src/main/java/net/frozenorb/apiv3/util/ZangUtils.java index ef7d3c8..f9638aa 100644 --- a/src/main/java/net/frozenorb/apiv3/util/ZangUtils.java +++ b/src/main/java/net/frozenorb/apiv3/util/ZangUtils.java @@ -17,52 +17,52 @@ import java.util.Base64; @UtilityClass public class ZangUtils { - private static final String zangAccountSid = APIv3.getConfig().getProperty("zang.accountSid"); - private static final String zangAuthToken = APIv3.getConfig().getProperty("zang.authToken"); - private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); + private static final String zangAccountSid = APIv3.getConfig().getProperty("zang.accountSid"); + private static final String zangAuthToken = APIv3.getConfig().getProperty("zang.authToken"); + private static final HttpClient httpsClient = APIv3.getVertxInstance().createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)); - public static void sendText(String to, String messageBody, SingleResultCallback callback) { - String authHeader = "Basic " + Base64.getEncoder().encodeToString((zangAccountSid + ":" + zangAuthToken).getBytes(Charsets.UTF_8)); + public static void sendText(String to, String messageBody, SingleResultCallback callback) { + String authHeader = "Basic " + Base64.getEncoder().encodeToString((zangAccountSid + ":" + zangAuthToken).getBytes(Charsets.UTF_8)); - httpsClient.post(443, "api.zang.io", "/v2/Accounts/" + zangAccountSid + "/SMS/Messages.json", (response) -> { - response.bodyHandler((body) -> { - JsonObject bodyJson = new JsonObject(body.toString()); + httpsClient.post(443, "api.zang.io", "/v2/Accounts/" + zangAccountSid + "/SMS/Messages.json", (response) -> { + response.bodyHandler((body) -> { + JsonObject bodyJson = new JsonObject(body.toString()); - if (bodyJson.getString("status", "").equals("queued")) { - callback.onResult(null, null); - } else { - callback.onResult(null, new IOException("Could not send text message: " + bodyJson.encode())); - } - }); + if (bodyJson.getString("status", "").equals("queued")) { + callback.onResult(null, null); + } else { + callback.onResult(null, new IOException("Could not send text message: " + bodyJson.encode())); + } + }); - response.exceptionHandler((error) -> callback.onResult(null, error)); - }) - .putHeader("Authorization", authHeader) - .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) - .end("To=" + to + "&From=339-337-5300&Body=" + messageBody); - } + response.exceptionHandler((error) -> callback.onResult(null, error)); + }) + .putHeader("Authorization", authHeader) + .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) + .end("To=" + to + "&From=339-337-5300&Body=" + messageBody); + } - public static void getCarrierInfo(String phoneNumber, SingleResultCallback callback) { - String authHeader = "Basic " + Base64.getEncoder().encodeToString((zangAccountSid + ":" + zangAuthToken).getBytes(Charsets.UTF_8)); + public static void getCarrierInfo(String phoneNumber, SingleResultCallback callback) { + String authHeader = "Basic " + Base64.getEncoder().encodeToString((zangAccountSid + ":" + zangAuthToken).getBytes(Charsets.UTF_8)); - httpsClient.post(443, "api.zang.io", "/v2/Accounts/" + zangAccountSid + "/Lookups/Carrier.json", (response) -> { - response.bodyHandler((body) -> { - JsonObject bodyJson = new JsonObject(body.toString()); + httpsClient.post(443, "api.zang.io", "/v2/Accounts/" + zangAccountSid + "/Lookups/Carrier.json", (response) -> { + response.bodyHandler((body) -> { + JsonObject bodyJson = new JsonObject(body.toString()); - if (bodyJson.containsKey("carrier_lookups")) { - // Zang returns an array, but we don't batch at all so we always just get the first element - JsonObject lookupResult = bodyJson.getJsonArray("carrier_lookups").getJsonObject(0); - callback.onResult(new ZangResult(lookupResult), null); - } else { - callback.onResult(null, new IOException("Could not parse Zang result: " + bodyJson.encode())); - } - }); + if (bodyJson.containsKey("carrier_lookups")) { + // Zang returns an array, but we don't batch at all so we always just get the first element + JsonObject lookupResult = bodyJson.getJsonArray("carrier_lookups").getJsonObject(0); + callback.onResult(new ZangResult(lookupResult), null); + } else { + callback.onResult(null, new IOException("Could not parse Zang result: " + bodyJson.encode())); + } + }); - response.exceptionHandler((error) -> callback.onResult(null, error)); - }) - .putHeader("Authorization", authHeader) - .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) - .end("PhoneNumber=" + phoneNumber); - } + response.exceptionHandler((error) -> callback.onResult(null, error)); + }) + .putHeader("Authorization", authHeader) + .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) + .end("PhoneNumber=" + phoneNumber); + } } \ No newline at end of file diff --git a/src/main/java/net/frozenorb/apiv3/zang/ZangResult.java b/src/main/java/net/frozenorb/apiv3/zang/ZangResult.java index 78fb3ab..983180d 100644 --- a/src/main/java/net/frozenorb/apiv3/zang/ZangResult.java +++ b/src/main/java/net/frozenorb/apiv3/zang/ZangResult.java @@ -5,18 +5,18 @@ import lombok.Getter; public final class ZangResult { - @Getter private String countryCode; - @Getter private int carrierId; - @Getter private String network; - @Getter private boolean mobile; + @Getter private String countryCode; + @Getter private int carrierId; + @Getter private String network; + @Getter private boolean mobile; - private ZangResult() {} // For Jackson + private ZangResult() {} // For Jackson - public ZangResult(JsonObject legacy) { - this.countryCode = legacy.getString("country_code"); - this.carrierId = legacy.getInteger("carrier_id"); - this.network = legacy.getString("network"); - this.mobile = Boolean.parseBoolean(legacy.getString("mobile")); - } + public ZangResult(JsonObject legacy) { + this.countryCode = legacy.getString("country_code"); + this.carrierId = legacy.getInteger("carrier_id"); + this.network = legacy.getString("network"); + this.mobile = Boolean.parseBoolean(legacy.getString("mobile")); + } } \ No newline at end of file diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml index 4226e1b..4ef59d6 100644 --- a/src/main/resources/log4j.xml +++ b/src/main/resources/log4j.xml @@ -3,8 +3,8 @@ - - + + @@ -19,8 +19,8 @@ - - + + \ No newline at end of file