Skip to content

Commit

Permalink
Revert "impl. Cloudflare Turnstile to client and server"
Browse files Browse the repository at this point in the history
This reverts commit b733d24.
  • Loading branch information
cankurttekin committed Nov 12, 2024
1 parent df7ee5b commit 3786bd4
Show file tree
Hide file tree
Showing 12 changed files with 17 additions and 148 deletions.
1 change: 0 additions & 1 deletion backend/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ services:
MAIL_PORT: ${MAIL_PORT}
MAIL_USER: ${MAIL_USER}
MAIL_PASS: ${MAIL_PASS}
TURNSTILE_SECRET: ${TURNSTILE_SECRET}

depends_on:
- db
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ public JavaMailSender javaMailSender() {

return mailSender;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.kurttekin.can.job_track.application.dto.ErrorResponse;
import com.kurttekin.can.job_track.application.dto.UserRegistrationRequest;
import com.kurttekin.can.job_track.application.service.TurnstileVerificationService;
import com.kurttekin.can.job_track.domain.model.user.User;
import com.kurttekin.can.job_track.domain.service.UserService;
import com.kurttekin.can.job_track.domain.service.VerificationService;
Expand Down Expand Up @@ -35,19 +34,9 @@ public class AuthController {
@Autowired
private VerificationService verificationService;

@Autowired
private TurnstileVerificationService turnstileVerificationService;

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest,
@RequestParam String turnstileToken) {
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
try {
// Verify Turnstile token
boolean isTokenValid = turnstileVerificationService.verifyToken(turnstileToken);
if (!isTokenValid) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ErrorResponse("CAPTCHA failed."));
}

User user = userService.findUserByUsername(loginRequest.getUsername())
.orElseThrow(() -> new BadCredentialsException("Invalid credentials"));

Expand Down Expand Up @@ -75,14 +64,8 @@ public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest,
}

@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody UserRegistrationRequest userRequest,
@RequestParam String turnstileToken) {
public ResponseEntity<String> registerUser(@RequestBody UserRegistrationRequest userRequest) {
try {
// Verify Turnstile token
boolean isTokenValid = turnstileVerificationService.verifyToken(turnstileToken);
if (!isTokenValid) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("CAPTCHA failed.");
}
userService.registerUser(userRequest);
return ResponseEntity.ok("User registered successfully! Please verify your email before logging in.");
} catch (Exception e) {
Expand Down
2 changes: 0 additions & 2 deletions backend/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,3 @@ server.port=${PORT:8080}
#server.ssl.key-store-password=${KEY_STORE_PASS}
#server.ssl.keyStoreType=PKCS12
#server.ssl.key-alias=${KEY_STORE_ALIAS}

turnstile.secret-key=${TURNSTILE_SECRET:"0x0000"}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.kurttekin.can.job_track.application.dto.LoginRequest;
import com.kurttekin.can.job_track.application.dto.UserRegistrationRequest;
import com.kurttekin.can.job_track.application.service.EmailService;
import com.kurttekin.can.job_track.application.service.TurnstileVerificationService;
import com.kurttekin.can.job_track.domain.service.UserService;
import com.kurttekin.can.job_track.infrastructure.security.jwt.JwtProvider;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -49,13 +48,10 @@ class AuthControllerTest {
@Mock
private EmailService emailService;

@Mock
private TurnstileVerificationService turnstileVerificationService;

private LoginRequest loginRequest;
private UserRegistrationRequest userRegistrationRequest;
private String token;
private String turnstileToken;


@BeforeEach
public void setUp() {
Expand All @@ -64,19 +60,14 @@ public void setUp() {

userRegistrationRequest = new UserRegistrationRequest("testuser", "[email protected]", "testpassword");
token = "test.jwt.token";
turnstileToken= "test.jwt.turnstile";
}

@Test
public void testLogin_InvalidCredentials() {
// Mock Turnstile verification logic
//when(turnstileVerificationService.verifyToken(anyString())).thenReturn(true);
when(turnstileVerificationService.verifyToken(turnstileToken)).thenReturn(true);

when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenThrow(new BadCredentialsException("Invalid credentials"));

ResponseEntity<?> response = authController.login(loginRequest, turnstileToken);
ResponseEntity<?> response = authController.login(loginRequest);

assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertEquals("Invalid credentials", response.getBody());
Expand All @@ -91,10 +82,8 @@ public void testRegisterUser_Success() {
doNothing().when(userService).registerUser(any(UserRegistrationRequest.class));
doNothing().when(emailService).sendVerificationEmail(anyString(),anyString(), anyString()); // Mock email sending

when(turnstileVerificationService.verifyToken(turnstileToken)).thenReturn(true);

// Call the registerUser method in the controller
ResponseEntity<String> response = authController.registerUser(userRegistrationRequest, turnstileToken);
ResponseEntity<String> response = authController.registerUser(userRegistrationRequest);

// Check the status and response body
assertEquals(HttpStatus.OK, response.getStatusCode());
Expand All @@ -105,9 +94,7 @@ public void testRegisterUser_Success() {
public void testRegisterUser_Failure() {
doThrow(new RuntimeException("Registration failed")).when(userService).registerUser(any(UserRegistrationRequest.class));

when(turnstileVerificationService.verifyToken(turnstileToken)).thenReturn(true);

ResponseEntity<String> response = authController.registerUser(userRegistrationRequest, turnstileToken);
ResponseEntity<String> response = authController.registerUser(userRegistrationRequest);

assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertEquals("Registration failed", response.getBody());
Expand Down
14 changes: 1 addition & 13 deletions frontend/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import React, { useContext, useState } from 'react';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/AuthContext'; // Import the context
import Turnstile from "./Turnstile";
import { REACT_APP_TURNSTILE_SITE_KEY } from '../config.js';

const Container = styled.div`
display: flex;
Expand Down Expand Up @@ -52,7 +50,6 @@ const Login = () => {
const [password, setPassword] = useState("");
const [error, setError] = useState(""); // To store and display error messages
const { login } = useContext(AuthContext);
const [turnstileToken, setTurnstileToken] = useState('');

const handleSubmit = async (e) => {
e.preventDefault();
Expand All @@ -64,13 +61,8 @@ const Login = () => {
return;
}

if (!turnstileToken) {
setError("Please complete the CAPTCHA.");
return;
}

try {
await login(username, password, turnstileToken); // Call the login function
await login(username, password); // Call the login function
navigate('/job-applications'); // Redirect after successful login
} catch (error) {
setError(error.message); // Set the error message
Expand All @@ -95,10 +87,6 @@ const Login = () => {
value={password}
onChange={e => setPassword(e.target.value)}
/>
<Turnstile
siteKey={REACT_APP_TURNSTILE_SITE_KEY}
onVerify={(token) => setTurnstileToken(token)}
/>
<Button type="submit">Login</Button>
{error && <Error>{error}</Error>} {/* Display error message */}
</form>
Expand Down
15 changes: 2 additions & 13 deletions frontend/src/components/Register.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { register as registerService } from '../services/authService'; // Import the register function from authService
import Turnstile from "./Turnstile";
import {REACT_APP_TURNSTILE_SITE_KEY} from "../config";

// Styled components for layout and styling
const Container = styled.div`
Expand Down Expand Up @@ -77,7 +75,7 @@ const Register = () => {
specialChar: false,
});
const [isPasswordFocused, setIsPasswordFocused] = useState(false); // Track if the password field is focused
const [turnstileToken, setTurnstileToken] = useState('');

const navigate = useNavigate();

// Password validation function
Expand Down Expand Up @@ -126,13 +124,8 @@ const Register = () => {
return;
}

if (!turnstileToken) {
setError("Please complete the CAPTCHA.");
return;
}

try {
await registerService(username, email, password, turnstileToken); // Call the register function
await registerService(username, email, password); // Call the register function
setError('Registration successful. Please verify your email before logging in.');
setTimeout(() => navigate('/login'), 1500); // Redirect after 1.5 seconds
} catch (err) {
Expand Down Expand Up @@ -192,10 +185,6 @@ const Register = () => {
</PasswordStrengthFeedback>
)}

<Turnstile
siteKey={REACT_APP_TURNSTILE_SITE_KEY}
onVerify={(token) => setTurnstileToken(token)}
/>
<Button type="submit" disabled={!Object.values(passwordFeedback).every(Boolean)}>
Register
</Button>
Expand Down
46 changes: 0 additions & 46 deletions frontend/src/components/Turnstile.js

This file was deleted.

3 changes: 1 addition & 2 deletions frontend/src/config.js
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export const REACT_APP_BACKEND_URL = process.env.REACT_APP_BACKEND_URL+'/api';
export const REACT_APP_TURNSTILE_SITE_KEY = process.env.REACT_APP_TURNSTILE_SITE_KEY;
export const REACT_APP_BACKEND_URL = process.env.REACT_APP_BACKEND_URL+'/api';
4 changes: 2 additions & 2 deletions frontend/src/contexts/AuthContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export const AuthProvider = ({ children }) => {
}
}, []);

const login = async (username, password, turnstileToken) => {
const login = async (username, password) => {
try {
const response = await loginService(username, password, turnstileToken);
const response = await loginService(username, password);
const { token } = response;

if (token) {
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/services/authService.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import axios from 'axios';
import { REACT_APP_BACKEND_URL } from '../config';

export const login = async (username, password, turnstileToken) => {
export const login = async (username, password) => {
try {
const response = await axios.post(
`${REACT_APP_BACKEND_URL}/auth/login`,
{ username, password, turnstileToken },
{ username, password },
{
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -33,8 +33,8 @@ export const login = async (username, password, turnstileToken) => {
}
};

export const register = async (username, email, password, turnstileToken) => {
return axios.post(`${REACT_APP_BACKEND_URL}/auth/register`, { username, email, password, turnstileToken });
export const register = async (username, email, password) => {
return axios.post(`${REACT_APP_BACKEND_URL}/auth/register`, { username, email, password });
};

export const logout = () => {
Expand Down

0 comments on commit 3786bd4

Please sign in to comment.