[FEATURE][EXPERIMENTAL] Переработка DAO/Hibernate

This commit is contained in:
Gravit 2020-05-26 04:38:47 +07:00
parent c7688afb32
commit bdecd57470
No known key found for this signature in database
GPG key ID: 061981E1E85D3216
11 changed files with 14 additions and 352 deletions

View file

@ -1,32 +0,0 @@
package pro.gravit.launchserver.command.dao;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.dao.User;
import pro.gravit.utils.helper.LogHelper;
public class GetAllUsersCommand extends Command {
public GetAllUsersCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "";
}
@Override
public String getUsageDescription() {
return "get all users information";
}
@Override
public void invoke(String... args) {
int count = 0;
for (User user : server.config.dao.userDAO.findAll()) {
LogHelper.subInfo("[%s] UUID: %s", user.getUsername(), user.getUuid().toString());
count++;
}
LogHelper.info("Print %d users", count);
}
}

View file

@ -1,37 +0,0 @@
package pro.gravit.launchserver.command.dao;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.dao.User;
import pro.gravit.utils.helper.LogHelper;
public class GetUserCommand extends Command {
public GetUserCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "[username]";
}
@Override
public String getUsageDescription() {
return "get user information";
}
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 1);
User user = server.config.dao.userDAO.findByUsername(args[0]);
if (user == null) {
LogHelper.error("User %s not found", args[0]);
return;
}
LogHelper.info("[%s] UUID: %s", user.getUsername(), user.getUuid().toString());
//for(UserHWID hwid : user.hwids)
//{
// LogHelper.info("[%s] HWID: memory: %d | serial %s | hwdiskserial: %s | processorID %s | macAddr %s", user.username, hwid.totalMemory, hwid.serialNumber, hwid.HWDiskSerial, hwid.processorID, hwid.macAddr);
//}
}
}

View file

@ -1,35 +0,0 @@
package pro.gravit.launchserver.command.dao;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.dao.impl.UserHibernateImpl;
import pro.gravit.utils.helper.LogHelper;
import java.util.UUID;
public class RegisterCommand extends Command {
public RegisterCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "[login] [password]";
}
@Override
public String getUsageDescription() {
return "Register new user";
}
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 2);
UserHibernateImpl user = new UserHibernateImpl();
user.username = args[0];
user.setPassword(args[1]);
user.uuid = UUID.randomUUID();
server.config.dao.userDAO.save(user);
LogHelper.info("User %s registered. UUID: %s", user.username, user.uuid.toString());
}
}

View file

@ -1,36 +0,0 @@
package pro.gravit.launchserver.command.dao;
import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.command.Command;
import pro.gravit.launchserver.dao.User;
import pro.gravit.utils.helper.LogHelper;
public class SetUserPasswordCommand extends Command {
public SetUserPasswordCommand(LaunchServer server) {
super(server);
}
@Override
public String getArgsDescription() {
return "[username] [new password]";
}
@Override
public String getUsageDescription() {
return "Set user password";
}
@Override
public void invoke(String... args) throws Exception {
verifyArgs(args, 2);
User user = server.config.dao.userDAO.findByUsername(args[0]);
if (user == null) {
LogHelper.error("User %s not found", args[1]);
return;
}
user.setPassword(args[1]);
server.config.dao.userDAO.update(user);
LogHelper.info("[%s] UUID: %s | New Password: %s", user.getUsername(), user.getUuid().toString(), args[1]);
}
}

View file

@ -5,10 +5,6 @@
import pro.gravit.launchserver.command.auth.UUIDToUsernameCommand; import pro.gravit.launchserver.command.auth.UUIDToUsernameCommand;
import pro.gravit.launchserver.command.auth.UsernameToUUIDCommand; import pro.gravit.launchserver.command.auth.UsernameToUUIDCommand;
import pro.gravit.launchserver.command.basic.*; import pro.gravit.launchserver.command.basic.*;
import pro.gravit.launchserver.command.dao.GetAllUsersCommand;
import pro.gravit.launchserver.command.dao.GetUserCommand;
import pro.gravit.launchserver.command.dao.RegisterCommand;
import pro.gravit.launchserver.command.dao.SetUserPasswordCommand;
import pro.gravit.launchserver.command.dump.DumpSessionsCommand; import pro.gravit.launchserver.command.dump.DumpSessionsCommand;
import pro.gravit.launchserver.command.hash.*; import pro.gravit.launchserver.command.hash.*;
import pro.gravit.launchserver.command.install.CheckInstallCommand; import pro.gravit.launchserver.command.install.CheckInstallCommand;
@ -56,15 +52,6 @@ public static void registerCommands(pro.gravit.utils.command.CommandHandler hand
Category updatesCategory = new Category(updates, "updates", "Update and Sync Management"); Category updatesCategory = new Category(updates, "updates", "Update and Sync Management");
handler.registerCategory(updatesCategory); handler.registerCategory(updatesCategory);
//Register dao commands
BaseCommandCategory dao = new BaseCommandCategory();
dao.registerCommand("register", new RegisterCommand(server));
dao.registerCommand("setUserPassword", new SetUserPasswordCommand(server));
dao.registerCommand("getUser", new GetUserCommand(server));
dao.registerCommand("getAllUsers", new GetAllUsersCommand(server));
Category daoCategory = new Category(dao, "DAO", "Data Management");
handler.registerCategory(daoCategory);
// Register auth commands // Register auth commands
BaseCommandCategory auth = new BaseCommandCategory(); BaseCommandCategory auth = new BaseCommandCategory();
auth.registerCommand("auth", new AuthCommand(server)); auth.registerCommand("auth", new AuthCommand(server));

View file

@ -1,83 +0,0 @@
package pro.gravit.launchserver.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import pro.gravit.launchserver.dao.User;
import pro.gravit.launchserver.dao.UserDAO;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.UUID;
public class HibernateUserDAOImpl implements UserDAO {
private final SessionFactory factory;
public HibernateUserDAOImpl(SessionFactory factory) {
this.factory = factory;
}
public UserHibernateImpl findById(int id) {
try (Session s = factory.openSession()) {
return s.get(UserHibernateImpl.class, id);
}
}
public UserHibernateImpl findByUsername(String username) {
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserHibernateImpl> personCriteria = cb.createQuery(UserHibernateImpl.class);
Root<UserHibernateImpl> rootUser = personCriteria.from(UserHibernateImpl.class);
personCriteria.select(rootUser).where(cb.equal(rootUser.get("username"), username));
List<UserHibernateImpl> ret = em.createQuery(personCriteria).getResultList();
em.close();
return ret.size() == 0 ? null : ret.get(0);
}
public UserHibernateImpl findByUUID(UUID uuid) {
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserHibernateImpl> personCriteria = cb.createQuery(UserHibernateImpl.class);
Root<UserHibernateImpl> rootUser = personCriteria.from(UserHibernateImpl.class);
personCriteria.select(rootUser).where(cb.equal(rootUser.get("uuid"), uuid));
List<UserHibernateImpl> ret = em.createQuery(personCriteria).getResultList();
em.close();
return ret.size() == 0 ? null : ret.get(0);
}
public void save(User user) {
try (Session session = factory.openSession()) {
Transaction tx1 = session.beginTransaction();
session.save(user);
tx1.commit();
}
}
public void update(User user) {
try (Session session = factory.openSession()) {
Transaction tx1 = session.beginTransaction();
session.update(user);
tx1.commit();
}
}
public void delete(User user) {
try (Session session = factory.openSession()) {
Transaction tx1 = session.beginTransaction();
session.delete(user);
tx1.commit();
}
}
@SuppressWarnings("unchecked")
public List<User> findAll() {
try (Session s = factory.openSession()) {
return (List<User>) s.createQuery("From User").list();
}
}
}

View file

@ -1,101 +0,0 @@
package pro.gravit.launchserver.dao.impl;
import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launchserver.dao.User;
import pro.gravit.utils.helper.LogHelper;
import pro.gravit.utils.helper.SecurityHelper;
import javax.persistence.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;
@Entity(name = "User")
@Table(name = "users")
public class UserHibernateImpl implements User {
@Column(unique = true)
public String username;
public String email;
@Column(unique = true)
public UUID uuid;
public String serverID;
public long permissions;
public long flags;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "password")
private byte[] password;
private String accessToken;
private String password_salt;
public void setPassword(String password) {
password_salt = SecurityHelper.randomStringAESKey();
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
LogHelper.error(e);
return;
}
this.password = digest.digest(password.concat(password_salt).getBytes(StandardCharsets.UTF_8));
}
public boolean verifyPassword(String password) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
LogHelper.error(e);
return false;
}
byte[] enpassword = digest.digest(password.concat(password_salt).getBytes(StandardCharsets.UTF_8));
return Arrays.equals(enpassword, this.password);
}
public ClientPermissions getPermissions() {
return new ClientPermissions(permissions, flags);
}
public void setPermissions(ClientPermissions permissions) {
this.permissions = permissions.permissions;
this.flags = permissions.flags;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@Override
public String getServerID() {
return serverID;
}
@Override
public void setServerID(String serverID) {
this.serverID = serverID;
}
}

View file

@ -9,7 +9,7 @@ public abstract class DaoProvider {
public UserDAO userDAO; public UserDAO userDAO;
public static void registerProviders() { public static void registerProviders() {
providers.register("hibernate", HibernateDaoProvider.class); // None
} }
public abstract void init(LaunchServer server); public abstract void init(LaunchServer server);

View file

@ -6,8 +6,7 @@
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.Reconfigurable; import pro.gravit.launchserver.Reconfigurable;
import pro.gravit.launchserver.dao.User; import pro.gravit.launchserver.dao.User;
import pro.gravit.launchserver.dao.impl.HibernateUserDAOImpl; import pro.gravit.launchserver.dao.UserDAO;
import pro.gravit.launchserver.dao.impl.UserHibernateImpl;
import pro.gravit.utils.command.Command; import pro.gravit.utils.command.Command;
import pro.gravit.utils.command.SubCommand; import pro.gravit.utils.command.SubCommand;
import pro.gravit.utils.helper.CommonHelper; import pro.gravit.utils.helper.CommonHelper;
@ -17,7 +16,7 @@
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class HibernateDaoProvider extends DaoProvider implements Reconfigurable, AutoCloseable { public abstract class HibernateDaoProvider extends DaoProvider implements Reconfigurable, AutoCloseable {
public String driver; public String driver;
public String url; public String url;
public String username; public String username;
@ -26,13 +25,13 @@ public class HibernateDaoProvider extends DaoProvider implements Reconfigurable,
public String pool_size; public String pool_size;
public String hibernateConfig; public String hibernateConfig;
public boolean parallelHibernateInit; public boolean parallelHibernateInit;
private transient SessionFactory sessionFactory; protected transient SessionFactory sessionFactory;
@Override @Override
public void init(LaunchServer server) { public void init(LaunchServer server) {
Runnable init = () -> { Runnable init = () -> {
Configuration cfg = new Configuration() Configuration cfg = new Configuration()
.addAnnotatedClass(UserHibernateImpl.class) //.addAnnotatedClass(UserHibernateImpl.class)
.setProperty("hibernate.connection.driver_class", driver) .setProperty("hibernate.connection.driver_class", driver)
.setProperty("hibernate.connection.url", url) .setProperty("hibernate.connection.url", url)
.setProperty("hibernate.connection.username", username) .setProperty("hibernate.connection.username", username)
@ -42,8 +41,9 @@ public void init(LaunchServer server) {
cfg.setProperty("hibernate.dialect", dialect); cfg.setProperty("hibernate.dialect", dialect);
if (hibernateConfig != null) if (hibernateConfig != null)
cfg.configure(Paths.get(hibernateConfig).toFile()); cfg.configure(Paths.get(hibernateConfig).toFile());
onConfigure(cfg);
sessionFactory = cfg.buildSessionFactory(); sessionFactory = cfg.buildSessionFactory();
userDAO = new HibernateUserDAOImpl(sessionFactory); userDAO = newUserDAO();
}; };
if (parallelHibernateInit) if (parallelHibernateInit)
CommonHelper.newThread("Hibernate Thread", true, init); CommonHelper.newThread("Hibernate Thread", true, init);
@ -51,6 +51,10 @@ public void init(LaunchServer server) {
init.run(); init.run();
} }
protected abstract void onConfigure(Configuration configuration);
protected abstract UserDAO newUserDAO();
@Override @Override
public Map<String, Command> getCommands() { public Map<String, Command> getCommands() {
Map<String, Command> commands = new HashMap<>(); Map<String, Command> commands = new HashMap<>();

View file

@ -5,6 +5,7 @@
import pro.gravit.launcher.request.secure.HardwareReportRequest; import pro.gravit.launcher.request.secure.HardwareReportRequest;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.auth.AuthProviderPair; import pro.gravit.launchserver.auth.AuthProviderPair;
import pro.gravit.launchserver.dao.User;
import pro.gravit.launchserver.socket.response.auth.AuthResponse; import pro.gravit.launchserver.socket.response.auth.AuthResponse;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
@ -23,6 +24,8 @@ public class Client {
public transient AuthProviderPair auth; public transient AuthProviderPair auth;
public transient User daoObject;
public Client(long session) { public Client(long session) {
this.session = session; this.session = session;
timestamp = System.currentTimeMillis(); timestamp = System.currentTimeMillis();

View file

@ -3,7 +3,6 @@
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import pro.gravit.launcher.ClientPermissions; import pro.gravit.launcher.ClientPermissions;
import pro.gravit.launchserver.dao.User; import pro.gravit.launchserver.dao.User;
import pro.gravit.launchserver.dao.impl.UserHibernateImpl;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.response.SimpleResponse; import pro.gravit.launchserver.socket.response.SimpleResponse;
@ -11,7 +10,6 @@
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID;
public class RegisterResponse extends SimpleResponse { public class RegisterResponse extends SimpleResponse {
public String login; public String login;
@ -37,12 +35,6 @@ public void execute(ChannelHandlerContext ctx, Client client) throws Exception {
sendError("User already register"); sendError("User already register");
return; return;
} }
UserHibernateImpl user = new UserHibernateImpl();
user.username = login;
user.email = email;
user.setPassword(password);
user.uuid = UUID.randomUUID();
server.config.dao.userDAO.save(user);
} }
@Override @Override