Browse Source

Merge branch 'main' into test/client/add-test-cases

remotes/origin/test/client/add-test-cases
Alena Bandarovich 11 months ago
parent
commit
f90278703a
  1. 96
      README.md
  2. 1
      notizen.txt
  3. 7
      pom.xml
  4. 33
      src/main/java/CreateUser.java
  5. 34
      src/main/java/LoginGUI.java
  6. 25
      src/main/java/PasswordHasher.java
  7. 49
      src/main/java/SignUpGUI.java
  8. 3
      src/test/java/ChatGUITest.java
  9. 1
      src/test/java/CreateUserTest.java
  10. 26
      src/test/java/PasswordHasherTest.java
  11. 35
      user.json

96
README.md

@ -1,92 +1,12 @@
# Java Chat # Java Chat
Projekt Informationen
Führe build-project.sh aus
Eventuell führt das Skript die Dateien in einer falschen Reihenfolge aus
Wichtig für JavaChat-Start...in dieser Reihenfolge ausführen:
1. Starte ChatServer-Klasse
2. Starte ChatClient-Klasse und verbinde mit ChatServer über dessen IP(falls Lokal auf gleichem Rechner, kann 127.0.0.1 verwendet werden)
3. Andere Clients im gleichen Netzwerk können sich über starten eines ChatClients über die IP des Servers ebenfalls mit dem Chat verbinden.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.cs.hs-fulda.de/fdai7332/java-chat.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.cs.hs-fulda.de/fdai7332/java-chat/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
Zusatzklassen im Repository können einzeln ausgeführt werden

1
notizen.txt

@ -0,0 +1 @@
Äpfel & Birnen €

7
pom.xml

@ -17,6 +17,13 @@
<version>4.13.2</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

33
src/main/java/CreateUser.java

@ -10,9 +10,6 @@ import java.util.List;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID; import java.util.UUID;
class CreateUser { class CreateUser {
@ -29,7 +26,7 @@ class CreateUser {
public CreateUser(String id, String name, String password, String birthday, String firstName, String surname) { public CreateUser(String id, String name, String password, String birthday, String firstName, String surname) {
this.id = id; this.id = id;
this.userName = name; this.userName = name;
this.password = hashPassword(password);
this.password = PasswordHasher.hashPassword(password);
this.birthday = birthday; this.birthday = birthday;
this.firstName = firstName; this.firstName = firstName;
this.surname = surname; this.surname = surname;
@ -94,32 +91,24 @@ class CreateUser {
// Function to create user with validation // Function to create user with validation
public static CreateUser createUser(String id, String userName, String password, String birthday, String firstName, String surname) { public static CreateUser createUser(String id, String userName, String password, String birthday, String firstName, String surname) {
validateUserName(userName);
validatePassword(password);
return new CreateUser(id, userName, password, birthday, firstName, surname);
}
private static void validateUserName(String userName) {
if (userName == null || userName.isEmpty()) { if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("Username cannot be empty"); throw new IllegalArgumentException("Username cannot be empty");
} }
}
private static void validatePassword(String password) {
if (password == null || password.isEmpty()) { if (password == null || password.isEmpty()) {
throw new IllegalArgumentException("Password cannot be empty"); throw new IllegalArgumentException("Password cannot be empty");
} }
if (password.length() < 6) { if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long"); throw new IllegalArgumentException("Password must be at least 6 characters long");
} return new CreateUser(id, userName, password, birthday, firstName, surname);
}
// Function to hash the password using SHA-256 algorithm
private String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} }
} }

34
src/main/java/LoginGUI.java

@ -5,10 +5,11 @@ import java.util.List;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.KeyListener; import java.awt.event.KeyListener;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LoginGUI extends JFrame implements ActionListener { public class LoginGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField usernameField; private JTextField usernameField;
private JPasswordField passwordField; private JPasswordField passwordField;
private JButton loginButton; private JButton loginButton;
@ -75,17 +76,13 @@ public class LoginGUI extends JFrame implements ActionListener {
passwordField.addKeyListener(new EnterKeyListener()); passwordField.addKeyListener(new EnterKeyListener());
stayLoggedInCheckbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stayLoggedInCheckbox.addActionListener(e -> {
boolean stayLoggedIn = stayLoggedInCheckbox.isSelected(); boolean stayLoggedIn = stayLoggedInCheckbox.isSelected();
String username = usernameField.getText(); String username = usernameField.getText();
// Set stayLoggedIn to false if the checkbox is unchecked
if (!stayLoggedInCheckbox.isSelected()) { if (!stayLoggedInCheckbox.isSelected()) {
stayLoggedIn = false; stayLoggedIn = false;
} }
updateStayLoggedIn(username, stayLoggedIn); updateStayLoggedIn(username, stayLoggedIn);
}
}); });
} }
@ -123,7 +120,7 @@ public class LoginGUI extends JFrame implements ActionListener {
if (userList != null) { if (userList != null) {
for (CreateUser user : userList) { for (CreateUser user : userList) {
if (user.getUserName().equals(username)) { if (user.getUserName().equals(username)) {
String hashedPassword = hashPassword(password);
String hashedPassword = PasswordHasher.hashPassword(password);
if (user.getPassword().equals(hashedPassword)) { if (user.getPassword().equals(hashedPassword)) {
return true; return true;
} }
@ -133,25 +130,6 @@ public class LoginGUI extends JFrame implements ActionListener {
return false; return false;
} }
private String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private class EnterKeyListener implements KeyListener { private class EnterKeyListener implements KeyListener {
@Override @Override
public void keyTyped(KeyEvent e) {} public void keyTyped(KeyEvent e) {}

25
src/main/java/PasswordHasher.java

@ -0,0 +1,25 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PasswordHasher {
public static String hashPassword(String password) {
if (password == null) {
throw new IllegalArgumentException("Password cannot be null");
}
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}

49
src/main/java/SignUpGUI.java

@ -5,6 +5,10 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
public class SignUpGUI extends JFrame implements ActionListener { public class SignUpGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField usernameField, passwordField, confirmPasswordField, birthdayField, firstNameField, surnameField; private JTextField usernameField, passwordField, confirmPasswordField, birthdayField, firstNameField, surnameField;
private JButton signUpButton; private JButton signUpButton;
@ -97,6 +101,11 @@ public class SignUpGUI extends JFrame implements ActionListener {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (e.getSource() == signUpButton) { if (e.getSource() == signUpButton) {
signUpUser();
}
}
private void signUpUser() {
String username = usernameField.getText(); String username = usernameField.getText();
String password = passwordField.getText(); String password = passwordField.getText();
String confirmPassword = confirmPasswordField.getText(); String confirmPassword = confirmPasswordField.getText();
@ -104,39 +113,47 @@ public class SignUpGUI extends JFrame implements ActionListener {
String firstName = firstNameField.getText(); String firstName = firstNameField.getText();
String surname = surnameField.getText(); String surname = surnameField.getText();
if (!password.equals(confirmPassword)) {
JOptionPane.showMessageDialog(this, "Passwords do not match!", "Sign Up Error", JOptionPane.ERROR_MESSAGE);
if (!validatePasswordConfirmation(password, confirmPassword)) {
showErrorMessage("Passwords do not match!");
return; return;
} }
if (!isUsernameAvailable("user.json", username)) { if (!isUsernameAvailable("user.json", username)) {
JOptionPane.showMessageDialog(this, "Username already exists!", "Sign Up Error", JOptionPane.ERROR_MESSAGE);
showErrorMessage("Username already exists!");
return; return;
} }
try { try {
UUID randomUUID = UUID.randomUUID();
CreateUser user = CreateUser.createUser(randomUUID.toString(), username, password, birthday, firstName, surname);
user.saveToJsonFile("user.json");
JOptionPane.showMessageDialog(this, "User signed up successfully!");
createUserAndSave(username, password, birthday, firstName, surname);
showSuccessMessage("User signed up successfully!");
dispose(); dispose();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Sign Up Error", JOptionPane.ERROR_MESSAGE);
showErrorMessage("Error: " + ex.getMessage());
} }
} }
private boolean validatePasswordConfirmation(String password, String confirmPassword) {
return password.equals(confirmPassword);
} }
// Function to check if the input username doesn't already exist in the JSON file
private boolean isUsernameAvailable(String filename, String username) {
List<CreateUser> userList = CreateUser.readUserListFromJsonFile(filename);
if (userList != null) {
for (CreateUser user : userList) {
if (user.getUserName().equals(username)) {
return false;
private void showErrorMessage(String message) {
JOptionPane.showMessageDialog(this, message, "Sign Up Error", JOptionPane.ERROR_MESSAGE);
} }
private void showSuccessMessage(String message) {
JOptionPane.showMessageDialog(this, message);
} }
private void createUserAndSave(String username, String password, String birthday, String firstName, String surname) {
UUID randomUUID = UUID.randomUUID();
CreateUser user = CreateUser.createUser(randomUUID.toString(), username, password, birthday, firstName, surname);
user.saveToJsonFile("user.json");
} }
return true;
// Function to check if the input username doesn't already exist in the JSON file
private boolean isUsernameAvailable(String filename, String username) {
List<CreateUser> userList = CreateUser.readUserListFromJsonFile(filename);
return userList == null || userList.stream().noneMatch(user -> user.getUserName().equals(username));
} }
public static void main(String[] args) { public static void main(String[] args) {

3
src/test/java/ChatGUITest.java

@ -1,3 +1,5 @@
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -8,7 +10,6 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.junit.Before; import org.junit.Before;
import org.junit.Test;
public class ChatGUITest { public class ChatGUITest {

1
src/test/java/CreateUserTest.java

@ -2,7 +2,6 @@ import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CreateUserTest { class CreateUserTest {

26
src/test/java/PasswordHasherTest.java

@ -0,0 +1,26 @@
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PasswordHasherTest {
@Test
void testHashPassword() {
String password = "password123";
String hashedPassword = PasswordHasher.hashPassword(password);
// Check that the hashed password is not null
assertEquals(64, hashedPassword.length());
// Test with an empty password
String emptyPassword = "";
String hashedEmptyPassword = PasswordHasher.hashPassword(emptyPassword);
assertEquals(64, hashedEmptyPassword.length());
// Test with a null password
assertThrows(IllegalArgumentException.class, () -> {
PasswordHasher.hashPassword(null);
});
}
}

35
user.json

@ -1,34 +1,7 @@
[ [
{ {
"id": "d7ae19fe-4684-4d69-a73d-4cca612962a3",
"userName": "Test",
"password": "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"birthday": "",
"firstName": "",
"surname": "",
"stayLoggedIn": false
},
{
"id": "2ec2c0c5-677c-4262-8958-fef98d11cc63",
"userName": "Test2",
"password": "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"birthday": "",
"firstName": "",
"surname": "",
"stayLoggedIn": false
},
{
"id": "ccfcc294-48ad-49db-996f-d7c99a93bac9",
"userName": "testuser",
"password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
"birthday": "2000-01-01",
"firstName": "John",
"surname": "Doe",
"stayLoggedIn": false
},
{
"id": "27ffc70f-dd76-4765-81e3-76fde9b618e5",
"userName": "testUser",
"id": "20311680-1dbc-4a1d-af43-48462ab5dcef",
"userName": "existinguser",
"password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", "password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
"birthday": "1990-01-01", "birthday": "1990-01-01",
"firstName": "John", "firstName": "John",
@ -36,8 +9,8 @@
"stayLoggedIn": false "stayLoggedIn": false
}, },
{ {
"id": "731fda82-6b51-4f3f-ae97-c9b01c9b4a1a",
"userName": "existinguser",
"id": "aed49698-89cd-4712-920f-e30f23793f46",
"userName": "testUser",
"password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", "password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
"birthday": "1990-01-01", "birthday": "1990-01-01",
"firstName": "John", "firstName": "John",

Loading…
Cancel
Save