Merge pull request #43 from FrozenOrb/reformat-test

Proper formatting
This commit is contained in:
Colin McDonald 2016-07-14 21:58:30 -04:00 committed by GitHub
commit 8f7f19035f
137 changed files with 4484 additions and 4476 deletions

View File

@ -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<MongoCredential> credentials = ImmutableList.of();
private void setupDatabase() {
List<MongoCredential> 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));
}
}

View File

@ -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());
}
}

View File

@ -2,8 +2,10 @@ package net.frozenorb.apiv3.actor;
public interface Actor {
boolean isAuthorized();
String getName();
ActorType getType();
boolean isAuthorized();
String getName();
ActorType getType();
}

View File

@ -2,6 +2,6 @@ package net.frozenorb.apiv3.actor;
public enum ActorType {
WEBSITE, STORE, BUNGEE_CORD, SERVER, UNKNOWN
WEBSITE, STORE, BUNGEE_CORD, SERVER, UNKNOWN
}

View File

@ -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;
}

View File

@ -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<AuditLogEntry> callback) {
log(performedBy, performedByIp, ctx, actionType, ImmutableMap.of(), callback);
}
public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, SingleResultCallback<AuditLogEntry> callback) {
log(performedBy, performedByIp, ctx, actionType, ImmutableMap.of(), callback);
}
public static void log(UUID performedBy, String performedByIp, RoutingContext ctx, AuditLogActionType actionType, Map<String, Object> actionData, SingleResultCallback<AuditLogEntry> 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<String, Object> actionData, SingleResultCallback<AuditLogEntry> 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);
}
});
}
}

View File

@ -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<Void> callback) {
String punishmentId = (String) entry.getMetadata().get("punishmentId");
@Override
public void reverse(AuditLogEntry entry, SingleResultCallback<Void> 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<Void> callback) {
callback.onResult(null, new UnsupportedOperationException());
}
public void reverse(AuditLogEntry entry, SingleResultCallback<Void> callback) {
callback.onResult(null, new UnsupportedOperationException());
}
}

View File

@ -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<Void> callback) {
Map<ObjectId, UUID> oidToUniqueId = new HashMap<>();
public void startImport(SingleResultCallback<Void> callback) {
Map<ObjectId, UUID> 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<Void> punishmentsFuture = Future.future();
Future<Void> grantsFuture = Future.future();
Future<Void> ipLogFuture = Future.future();
Future<Void> punishmentsFuture = Future.future();
Future<Void> grantsFuture = Future.future();
Future<Void> 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());
}
});
});
}
}

View File

@ -16,51 +16,51 @@ import java.util.UUID;
@Slf4j
public final class GrantConverter implements Block<Document> {
private final Map<ObjectId, UUID> oidToUniqueId;
private final Map<ObjectId, UUID> oidToUniqueId;
public GrantConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
public GrantConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
@SuppressWarnings("unchecked")
@Override
public void apply(Document grant) {
UUID target = oidToUniqueId.get(((Map<String, Object>) grant.get("target")).get("$id"));
@SuppressWarnings("unchecked")
@Override
public void apply(Document grant) {
UUID target = oidToUniqueId.get(((Map<String, Object>) 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<String>) grant.get("scope")) : ImmutableSet.of(),
rank,
grant.containsKey("expires") ? grant.getDate("expires").toInstant() : null,
grant.containsKey("addedBy") ? oidToUniqueId.get(((Map<String, Object>) 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<String>) grant.get("scope")) : ImmutableSet.of(),
rank,
grant.containsKey("expires") ? grant.getDate("expires").toInstant() : null,
grant.containsKey("addedBy") ? oidToUniqueId.get(((Map<String, Object>) grant.get("addedBy")).get("$id")) : null,
grant.containsKey("created") ? grant.getDate("created").toInstant() : Instant.now(),
null,
null,
null,
-1,
-1
);
SyncUtils.<Void>runBlocking(v -> created.insert(v));
log.info("Created grant " + created.getId() + " (" + created.getRank() + ")");
}
SyncUtils.<Void>runBlocking(v -> created.insert(v));
log.info("Created grant " + created.getId() + " (" + created.getRank() + ")");
}
}

View File

@ -15,44 +15,44 @@ import java.util.UUID;
@Slf4j
public final class IpLogConverter implements Block<Document> {
private final Map<ObjectId, UUID> oidToUniqueId;
private final Map<ObjectId, UUID> oidToUniqueId;
public IpLogConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
public IpLogConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
@SuppressWarnings("unchecked")
@Override
public void apply(Document ipLogEntry) {
UUID user = oidToUniqueId.get(((Map<String, Object>) ipLogEntry.get("user")).get("$id"));
@SuppressWarnings("unchecked")
@Override
public void apply(Document ipLogEntry) {
UUID user = oidToUniqueId.get(((Map<String, Object>) 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.<Void>runBlocking(v -> created.insert(v));
log.info("Created ip log entry " + created.getId() + " (" + created.getUser() + " - " + created.getUserIp() + ")");
}
SyncUtils.<Void>runBlocking(v -> created.insert(v));
log.info("Created ip log entry " + created.getId() + " (" + created.getUser() + " - " + created.getUserIp() + ")");
}
}

View File

@ -16,46 +16,46 @@ import java.util.UUID;
@Slf4j
public final class PunishmentConverter implements Block<Document> {
private final Map<ObjectId, UUID> oidToUniqueId;
private final Map<ObjectId, UUID> oidToUniqueId;
public PunishmentConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
public PunishmentConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
@SuppressWarnings("unchecked")
@Override
public void apply(Document punishment) {
UUID target = oidToUniqueId.get(((Map<String, Object>) punishment.get("user")).get("$id"));
@SuppressWarnings("unchecked")
@Override
public void apply(Document punishment) {
UUID target = oidToUniqueId.get(((Map<String, Object>) 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<String, Object>) punishment.get("addedBy")).get("$id")) : null,
punishment.getDate("created").toInstant(),
punishment.containsKey("createdOn") ? String.valueOf(((Map<String, Object>) punishment.get("createdOn")).get("$id")) : "Old Website",
punishment.containsKey("createdOn") ? ActorType.SERVER : ActorType.WEBSITE,
punishment.containsKey("removedBy") ? (((Map<String, Object>) punishment.get("removedBy")).get("$ref").equals("user") ? oidToUniqueId.get(((Map<String, Object>) 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<String, Object>) punishment.get("addedBy")).get("$id")) : null,
punishment.getDate("created").toInstant(),
punishment.containsKey("createdOn") ? String.valueOf(((Map<String, Object>) punishment.get("createdOn")).get("$id")) : "Old Website",
punishment.containsKey("createdOn") ? ActorType.SERVER : ActorType.WEBSITE,
punishment.containsKey("removedBy") ? (((Map<String, Object>) punishment.get("removedBy")).get("$ref").equals("user") ? oidToUniqueId.get(((Map<String, Object>) 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.<Void>runBlocking(v -> created.insert(v));
log.info("Created punishment " + created.getId() + " (" + created.getType() + ")");
}
SyncUtils.<Void>runBlocking(v -> created.insert(v));
log.info("Created punishment " + created.getId() + " (" + created.getType() + ")");
}
}

View File

@ -16,56 +16,56 @@ import java.util.UUID;
@Slf4j
public final class UserConverter implements Block<Document> {
private final Map<ObjectId, UUID> oidToUniqueId;
private final Map<ObjectId, UUID> oidToUniqueId;
public UserConverter(Map<ObjectId, UUID> oidToUniqueId) {
this.oidToUniqueId = oidToUniqueId;
}
public UserConverter(Map<ObjectId, UUID> 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.<Void>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.<Void>runBlocking(v -> created.insert(v));
log.info("Created user " + created.getLastUsername() + " (" + created.getId() + ")");
}
}

View File

@ -10,51 +10,51 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class ActorAttributeHandler implements Handler<RoutingContext> {
@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();
}
}

View File

@ -8,15 +8,15 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class AuthorizationHandler implements Handler<RoutingContext> {
@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());
}
}
}

View File

@ -49,7 +49,7 @@ public final class WebsiteUserSessionHandler implements Handler<RoutingContext>
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());

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<MaxMindSubdivision> 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<MaxMindSubdivision> 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<MaxMindSubdivision> subdivisions = new LinkedList<>();
List<MaxMindSubdivision> 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);
}
}

View File

@ -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", "");
}
}

View File

@ -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;
}
}

View File

@ -22,53 +22,53 @@ import java.util.UUID;
@AllArgsConstructor
public final class AccessToken {
private static final MongoCollection<AccessToken> accessTokensCollection = APIv3.getDatabase().getCollection("accessTokens", AccessToken.class);
private static final MongoCollection<AccessToken> accessTokensCollection = APIv3.getDatabase().getCollection("accessTokens", AccessToken.class);
@Getter @Id private String id;
@Getter private String actorName;
@Getter private ActorType actorType;
@Getter private List<String> 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<String> lockedIps;
@Getter private Instant createdAt;
@Getter private Instant lastUpdatedAt;
public static void findAll(SingleResultCallback<List<AccessToken>> callback) {
accessTokensCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<AccessToken>> callback) {
accessTokensCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<AccessToken> callback) {
accessTokensCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<AccessToken> callback) {
accessTokensCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByNameAndType(String actorName, ActorType actorType, SingleResultCallback<AccessToken> callback) {
accessTokensCollection.find(new Document("actorName", actorName).append("actorType", actorType.name())).first(SyncUtils.vertxWrap(callback));
}
public static void findByNameAndType(String actorName, ActorType actorType, SingleResultCallback<AccessToken> 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<String> 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<String> 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<Void> callback) {
accessTokensCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
accessTokensCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
accessTokensCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
accessTokensCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
accessTokensCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
accessTokensCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -23,50 +23,50 @@ import java.util.UUID;
@Entity
public final class AuditLogEntry {
private static final MongoCollection<AuditLogEntry> auditLogCollection = APIv3.getDatabase().getCollection("auditLog", AuditLogEntry.class);
private static final MongoCollection<AuditLogEntry> 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<String, Object> 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<String, Object> metadata;
public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback<List<AuditLogEntry>> 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<List<AuditLogEntry>> 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<AuditLogEntry> callback) {
auditLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<AuditLogEntry> callback) {
auditLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void find(Document query, SingleResultCallback<List<AuditLogEntry>> callback) {
auditLogCollection.find(query).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void find(Document query, SingleResultCallback<List<AuditLogEntry>> 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<String, Object> 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<String, Object> 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<Void> callback) {
auditLogCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
auditLogCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
}

View File

@ -22,74 +22,74 @@ import java.util.concurrent.TimeUnit;
@Entity
public final class BannedAsn {
private static final MongoCollection<BannedAsn> bannedAsnsCollection = APIv3.getDatabase().getCollection("bannedAsns", BannedAsn.class);
private static final MongoCollection<BannedAsn> bannedAsnsCollection = APIv3.getDatabase().getCollection("bannedAsns", BannedAsn.class);
private static Map<Integer, BannedAsn> bannedAsnIdCache = null;
private static List<BannedAsn> bannedAsnCache = null;
private static Map<Integer, BannedAsn> bannedAsnIdCache = null;
private static List<BannedAsn> 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<BannedAsn> findAll() {
return ImmutableList.copyOf(bannedAsnCache);
}
public static List<BannedAsn> 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<Integer, BannedAsn> working = new HashMap<>();
Map<Integer, BannedAsn> 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<Void> callback) {
bannedAsnCache.add(this);
bannedAsnIdCache.put(id, this);
bannedAsnsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
bannedAsnCache.add(this);
bannedAsnIdCache.put(id, this);
bannedAsnsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
bannedAsnsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
bannedAsnsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
bannedAsnCache.remove(this);
bannedAsnIdCache.remove(id);
bannedAsnsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
bannedAsnCache.remove(this);
bannedAsnIdCache.remove(id);
bannedAsnsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -23,74 +23,74 @@ import java.util.concurrent.TimeUnit;
@Entity
public final class BannedCellCarrier {
private static final MongoCollection<BannedCellCarrier> bannedCellCarriersCollection = APIv3.getDatabase().getCollection("bannedCellCarriers", BannedCellCarrier.class);
private static final MongoCollection<BannedCellCarrier> bannedCellCarriersCollection = APIv3.getDatabase().getCollection("bannedCellCarriers", BannedCellCarrier.class);
private static Map<Integer, BannedCellCarrier> bannedCellCarrierIdCache = null;
private static List<BannedCellCarrier> bannedCellCarrierCache = null;
private static Map<Integer, BannedCellCarrier> bannedCellCarrierIdCache = null;
private static List<BannedCellCarrier> 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<BannedCellCarrier> findAll() {
return ImmutableList.copyOf(bannedCellCarrierCache);
}
public static List<BannedCellCarrier> 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<Integer, BannedCellCarrier> working = new HashMap<>();
Map<Integer, BannedCellCarrier> 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<Void> callback) {
bannedCellCarrierCache.add(this);
bannedCellCarrierIdCache.put(id, this);
bannedCellCarriersCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
bannedCellCarrierCache.add(this);
bannedCellCarrierIdCache.put(id, this);
bannedCellCarriersCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
bannedCellCarriersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
bannedCellCarriersCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
bannedCellCarrierCache.remove(this);
bannedCellCarrierIdCache.remove(id);
bannedCellCarriersCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
bannedCellCarrierCache.remove(this);
bannedCellCarrierIdCache.remove(id);
bannedCellCarriersCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -21,119 +21,119 @@ import java.util.stream.Collectors;
@AllArgsConstructor
public final class Grant {
private static final MongoCollection<Grant> grantsCollection = APIv3.getDatabase().getCollection("grants", Grant.class);
private static final MongoCollection<Grant> grantsCollection = APIv3.getDatabase().getCollection("grants", Grant.class);
@Getter @Id private String id;
@Getter private UUID user;
@Getter private String reason;
@Getter private Set<String> 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<String> 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<List<Grant>> callback) {
grantsCollection.find().sort(new Document("addedAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<Grant>> callback) {
grantsCollection.find().sort(new Document("addedAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByRank(Collection<Rank> ranks, SingleResultCallback<List<Grant>> callback) {
Collection<String> 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<Rank> ranks, SingleResultCallback<List<Grant>> callback) {
Collection<String> 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<List<Grant>> 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<List<Grant>> 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<Grant> callback) {
grantsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<Grant> callback) {
grantsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByUser(User user, SingleResultCallback<List<Grant>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(User user, SingleResultCallback<List<Grant>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(UUID user, SingleResultCallback<List<Grant>> callback) {
grantsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByUser(UUID user, SingleResultCallback<List<Grant>> callback) {
grantsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByUserGrouped(Iterable<UUID> users, SingleResultCallback<Map<UUID, List<Grant>>> 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<UUID, List<Grant>> result = new HashMap<>();
public static void findByUserGrouped(Iterable<UUID> users, SingleResultCallback<Map<UUID, List<Grant>>> 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<UUID, List<Grant>> 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<ServerGroup> scopes, Rank rank, Instant expiresAt, User addedBy) {
this(user, reason, scopes, rank, expiresAt, addedBy, -1, -1);
}
public Grant(User user, String reason, Set<ServerGroup> scopes, Rank rank, Instant expiresAt, User addedBy) {
this(user, reason, scopes, rank, expiresAt, addedBy, -1, -1);
}
public Grant(User user, String reason, Set<ServerGroup> 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<ServerGroup> 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<Void> callback) {
grantsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
grantsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void delete(User removedBy, String reason, SingleResultCallback<Void> callback) {
this.removedBy = removedBy == null ? null : removedBy.getId();
this.removedAt = Instant.now();
this.removalReason = reason;
public void delete(User removedBy, String reason, SingleResultCallback<Void> 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)));
}
}

View File

@ -22,143 +22,143 @@ import java.util.*;
@AllArgsConstructor
public final class IpBan {
private static final MongoCollection<IpBan> ipBansCollection = APIv3.getDatabase().getCollection("ipBans", IpBan.class);
private static final MongoCollection<IpBan> 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<List<IpBan>> callback) {
ipBansCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void find(SingleResultCallback<List<IpBan>> callback) {
ipBansCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findPaginated(Document query, int skip, int pageSize, SingleResultCallback<List<IpBan>> 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<List<IpBan>> 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<IpBan> callback) {
ipBansCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<IpBan> callback) {
ipBansCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByIp(String userIp, SingleResultCallback<List<IpBan>> callback) {
ipBansCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByIp(String userIp, SingleResultCallback<List<IpBan>> callback) {
ipBansCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByIpGrouped(Iterable<String> userIps, SingleResultCallback<Map<String, List<IpBan>>> 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<String, List<IpBan>> result = new HashMap<>();
public static void findByIpGrouped(Iterable<String> userIps, SingleResultCallback<Map<String, List<IpBan>>> 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<String, List<IpBan>> 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<String> callback) {
Punishment.findByLinkedIpBanId(id, (punishment, error) -> {
if (error != null) {
callback.onResult(null, error);
return;
}
public void getAccessDenialReason(SingleResultCallback<String> 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<Void> callback) {
ipBansCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
ipBansCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void delete(User removedBy, String reason, SingleResultCallback<Void> callback) {
this.removedBy = removedBy == null ? null : removedBy.getId();
this.removedAt = Instant.now();
this.removalReason = reason;
public void delete(User removedBy, String reason, SingleResultCallback<Void> 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)));
}
}

View File

@ -22,113 +22,113 @@ import java.util.concurrent.ConcurrentHashMap;
@AllArgsConstructor
public final class IpIntel {
private static final MongoCollection<IpIntel> ipIntelCollection = APIv3.getDatabase().getCollection("ipIntel", IpIntel.class);
private static final MongoCollection<IpIntel> 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<List<IpIntel>> callback) {
ipIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<IpIntel>> callback) {
ipIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<IpIntel> callback) {
ipIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<IpIntel> callback) {
ipIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findOrCreateById(String id, SingleResultCallback<IpIntel> 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<IpIntel> 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<String> search, SingleResultCallback<Map<String, IpIntel>> 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<String> search, SingleResultCallback<Map<String, IpIntel>> 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<String, IpIntel> result = new ConcurrentHashMap<>();
Map<String, IpIntel> result = new ConcurrentHashMap<>();
for (IpIntel ipIntel : existingIntel) {
result.put(ipIntel.getId(), ipIntel);
}
for (IpIntel ipIntel : existingIntel) {
result.put(ipIntel.getId(), ipIntel);
}
List<Future> createNewIntelFutures = new ArrayList<>();
List<Future> 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;
}
}

View File

@ -21,65 +21,65 @@ import java.util.UUID;
@AllArgsConstructor
public final class IpLogEntry {
private static final MongoCollection<IpLogEntry> ipLogCollection = APIv3.getDatabase().getCollection("ipLog", IpLogEntry.class);
private static final MongoCollection<IpLogEntry> 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<List<IpLogEntry>> callback) {
ipLogCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<IpLogEntry>> callback) {
ipLogCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<IpLogEntry> callback) {
ipLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<IpLogEntry> callback) {
ipLogCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByUser(User user, SingleResultCallback<List<IpLogEntry>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(User user, SingleResultCallback<List<IpLogEntry>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(UUID user, SingleResultCallback<List<IpLogEntry>> 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<List<IpLogEntry>> 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<List<IpLogEntry>> callback) {
ipLogCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByIp(String userIp, SingleResultCallback<List<IpLogEntry>> callback) {
ipLogCollection.find(new Document("userIp", userIp)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByUserAndIp(User user, String userIp, SingleResultCallback<IpLogEntry> callback) {
findByUserAndIp(user.getId(), userIp, callback);
}
public static void findByUserAndIp(User user, String userIp, SingleResultCallback<IpLogEntry> callback) {
findByUserAndIp(user.getId(), userIp, callback);
}
public static void findByUserAndIp(UUID user, String userIp, SingleResultCallback<IpLogEntry> callback) {
ipLogCollection.find(new Document("user", user).append("userIp", userIp)).first(SyncUtils.vertxWrap(callback));
}
public static void findByUserAndIp(UUID user, String userIp, SingleResultCallback<IpLogEntry> 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<Void> callback) {
ipLogCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
ipLogCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
ipLogCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
ipLogCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -18,53 +18,53 @@ import java.util.Map;
@Entity
public final class NotificationTemplate {
private static final MongoCollection<NotificationTemplate> notificationTemplatesCollection = APIv3.getDatabase().getCollection("notificationTemplates", NotificationTemplate.class);
private static final MongoCollection<NotificationTemplate> 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<List<NotificationTemplate>> callback) {
notificationTemplatesCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<NotificationTemplate>> callback) {
notificationTemplatesCollection.find().into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<NotificationTemplate> callback) {
notificationTemplatesCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<NotificationTemplate> 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<String, Object> replacements) {
return fill(subject, replacements);
}
public String fillSubject(Map<String, Object> replacements) {
return fill(subject, replacements);
}
public String fillBody(Map<String, Object> replacements) {
return fill(body, replacements);
}
public String fillBody(Map<String, Object> replacements) {
return fill(body, replacements);
}
private String fill(String working, Map<String, Object> replacements) {
for (Map.Entry<String, Object> replacement : replacements.entrySet()) {
String key = replacement.getKey();
String value = String.valueOf(replacement.getValue());
private String fill(String working, Map<String, Object> replacements) {
for (Map.Entry<String, Object> 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<Void> callback) {
notificationTemplatesCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
notificationTemplatesCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void delete(SingleResultCallback<Void> callback) {
notificationTemplatesCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
notificationTemplatesCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -20,52 +20,52 @@ import java.util.List;
@AllArgsConstructor
public final class PhoneIntel {
private static final MongoCollection<PhoneIntel> phoneIntelCollection = APIv3.getDatabase().getCollection("phoneIntel", PhoneIntel.class);
private static final MongoCollection<PhoneIntel> 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<List<PhoneIntel>> callback) {
phoneIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findAll(SingleResultCallback<List<PhoneIntel>> callback) {
phoneIntelCollection.find().sort(new Document("lastSeenAt", -1)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<PhoneIntel> callback) {
phoneIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<PhoneIntel> callback) {
phoneIntelCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findOrCreateById(String id, SingleResultCallback<PhoneIntel> 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<PhoneIntel> 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;
}
}

View File

@ -23,169 +23,169 @@ import java.util.stream.Collectors;
@AllArgsConstructor
public final class Punishment {
private static final MongoCollection<Punishment> punishmentsCollection = APIv3.getDatabase().getCollection("punishments", Punishment.class);
private static final MongoCollection<Punishment> 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<String, Object> 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<String, Object> 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<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
Collection<String> 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<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
Collection<String> 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<List<Punishment>> 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<List<Punishment>> 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<Punishment> callback) {
punishmentsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findById(String id, SingleResultCallback<Punishment> callback) {
punishmentsCollection.find(new Document("_id", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByLinkedIpBanId(String id, SingleResultCallback<Punishment> callback) {
punishmentsCollection.find(new Document("linkedIpBanId", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByLinkedIpBanId(String id, SingleResultCallback<Punishment> callback) {
punishmentsCollection.find(new Document("linkedIpBanId", id)).first(SyncUtils.vertxWrap(callback));
}
public static void findByUser(User user, SingleResultCallback<List<Punishment>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(User user, SingleResultCallback<List<Punishment>> callback) {
findByUser(user.getId(), callback);
}
public static void findByUser(UUID user, SingleResultCallback<List<Punishment>> callback) {
punishmentsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByUser(UUID user, SingleResultCallback<List<Punishment>> callback) {
punishmentsCollection.find(new Document("user", user)).into(new LinkedList<>(), SyncUtils.vertxWrap(callback));
}
public static void findByUserGrouped(Iterable<UUID> users, SingleResultCallback<Map<UUID, List<Punishment>>> 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<UUID, List<Punishment>> result = new HashMap<>();
public static void findByUserGrouped(Iterable<UUID> users, SingleResultCallback<Map<UUID, List<Punishment>>> 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<UUID, List<Punishment>> 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<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
findByUserAndType(user.getId(), types, callback);
}
public static void findByUserAndType(User user, Collection<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
findByUserAndType(user.getId(), types, callback);
}
public static void findByUserAndType(UUID user, Collection<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
Collection<String> 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<PunishmentType> types, SingleResultCallback<List<Punishment>> callback) {
Collection<String> 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<String, Object> 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<String, Object> 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<Void> callback) {
punishmentsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
punishmentsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void delete(User removedBy, String reason, SingleResultCallback<Void> callback) {
this.removedBy = removedBy == null ? null : removedBy.getId();
this.removedAt = Instant.now();
this.removalReason = reason;
public void delete(User removedBy, String reason, SingleResultCallback<Void> 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
}
}
}

View File

@ -20,73 +20,73 @@ import java.util.concurrent.TimeUnit;
@Entity
public final class Rank {
private static final MongoCollection<Rank> ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class);
private static final MongoCollection<Rank> ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class);
private static Map<String, Rank> rankIdCache = null;
private static List<Rank> rankCache = null;
private static Map<String, Rank> rankIdCache = null;
private static List<Rank> 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<Rank> findAll() {
return ImmutableList.copyOf(rankCache);
}
public static List<Rank> 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<String, Rank> working = new HashMap<>();
Map<String, Rank> 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<Void> callback) {
rankCache.add(this);
rankIdCache.put(id, this);
ranksCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
rankCache.add(this);
rankIdCache.put(id, this);
ranksCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void delete(SingleResultCallback<Void> callback) {
rankCache.remove(this);
rankIdCache.remove(id);
ranksCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
rankCache.remove(this);
rankIdCache.remove(id);
ranksCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -21,116 +21,116 @@ import java.util.concurrent.TimeUnit;
@Entity
public final class Server {
private static final MongoCollection<Server> serversCollection = APIv3.getDatabase().getCollection("servers", Server.class);
private static final MongoCollection<Server> serversCollection = APIv3.getDatabase().getCollection("servers", Server.class);
private static Map<String, Server> serverIdCache = null;
private static List<Server> serverCache = null;
private static Map<String, Server> serverIdCache = null;
private static List<Server> 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<UUID> 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<UUID> players;
public static List<Server> findAll() {
return ImmutableList.copyOf(serverCache);
}
public static List<Server> 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<String, Server> working = new HashMap<>();
Map<String, Server> 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<UUID> players) {
this.lastUpdatedAt = Instant.now();
this.lastTps = tps;
this.players = ImmutableSet.copyOf(players);
}
public void receivedHeartbeat(double tps, Iterable<UUID> players) {
this.lastUpdatedAt = Instant.now();
this.lastTps = tps;
this.players = ImmutableSet.copyOf(players);
}
public void insert(SingleResultCallback<Void> callback) {
serverCache.add(this);
serverIdCache.put(id, this);
serversCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
serverCache.add(this);
serverIdCache.put(id, this);
serversCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
serversCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
serversCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
serverCache.remove(this);
serverIdCache.remove(id);
serversCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
serverCache.remove(this);
serverIdCache.remove(id);
serversCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

View File

@ -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<ServerGroup> serverGroupsCollection = APIv3.getDatabase().getCollection("serverGroups", ServerGroup.class);
public static final String DEFAULT_GROUP_ID = "default";
private static final MongoCollection<ServerGroup> serverGroupsCollection = APIv3.getDatabase().getCollection("serverGroups", ServerGroup.class);
private static Map<String, ServerGroup> serverGroupIdCache = null;
private static List<ServerGroup> serverGroupCache = null;
private static Map<String, ServerGroup> serverGroupIdCache = null;
private static List<ServerGroup> serverGroupCache = null;
@Getter @Id private String id;
@Getter private String image;
@Getter @Setter private Set<String> announcements;
@Getter @Setter @ExcludeFromReplies private Map<String, List<String>> permissions;
@Getter @Id private String id;
@Getter private String image;
@Getter @Setter private Set<String> announcements;
@Getter @Setter @ExcludeFromReplies private Map<String, List<String>> permissions;
public static List<ServerGroup> findAll() {
return ImmutableList.copyOf(serverGroupCache);
}
public static List<ServerGroup> 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<String, ServerGroup> working = new HashMap<>();
Map<String, ServerGroup> 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<String, Boolean> calculatePermissions(Rank rank) {
if (permissions == null) {
return ImmutableMap.of();
} else {
return PermissionUtils.mergeUpTo(permissions, rank);
}
}
public Map<String, Boolean> calculatePermissions(Rank rank) {
if (permissions == null) {
return ImmutableMap.of();
} else {
return PermissionUtils.mergeUpTo(permissions, rank);
}
}
public void insert(SingleResultCallback<Void> callback) {
serverGroupCache.add(this);
serverGroupIdCache.put(id, this);
serverGroupsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void insert(SingleResultCallback<Void> callback) {
serverGroupCache.add(this);
serverGroupIdCache.put(id, this);
serverGroupsCollection.insertOne(this, SyncUtils.vertxWrap(callback));
}
public void save(SingleResultCallback<Void> callback) {
serverGroupsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void save(SingleResultCallback<Void> callback) {
serverGroupsCollection.replaceOne(new Document("_id", id), this, SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
serverGroupCache.remove(this);
serverGroupIdCache.remove(id);
serverGroupsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
public void delete(SingleResultCallback<Void> callback) {
serverGroupCache.remove(this);
serverGroupIdCache.remove(id);
serverGroupsCollection.deleteOne(new Document("_id", id), SyncUtils.vertxWrap(new MongoToVoidMongoCallback<>(callback)));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -16,117 +16,117 @@ import java.util.concurrent.TimeUnit;
public final class GETDumpsType implements Handler<RoutingContext> {
private static List<UUID> banCache = ImmutableList.of();
private static List<UUID> blacklistCache = ImmutableList.of();
private static List<String> ipBanCache = ImmutableList.of();
private static Map<String, List<UUID>> grantCache = ImmutableMap.of();
private static List<UUID> banCache = ImmutableList.of();
private static List<UUID> blacklistCache = ImmutableList.of();
private static List<String> ipBanCache = ImmutableList.of();
private static Map<String, List<UUID>> 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<UUID> banCache = new LinkedList<>();
List<UUID> blacklistCache = new LinkedList<>();
List<UUID> banCache = new LinkedList<>();
List<UUID> 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<String, List<UUID>> grantCache = new HashMap<>();
Map<String, List<UUID>> grantCache = new HashMap<>();
for (Grant grant : grants) {
if (!grant.isActive()) {
continue;
}
for (Grant grant : grants) {
if (!grant.isActive()) {
continue;
}
List<UUID> users = grantCache.get(grant.getRank());
List<UUID> 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<String> ipBanCache = new LinkedList<>();
List<String> 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<UUID> 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<UUID> 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]");
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.actor.Actor;
public final class GETWhoAmI implements Handler<RoutingContext> {
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()
));
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEAccessTokensId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> accessToken.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -11,29 +11,29 @@ import net.frozenorb.apiv3.util.SyncUtils;
public final class GETAccessTokens implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETAccessTokensId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -18,36 +18,36 @@ import java.util.List;
public final class POSTAccessTokens implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
JsonObject requestBody = ctx.getBodyAsJson();
String actorName = requestBody.getString("actorName");
ActorType actorType = ActorType.valueOf(requestBody.getString("actorType").toUpperCase());
List<String> lockedIps = (List<String>) 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<String> lockedIps = (List<String>) 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.<Void>runBlocking(v -> accessToken.insert(v));
AccessToken accessToken = new AccessToken(actorName, actorType, lockedIps);
SyncUtils.<Void>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);
}
});
}
}

View File

@ -14,34 +14,34 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEAuditLogId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> auditLogEntry.getType().reverse(auditLogEntry, v));
SyncUtils.<Void>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);
}
}
}

View File

@ -10,21 +10,21 @@ import org.bson.Document;
public final class GETAuditLog implements Handler<RoutingContext> {
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.");
}
}
}

View File

@ -12,44 +12,44 @@ import net.frozenorb.apiv3.util.IpUtils;
public final class POSTAuditLog implements Handler<RoutingContext> {
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);
}
});
});
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEBannedAsnsId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> bannedAsn.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedAsn;
public final class GETBannedAsns implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, BannedAsn.findAll());
}
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, BannedAsn.findAll());
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedAsn;
public final class GETBannedAsnsId implements Handler<RoutingContext> {
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"))));
}
}

View File

@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTBannedAsns implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> bannedAsn.insert(v));
BannedAsn bannedAsn = new BannedAsn(id, note);
SyncUtils.<Void>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);
}
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEBannedCellCarriersId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> bannedCellCarrier.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedCellCarrier;
public final class GETBannedCellCarriers implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, BannedCellCarrier.findAll());
}
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, BannedCellCarrier.findAll());
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.BannedCellCarrier;
public final class GETBannedCellCarriersId implements Handler<RoutingContext> {
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"))));
}
}

View File

@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTBannedCellCarriers implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> bannedCellCarrier.insert(v));
BannedCellCarrier bannedCellCarrier = new BannedCellCarrier(id, note);
SyncUtils.<Void>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);
}
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEChatFilterId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> chatFilterEntry.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETChatFilter implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETChatFilterId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTChatFilter implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> chatFilterEntry.insert(v));
ChatFilterEntry chatFilterEntry = new ChatFilterEntry(id, regex);
SyncUtils.<Void>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);
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETEmailTokensIdOwner implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -15,45 +15,45 @@ import java.util.concurrent.TimeUnit;
public final class POSTEmailTokensIdConfirm implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> user.save(v));
user.completeEmailRegistration(user.getPendingEmail());
user.updatePassword(password);
SyncUtils.<Void>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
));
}
});
}
}

View File

@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils;
public final class DELETEGrantsId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> grant.delete(removedBy, reason, v));
SyncUtils.<Void>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);
}
}
}

View File

@ -12,22 +12,22 @@ import java.util.stream.Collectors;
public final class GETGrants implements Handler<RoutingContext> {
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.");
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETGrantsId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -22,87 +22,87 @@ import java.util.Set;
public final class POSTGrants implements Handler<RoutingContext> {
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<ServerGroup> scopes = new HashSet<>();
List<String> scopeIds = (List<String>) requestBody.getJsonArray("scopes").getList();
Set<ServerGroup> scopes = new HashSet<>();
List<String> scopeIds = (List<String>) 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.<Void>runBlocking(v -> grant.insert(v));
Grant grant = new Grant(target, reason, scopes, rank, expiresAt, addedBy, storeItemId, storeOrderId);
SyncUtils.<Void>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);
}
}
}

View File

@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils;
public final class DELETEIpBansId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> ipBan.delete(removedBy, reason, v));
SyncUtils.<Void>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);
}
}
}

View File

@ -10,21 +10,21 @@ import org.bson.Document;
public final class GETIpBans implements Handler<RoutingContext> {
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.");
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETIpBansId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -17,51 +17,51 @@ import java.time.Instant;
public final class POSTIpBans implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> ipBan.insert(v));
IpBan ipBan = new IpBan(userIp, reason, expiresAt, addedBy, ctx.get("actor"));
SyncUtils.<Void>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);
}
}
}

View File

@ -9,21 +9,21 @@ import net.frozenorb.apiv3.util.IpUtils;
public final class GETIpInteld implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -9,34 +9,34 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETIpLogId implements Handler<RoutingContext> {
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);
}
});
}
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETENotificationTemplatesId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> notificationTemplate.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETNotificationTemplates implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETNotificationTemplatesId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -14,26 +14,26 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTNotificationTemplates implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> notificationTemplate.insert(v));
NotificationTemplate notificationTemplate = new NotificationTemplate(id, subject, body);
SyncUtils.<Void>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);
}
}
}

View File

@ -9,21 +9,21 @@ import net.frozenorb.apiv3.util.PhoneUtils;
public final class GETPhoneInteld implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -14,40 +14,40 @@ import net.frozenorb.apiv3.util.SyncUtils;
public final class DELETEPunishmentsId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> punishment.delete(removedBy, reason, v));
SyncUtils.<Void>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);
}
}
}

View File

@ -17,54 +17,54 @@ import java.util.List;
public final class DELETEUsersIdActivePunishment implements Handler<RoutingContext> {
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<Punishment> punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v));
Punishment activePunishment = null;
List<Punishment> 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.<Void>runBlocking(v -> finalActivePunishment.delete(removedBy, reason, v));
Punishment finalActivePunishment = activePunishment;
SyncUtils.<Void>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);
}
}
}

View File

@ -12,26 +12,26 @@ import java.util.stream.Collectors;
public final class GETPunishments implements Handler<RoutingContext> {
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.");
}
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETPunishmentsId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -21,100 +21,100 @@ import java.util.Map;
public final class POSTPunishments implements Handler<RoutingContext> {
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<Punishment> punishments = SyncUtils.runBlocking(v -> Punishment.findByUserAndType(target, ImmutableSet.of(type), v));
if (type != Punishment.PunishmentType.WARN) {
List<Punishment> 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<String, Object> meta = requestBody.getJsonObject("metadata").getMap();
Map<String, Object> 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.<Void>runBlocking(v -> ipBan.insert(v));
if ((type == Punishment.PunishmentType.BAN || type == Punishment.PunishmentType.BLACKLIST) && userIp != null) {
IpBan ipBan = new IpBan(userIp, punishment);
SyncUtils.<Void>runBlocking(v -> ipBan.insert(v));
punishment.linkIpBan(ipBan);
}
punishment.linkIpBan(ipBan);
}
SyncUtils.<Void>runBlocking(v -> punishment.insert(v));
SyncUtils.<Void>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
));
}
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETERanksId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> rank.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Rank;
public final class GETRanks implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, Rank.findAll());
}
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, Rank.findAll());
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Rank;
public final class GETRanksId implements Handler<RoutingContext> {
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")));
}
}

View File

@ -14,31 +14,31 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTRanks implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> rank.insert(v));
Rank rank = new Rank(id, inheritsFromId, weight, displayName, gameColor, websiteColor, staffRank, higherStaffRank);
SyncUtils.<Void>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);
}
}
}

View File

@ -14,29 +14,29 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEServerGroupsId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> serverGroup.delete(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.ServerGroup;
public final class GETServerGroups implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, ServerGroup.findAll());
}
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, ServerGroup.findAll());
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.ServerGroup;
public final class GETServerGroupsId implements Handler<RoutingContext> {
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")));
}
}

View File

@ -14,25 +14,25 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTServerGroups implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> serverGroup.insert(v));
ServerGroup serverGroup = new ServerGroup(id, image);
SyncUtils.<Void>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);
}
}
}

View File

@ -16,47 +16,47 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class DELETEServersId implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> server.insert(v));
SyncUtils.<Void>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);
}
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Server;
public final class GETServers implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, Server.findAll());
}
public void handle(RoutingContext ctx) {
APIv3.respondJson(ctx, 200, Server.findAll());
}
}

View File

@ -7,8 +7,8 @@ import net.frozenorb.apiv3.model.Server;
public final class GETServersId implements Handler<RoutingContext> {
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")));
}
}

View File

@ -17,42 +17,42 @@ import net.frozenorb.apiv3.util.UuidUtils;
public final class POSTServers implements Handler<RoutingContext> {
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.<Void>runBlocking(v -> server.insert(v));
Server server = new Server(id, displayName, group, ip);
SyncUtils.<Void>runBlocking(v -> server.insert(v));
AccessToken accessToken = new AccessToken(server);
SyncUtils.<Void>runBlocking(v -> accessToken.insert(v));
AccessToken accessToken = new AccessToken(server);
SyncUtils.<Void>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);
}
}
}

View File

@ -23,221 +23,221 @@ import java.util.*;
@Slf4j
public final class POSTServersHeartbeat implements Handler<RoutingContext> {
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<UUID, String> playerNames = extractPlayerNames(players);
Map<UUID, String> playerIps = extractPlayerIps(players);
Server actorServer = Server.findById(actor.getName());
JsonObject requestBody = ctx.getBodyAsJson();
JsonObject players = requestBody.getJsonObject("players");
Map<UUID, String> playerNames = extractPlayerNames(players);
Map<UUID, String> 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<Void> createInfoResponse(Server server, double tps, Map<UUID, String> playerNames) {
Future<Void> callback = Future.future();
private Future<Void> createInfoResponse(Server server, double tps, Map<UUID, String> playerNames) {
Future<Void> 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<Map<String, Object>> createPlayerResponse(Server server, Map<UUID, String> playerNames, Map<UUID, String> playerIps) {
Future<Map<String, Object>> callback = Future.future();
private Future<Map<String, Object>> createPlayerResponse(Server server, Map<UUID, String> playerNames, Map<UUID, String> playerIps) {
Future<Map<String, Object>> callback = Future.future();
Future<Map<UUID, User>> userLookupCallback = Future.future();
Future<Map<String, IpIntel>> ipIntelCallback = Future.future();
Future<Map<UUID, List<Grant>>> grantLookupCallback = Future.future();
Future<Map<UUID, List<Punishment>>> punishmentLookupCallback = Future.future();
Future<Map<UUID, User>> userLookupCallback = Future.future();
Future<Map<String, IpIntel>> ipIntelCallback = Future.future();
Future<Map<UUID, List<Grant>>> grantLookupCallback = Future.future();
Future<Map<UUID, List<Punishment>>> 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<UUID, User> users = batchLookupInfo.result().result(0);
Map<String, IpIntel> ipIntel = batchLookupInfo.result().result(1);
Map<UUID, List<Grant>> grants = batchLookupInfo.result().result(2);
Map<UUID, List<Punishment>> punishments = batchLookupInfo.result().result(3);
Map<UUID, Future> loginInfoFutures = new HashMap<>();
Map<UUID, User> users = batchLookupInfo.result().result(0);
Map<String, IpIntel> ipIntel = batchLookupInfo.result().result(1);
Map<UUID, List<Grant>> grants = batchLookupInfo.result().result(2);
Map<UUID, List<Punishment>> punishments = batchLookupInfo.result().result(3);
Map<UUID, Future> loginInfoFutures = new HashMap<>();
users.forEach((uuid, user) -> {
Future<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> response = new HashMap<>();
loginInfoFutures.forEach((uuid, loginInfo) -> response.put(uuid.toString(), loginInfo.result()));
callback.complete(response);
});
});
Map<String, Object> response = new HashMap<>();
loginInfoFutures.forEach((uuid, loginInfo) -> response.put(uuid.toString(), loginInfo.result()));
callback.complete(response);
});
});
return callback;
}
return callback;
}
private Future<Map<String, Object>> createPermissionsResponse(ServerGroup serverGroup) {
Future<Map<String, Object>> callback = Future.future();
Map<String, Object> permissionsResponse = new HashMap<>();
private Future<Map<String, Object>> createPermissionsResponse(ServerGroup serverGroup) {
Future<Map<String, Object>> callback = Future.future();
Map<String, Object> permissionsResponse = new HashMap<>();
for (Rank rank : Rank.findAll()) {
Map<String, Boolean> scopedPermissions = PermissionUtils.mergePermissions(
ServerGroup.findDefault().calculatePermissions(rank),
serverGroup.calculatePermissions(rank)
);
for (Rank rank : Rank.findAll()) {
Map<String, Boolean> 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<Map<String, Object>> createEventsResponse(Server server, JsonArray events) {
Future<Map<String, Object>> callback = Future.future();
List<Future> eventFutures = new ArrayList<>();
private Future<Map<String, Object>> createEventsResponse(Server server, JsonArray events) {
Future<Map<String, Object>> callback = Future.future();
List<Future> 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<UUID, String> extractPlayerNames(JsonObject players) {
Map<UUID, String> result = new HashMap<>();
private Map<UUID, String> extractPlayerNames(JsonObject players) {
Map<UUID, String> 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<UUID, String> extractPlayerIps(JsonObject players) {
Map<UUID, String> result = new HashMap<>();
private Map<UUID, String> extractPlayerIps(JsonObject players) {
Map<UUID, String> 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<Grant> grants, List<Punishment> punishments, Future<Map<String, Object>> 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<Grant> grants, List<Punishment> punishments, Future<Map<String, Object>> 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));
}
}
}

View File

@ -12,38 +12,38 @@ import java.util.*;
public final class GETStaff implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
Map<String, Rank> staffRanks = new HashMap<>();
public void handle(RoutingContext ctx) {
Map<String, Rank> 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<String, Set<User>> result = new TreeMap<>((first, second) -> {
Rank firstRank = staffRanks.get(first);
Rank secondRank = staffRanks.get(second);
Map<String, Set<User>> 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<Grant> staffGrants = SyncUtils.runBlocking(v -> Grant.findByRank(staffRanks.values(), v));
List<Grant> 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);
}
}

View File

@ -8,14 +8,14 @@ import net.frozenorb.apiv3.util.ErrorUtils;
public final class GETUsersId implements Handler<RoutingContext> {
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);
}
});
}
}

View File

@ -9,22 +9,22 @@ import net.frozenorb.apiv3.util.PermissionUtils;
public final class GETUsersIdCompoundedPermissions implements Handler<RoutingContext> {
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));
}
});
}
});
}
}

View File

@ -16,27 +16,27 @@ import java.util.Map;
public final class GETUsersIdDetails implements Handler<RoutingContext> {
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<Grant> grants = SyncUtils.runBlocking(v -> Grant.findByUser(user, v));
List<IpLogEntry> ipLog = SyncUtils.runBlocking(v -> IpLogEntry.findByUser(user, v));
List<Punishment> punishments = SyncUtils.runBlocking(v -> Punishment.findByUser(user, v));
Map<String, Object> result = new HashMap<>();
List<Grant> grants = SyncUtils.runBlocking(v -> Grant.findByUser(user, v));
List<IpLogEntry> ipLog = SyncUtils.runBlocking(v -> IpLogEntry.findByUser(user, v));
List<Punishment> punishments = SyncUtils.runBlocking(v -> Punishment.findByUser(user, v));
Map<String, Object> 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);
}
}

View File

@ -11,36 +11,36 @@ import net.frozenorb.apiv3.util.IpUtils;
public final class GETUsersIdRequiresTotp implements Handler<RoutingContext> {
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()
));
}
});
});
}
}

Some files were not shown because too many files have changed in this diff Show More