package net.frozenorb.apiv3.models; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.hash.Hashing; import com.mongodb.async.SingleResultCallback; import com.mongodb.async.client.MongoCollection; import com.mongodb.client.result.UpdateResult; import fr.javatic.mongo.jacksonCodec.objectId.Id; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import net.frozenorb.apiv3.APIv3; import net.frozenorb.apiv3.serialization.ExcludeFromReplies; import net.frozenorb.apiv3.serialization.UUIDJsonDeserializer; import net.frozenorb.apiv3.serialization.UUIDJsonSerializer; import net.frozenorb.apiv3.unsorted.BlockingCallback; import net.frozenorb.apiv3.utils.MojangUtils; import net.frozenorb.apiv3.utils.PermissionUtils; import net.frozenorb.apiv3.utils.SyncUtils; import net.frozenorb.apiv3.utils.UUIDUtils; import org.bson.Document; import java.util.*; @AllArgsConstructor public final class User { private static final MongoCollection usersCollection = APIv3.getDatabase().getCollection("users", User.class); @Getter @Id @JsonSerialize(using=UUIDJsonSerializer.class) @JsonDeserialize(using=UUIDJsonDeserializer.class) private UUID id; @Getter private String lastUsername; @Getter @ExcludeFromReplies private Map aliases = new HashMap<>(); @Getter @ExcludeFromReplies @Setter private String totpSecret; @Getter @ExcludeFromReplies @Setter private String emailToken; @Getter @ExcludeFromReplies @Setter private Date emailTokenSetAt; @Getter @ExcludeFromReplies private String password; @Getter @Setter private String email; @Getter private String phoneNumber; @Getter private String lastSeenOn; @Getter private Date lastSeenAt; @Getter private Date firstSeenAt; @Getter private boolean online; public static List findAllSync() { return SyncUtils.blockMulti(usersCollection.find()); } public static User findByIdSync(String id) { UUID uuid; try { uuid = UUID.fromString(id); } catch (IllegalArgumentException ex) { return null; } return findByIdSync(uuid); } public static User findByIdSync(UUID id) { if (UUIDUtils.isAcceptableUUID(id)) { return SyncUtils.blockOne(usersCollection.find(new Document("_id", id))); } else { return null; } } public static User findByEmailTokenSync(String emailToken) { return SyncUtils.blockOne(usersCollection.find(new Document("emailToken", emailToken))); } public static User findByLastUsernameSync(String lastUsername) { return SyncUtils.blockOne(usersCollection.find(new Document("lastUsername", lastUsername))); } public static void findAll(SingleResultCallback> callback) { usersCollection.find().into(new ArrayList<>(), callback); } public static void findById(String id, SingleResultCallback callback) { try { UUID uuid = UUID.fromString(id); findById(uuid, callback); } catch (IllegalArgumentException ex) { // from UUID parsing callback.onResult(null, ex); } } public static void findById(UUID id, SingleResultCallback callback) { if (UUIDUtils.isAcceptableUUID(id)) { usersCollection.find(new Document("_id", id)).first(callback); } else { callback.onResult(null, null); } } public static void findByIdGrouped(Iterable search, SingleResultCallback> callback) { usersCollection.find(new Document("_id", new Document("$in", search))).into(new ArrayList<>(), (users, error) -> { if (error != null) { callback.onResult(null, error); } else { Map result = new HashMap<>(); for (UUID user : search) { result.put(user, null); } for (User user : users) { result.put(user.getId(), user); } callback.onResult(result, null); } }); } public static void findByEmailToken(String emailToken, SingleResultCallback callback) { usersCollection.find(new Document("emailToken", emailToken)).first(callback); } public static void findByLastUsername(String lastUsername, SingleResultCallback callback) { usersCollection.find(new Document("lastUsername", lastUsername)).first(callback); } public User() {} // For Morphia public User(UUID id, String lastUsername) { this.id = id; this.lastUsername = ""; // Intentional, so updateUsername actually does something. this.aliases = new HashMap<>(); this.totpSecret = null; this.password = null; this.email = null; this.phoneNumber = null; this.lastSeenOn = null; this.lastSeenAt = new Date(); this.firstSeenAt = new Date(); updateUsername(lastUsername); } public boolean hasPermissionAnywhere(String permission) { Map globalPermissions = PermissionUtils.getDefaultPermissions(getHighestRankAnywhere()); for (Map.Entry serverGroupEntry : getHighestRanks().entrySet()) { ServerGroup serverGroup = serverGroupEntry.getKey(); Rank rank = serverGroupEntry.getValue(); globalPermissions = PermissionUtils.mergePermissions( globalPermissions, serverGroup.calculatePermissions(rank) ); } return globalPermissions.containsKey(permission) && globalPermissions.get(permission); } // TODO: Clean public boolean seenOnServer(Server server) { if (online && server.getId().equals(this.lastSeenOn)) { return false; } this.lastSeenOn = server.getId(); if (!online) { this.lastSeenAt = new Date(); } this.online = true; return true; } public void leftServer() { this.lastSeenAt = new Date(); this.online = false; } public void updateUsername(String username) { if (!username.equals(lastUsername)) { this.lastUsername = username; User withNewUsername; while ((withNewUsername = User.findByLastUsernameSync(username)) != null) { BlockingCallback callback = new BlockingCallback<>(); MojangUtils.getName(withNewUsername.getId(), callback); String newUsername = callback.get(); withNewUsername.updateUsername(newUsername); } } this.aliases.put(username, new Date()); } public void setPassword(String input) { this.password = Hashing .sha256() .hashString(input + "$" + id.toString(), Charsets.UTF_8) .toString(); } public boolean checkPassword(String input) { String hashed = Hashing .sha256() .hashString(input + "$" + id.toString(), Charsets.UTF_8) .toString(); return hashed.equals(password); } public Rank getHighestRankAnywhere() { return getHighestRankScoped(null); } public Rank getHighestRankScoped(ServerGroup serverGroup) { return getHighestRankScoped(serverGroup, Grant.findByUserSync(this)); } // TODO: Clean // This is only used to help batch requests to mongo public Rank getHighestRankScoped(ServerGroup serverGroup, Iterable grants) { Rank highest = null; for (Grant grant : grants) { if (!grant.isActive() || (serverGroup != null && !grant.appliesOn(serverGroup))) { continue; } Rank rank = Rank.findById(grant.getRank()); if (highest == null || rank.getWeight() > highest.getWeight()) { highest = rank; } } if (highest != null) { return highest; } else { return Rank.findById("default"); } } // TODO: Clean public Map getHighestRanks() { Map highestRanks = new HashMap<>(); Rank defaultRank = Rank.findById("default"); List userGrants = Grant.findByUserSync(this); for (ServerGroup serverGroup : ServerGroup.findAll()) { Rank highest = defaultRank; for (Grant grant : userGrants) { if (!grant.isActive() || !grant.appliesOn(serverGroup)) { continue; } Rank rank = Rank.findById(grant.getRank()); if (highest == null || rank.getWeight() > highest.getWeight()) { highest = rank; } } highestRanks.put(serverGroup, highest); } return highestRanks; } public Map getLoginInfo(Server server) { return createLoginInfo( server, Punishment.findByUserAndTypeSync(this, ImmutableSet.of( Punishment.PunishmentType.BLACKLIST, Punishment.PunishmentType.BAN, Punishment.PunishmentType.MUTE )), Grant.findByUserSync(this) ); } // This is only used to help batch requests to mongo public Map createLoginInfo(Server server, Iterable punishments, Iterable grants) { Punishment activeMute = null; String accessDenialReason = null; for (Punishment punishment : punishments) { if (!punishment.isActive()) { continue; } if (punishment.getType() == Punishment.PunishmentType.MUTE) { activeMute = punishment; } else { accessDenialReason = punishment.getAccessDenialReason(); } } Rank highestRank = getHighestRankScoped(ServerGroup.findById(server.getServerGroup()), grants); // Generics are weird, yes we have to do this. ImmutableMap.Builder result = ImmutableMap.builder() .put("user", this) .put("access", ImmutableMap.of( "allowed", accessDenialReason == null, "message", accessDenialReason == null ? "Public server" : accessDenialReason )) .put("rank", highestRank.getId()) .put("totpSetup", getTotpSecret() != null); if (activeMute != null) { result.put("mute", activeMute); } return result.build(); } public void insert() { BlockingCallback callback = new BlockingCallback<>(); usersCollection.insertOne(this, callback); callback.get(); } public void save() { BlockingCallback callback = new BlockingCallback<>(); usersCollection.replaceOne(new Document("_id", id), this, callback); callback.get(); } }