Added DBAuthenticator & Test with H2 DB

This commit is contained in:
mackristof
2016-05-12 15:47:49 +02:00
committed by mackristof
parent d24f14a8f2
commit cad1165071
3 changed files with 170 additions and 0 deletions
@@ -0,0 +1,79 @@
package io.moquette.spi.impl.security;
import org.apache.commons.codec.binary.Hex;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by mackristof on 12/05/2016.
*/
public class DBAuthenticatorTest {
private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticatorTest.class);
public static final String ORG_H2_DRIVER = "org.h2.Driver";
public static final String JDBC_H2_MEM_TEST = "jdbc:h2:mem:test";
public static final String SHA_256 = "SHA-256";
private Connection connection;
@Before
public void setup() throws ClassNotFoundException, SQLException, NoSuchAlgorithmException {
Class.forName(ORG_H2_DRIVER);
this.connection = DriverManager.getConnection(JDBC_H2_MEM_TEST);
Statement statement = this.connection.createStatement();
try {
statement.execute("DROP TABLE USER");
} catch(SQLException sqle) {
LOG.info("Table not found, not dropping",sqle);
}
MessageDigest digest = MessageDigest.getInstance(SHA_256);
String hash = new String(Hex.encodeHex(digest.digest("password".getBytes(StandardCharsets.UTF_8))));
try {
if (statement.execute("CREATE TABLE PUBLIC.USER ( LOGIN VARCHAR(64), PASSWORD VARCHAR(256))")){
throw new SQLException("can't create USER table");
}
if (statement.execute("INSERT INTO PUBLIC.USER ( LOGIN , PASSWORD ) VALUES ('testuser', '"+hash+"')")){
throw new SQLException("can't insert in USER table");
}
} catch(SQLException sqle) {
LOG.error("Table not created, not inserted",sqle);
return;
}
LOG.info("Table User created");
statement.close();
}
@Test
public void Db_verifyValid() {
final DBAuthenticator dbAuthenticator = new DBAuthenticator(ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM USER WHERE LOGIN=?", SHA_256);
assertTrue(dbAuthenticator.checkValid("testuser","password".getBytes()));
}
@Test
public void Db_verifyInvalid(){
final DBAuthenticator dbAuthenticator = new DBAuthenticator(ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM USER WHERE LOGIN=?", SHA_256);
assertFalse(dbAuthenticator.checkValid("testuser2","password".getBytes()));
}
@After
public void teardown(){
try {
this.connection.close();
} catch (SQLException e) {
LOG.error("can't close connection",e);
}
}
}