Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit Testing #10

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Java Unit Testing

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
# Step 1: Check out the repository
- name: Checkout repository
uses: actions/checkout@v4

# Step 2: Set up JDK
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
java-version: '11'
distribution: 'temurin' # You can change this to your desired distribution (e.g., 'zulu', 'adopt')

# Step 3: Cache Maven dependencies
- name: Cache Maven dependencies
uses: actions/cache@v3
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-m2

# Step 4: Build and test with Maven
- name: Build and run tests
run: |
cd MavenBack/
mvn clean test
17 changes: 17 additions & 0 deletions MavenBack/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>11.0.12</jetty.version>
<powermock.version>2.0.9</powermock.version>
<exec.mainClass>ppp.ServerMain</exec.mainClass>
</properties>

Expand Down Expand Up @@ -65,6 +66,14 @@
<version>7.5.0</version>
</dependency>

<!-- J-unit testing -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>compile</scope>
</dependency>

<!-- Anti "; DROP TABLE *;" -->
<!--
<dependency>
Expand Down Expand Up @@ -139,6 +148,14 @@
</execution>
</executions>
</plugin>

<!-- Allow unit testing from maven -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<!-- JUnit 5 requires Surefire version 2.22.0 or higher -->
<version>3.5.2</version>
</plugin>
</plugins>

<!-- The output .war file's name, which will be the name of the webapp. -->
Expand Down
5 changes: 5 additions & 0 deletions MavenBack/src/main/java/ppp/ServerMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ public static void main(String[] args) throws Exception {
// Load the env variables from the config. This will also build a new cfg file if none exists.
new ConfigurationBuilder(ServerConfig.class, new File("application.cfg")).build(true);

if (ServerConfig.EMAIL_USER.isBlank()) {
logger.error("No EMAIL_USER provided!");
System.exit(-1);
}

// Connect to the DB
logger.info("DB connecting...");
WebDb.init();
Expand Down
11 changes: 7 additions & 4 deletions MavenBack/src/main/java/ppp/api/GetGames.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ppp.auth.Authenticator;
import ppp.db.UserRepository;
import ppp.db.controllers.CGames;
import ppp.db.controllers.CUser;
import ppp.db.controllers.CUserRepository;
import ppp.db.model.OGame;
import ppp.db.model.OUser;
import ppp.meta.GlickoTwo;
Expand All @@ -37,14 +39,16 @@
@WebServlet("/api/games")
public class GetGames extends HttpServlet {

UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, String[]> parameters = request.getParameterMap();
List<OGame> games = null; // Our list of games to be returned
StatusEnum.Status status = Status.ANY;
int limit = 20; // Return a maximum of 20 games by default

Authenticator auth = new Authenticator();

boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS; // Check with the Authenticator to see if the request is authorized

try {
Expand Down Expand Up @@ -188,8 +192,7 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) thr

Map<String, String[]> parameters = request.getParameterMap();
StatusEnum.Status status = Status.ANY;

Authenticator auth = new Authenticator();

boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;
if (!loggedIn) { // Every request to modify games must be authenticated.
response.setStatus(401);
Expand Down
5 changes: 4 additions & 1 deletion MavenBack/src/main/java/ppp/api/GetUsers.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ppp.auth.Authenticator;
import ppp.db.UserRepository;
import ppp.db.controllers.CUser;
import ppp.db.controllers.CUserRepository;
import ppp.db.model.OUser;
import ppp.meta.LoginEnum;

Expand Down Expand Up @@ -40,7 +42,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro

Map<String, String[]> parameters = request.getParameterMap();
List<OUser> users = null;
Authenticator auth = new Authenticator();
UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);
boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;
int limit = 10; // Return maximum 10 users by default
boolean withHistory = parameters.containsKey("withHistory");
Expand Down
7 changes: 5 additions & 2 deletions MavenBack/src/main/java/ppp/auth/AuthServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@
import jakarta.servlet.http.HttpServletResponse;
import ppp.ServerConfig;
import ppp.api.GetGames;
import ppp.db.UserRepository;
import ppp.db.controllers.CGlicko;
import ppp.db.controllers.CUser;
import ppp.db.controllers.CUserRepository;
import ppp.db.model.OGlicko;
import ppp.db.model.OUser;
import ppp.meta.LoginEnum;
import ppp.meta.StatusEnum;

@WebServlet("/api/auth")
public class AuthServlet extends HttpServlet {

Authenticator emailer = new Authenticator();

UserRepository repository = new CUserRepository();
Authenticator emailer = new Authenticator(repository);

/**
* Creates a new 24-bit, Base64 Token
Expand Down
34 changes: 23 additions & 11 deletions MavenBack/src/main/java/ppp/auth/Authenticator.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import jakarta.servlet.http.HttpServletRequest;
import ppp.ServerConfig;
import ppp.db.controllers.CUser;
import ppp.db.UserRepository;
import ppp.db.model.OUser;
import ppp.meta.LoginEnum;

Expand All @@ -23,7 +23,14 @@ public class Authenticator {
* index 1: AuthCode<br>
* index 2: Attempts
*/
private static Map<String, Integer[]> emailsSent = new HashMap<String, Integer[]>();
protected static Map<String, Integer[]> emailsSent = new HashMap<String, Integer[]>();

// Access to CUser that can be unit tested
private final UserRepository userRepository;

public Authenticator(UserRepository userRepository) {
this.userRepository = userRepository;
}

/**
* Checks the input authentication code to the one sent
Expand Down Expand Up @@ -80,7 +87,7 @@ public LoginEnum.Status login(HttpServletRequest request) {
*/
public LoginEnum.Status login(String email, String token) {
email = email.toLowerCase();
OUser user = CUser.findByEmail(email, true);
OUser user = userRepository.findByEmail(email, true);
if (user.id == 0) return LoginEnum.Status.USER_INVALID;
if (user.email == "") return LoginEnum.Status.EMAIL_INVALID;
if (user.token == "" || user.tokenExpiryDate.before(new Date()) || user.token.length() < 2) return LoginEnum.Status.TOKEN_EXPIRED;
Expand All @@ -89,7 +96,7 @@ public LoginEnum.Status login(String email, String token) {

// Successful login. Timestamp & log it.
user.lastSignIn = new Timestamp(new Date().getTime()); // Should we use new Timestamp(System.currentTimeMillis()); instead?
CUser.update(user);
userRepository.update(user);

return LoginEnum.Status.SUCCESS;
}
Expand All @@ -113,14 +120,19 @@ public LoginEnum.Status sendAuthEmail(String toEmailAddress) {
final int authCode = (int)(Math.random() * Math.pow(10, ServerConfig.AUTH_NUM_DIGITS)); // TODO: This can produce numbers LESS than the number of digits with the current implementation.

// Everything looks in order. Create, send, and store the email
Email email = EmailBuilder.startingBlank()
.from("PingPongPage", ServerConfig.EMAIL_USER)
.to(toEmailAddress)
.withSubject("One-Time Password")
.withPlainText("Hi! Your one-time password is: " + authCode + ". It'll expire in " + ServerConfig.AUTH_CODE_VALIDITY_PERIOD + " minutes.\nThanks for using our service\n\t- Backend Software Engineer, Anthony Ford")
.buildEmail();
try {
Email email = EmailBuilder.startingBlank()
.from("PingPongPage", ServerConfig.EMAIL_USER)
.to(toEmailAddress)
.withSubject("One-Time Password")
.withPlainText("Hi! Your one-time password is: " + authCode + ". It'll expire in " + ServerConfig.AUTH_CODE_VALIDITY_PERIOD + " minutes.\nThanks for using our service\n\t- Backend Software Engineer, Anthony Ford")
.buildEmail();

Emailer.getMailer(true).sendMail(email);
} catch (Exception e) {
return LoginEnum.Status.EMAILING_ERROR;
}

Emailer.getMailer(true).sendMail(email);
Integer mapVal[] = {Integer.valueOf((int)now), Integer.valueOf(authCode), 0};
emailsSent.put(toEmailAddress, mapVal);
return LoginEnum.Status.EMAIL_SENT;
Expand Down
8 changes: 8 additions & 0 deletions MavenBack/src/main/java/ppp/db/UserRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ppp.db;

import ppp.db.model.OUser;

public interface UserRepository {
OUser findByEmail(String email, boolean withToken);
void update(OUser user);
}
17 changes: 17 additions & 0 deletions MavenBack/src/main/java/ppp/db/controllers/CUserRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ppp.db.controllers;

import ppp.db.UserRepository;
import ppp.db.model.OUser;

public class CUserRepository implements UserRepository {

@Override
public OUser findByEmail(String email, boolean withToken) {
return CUser.findByEmail(email, withToken);
}

@Override
public void update(OUser user) {
CUser.update(user);
}
}
1 change: 1 addition & 0 deletions MavenBack/src/main/java/ppp/meta/LoginEnum.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public static enum Status {
BANNED(401, "omegalol"),

UNKNOWN_ERROR(500),
EMAILING_ERROR(503, "The emailer is having issues. Please contact PPP administrators."),

EMAIL_SENT(200),
SUCCESS(200);
Expand Down
10 changes: 7 additions & 3 deletions MavenBack/src/main/java/ppp/staticServe/DashServe.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
import jakarta.servlet.http.HttpServletResponse;
import ppp.api.GetGames;
import ppp.auth.Authenticator;
import ppp.db.UserRepository;
import ppp.db.controllers.CGames;
import ppp.db.controllers.CUser;
import ppp.db.controllers.CUserRepository;
import ppp.db.model.OUser;
import ppp.meta.GlickoTwo;
import ppp.meta.LoginEnum;
Expand All @@ -27,7 +29,8 @@ public class DashServe extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

Authenticator auth = new Authenticator();
UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);
boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;
OUser user = new OUser();
if (loggedIn) user = CUser.findByEmail((String)request.getSession().getAttribute("email"));
Expand Down Expand Up @@ -56,8 +59,9 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

Map<String, String[]> parameters = request.getParameterMap();

Authenticator auth = new Authenticator();

UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);
boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;
if (!loggedIn) {
response.setStatus(401);
Expand Down
5 changes: 4 additions & 1 deletion MavenBack/src/main/java/ppp/staticServe/GamesServe.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ppp.auth.Authenticator;
import ppp.db.UserRepository;
import ppp.db.controllers.CUserRepository;
import ppp.meta.LoginEnum;

@WebServlet("/games")
Expand All @@ -24,7 +26,8 @@ public class GamesServe extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {

Authenticator auth = new Authenticator();
UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);
boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;

try {
Expand Down
5 changes: 4 additions & 1 deletion MavenBack/src/main/java/ppp/staticServe/LoginServe.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ppp.auth.Authenticator;
import ppp.db.UserRepository;
import ppp.db.controllers.CUserRepository;
import ppp.meta.LoginEnum;

@WebServlet("/login")
Expand All @@ -18,7 +20,8 @@ public class LoginServe extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

Authenticator auth = new Authenticator();
UserRepository repository = new CUserRepository();
Authenticator auth = new Authenticator(repository);
boolean loggedIn = auth.login(request) == LoginEnum.Status.SUCCESS;

try {
Expand Down
Loading
Loading