Initial commit for site for forms

This commit is contained in:
Teriuihi 2024-01-13 16:24:54 +01:00
commit 2b908b4e94
39 changed files with 1649 additions and 0 deletions

42
.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

17
.idea/dataSources.xml Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="site@localhost" uuid="8d8254c8-a4de-441f-8e2f-74ac3935ed6c">
<driver-ref>mariadb</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.mariadb.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mariadb://localhost:3306/site</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

16
.idea/gradle.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

10
.idea/misc.xml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

124
.idea/uiDesigner.xml Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

205
.idea/workspace.xml Normal file
View File

@ -0,0 +1,205 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="ce59df2a-8d56-446a-867b-80e627daf479" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/dataSources.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/gradle.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/uiDesigner.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/build.gradle" afterDir="false" />
<change afterPath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.jar" afterDir="false" />
<change afterPath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/gradlew" afterDir="false" />
<change afterPath="$PROJECT_DIR$/gradlew.bat" afterDir="false" />
<change afterPath="$PROJECT_DIR$/settings.gradle" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/Main.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/beans/WebConfig.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/contact/ContactController.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/contact/ContactFormData.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/contact/StoreFormQuery.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/database/Database.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/database/DatabaseConnection.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/form/Form.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/mail/MailSettings.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/mail/mail_forms/MailForm.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/mail/verification/VerificationResult.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/mail/verification/Verify.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/properties/JarPath.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/properties/PropertiesLoader.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/properties/PropertiesWriter.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/verify_mail/FormQuery.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/verify_mail/FormQueryResult.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/verify_mail/VerificationData.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/alttd/forms/verify_mail/VerifyController.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/META-INF/beans.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/META-INF/persistence.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/application-dev.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/application.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/logback-spring.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/webapp/WEB-INF/web.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/webapp/index.jsp" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ExternalProjectsData">
<projectState path="$PROJECT_DIR$">
<ProjectState />
</projectState>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Jsp File" />
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GitToolBoxStore">
<option name="projectConfigVersion" value="5" />
</component>
<component name="KubernetesApiProvider">{
&quot;isMigrated&quot;: true
}</component>
<component name="LogFilters">
<option name="FILTER_ERRORS" value="false" />
<option name="FILTER_WARNINGS" value="false" />
<option name="FILTER_INFO" value="true" />
<option name="FILTER_DEBUG" value="true" />
<option name="CUSTOM_FILTER" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 7
}</component>
<component name="ProjectId" id="2aJVOGgvEjzOGrKFJ1xKKH5Oshq" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"Gradle.Build forms.executor": "Run",
"RequestMappingsPanelOrder0": "0",
"RequestMappingsPanelOrder1": "1",
"RequestMappingsPanelWidth0": "75",
"RequestMappingsPanelWidth1": "75",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"Spring Boot.Main.executor": "Debug",
"Tomcat Server.Tomcat 10.1.17.executor": "Run",
"git-widget-placeholder": "master",
"ignore.virus.scanning.warn.message": "true",
"kotlin-language-version-configured": "true",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"project.structure.last.edited": "Project",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.0",
"vue.rearranger.settings.migration": "true"
},
"keyToStringList": {
"DatabaseDriversLRU": [
"mysql",
"mariadb"
]
}
}]]></component>
<component name="RunManager" selected="Spring Boot.Main">
<configuration name="Main" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot" nameIsGenerated="true">
<option name="ACTIVE_PROFILES" value="dev" />
<module name="forms.main" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.alttd.forms.Main" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Tomcat 10.1.17" type="#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory" factoryName="Local" APPLICATION_SERVER_NAME="Tomcat 10.1.17" ALTERNATIVE_JRE_ENABLED="false">
<deployment>
<artifact name="Gradle : com.alttd : forms-1.0-SNAPSHOT.war">
<settings>
<option name="CONTEXT_PATH" value="/Gradle___com_alttd___forms_1_0_SNAPSHOT_war" />
</settings>
</artifact>
</deployment>
<server-settings>
<option name="BASE_DIRECTORY_NAME" value="f710d80b-33cf-48d5-9d94-7e9dacc0f171" />
</server-settings>
<predefined_log_file enabled="true" id="Tomcat" />
<predefined_log_file enabled="true" id="Tomcat Catalina" />
<predefined_log_file id="Tomcat Manager" />
<predefined_log_file id="Tomcat Host Manager" />
<predefined_log_file id="Tomcat Localhost Access" />
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Run">
<option name="USE_ENV_VARIABLES" value="true" />
<STARTUP>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</STARTUP>
<SHUTDOWN>
<option name="USE_DEFAULT" value="true" />
<option name="SCRIPT" value="" />
<option name="VM_PARAMETERS" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
</SHUTDOWN>
</ConfigurationWrapper>
<method v="2">
<option name="Make" enabled="true" />
<option name="BuildArtifacts" enabled="true">
<artifact name="Gradle : com.alttd : forms-1.0-SNAPSHOT.war" />
</option>
</method>
</configuration>
<list>
<item itemvalue="Spring Boot.Main" />
<item itemvalue="Tomcat Server.Tomcat 10.1.17" />
</list>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="jdk-17.0.9-corretto-17.0.9-3183f394aec4-8f899f12" />
</set>
</attachedChunks>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="ce59df2a-8d56-446a-867b-80e627daf479" name="Changes" comment="" />
<created>1704036635730</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1704036635730</updated>
<workItem from="1704036636799" duration="105000" />
<workItem from="1704549979998" duration="2844000" />
<workItem from="1704629811001" duration="6145000" />
<workItem from="1704639914630" duration="2938000" />
<workItem from="1704742191416" duration="685000" />
<workItem from="1705152717665" duration="5692000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>

36
build.gradle Normal file
View File

@ -0,0 +1,36 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.1'
id 'io.spring.dependency-management' version '1.1.4'
}
group 'com.alttd'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
ext {
junitVersion = '5.9.2'
}
sourceCompatibility = '17'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'javax.mail', name: 'mail', version: '1.4'
implementation 'org.springframework.boot:spring-boot-starter-logging'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'org.mariadb.jdbc:mariadb-java-client:2.1.2'
}
test {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = "forms"

View File

@ -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();
}
}

View File

@ -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);
}
};
}
}

View File

@ -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");
});
}
}

View File

@ -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>";
}
}

View File

@ -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();
});
}
}

View File

@ -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);
}
}
}

View File

@ -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"));
}
}
}

View File

@ -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();
}

View File

@ -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", "test@test.test");
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;
}
}

View File

@ -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);
}
}
}

View File

@ -0,0 +1,6 @@
package com.alttd.forms.mail.verification;
public enum VerificationResult {
NO_MAIL_ACCOUNT, FAILED_TO_SEND, VERIFICATION_SENT,
}

View File

@ -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);
}
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
});
}
}

View File

@ -0,0 +1,6 @@
package com.alttd.forms.verify_mail;
import java.util.Optional;
public record FormQueryResult(Optional<String> formJson, String failReason) {
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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("akastijn@alttd.com", 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 admin@alttd.com"));
}
}

View File

@ -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>

View File

@ -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>

View File

@ -0,0 +1,2 @@
logging.level.com.alttd.forms=debug
logging.level.org.springframework.web=warn

View File

@ -0,0 +1 @@
logging.level.com.alttd.forms=warn

View File

@ -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>

View File

@ -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>

12
src/main/webapp/index.jsp Normal file
View File

@ -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>