Add support for DigestAuth

This commit is contained in:
Rohit Awate 2018-08-31 19:38:29 +05:30
parent c3e25a8f8f
commit d348218541
9 changed files with 213 additions and 108 deletions

View file

@ -26,7 +26,10 @@ import javafx.scene.image.Image;
import javafx.stage.Screen; import javafx.stage.Screen;
import javafx.stage.Stage; import javafx.stage.Stage;
public class Main extends Application { public class Main extends Application {
public static final String APP_NAME = "Everest";
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
SettingsLoader settingsLoader = new SettingsLoader(); SettingsLoader settingsLoader = new SettingsLoader();
@ -43,7 +46,7 @@ public class Main extends Application {
dashboardStage.getIcons().add(new Image(getClass().getResource("/assets/Logo.png").toExternalForm())); dashboardStage.getIcons().add(new Image(getClass().getResource("/assets/Logo.png").toExternalForm()));
dashboardStage.setScene(new Scene(homeWindow)); dashboardStage.setScene(new Scene(homeWindow));
dashboardStage.setTitle("Everest"); dashboardStage.setTitle(APP_NAME);
dashboardStage.show(); dashboardStage.show();
} }

View file

@ -1,11 +1,15 @@
package com.rohitawate.everest.auth; package com.rohitawate.everest.auth;
import com.rohitawate.everest.Main;
import com.rohitawate.everest.logging.LoggingService;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -43,6 +47,7 @@ public class DigestAuthProvider implements AuthProvider {
try { try {
URL digestURL = new URL(url); URL digestURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) digestURL.openConnection(); HttpURLConnection conn = (HttpURLConnection) digestURL.openConnection();
conn.setRequestProperty("User-Agent", Main.APP_NAME);
String nonceHeader = conn.getHeaderField("WWW-Authenticate"); String nonceHeader = conn.getHeaderField("WWW-Authenticate");
Pattern digestPattern = Pattern.compile("(\\w+)[:=] ?\"?([^\" ,]+)\"?"); Pattern digestPattern = Pattern.compile("(\\w+)[:=] ?\"?([^\" ,]+)\"?");
@ -77,7 +82,7 @@ public class DigestAuthProvider implements AuthProvider {
header.append(response); header.append(response);
header.append("\""); header.append("\"");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); LoggingService.logSevere("Digest Authentication Error: Could not make initial request.", e, LocalDateTime.now());
} }
return header.toString(); return header.toString();

View file

@ -126,11 +126,12 @@ public class DashboardController implements Initializable {
@Override @Override
public void initialize(URL url, ResourceBundle rb) { public void initialize(URL url, ResourceBundle rb) {
try { try {
// Loading the headers tab // Loading the auth tab
FXMLLoader authTabLoader = new FXMLLoader(getClass().getResource("/fxml/homewindow/auth/AuthTab.fxml")); FXMLLoader authTabLoader = new FXMLLoader(getClass().getResource("/fxml/homewindow/auth/AuthTab.fxml"));
Parent authTabFXML = authTabLoader.load(); Parent authTabFXML = authTabLoader.load();
ThemeManager.setTheme(authTabFXML); ThemeManager.setTheme(authTabFXML);
authTabController = authTabLoader.getController(); authTabController = authTabLoader.getController();
authTabController.setDashboard(this);
authTab.setContent(authTabFXML); authTab.setContent(authTabFXML);
// Loading the headers tab // Loading the headers tab
@ -172,7 +173,7 @@ public class DashboardController implements Initializable {
Bindings.or(httpMethodBox.valueProperty().isEqualTo(HTTPConstants.GET), Bindings.or(httpMethodBox.valueProperty().isEqualTo(HTTPConstants.GET),
httpMethodBox.valueProperty().isEqualTo(HTTPConstants.DELETE))); httpMethodBox.valueProperty().isEqualTo(HTTPConstants.DELETE)));
// Disabling Ctrl+Tab navigation // Disabling Ctrl + Tab navigation
requestOptionsTab.setOnKeyPressed(e -> { requestOptionsTab.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.TAB) { if (e.getCode() == KeyCode.TAB) {
e.consume(); e.consume();
@ -858,4 +859,13 @@ public class DashboardController implements Initializable {
void setTabPane(TabPane tabPane) { void setTabPane(TabPane tabPane) {
this.tabPane = tabPane; this.tabPane = tabPane;
} }
public String getAddress() {
return addressField.getText();
}
public String getHttpMethod() {
return httpMethodBox.getValue();
}
} }

View file

@ -2,6 +2,8 @@ package com.rohitawate.everest.controllers.auth;
import com.rohitawate.everest.auth.AuthProvider; import com.rohitawate.everest.auth.AuthProvider;
import com.rohitawate.everest.auth.BasicAuthProvider; import com.rohitawate.everest.auth.BasicAuthProvider;
import com.rohitawate.everest.auth.DigestAuthProvider;
import com.rohitawate.everest.controllers.DashboardController;
import com.rohitawate.everest.state.ComposerState; import com.rohitawate.everest.state.ComposerState;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
@ -20,25 +22,47 @@ public class AuthTabController implements Initializable {
@FXML @FXML
private Tab basicTab, digestTab; private Tab basicTab, digestTab;
private BasicAuthController basicController; private SimpleAuthController basicController, digestController;
private DashboardController dashboard;
@Override @Override
public void initialize(URL location, ResourceBundle resources) { public void initialize(URL location, ResourceBundle resources) {
try { try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/homewindow/auth/BasicAuth.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/homewindow/auth/SimpleAuth.fxml"));
Parent basicFXML = loader.load(); Parent basicFXML = loader.load();
basicTab.setContent(basicFXML); basicTab.setContent(basicFXML);
basicController = loader.getController(); basicController = loader.getController();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/homewindow/auth/SimpleAuth.fxml"));
Parent digestFXML = loader.load();
digestTab.setContent(digestFXML);
digestController = loader.getController();
} catch (IOException e) {
e.printStackTrace();
}
} }
public AuthProvider getAuthProvider() { public AuthProvider getAuthProvider() {
switch (authTabPane.getSelectionModel().getSelectedIndex()) { switch (authTabPane.getSelectionModel().getSelectedIndex()) {
case 0: case 0:
return new BasicAuthProvider( return new BasicAuthProvider(
basicController.getUsername(), basicController.getPassword(), basicController.isSelected()); basicController.getUsername(),
basicController.getPassword(),
basicController.isSelected()
);
case 1:
return new DigestAuthProvider(
dashboard.getAddress(),
dashboard.getHttpMethod(),
digestController.getUsername(),
digestController.getPassword(),
digestController.isSelected()
);
default: default:
return null; return null;
} }
@ -47,10 +71,19 @@ public class AuthTabController implements Initializable {
public void getState(ComposerState state) { public void getState(ComposerState state) {
state.basicUsername = basicController.getUsername(); state.basicUsername = basicController.getUsername();
state.basicPassword = basicController.getPassword(); state.basicPassword = basicController.getPassword();
state.basicAuthEnabled = basicController.isSelected(); state.basicEnabled = basicController.isSelected();
state.digestUsername = digestController.getUsername();
state.digestPassword = digestController.getPassword();
state.digestEnabled = digestController.isSelected();
} }
public void setState(ComposerState state) { public void setState(ComposerState state) {
basicController.setState(state.basicUsername, state.basicPassword, state.basicAuthEnabled); basicController.setState(state.basicUsername, state.basicPassword, state.basicEnabled);
digestController.setState(state.digestUsername, state.digestPassword, state.digestEnabled);
}
public void setDashboard(DashboardController dashboard) {
this.dashboard = dashboard;
} }
} }

View file

@ -1,30 +1,36 @@
package com.rohitawate.everest.controllers.auth; package com.rohitawate.everest.controllers.auth;
import com.jfoenix.controls.JFXCheckBox; import com.jfoenix.controls.JFXCheckBox;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
public class BasicAuthController { public class SimpleAuthController {
@FXML @FXML
private TextField usernameField, passwordField; private TextField usernameField, passwordField;
@FXML @FXML
private JFXCheckBox checkBox; private JFXCheckBox checkBox;
boolean isSelected() { boolean isSelected() {
return checkBox.isSelected(); return checkBox.isSelected();
} }
String getUsername() { String getUsername() {
return usernameField.getText(); if (usernameField.getText() == null)
} return "";
String getPassword() { return usernameField.getText();
return passwordField.getText(); }
}
String getPassword() {
void setState(String username, String password, boolean enabled) { if (passwordField.getText() == null)
usernameField.setText(username); return "";
passwordField.setText(password);
checkBox.setSelected(enabled); return passwordField.getText();
} }
}
void setState(String username, String password, boolean enabled) {
usernameField.setText(username);
passwordField.setText(password);
checkBox.setSelected(enabled);
}
}

View file

@ -15,6 +15,7 @@
*/ */
package com.rohitawate.everest.requestmanager; package com.rohitawate.everest.requestmanager;
import com.rohitawate.everest.Main;
import com.rohitawate.everest.exceptions.NullResponseException; import com.rohitawate.everest.exceptions.NullResponseException;
import com.rohitawate.everest.exceptions.RedirectException; import com.rohitawate.everest.exceptions.RedirectException;
import com.rohitawate.everest.models.requests.*; import com.rohitawate.everest.models.requests.*;
@ -95,6 +96,8 @@ public class RequestManager extends Service<EverestResponse> {
protected EverestResponse call() throws Exception { protected EverestResponse call() throws Exception {
Response serverResponse = null; Response serverResponse = null;
addAuthHeader();
if (request.getClass().equals(GETRequest.class)) { if (request.getClass().equals(GETRequest.class)) {
initialTime = System.currentTimeMillis(); initialTime = System.currentTimeMillis();
serverResponse = requestBuilder.get(); serverResponse = requestBuilder.get();
@ -129,15 +132,17 @@ public class RequestManager extends Service<EverestResponse> {
return this.request; return this.request;
} }
private void appendHeaders() { private void addAuthHeader() {
request.getHeaders().forEach((key, value) -> requestBuilder.header(key, value));
requestBuilder.header("User-Agent", "Everest");
if (request.getAuthProvider() != null && request.getAuthProvider().isEnabled()) { if (request.getAuthProvider() != null && request.getAuthProvider().isEnabled()) {
requestBuilder.header("Authorization", request.getAuthProvider().getAuthHeader()); requestBuilder.header("Authorization", request.getAuthProvider().getAuthHeader());
} }
} }
private void appendHeaders() {
request.getHeaders().forEach((key, value) -> requestBuilder.header(key, value));
requestBuilder.header("User-Agent", Main.APP_NAME);
}
/** /**
* Takes a ServerResponse and extracts all the headers, the body, the response time and other details * Takes a ServerResponse and extracts all the headers, the body, the response time and other details
* into a EverestResponse. * into a EverestResponse.

View file

@ -37,7 +37,11 @@ public class ComposerState {
public String basicUsername; public String basicUsername;
public String basicPassword; public String basicPassword;
public boolean basicAuthEnabled; public boolean basicEnabled;
public String digestUsername;
public String digestPassword;
public boolean digestEnabled;
// Tuples of URL-encoded requests // Tuples of URL-encoded requests
public List<FieldState> urlStringTuples; public List<FieldState> urlStringTuples;
@ -65,7 +69,10 @@ public class ComposerState {
if (!headers.equals(state.headers)) return false; if (!headers.equals(state.headers)) return false;
if (!basicUsername.equals(state.basicUsername)) return false; if (!basicUsername.equals(state.basicUsername)) return false;
if (!basicPassword.equals(state.basicPassword)) return false; if (!basicPassword.equals(state.basicPassword)) return false;
if (basicAuthEnabled != state.basicAuthEnabled) return false; if (basicEnabled != state.basicEnabled) return false;
if (!digestUsername.equals(state.digestUsername)) return false;
if (!digestPassword.equals(state.digestPassword)) return false;
if (digestEnabled != state.digestEnabled) return false;
if (state.httpMethod.equals(HTTPConstants.GET) if (state.httpMethod.equals(HTTPConstants.GET)
|| state.httpMethod.equals(HTTPConstants.DELETE)) return true; || state.httpMethod.equals(HTTPConstants.DELETE)) return true;

View file

@ -35,30 +35,39 @@ class SQLiteManager implements DataManager {
private PreparedStatement statement; private PreparedStatement statement;
private static class Queries { private static class Queries {
private static final String[] createQueries = { private static final String[] CREATE_QUERIES = {
"CREATE TABLE IF NOT EXISTS Requests(ID INTEGER PRIMARY KEY, Type TEXT NOT NULL, Target TEXT NOT NULL, Date TEXT NOT NULL)", "CREATE TABLE IF NOT EXISTS Requests(ID INTEGER PRIMARY KEY, Type TEXT NOT NULL, Target TEXT NOT NULL, Date TEXT NOT NULL)",
"CREATE TABLE IF NOT EXISTS RequestContentMap(RequestID INTEGER, ContentType TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))", "CREATE TABLE IF NOT EXISTS RequestContentMap(RequestID INTEGER, ContentType TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))",
"CREATE TABLE IF NOT EXISTS Bodies(RequestID INTEGER, Type TEXT NOT NULL CHECK(Type IN ('application/json', 'application/xml', 'text/html', 'text/plain')), Body TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))", "CREATE TABLE IF NOT EXISTS Bodies(RequestID INTEGER, Type TEXT NOT NULL CHECK(Type IN ('application/json', 'application/xml', 'text/html', 'text/plain')), Body TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))",
"CREATE TABLE IF NOT EXISTS FilePaths(RequestID INTEGER, Path TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))", "CREATE TABLE IF NOT EXISTS FilePaths(RequestID INTEGER, Path TEXT NOT NULL, FOREIGN KEY(RequestID) REFERENCES Requests(ID))",
"CREATE TABLE IF NOT EXISTS Tuples(RequestID INTEGER, Type TEXT NOT NULL CHECK(Type IN ('Header', 'Param', 'URLString', 'FormString', 'File')), Key TEXT NOT NULL, Value TEXT NOT NULL, Checked INTEGER CHECK (Checked IN (0, 1)), FOREIGN KEY(RequestID) REFERENCES Requests(ID))", "CREATE TABLE IF NOT EXISTS Tuples(RequestID INTEGER, Type TEXT NOT NULL CHECK(Type IN ('Header', 'Param', 'URLString', 'FormString', 'File')), Key TEXT NOT NULL, Value TEXT NOT NULL, Checked INTEGER CHECK (Checked IN (0, 1)), FOREIGN KEY(RequestID) REFERENCES Requests(ID))",
"CREATE TABLE IF NOT EXISTS BasicAuthCredentials(RequestID INTEGER, Username TEXT NOT NULL, Password TEXT NOT NULL, Enabled INTEGER CHECK (Enabled IN (1, 0)), FOREIGN KEY(RequestID) REFERENCES Requests(ID))" "CREATE TABLE IF NOT EXISTS SimpleAuthCredentials(RequestID INTEGER, Type TEXT NOT NULL, Username TEXT NOT NULL, Password TEXT NOT NULL, Enabled INTEGER CHECK (Enabled IN (1, 0)), FOREIGN KEY(RequestID) REFERENCES Requests(ID))"
}; };
private static final String saveRequest = "INSERT INTO Requests(Type, Target, Date) VALUES(?, ?, ?)"; private static final String SAVE_REQUEST = "INSERT INTO Requests(Type, Target, Date) VALUES(?, ?, ?)";
private static final String saveRequestContentPair = "INSERT INTO RequestContentMap(RequestID, ContentType) VALUES(?, ?)"; private static final String SAVE_REQUEST_CONTENT_PAIR = "INSERT INTO RequestContentMap(RequestID, ContentType) VALUES(?, ?)";
private static final String saveBody = "INSERT INTO Bodies(RequestID, Body, Type) VALUES(?, ?, ?)"; private static final String SAVE_BODY = "INSERT INTO Bodies(RequestID, Body, Type) VALUES(?, ?, ?)";
private static final String saveFilePath = "INSERT INTO FilePaths(RequestID, Path) VALUES(?, ?)"; private static final String SAVE_FILE_PATH = "INSERT INTO FilePaths(RequestID, Path) VALUES(?, ?)";
private static final String saveTuple = "INSERT INTO Tuples(RequestID, Type, Key, Value, Checked) VALUES(?, ?, ?, ?, ?)"; private static final String SAVE_TUPLE = "INSERT INTO Tuples(RequestID, Type, Key, Value, Checked) VALUES(?, ?, ?, ?, ?)";
private static final String saveBasicAuthCredentials = "INSERT INTO BasicAuthCredentials(RequestID, Username, Password, Enabled) VALUES(?, ?, ?, ?)"; private static final String SAVE_SIMPLE_AUTH_CREDENTIALS = "INSERT INTO SimpleAuthCredentials(RequestID, Type, Username, Password, Enabled) VALUES(?, ?, ?, ?, ?)";
private static final String selectRecentRequests = "SELECT * FROM Requests WHERE Requests.Date > ?"; private static final String SELECT_RECENT_REQUESTS = "SELECT * FROM Requests WHERE Requests.Date > ?";
private static final String selectRequestContentType = "SELECT ContentType FROM RequestContentMap WHERE RequestID == ?"; private static final String SELECT_REQUEST_CONTENT_TYPE = "SELECT ContentType FROM RequestContentMap WHERE RequestID == ?";
private static final String selectRequestBody = "SELECT Body, Type FROM Bodies WHERE RequestID == ?"; private static final String SELECT_REQUEST_BODY = "SELECT Body, Type FROM Bodies WHERE RequestID == ?";
private static final String selectFilePath = "SELECT Path FROM FilePaths WHERE RequestID == ?"; private static final String SELECT_FILE_PATH = "SELECT Path FROM FilePaths WHERE RequestID == ?";
private static final String selectBasicAuthCredentials = "SELECT * FROM BasicAuthCredentials WHERE RequestID == ?"; private static final String SELECT_SIMPLE_AUTH_CREDENTIALS = "SELECT * FROM SimpleAuthCredentials WHERE RequestID == ? AND Type == ?";
private static final String selectTuplesByType = "SELECT * FROM Tuples WHERE RequestID == ? AND Type == ?"; private static final String SELECT_TUPLES_BY_TYPE = "SELECT * FROM Tuples WHERE RequestID == ? AND Type == ?";
private static final String selectMostRecentRequest = "SELECT * FROM Requests ORDER BY ID DESC LIMIT 1"; private static final String SELECT_MOST_RECENT_REQUEST = "SELECT * FROM Requests ORDER BY ID DESC LIMIT 1";
} }
private static final String ID = "ID";
private static final String HEADER = "Header";
private static final String PARAM = "Param";
private static final String URL_STRING = "URLString";
private static final String FORM_STRING = "FormString";
private static final String FILE = "File";
private static final String BASIC = "Basic";
private static final String DIGEST = "Digest";
public SQLiteManager() { public SQLiteManager() {
try { try {
String configPath = "Everest/config/"; String configPath = "Everest/config/";
@ -70,9 +79,9 @@ class SQLiteManager implements DataManager {
conn = DriverManager.getConnection("jdbc:sqlite:Everest/config/history.sqlite"); conn = DriverManager.getConnection("jdbc:sqlite:Everest/config/history.sqlite");
createDatabase(); createDatabase();
LoggingService.logInfo("Connected to database", LocalDateTime.now()); LoggingService.logInfo("Connected to database.", LocalDateTime.now());
} catch (Exception E) { } catch (Exception E) {
LoggingService.logSevere("Exception while initializing DataManager.", E, LocalDateTime.now()); LoggingService.logSevere("Exception while initializing SQLiteManager.", E, LocalDateTime.now());
} }
} }
@ -80,7 +89,7 @@ class SQLiteManager implements DataManager {
* Creates and initializes the database with necessary tables if not already done. * Creates and initializes the database with necessary tables if not already done.
*/ */
private void createDatabase() throws SQLException { private void createDatabase() throws SQLException {
for (String query : Queries.createQueries) { for (String query : Queries.CREATE_QUERIES) {
statement = conn.prepareStatement(query); statement = conn.prepareStatement(query);
statement.execute(); statement.execute();
} }
@ -94,7 +103,7 @@ class SQLiteManager implements DataManager {
*/ */
@Override @Override
public synchronized void saveState(ComposerState newState) throws SQLException { public synchronized void saveState(ComposerState newState) throws SQLException {
statement = conn.prepareStatement(Queries.saveRequest); statement = conn.prepareStatement(Queries.SAVE_REQUEST);
statement.setString(1, newState.httpMethod); statement.setString(1, newState.httpMethod);
statement.setString(2, newState.target); statement.setString(2, newState.target);
@ -109,44 +118,50 @@ class SQLiteManager implements DataManager {
if (RS.next()) if (RS.next())
requestID = RS.getInt("MaxID"); requestID = RS.getInt("MaxID");
saveTuple(newState.headers, "Header", requestID); saveTuple(newState.headers, HEADER, requestID);
saveTuple(newState.params, "Param", requestID); saveTuple(newState.params, PARAM, requestID);
saveBasicAuthCredentials(requestID, newState.basicUsername, newState.basicPassword, newState.basicAuthEnabled); saveSimpleAuthCredentials(requestID, BASIC, newState.basicUsername, newState.basicPassword, newState.basicEnabled);
saveSimpleAuthCredentials(requestID, DIGEST, newState.digestUsername, newState.digestPassword, newState.digestEnabled);
if (!(newState.httpMethod.equals(HTTPConstants.GET) || newState.httpMethod.equals(HTTPConstants.DELETE))) { if (!(newState.httpMethod.equals(HTTPConstants.GET) || newState.httpMethod.equals(HTTPConstants.DELETE))) {
// Maps the request to its ContentType for faster retrieval // Maps the request to its ContentType for faster retrieval
statement = conn.prepareStatement(Queries.saveRequestContentPair); statement = conn.prepareStatement(Queries.SAVE_REQUEST_CONTENT_PAIR);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, newState.contentType); statement.setString(2, newState.contentType);
statement.executeUpdate(); statement.executeUpdate();
statement = conn.prepareStatement(Queries.saveBody); statement = conn.prepareStatement(Queries.SAVE_BODY);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, newState.rawBody); statement.setString(2, newState.rawBody);
statement.setString(3, newState.rawBodyBoxValue); statement.setString(3, newState.rawBodyBoxValue);
statement.executeUpdate(); statement.executeUpdate();
statement = conn.prepareStatement(Queries.saveFilePath); statement = conn.prepareStatement(Queries.SAVE_FILE_PATH);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, newState.binaryFilePath); statement.setString(2, newState.binaryFilePath);
statement.executeUpdate(); statement.executeUpdate();
saveTuple(newState.urlStringTuples, "URLString", requestID); saveTuple(newState.urlStringTuples, URL_STRING, requestID);
saveTuple(newState.formStringTuples, "FormString", requestID); saveTuple(newState.formStringTuples, FORM_STRING, requestID);
saveTuple(newState.formFileTuples, "File", requestID); saveTuple(newState.formFileTuples, FILE, requestID);
} }
} }
private void saveBasicAuthCredentials(int requestID, String username, String password, boolean enabled) throws SQLException { private void saveSimpleAuthCredentials(int requestID,
if (username == null || password == null) String type,
String username,
String password,
boolean enabled) throws SQLException {
if (username == null || username.isEmpty() || password == null || password.isEmpty())
return; return;
statement = conn.prepareStatement(Queries.saveBasicAuthCredentials); statement = conn.prepareStatement(Queries.SAVE_SIMPLE_AUTH_CREDENTIALS);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, username); statement.setString(2, type);
statement.setString(3, password); statement.setString(3, username);
statement.setInt(4, enabled ? 1 : 0); statement.setString(4, password);
statement.setInt(5, enabled ? 1 : 0);
statement.executeUpdate(); statement.executeUpdate();
} }
@ -158,7 +173,7 @@ class SQLiteManager implements DataManager {
public synchronized List<ComposerState> getHistory() throws SQLException { public synchronized List<ComposerState> getHistory() throws SQLException {
List<ComposerState> history = new ArrayList<>(); List<ComposerState> history = new ArrayList<>();
// Loads the requests from the last x number of days, x being Settings.showHistoryRange // Loads the requests from the last x number of days, x being Settings.showHistoryRange
statement = conn.prepareStatement(Queries.selectRecentRequests); statement = conn.prepareStatement(Queries.SELECT_RECENT_REQUESTS);
String historyStartDate = LocalDate.now().minusDays(Settings.showHistoryRange).toString(); String historyStartDate = LocalDate.now().minusDays(Settings.showHistoryRange).toString();
statement.setString(1, historyStartDate); statement.setString(1, historyStartDate);
@ -170,11 +185,12 @@ class SQLiteManager implements DataManager {
state.target = resultSet.getString("Target"); state.target = resultSet.getString("Target");
int requestID = resultSet.getInt("ID"); int requestID = resultSet.getInt(ID);
state.headers = getTuples(requestID, "Header"); state.headers = getTuples(requestID, HEADER);
state.params = getTuples(requestID, "Param"); state.params = getTuples(requestID, PARAM);
state.httpMethod = resultSet.getString("Type"); state.httpMethod = resultSet.getString("Type");
getBasicAuthCredentials(state, requestID); getSimpleAuthCredentials(state, requestID, BASIC);
getSimpleAuthCredentials(state, requestID, DIGEST);
if (!(state.httpMethod.equals(HTTPConstants.GET) || state.httpMethod.equals(HTTPConstants.DELETE))) { if (!(state.httpMethod.equals(HTTPConstants.GET) || state.httpMethod.equals(HTTPConstants.DELETE))) {
// Retrieves request body ContentType for querying corresponding table // Retrieves request body ContentType for querying corresponding table
@ -189,9 +205,9 @@ class SQLiteManager implements DataManager {
state.binaryFilePath = getFilePath(requestID); state.binaryFilePath = getFilePath(requestID);
state.urlStringTuples = getTuples(requestID, "URLString"); state.urlStringTuples = getTuples(requestID, URL_STRING);
state.formStringTuples = getTuples(requestID, "FormString"); state.formStringTuples = getTuples(requestID, FORM_STRING);
state.formFileTuples = getTuples(requestID, "File"); state.formFileTuples = getTuples(requestID, FILE);
} }
history.add(state); history.add(state);
@ -200,23 +216,42 @@ class SQLiteManager implements DataManager {
return history; return history;
} }
private void getBasicAuthCredentials(ComposerState state, int requestID) throws SQLException { private void getSimpleAuthCredentials(ComposerState state, int requestID, String type) throws SQLException {
statement = conn.prepareStatement(Queries.selectBasicAuthCredentials); if (!(type.equals(BASIC) || type.equals(DIGEST)))
return;
statement = conn.prepareStatement(Queries.SELECT_SIMPLE_AUTH_CREDENTIALS);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, type);
ResultSet RS = statement.executeQuery(); ResultSet RS = statement.executeQuery();
if (RS.next()) { if (RS.next()) {
state.basicUsername = RS.getString("Username"); if (type.equals(BASIC)) {
state.basicPassword = RS.getString("Password"); state.basicUsername = RS.getString("Username");
state.basicAuthEnabled = RS.getInt("Enabled") == 1; state.basicPassword = RS.getString("Password");
state.basicEnabled = RS.getInt("Enabled") == 1;
} else if (type.equals(DIGEST)) {
state.digestUsername = RS.getString("Username");
state.digestPassword = RS.getString("Password");
state.digestEnabled = RS.getInt("Enabled") == 1;
}
} else {
String empty = "";
state.basicUsername = empty;
state.basicPassword = empty;
state.basicEnabled = false;
state.digestUsername = empty;
state.digestPassword = empty;
state.digestEnabled = false;
} }
} }
private String getRequestContentType(int requestID) throws SQLException { private String getRequestContentType(int requestID) throws SQLException {
String contentType = null; String contentType = null;
statement = conn.prepareStatement(Queries.selectRequestContentType); statement = conn.prepareStatement(Queries.SELECT_REQUEST_CONTENT_TYPE);
statement.setInt(1, requestID); statement.setInt(1, requestID);
ResultSet RS = statement.executeQuery(); ResultSet RS = statement.executeQuery();
@ -233,13 +268,13 @@ class SQLiteManager implements DataManager {
* @return fieldStates - List of FieldStates for the tuples * @return fieldStates - List of FieldStates for the tuples
*/ */
private List<FieldState> getTuples(int requestID, String type) throws SQLException { private List<FieldState> getTuples(int requestID, String type) throws SQLException {
if (!(type.equals("FormString") || type.equals("URLString") || if (!(type.equals(FORM_STRING) || type.equals(URL_STRING) ||
type.equals("File") || type.equals("Param") || type.equals("Header"))) type.equals(FILE) || type.equals(PARAM) || type.equals(HEADER)))
return null; return null;
ArrayList<FieldState> fieldStates = new ArrayList<>(); ArrayList<FieldState> fieldStates = new ArrayList<>();
PreparedStatement statement = conn.prepareStatement(Queries.selectTuplesByType); PreparedStatement statement = conn.prepareStatement(Queries.SELECT_TUPLES_BY_TYPE);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, type); statement.setString(2, type);
@ -261,23 +296,24 @@ class SQLiteManager implements DataManager {
public ComposerState getLastAdded() { public ComposerState getLastAdded() {
ComposerState lastRequest = new ComposerState(); ComposerState lastRequest = new ComposerState();
try { try {
statement = conn.prepareStatement(Queries.selectMostRecentRequest); statement = conn.prepareStatement(Queries.SELECT_MOST_RECENT_REQUEST);
ResultSet RS = statement.executeQuery(); ResultSet RS = statement.executeQuery();
int requestID = -1; int requestID = -1;
if (RS.next()) { if (RS.next()) {
requestID = RS.getInt("ID"); requestID = RS.getInt(ID);
lastRequest.target = RS.getString("Target"); lastRequest.target = RS.getString("Target");
lastRequest.httpMethod = RS.getString("Type"); lastRequest.httpMethod = RS.getString("Type");
} }
getBasicAuthCredentials(lastRequest, requestID); getSimpleAuthCredentials(lastRequest, requestID, BASIC);
getSimpleAuthCredentials(lastRequest, requestID, DIGEST);
lastRequest.headers = getTuples(requestID, "Header"); lastRequest.headers = getTuples(requestID, HEADER);
lastRequest.params = getTuples(requestID, "Param"); lastRequest.params = getTuples(requestID, PARAM);
lastRequest.urlStringTuples = getTuples(requestID, "URLString"); lastRequest.urlStringTuples = getTuples(requestID, URL_STRING);
lastRequest.formStringTuples = getTuples(requestID, "FormString"); lastRequest.formStringTuples = getTuples(requestID, FORM_STRING);
lastRequest.formFileTuples = getTuples(requestID, "File"); lastRequest.formFileTuples = getTuples(requestID, FILE);
lastRequest.contentType = getRequestContentType(requestID); lastRequest.contentType = getRequestContentType(requestID);
@ -297,7 +333,7 @@ class SQLiteManager implements DataManager {
} }
private Pair<String, String> getRequestBody(int requestID) throws SQLException { private Pair<String, String> getRequestBody(int requestID) throws SQLException {
statement = conn.prepareStatement(Queries.selectRequestBody); statement = conn.prepareStatement(Queries.SELECT_REQUEST_BODY);
statement.setInt(1, requestID); statement.setInt(1, requestID);
ResultSet RS = statement.executeQuery(); ResultSet RS = statement.executeQuery();
@ -310,7 +346,7 @@ class SQLiteManager implements DataManager {
} }
private String getFilePath(int requestID) throws SQLException { private String getFilePath(int requestID) throws SQLException {
statement = conn.prepareStatement(Queries.selectFilePath); statement = conn.prepareStatement(Queries.SELECT_FILE_PATH);
statement.setInt(1, requestID); statement.setInt(1, requestID);
ResultSet RS = statement.executeQuery(); ResultSet RS = statement.executeQuery();
@ -325,7 +361,7 @@ class SQLiteManager implements DataManager {
if (tuples.size() > 0) { if (tuples.size() > 0) {
try { try {
for (FieldState fieldState : tuples) { for (FieldState fieldState : tuples) {
statement = conn.prepareStatement(Queries.saveTuple); statement = conn.prepareStatement(Queries.SAVE_TUPLE);
statement.setInt(1, requestID); statement.setInt(1, requestID);
statement.setString(2, tupleType); statement.setString(2, tupleType);
statement.setString(3, fieldState.key); statement.setString(3, fieldState.key);

View file

@ -7,7 +7,7 @@
<?import javafx.scene.control.TextField?> <?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?> <?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" spacing="10.0" stylesheets="@../../../css/Adreana.css" xmlns="http://javafx.com/javafx/8.0.141" <VBox alignment="CENTER" spacing="10.0" stylesheets="@../../../css/Adreana.css" xmlns="http://javafx.com/javafx/8.0.141"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.rohitawate.everest.controllers.auth.BasicAuthController"> xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.rohitawate.everest.controllers.auth.SimpleAuthController">
<children> <children>
<TextField fx:id="usernameField" maxWidth="400.0" minWidth="200.0" prefWidth="400.0" promptText="USERNAME" <TextField fx:id="usernameField" maxWidth="400.0" minWidth="200.0" prefWidth="400.0" promptText="USERNAME"
styleClass="KVField" VBox.vgrow="ALWAYS"/> styleClass="KVField" VBox.vgrow="ALWAYS"/>