Initial commit for site for forms
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.alttd.forms;
|
||||
|
||||
import com.alttd.forms.database.DatabaseConnection;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
SpringApplication.run(Main.class, args);
|
||||
DatabaseConnection.initialize();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.alttd.forms.beans;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNullApi;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/api/**")
|
||||
.allowedOrigins("http://localhost:3000")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.alttd.forms.contact;
|
||||
import com.alttd.forms.mail.mail_forms.MailForm;
|
||||
import com.alttd.forms.mail.verification.VerificationResult;
|
||||
import com.alttd.forms.mail.verification.Verify;
|
||||
import jakarta.validation.Valid;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/contact")
|
||||
public class ContactController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ContactController.class);
|
||||
|
||||
@PostMapping("/submitContactForm")
|
||||
public CompletableFuture<ResponseEntity<String>> submitForm(@Valid @RequestBody ContactFormData formData) {
|
||||
logger.debug(formData.toString());
|
||||
|
||||
CompletableFuture<Integer> storeFormForVerificationCode = new StoreFormQuery().storeFormForVerificationCode(formData.toJsonString(), formData.email);
|
||||
return storeFormForVerificationCode.thenCompose(code -> Verify.verifyEmail(formData.email, code).thenApply(verificationResult -> {
|
||||
if (verificationResult == VerificationResult.VERIFICATION_SENT) {
|
||||
//TODO if this is ok tell the user they have x min to verify if they fail to do so they have to remake the form
|
||||
return ResponseEntity.ok("User Data received and email verification sent.");
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("Failed to send verification email. Reason: " + verificationResult.name());
|
||||
}
|
||||
})).exceptionally(throwable -> {
|
||||
logger.error("Failed to store form", throwable);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to store your form");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.alttd.forms.contact;
|
||||
|
||||
import com.alttd.forms.form.Form;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import org.hibernate.validator.constraints.Length;
|
||||
|
||||
public class ContactFormData extends Form {
|
||||
|
||||
public ContactFormData(String username, String email, String question) {
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.question = question;
|
||||
}
|
||||
|
||||
@NotEmpty(message = "You have to provide a username")
|
||||
@Length(min = 3, max = 16, message = "Usernames have to be between 3 and 16 characters")
|
||||
@Pattern(regexp = "[a-zA-Z-0-9_]{3,16}", message = "Your username has to be a valid Minecraft username")
|
||||
public String username;
|
||||
|
||||
@NotEmpty(message = "You have to provide an e-mail address")
|
||||
@Email(regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)])",
|
||||
message = "This is not a valid e-mail address")
|
||||
public String email;
|
||||
|
||||
@Length(min = 11, max = 2000, message = "Your question should have between 10 and 2000 characters")
|
||||
public String question;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ContactFormData{" +
|
||||
"username='" + username + '\'' +
|
||||
", email='" + email + '\'' +
|
||||
", question='" + question + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toHtml() {
|
||||
return "<div style='margin: 10px; padding: 10px; border: 1px solid #000; width: 300px;'>" +
|
||||
"<p><strong>Username:</strong><br>" +
|
||||
"<span style='color: #007BFF;'>" +
|
||||
username +
|
||||
"</span></p>" +
|
||||
"<p><strong>Email:</strong><br>" +
|
||||
"<span style='color: #007BFF;'>" +
|
||||
email +
|
||||
"</span></p>" +
|
||||
"<p><strong>Question:</strong><br>" +
|
||||
"<span style='color: #007BFF;'>" +
|
||||
question +
|
||||
"</span></p>" +
|
||||
"</div>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.alttd.forms.contact;
|
||||
|
||||
import com.alttd.forms.database.DatabaseConnection;
|
||||
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class StoreFormQuery {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StoreFormQuery.class);
|
||||
|
||||
public int generateVerificationCode() {
|
||||
Random random = new Random();
|
||||
return 100000 + random.nextInt(900000);
|
||||
}
|
||||
|
||||
private Optional<Long> insertForm(Connection connection, String form) {
|
||||
String insertForm = "INSERT INTO form (creation_date, form_json) VALUES (?, ?)";
|
||||
try (PreparedStatement stmt = connection.prepareStatement(insertForm, Statement.RETURN_GENERATED_KEYS)) {
|
||||
stmt.setLong(1, Instant.now().toEpochMilli());
|
||||
stmt.setString(2, form);
|
||||
int affectedRows = stmt.executeUpdate();
|
||||
if (affectedRows == 0) {
|
||||
logger.error("No rows affected during insert of form: " + form);
|
||||
return Optional.empty();
|
||||
}
|
||||
ResultSet generatedKeys = stmt.getGeneratedKeys();
|
||||
if (generatedKeys.next()) {
|
||||
return Optional.of(generatedKeys.getLong(1));
|
||||
} else {
|
||||
logger.error("No primary key generated when inserting form " + form);
|
||||
return Optional.empty();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed insert form query for: " + form, e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<Integer> insertVerificationCodeForForm(Connection connection, String eMail, long formId) {
|
||||
String insertVerificationCodeForForm = "INSERT INTO verify_form (e_mail, verification_code, formId) VALUES (?, ?, ?)";
|
||||
int verificationCode = generateVerificationCode();
|
||||
try (PreparedStatement stmt = connection.prepareStatement(insertVerificationCodeForForm)) {
|
||||
stmt.setString(1, eMail);
|
||||
stmt.setInt(2, verificationCode);
|
||||
stmt.setLong(3, formId);
|
||||
stmt.executeUpdate();
|
||||
return Optional.of(verificationCode);
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed to insert verification code for form with id: " + formId);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> storeFormForVerificationCode(String form, String eMail) {
|
||||
Connection connection = DatabaseConnection.getConnection();
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
Optional<Long> optionalFormId = insertForm(connection, form);
|
||||
if (optionalFormId.isEmpty()) {
|
||||
throw new RuntimeException("Failed to store form");
|
||||
}
|
||||
Optional<Integer> verificationCode = insertVerificationCodeForForm(connection, eMail, optionalFormId.get());
|
||||
if (verificationCode.isEmpty()) {
|
||||
throw new RuntimeException("Failed to set verification code");
|
||||
}
|
||||
return verificationCode.get();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.alttd.forms.database;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Database {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Database.class);
|
||||
|
||||
public static void createTables() {
|
||||
String[] createTables = {
|
||||
"CREATE TABLE IF NOT EXISTS verify_form (e_mail VARCHAR(256), verification_code INT, formId INT, PRIMARY KEY(e_mail, verification_code))",
|
||||
"CREATE TABLE IF NOT EXISTS form (formId INT AUTO_INCREMENT, creation_date BIGINT, form_json TEXT, PRIMARY KEY(formId))"
|
||||
};
|
||||
Connection connection = DatabaseConnection.getConnection();
|
||||
for (String query : createTables) {
|
||||
createTable(connection, query);
|
||||
}
|
||||
}
|
||||
|
||||
private static void createTable(Connection connection, String query) {
|
||||
try {
|
||||
connection.createStatement().execute(query);
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed to create table", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.alttd.forms.database;
|
||||
|
||||
import com.alttd.forms.properties.PropertiesLoader;
|
||||
import com.alttd.forms.properties.PropertiesWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
public class DatabaseConnection {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DatabaseConnection.class);
|
||||
|
||||
public static DatabaseConnection instance;
|
||||
public Connection connection;
|
||||
private Properties properties;
|
||||
|
||||
public DatabaseConnection() throws SQLException {
|
||||
instance = this;
|
||||
loadProperties();
|
||||
instance.openConnection();
|
||||
Database.createTables();
|
||||
}
|
||||
|
||||
public static Connection getConnection() {
|
||||
try {
|
||||
instance.openConnection();
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed to get connection", e);
|
||||
}
|
||||
|
||||
return instance.connection;
|
||||
}
|
||||
|
||||
public static void initialize() throws SQLException {
|
||||
if (instance != null)
|
||||
return;
|
||||
instance = new DatabaseConnection();
|
||||
}
|
||||
|
||||
private void loadProperties() {
|
||||
String fileName = "database.properties";
|
||||
Optional<Properties> optionalProperties = PropertiesLoader.loadProperties(fileName);
|
||||
if (optionalProperties.isPresent()) {
|
||||
properties = optionalProperties.get();
|
||||
return;
|
||||
}
|
||||
|
||||
properties = new Properties();
|
||||
properties.setProperty("drivers", "mysql");
|
||||
properties.setProperty("ip", "localhost");
|
||||
properties.setProperty("port", "3306");
|
||||
properties.setProperty("database", "site");
|
||||
properties.setProperty("user", "root");
|
||||
properties.setProperty("password", "root");
|
||||
properties.setProperty("parameters", "autoReconnect=true&useSSL=false");
|
||||
PropertiesWriter.writeProperties(properties, fileName);
|
||||
}
|
||||
|
||||
public void openConnection() throws SQLException {
|
||||
if (this.connection != null && !this.connection.isClosed()) {
|
||||
return;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (this.connection != null && !this.connection.isClosed()) {
|
||||
return;
|
||||
}
|
||||
this.connection = DriverManager.getConnection("jdbc:" + properties.getProperty("drivers") + "://" +
|
||||
properties.getProperty("ip") + ":" + properties.getProperty("port") + "/" +
|
||||
properties.getProperty("database") + "?" + properties.getProperty("parameters"),
|
||||
properties.getProperty("user"),
|
||||
properties.getProperty("password"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.alttd.forms.form;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public abstract class Form {
|
||||
|
||||
public String toJsonString() {
|
||||
return new Gson().toJson(this);
|
||||
}
|
||||
|
||||
public abstract String toHtml();
|
||||
|
||||
@Override
|
||||
public abstract String toString();
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.alttd.forms.mail;
|
||||
|
||||
import com.alttd.forms.properties.PropertiesLoader;
|
||||
import com.alttd.forms.properties.PropertiesWriter;
|
||||
|
||||
import javax.mail.Authenticator;
|
||||
import javax.mail.PasswordAuthentication;
|
||||
import javax.mail.Session;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MailSettings {
|
||||
|
||||
private static Properties mailProperties = null;
|
||||
private static Properties accountDetails = null;
|
||||
private static PasswordAuthentication passwordAuthentication = null;
|
||||
private static Session session = null;
|
||||
|
||||
public static Properties getMailProperties() {
|
||||
if (mailProperties != null)
|
||||
return mailProperties;
|
||||
|
||||
String fileName = "mail_settings.properties";
|
||||
Optional<Properties> properties = PropertiesLoader.loadProperties(fileName);
|
||||
if (properties.isPresent()) {
|
||||
mailProperties = properties.get();
|
||||
return mailProperties;
|
||||
}
|
||||
|
||||
mailProperties = new Properties();
|
||||
mailProperties.put("mail.smtp.host", "smtp.zoho.com");
|
||||
mailProperties.put("mail.smtp.port", "465");
|
||||
mailProperties.put("mail.smtp.auth", "true");
|
||||
mailProperties.put("mail.smtp.socketFactory.port", "465");
|
||||
mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
|
||||
PropertiesWriter.writeProperties(mailProperties, fileName);
|
||||
return mailProperties;
|
||||
}
|
||||
|
||||
private static Optional<PasswordAuthentication> createPasswordAuthentication(Properties accountDetails) {
|
||||
String username = accountDetails.getProperty("username");
|
||||
if (username == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String password = accountDetails.getProperty("password");
|
||||
if (password == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
passwordAuthentication = new PasswordAuthentication(username, password);
|
||||
return Optional.of(passwordAuthentication);
|
||||
}
|
||||
|
||||
public static Optional<PasswordAuthentication> getAccountDetails() {
|
||||
if (passwordAuthentication != null)
|
||||
return Optional.of(passwordAuthentication);
|
||||
|
||||
if (accountDetails != null) {
|
||||
return createPasswordAuthentication(accountDetails);
|
||||
}
|
||||
|
||||
String fileName = "mail_account.properties";
|
||||
Optional<Properties> properties = PropertiesLoader.loadProperties(fileName);
|
||||
if (properties.isPresent()) {
|
||||
accountDetails = properties.get();
|
||||
return createPasswordAuthentication(accountDetails);
|
||||
}
|
||||
|
||||
accountDetails = new Properties();
|
||||
accountDetails.put("username", "[email protected]");
|
||||
accountDetails.put("password", "testpassword");
|
||||
|
||||
PropertiesWriter.writeProperties(accountDetails, fileName);
|
||||
return createPasswordAuthentication(accountDetails);
|
||||
}
|
||||
|
||||
public static Session getSession(Properties properties, PasswordAuthentication accountDetails) {
|
||||
if (session != null)
|
||||
return session;
|
||||
session = Session.getInstance(properties,
|
||||
new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return accountDetails;
|
||||
}
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.alttd.forms.mail.mail_forms;
|
||||
|
||||
import com.alttd.forms.contact.ContactFormData;
|
||||
import com.alttd.forms.form.Form;
|
||||
import com.alttd.forms.mail.MailSettings;
|
||||
import com.google.gson.Gson;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MailForm {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MailForm.class);
|
||||
|
||||
public static void sendForm(String receiver, String json) { //TODO something to convert json back to the right object, might need to store classname in db?
|
||||
ContactFormData contactFormData = new Gson().fromJson(json, ContactFormData.class);
|
||||
Properties mailProperties = MailSettings.getMailProperties();
|
||||
Optional<PasswordAuthentication> accountDetails = MailSettings.getAccountDetails();
|
||||
if (accountDetails.isEmpty()) {
|
||||
logger.error("No account details, can't send email to " + receiver + " with data " + contactFormData.toString());
|
||||
return;
|
||||
}
|
||||
PasswordAuthentication passwordAuthentication = accountDetails.get();
|
||||
Session session = MailSettings.getSession(mailProperties, passwordAuthentication);
|
||||
|
||||
//TODO rate limiting should be handled before anything ever gets here
|
||||
|
||||
try {
|
||||
Message message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(passwordAuthentication.getUserName()));
|
||||
message.setRecipients(
|
||||
Message.RecipientType.TO,
|
||||
InternetAddress.parse(receiver)
|
||||
);
|
||||
message.setSubject("Altitude Form");
|
||||
//TODO add something above the html form probably
|
||||
message.setContent(contactFormData.toHtml(), "text/html");
|
||||
try {
|
||||
Transport.send(message);
|
||||
logger.debug("Send mail to " + receiver + " containing " + contactFormData) ;
|
||||
} catch (MessagingException e) {
|
||||
logger.error("Unable to send mail to " + receiver + " with data " + contactFormData, e);
|
||||
}
|
||||
} catch (MessagingException e) {
|
||||
logger.error("Failed to create MimeMessage", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.alttd.forms.mail.verification;
|
||||
|
||||
public enum VerificationResult {
|
||||
NO_MAIL_ACCOUNT, FAILED_TO_SEND, VERIFICATION_SENT,
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.alttd.forms.mail.verification;
|
||||
|
||||
import com.alttd.forms.mail.MailSettings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class Verify {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Verify.class);
|
||||
|
||||
public static CompletableFuture<VerificationResult> verifyEmail(String address, int code) {
|
||||
Properties mailProperties = MailSettings.getMailProperties();
|
||||
Optional<PasswordAuthentication> accountDetails = MailSettings.getAccountDetails();
|
||||
if (accountDetails.isEmpty()) {
|
||||
return CompletableFuture.completedFuture(VerificationResult.NO_MAIL_ACCOUNT);
|
||||
}
|
||||
PasswordAuthentication passwordAuthentication = accountDetails.get();
|
||||
Session session = MailSettings.getSession(mailProperties, passwordAuthentication);
|
||||
|
||||
//TODO rate limit sending mail from IP and to specific e-mail addresses (max 1 per minute and max 10 per day)
|
||||
//TODO include a link to all emails that people can click to block us from sending mail to them so no one can use us to spam ppl
|
||||
try {
|
||||
Message message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(passwordAuthentication.getUserName()));
|
||||
message.setRecipients(
|
||||
Message.RecipientType.TO,
|
||||
InternetAddress.parse(address)
|
||||
);
|
||||
message.setSubject("Altitude Email Verification");
|
||||
message.setText("Please verify your email by entering the following code on the page you made the form in\n" + code); //TODO pretty html stuff
|
||||
//TODO include the form they filled in (also in pretty html stuff)
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
Transport.send(message);
|
||||
return VerificationResult.VERIFICATION_SENT;
|
||||
} catch (MessagingException e) {
|
||||
return VerificationResult.FAILED_TO_SEND;
|
||||
}
|
||||
});
|
||||
} catch (MessagingException e) {
|
||||
logger.error("Failed to create MimeMessage", e);
|
||||
return CompletableFuture.completedFuture(VerificationResult.FAILED_TO_SEND);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.alttd.forms.properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Optional;
|
||||
|
||||
public class JarPath {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(JarPath.class);
|
||||
|
||||
public static Optional<File> getCurrentJarDir() {
|
||||
try {
|
||||
String path = JarPath.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
|
||||
File parentFile = new File(path).getParentFile();
|
||||
if (!parentFile.isDirectory()) {
|
||||
logger.error("Parent file of jar is not a directory");
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(parentFile);
|
||||
} catch (Exception e) {
|
||||
logger.error("Error getting current jar directory", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.alttd.forms.properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
public class PropertiesLoader {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
|
||||
|
||||
public static Optional<Properties> loadProperties(String fileName) {
|
||||
Properties prop = new Properties();
|
||||
Optional<File> currentJarPath = JarPath.getCurrentJarDir();
|
||||
if (currentJarPath.isEmpty()) {
|
||||
logger.error("Unable to find jar path to load properties (" + fileName + ")");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
File file = new File(currentJarPath.get(), fileName);
|
||||
if (!file.exists()) {
|
||||
logger.warn("Tried to load properties file that doesnt exists (" + fileName + ")");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!file.canRead()) {
|
||||
logger.error("Unable to read properties file (" + fileName + ")");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (!file.isFile()) {
|
||||
logger.error("Invalid properties file (" + fileName + ")");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
try (FileInputStream input = new FileInputStream(file)) {
|
||||
prop.load(input);
|
||||
return Optional.of(prop);
|
||||
} catch (IOException ex) {
|
||||
logger.error("Failed to load properties due to an unexpected error", ex);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.alttd.forms.properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
public class PropertiesWriter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PropertiesWriter.class);
|
||||
|
||||
public static void writeProperties(Properties prop, String fileName) {
|
||||
Optional<File> currentJarPath = JarPath.getCurrentJarDir();
|
||||
if (currentJarPath.isEmpty()) {
|
||||
logger.error("Failed to get current jar directory");
|
||||
return;
|
||||
}
|
||||
File file = new File(currentJarPath.get(), fileName);
|
||||
if (file.exists()) {
|
||||
logger.error("File already exists (" + fileName + ")");
|
||||
return;
|
||||
}
|
||||
|
||||
try (FileOutputStream output = new FileOutputStream(file)) {
|
||||
logger.debug("Creating new properties file at " + file.getAbsolutePath());
|
||||
prop.store(output, null);
|
||||
} catch (IOException ex) {
|
||||
logger.error("Failed to write properties to file", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.alttd.forms.verify_mail;
|
||||
|
||||
import com.alttd.forms.database.DatabaseConnection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class FormQuery {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FormQuery.class);
|
||||
|
||||
public static Optional<Integer> getFormId(Connection connection, int verificationCode, String eMail) throws SQLException {
|
||||
String sql = "SELECT formId FROM verify_form WHERE verification_code = ? AND e_mail = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setInt(1, verificationCode);
|
||||
stmt.setString(2, eMail);
|
||||
ResultSet resultSet = stmt.executeQuery();
|
||||
if (!resultSet.next()) {
|
||||
logger.warn("A user tried to enter an invalid code: " + verificationCode + " with email: " + eMail);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(resultSet.getInt("formId"));
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed select form query for verification code: " + verificationCode + " with e-mail " + eMail, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<String> getFormForId(Connection connection, int formId) throws SQLException {
|
||||
String sql = "SELECT form_json FROM form WHERE formId = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setInt(1, formId);
|
||||
ResultSet resultSet = stmt.executeQuery();
|
||||
if (!resultSet.next()) {
|
||||
logger.warn("Could not find form with id: " + formId);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(resultSet.getString("form_json"));
|
||||
} catch (SQLException e) {
|
||||
logger.error("Failed select form query for form with id: " + formId, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static CompletableFuture<FormQueryResult> getFormForCode(String verificationCode, String eMail) {
|
||||
Connection connection = DatabaseConnection.getConnection();
|
||||
int code;
|
||||
try {
|
||||
code = Integer.parseInt(verificationCode);
|
||||
} catch (NumberFormatException e) {
|
||||
return CompletableFuture.completedFuture(new FormQueryResult(Optional.empty(), "Invalid code (not a number)"));
|
||||
}
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
Optional<Integer> formId;
|
||||
try {
|
||||
formId = getFormId(connection, code, eMail);
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
if (formId.isEmpty()) {
|
||||
return new FormQueryResult(Optional.empty(), "Unable to find form for a user with this code and e-mail");
|
||||
}
|
||||
|
||||
try {
|
||||
return getFormForId(connection, formId.get())
|
||||
.map(formJson -> new FormQueryResult(Optional.of(formJson), "Success"))
|
||||
.orElse(new FormQueryResult(Optional.empty(), "Unable to find your form"));
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.alttd.forms.verify_mail;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public record FormQueryResult(Optional<String> formJson, String failReason) {
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.alttd.forms.verify_mail;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class VerificationData {
|
||||
|
||||
public VerificationData(String code, String eMail) {
|
||||
this.code = code;
|
||||
this.eMail = eMail;
|
||||
}
|
||||
|
||||
@NotBlank(message = "You must provide a valid code")
|
||||
String code;
|
||||
|
||||
@NotBlank(message = "You must provide an email")
|
||||
@Email(regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)])",
|
||||
message = "This is not a valid e-mail address")
|
||||
String eMail;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "VerificationData{" +
|
||||
"code='" + code + '\'' +
|
||||
", eMail='" + eMail + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.alttd.forms.verify_mail;
|
||||
|
||||
import com.alttd.forms.mail.mail_forms.MailForm;
|
||||
import jakarta.validation.Valid;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/verify_email")
|
||||
public class VerifyController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VerifyController.class);
|
||||
|
||||
@PostMapping("/form")
|
||||
public CompletableFuture<ResponseEntity<String>> validateEmailFromForm(@Valid @RequestBody VerificationData verificationData) {
|
||||
logger.debug(verificationData.toString());
|
||||
return FormQuery.getFormForCode(verificationData.code, verificationData.eMail).thenApply(form -> form.formJson()
|
||||
.map(body -> {
|
||||
MailForm.sendForm("[email protected]", body);
|
||||
return ResponseEntity.ok(body);
|
||||
})
|
||||
.orElse(ResponseEntity.ok(form.failReason()))
|
||||
).exceptionally(throwable -> ResponseEntity.internalServerError()
|
||||
.body("The server was unable to process your request, if this issue persists please contact [email protected]"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
|
||||
version="3.0">
|
||||
<persistence-unit name="default">
|
||||
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
@@ -0,0 +1,2 @@
|
||||
logging.level.com.alttd.forms=debug
|
||||
logging.level.org.springframework.web=warn
|
||||
@@ -0,0 +1 @@
|
||||
logging.level.com.alttd.forms=warn
|
||||
@@ -0,0 +1,24 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="debug">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
<root level="warning">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
|
||||
version="5.0">
|
||||
</web-app>
|
||||
@@ -0,0 +1,12 @@
|
||||
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Welcome to the api page - If you are human you should not be here.</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1><%= "Hello World!" %>
|
||||
</h1>
|
||||
<br/>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user