From 8cc7dc369d471e5a69c727e2e2ff1d2552fd47ba Mon Sep 17 00:00:00 2001 From: Roottoot Date: Thu, 11 Sep 2025 22:04:48 +0200 Subject: [PATCH 01/11] Oidc google db save --- backend/pom.xml | 16 + .../org/example/backend/security/AppUser.java | 7 + .../example/backend/security/AppUserDto.java | 9 + .../backend/security/AppUserPrincipal.java | 6 + .../backend/security/AppUserRepository.java | 8 + .../backend/security/AuthController.java | 27 ++ .../backend/security/CustomOAuth2User.java | 37 ++ .../security/CustomOAuth2UserService.java | 74 ++++ .../backend/security/CustomOidcUser.java | 53 +++ .../security/CustomOidcUserService.java | 48 +++ .../backend/security/SecurityConfig.java | 42 +++ .../src/main/resources/application.properties | 17 + .../backend/security/AuthControllerTest.java | 58 +++ frontend/components/Dashboard.tsx | 14 + frontend/components/Navbar.tsx | 64 ++++ frontend/components/ProtectedRoute.tsx | 11 + frontend/package-lock.json | 336 +++++++++++++++++- frontend/package.json | 4 +- frontend/src/App.tsx | 59 +-- frontend/src/main.tsx | 5 +- frontend/type/UserInfoType.ts | 5 + 21 files changed, 871 insertions(+), 29 deletions(-) create mode 100644 backend/src/main/java/org/example/backend/security/AppUser.java create mode 100644 backend/src/main/java/org/example/backend/security/AppUserDto.java create mode 100644 backend/src/main/java/org/example/backend/security/AppUserPrincipal.java create mode 100644 backend/src/main/java/org/example/backend/security/AppUserRepository.java create mode 100644 backend/src/main/java/org/example/backend/security/AuthController.java create mode 100644 backend/src/main/java/org/example/backend/security/CustomOAuth2User.java create mode 100644 backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java create mode 100644 backend/src/main/java/org/example/backend/security/CustomOidcUser.java create mode 100644 backend/src/main/java/org/example/backend/security/CustomOidcUserService.java create mode 100644 backend/src/main/java/org/example/backend/security/SecurityConfig.java create mode 100644 backend/src/test/java/org/example/backend/security/AuthControllerTest.java create mode 100644 frontend/components/Dashboard.tsx create mode 100644 frontend/components/Navbar.tsx create mode 100644 frontend/components/ProtectedRoute.tsx create mode 100644 frontend/type/UserInfoType.ts diff --git a/backend/pom.xml b/backend/pom.xml index d2506b0..521960a 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -33,6 +33,12 @@ https://sonarcloud.io + + de.flapdoodle.embed + de.flapdoodle.embed.mongo.spring3x + 4.21.0 + test + org.springframework.boot spring-boot-starter-data-mongodb @@ -52,6 +58,16 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.security + spring-security-test + test + + diff --git a/backend/src/main/java/org/example/backend/security/AppUser.java b/backend/src/main/java/org/example/backend/security/AppUser.java new file mode 100644 index 0000000..b8f0bad --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/AppUser.java @@ -0,0 +1,7 @@ +package org.example.backend.security; + +import lombok.Builder; + +@Builder +public record AppUser(String id,String providerId,String provider,String userName, String avatarUrl) { +} diff --git a/backend/src/main/java/org/example/backend/security/AppUserDto.java b/backend/src/main/java/org/example/backend/security/AppUserDto.java new file mode 100644 index 0000000..95fa09d --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/AppUserDto.java @@ -0,0 +1,9 @@ +package org.example.backend.security; + +import lombok.Builder; +import lombok.With; + +@With +@Builder +public record AppUserDto(String id,String userName, String avatarUrl) { +} diff --git a/backend/src/main/java/org/example/backend/security/AppUserPrincipal.java b/backend/src/main/java/org/example/backend/security/AppUserPrincipal.java new file mode 100644 index 0000000..fe5584f --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/AppUserPrincipal.java @@ -0,0 +1,6 @@ +package org.example.backend.security; + +// An interface to unify our custom principal types +public interface AppUserPrincipal { + AppUser getAppUser(); +} \ No newline at end of file diff --git a/backend/src/main/java/org/example/backend/security/AppUserRepository.java b/backend/src/main/java/org/example/backend/security/AppUserRepository.java new file mode 100644 index 0000000..e1c5032 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/AppUserRepository.java @@ -0,0 +1,8 @@ +package org.example.backend.security; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AppUserRepository extends MongoRepository { +} diff --git a/backend/src/main/java/org/example/backend/security/AuthController.java b/backend/src/main/java/org/example/backend/security/AuthController.java new file mode 100644 index 0000000..315ebf6 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/AuthController.java @@ -0,0 +1,27 @@ +package org.example.backend.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/auth") +@RequiredArgsConstructor +public class AuthController { + @GetMapping("/me") + public AppUserDto getMe(@AuthenticationPrincipal AppUserPrincipal user){ + if (user == null || user.getAppUser() == null) { + return null; + } + AppUser appUser=user.getAppUser(); + return new AppUserDto(appUser.id(),appUser.userName(),appUser.avatarUrl()); + } + + @GetMapping("/params") + public String getParams(@AuthenticationPrincipal OAuth2User userParams){ + return userParams.getAttributes().keySet().toString(); + } +} diff --git a/backend/src/main/java/org/example/backend/security/CustomOAuth2User.java b/backend/src/main/java/org/example/backend/security/CustomOAuth2User.java new file mode 100644 index 0000000..5f73635 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/CustomOAuth2User.java @@ -0,0 +1,37 @@ +package org.example.backend.security; + +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.user.OAuth2User; + +import java.util.Collection; +import java.util.Map; + +public class CustomOAuth2User implements OAuth2User, AppUserPrincipal { + + private final OAuth2User oauth2User; + @Getter + private final AppUser appUser; + + public CustomOAuth2User(OAuth2User oauth2User, AppUser appUser) { + this.oauth2User = oauth2User; + this.appUser = appUser; + } + + @Override + public Map getAttributes() { + return oauth2User.getAttributes(); + } + + @Override + public Collection getAuthorities() { + return oauth2User.getAuthorities(); + } + + @Override + public String getName() { + // Return the unique ID from our AppUser, which is more reliable and consistent. + return appUser.id(); + } + +} \ No newline at end of file diff --git a/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java b/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java new file mode 100644 index 0000000..a55f384 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java @@ -0,0 +1,74 @@ +package org.example.backend.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.stereotype.Service; + +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class CustomOAuth2UserService extends DefaultOAuth2UserService { + + private final AppUserRepository userRepo; + + + public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { + OAuth2User oAuth2User = super.loadUser(userRequest); + String provider = userRequest.getClientRegistration().getRegistrationId(); + String providerId = oAuth2User.getName(); + String uniqueId = provider + ":" + providerId; + + AppUser appUser = userRepo.findById(uniqueId) + .orElseGet(() -> createAppUser(oAuth2User, uniqueId, provider, providerId)); + + System.out.println("Loaded user: " + appUser.userName() + " with ID: " + appUser.id()); + return new CustomOAuth2User(oAuth2User, appUser); + } + + @SuppressWarnings("unchecked") + private AppUser createAppUser(OAuth2User oAuth2User, String uniqueId, String provider,String providerId) throws OAuth2AuthenticationException { + + String name = null; + String avatarUrl = null; + + //Switch case + switch (provider){ + case "github": + name = oAuth2User.getAttribute("login"); + avatarUrl = oAuth2User.getAttribute("avatar_url"); + break; + case "google": + name = oAuth2User.getAttribute("name"); + avatarUrl = oAuth2User.getAttribute("picture"); + break; + case "facebook": + name = oAuth2User.getAttribute("name"); + Map picture=oAuth2User.getAttribute("picture"); + if(picture!=null){ + @SuppressWarnings("unchecked") + Map data = (Map) picture.get("data"); + if (data != null) { + avatarUrl = (String) data.get("url"); + } + } + break; + } + // GitHub user attributes + + AppUser newUser= AppUser.builder() + .id(uniqueId) + .provider(provider) + .providerId(providerId) + .userName(name) + .avatarUrl(avatarUrl) + .build(); + + userRepo.save(newUser); + System.out.println("Saved user:"+ newUser); + return newUser; + } +} diff --git a/backend/src/main/java/org/example/backend/security/CustomOidcUser.java b/backend/src/main/java/org/example/backend/security/CustomOidcUser.java new file mode 100644 index 0000000..37c7608 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/CustomOidcUser.java @@ -0,0 +1,53 @@ +package org.example.backend.security; + +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.OidcUserInfo; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; + +import java.util.Collection; +import java.util.Map; + +public class CustomOidcUser implements OidcUser, AppUserPrincipal { + + private final OidcUser oidcUser; + @Getter + private final AppUser appUser; + + public CustomOidcUser(OidcUser oidcUser, AppUser appUser) { + this.oidcUser = oidcUser; + this.appUser = appUser; + } + + @Override + public Map getClaims() { + return oidcUser.getClaims(); + } + + @Override + public OidcUserInfo getUserInfo() { + return oidcUser.getUserInfo(); + } + + @Override + public OidcIdToken getIdToken() { + return oidcUser.getIdToken(); + } + + @Override + public Map getAttributes() { + return oidcUser.getAttributes(); + } + + @Override + public Collection getAuthorities() { + return oidcUser.getAuthorities(); + } + + @Override + public String getName() { + // Use the consistent ID from our AppUser entity + return appUser.id(); + } +} \ No newline at end of file diff --git a/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java b/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java new file mode 100644 index 0000000..0aeb666 --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java @@ -0,0 +1,48 @@ +package org.example.backend.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.stereotype.Service; + +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class CustomOidcUserService extends OidcUserService { + + private final AppUserRepository userRepo; + + public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { + OidcUser oidcUser = super.loadUser(userRequest); + String provider = userRequest.getClientRegistration().getRegistrationId(); + + // 'sub' is the standard OIDC claim for user's unique ID + String providerId = oidcUser.getSubject(); + String uniqueId = provider + ":" + providerId; + + AppUser appUser = userRepo.findById(uniqueId) + .orElseGet(() -> createAppUser(oidcUser, uniqueId, provider, providerId)); + System.out.println("Loaded user: " + appUser.userName() + " with ID: " + appUser.id()); + return new CustomOidcUser(oidcUser, appUser); + } + + private AppUser createAppUser(OidcUser oidcUser, String uniqueId, String provider, String providerId) { + Map attributes = oidcUser.getAttributes(); + String name = attributes.get("name").toString(); + String avatarUrl = attributes.get("picture").toString(); + + AppUser newUser = AppUser.builder() + .id(uniqueId) + .provider(provider) + .providerId(providerId) + .userName(name) + .avatarUrl(avatarUrl) + .build(); + + System.out.println("Saved user:"+ newUser); + return userRepo.save(newUser); + } +} \ No newline at end of file diff --git a/backend/src/main/java/org/example/backend/security/SecurityConfig.java b/backend/src/main/java/org/example/backend/security/SecurityConfig.java new file mode 100644 index 0000000..5e1c31f --- /dev/null +++ b/backend/src/main/java/org/example/backend/security/SecurityConfig.java @@ -0,0 +1,42 @@ +package org.example.backend.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.HttpStatusEntryPoint; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + @Value("${app.url}") + private String appUrl; + private final CustomOAuth2UserService customOAuth2UserService; + private final CustomOidcUserService customOidcUserService; + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ + http + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(a-> a + .requestMatchers("/api/auth/params").permitAll() + .requestMatchers("/api/auth/me").authenticated() + .requestMatchers("/api/secured").authenticated() +// .requestMatchers("/api/discounts").authenticated() + .anyRequest().permitAll()) + .logout(l->l.logoutSuccessUrl(appUrl)) + .oauth2Login(o->o + .defaultSuccessUrl(appUrl) + .userInfoEndpoint(u->u + .userService(customOAuth2UserService) + .oidcUserService(customOidcUserService))) + .exceptionHandling(e -> e + .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))); + return http.build(); + } +} diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties index 3ca17a4..b993a7e 100644 --- a/backend/src/main/resources/application.properties +++ b/backend/src/main/resources/application.properties @@ -1 +1,18 @@ spring.application.name=backend +spring.data.mongodb.uri=${MONGODBCONNECTION} +spring.security.oauth2.client.registration.github.client-id=${GITHUB_ID} +spring.security.oauth2.client.registration.github.client-secret=${GITHUB_SECRET} +spring.security.oauth2.client.registration.github.scope=none +spring.security.oauth2.client.registration.google.client-id=${GOOGLE_ID} +spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_SECRET} +spring.security.oauth2.client.registration.facebook.client-id=${FACEBOOK_ID} +spring.security.oauth2.client.registration.facebook.client-secret=${FACEBOOK_SECRET} +spring.security.oauth2.client.registration.facebook.scope=public_profile +app.url=${APP_URL} + +# Facebook Provider Customization +spring.security.oauth2.client.provider.facebook.authorization-uri=https://www.facebook.com/v18.0/dialog/oauth +spring.security.oauth2.client.provider.facebook.token-uri=https://graph.facebook.com/v18.0/oauth/access_token +# This URI is crucial. It explicitly asks Facebook for the id, name, email, and a large picture. +spring.security.oauth2.client.provider.facebook.user-info-uri=https://graph.facebook.com/me?fields=id,name,email,picture.type(large) +spring.security.oauth2.client.provider.facebook.user-name-attribute=name \ No newline at end of file diff --git a/backend/src/test/java/org/example/backend/security/AuthControllerTest.java b/backend/src/test/java/org/example/backend/security/AuthControllerTest.java new file mode 100644 index 0000000..293d28a --- /dev/null +++ b/backend/src/test/java/org/example/backend/security/AuthControllerTest.java @@ -0,0 +1,58 @@ +package org.example.backend.security; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import static org.mockito.Mockito.mock; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Login; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(AuthController.class) +class AuthControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void getMe_whenLoggedInWithOidc_returnsAppUserDto() throws Exception { + OidcUser mockOidcUser = mock(OidcUser.class); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/auth/me") + .with(oidcLogin().oidcUser( + new CustomOidcUser(mockOidcUser, + new AppUser("google:123456789", + "123456789", + "google", + "George", + "George.jpg")) + ))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value("google:123456789")) + .andExpect(jsonPath("$.userName").value("George")) + .andExpect(jsonPath("$.avatarUrl").value("George.jpg")); + } + + @Test + void getMe_whenLoggedInWithOAuth2_returnsAppUserDto() throws Exception { + OAuth2User mockOAuth2User = mock(OAuth2User.class); + mockMvc.perform(MockMvcRequestBuilders.get("/api/auth/me") + .with(oauth2Login().oauth2User( + new CustomOAuth2User(mockOAuth2User, + new AppUser("github:123456789", + "123456789", + "github", + "Gerry", + "Gerry.jpg")) + ))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value("github:123456789")) + .andExpect(jsonPath("$.userName").value("Gerry")) + .andExpect(jsonPath("$.avatarUrl").value("Gerry.jpg")); + } +} diff --git a/frontend/components/Dashboard.tsx b/frontend/components/Dashboard.tsx new file mode 100644 index 0000000..1e34234 --- /dev/null +++ b/frontend/components/Dashboard.tsx @@ -0,0 +1,14 @@ +import type {userInfoType} from "../type/UserInfoType.ts"; + +type DashboardProps = { + user:userInfoType|null +} +export default function Dashboard(props:Readonly) { + + return ( +
+

Welcome {props.user?.userName}

+ {props.user?.userName}/ +
+ ); +} \ No newline at end of file diff --git a/frontend/components/Navbar.tsx b/frontend/components/Navbar.tsx new file mode 100644 index 0000000..c2dbdb8 --- /dev/null +++ b/frontend/components/Navbar.tsx @@ -0,0 +1,64 @@ +import axios from "axios"; +import type {userInfoType} from "../type/UserInfoType.ts"; + +interface NavbarProps { + user: userInfoType | null + setUser: (user: userInfoType | null) => void +} + +export function Navbar({user, setUser}: NavbarProps) { + + const loginParams = () => { + axios.get("/api/auth/params") + .then(response => { + console.log(response.data); + }).catch(e => console.error(e)) + } + + function loginWithGithub() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + //from video + // window.open(host + "/login/oauth2/code/github","_self"); + //universal login page for all providers + // window.open(host + "/login/","_self"); + //for GitHub + window.open(host + "/oauth2/authorization/github", "_self"); + } + + function loginWithGoogle() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/oauth2/authorization/google", "_self"); + } + function loginWithFacebook() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/oauth2/authorization/facebook", "_self"); + } + + function logout() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/logout", "_self"); + setUser(null) + } + + return ( +
+ + {user ? () : + ( +
+ + + +
+ )} +
+ ); +} \ No newline at end of file diff --git a/frontend/components/ProtectedRoute.tsx b/frontend/components/ProtectedRoute.tsx new file mode 100644 index 0000000..f039df2 --- /dev/null +++ b/frontend/components/ProtectedRoute.tsx @@ -0,0 +1,11 @@ +import {Navigate, Outlet} from "react-router-dom"; +import type {userInfoType} from "../type/UserInfoType.ts"; + +type ProtectedRouteProps={ + user:userInfoType|null +} +export default function ProtectedRoute(props:Readonly) { + return ( + props.user? : + ); +} \ No newline at end of file diff --git a/frontend/package-lock.json b/frontend/package-lock.json index b0fe9fe..3ec277f 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,8 +8,10 @@ "name": "frontend", "version": "0.0.0", "dependencies": { + "axios": "^1.11.0", "react": "^19.1.1", - "react-dom": "^19.1.1" + "react-dom": "^19.1.1", + "react-router-dom": "^7.8.2" }, "devDependencies": { "@eslint/js": "^9.33.0", @@ -1781,6 +1783,23 @@ "dev": true, "license": "Python-2.0" }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz", + "integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1845,6 +1864,19 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -1913,6 +1945,18 @@ "dev": true, "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -1927,6 +1971,15 @@ "dev": true, "license": "MIT" }, + "node_modules/cookie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz", + "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -1974,6 +2027,29 @@ "dev": true, "license": "MIT" }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.209", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.209.tgz", @@ -1981,6 +2057,51 @@ "dev": true, "license": "ISC" }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.25.9", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.9.tgz", @@ -2349,6 +2470,42 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2364,6 +2521,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -2374,6 +2540,43 @@ "node": ">=6.9.0" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2400,6 +2603,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -2417,6 +2632,45 @@ "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -2618,6 +2872,15 @@ "yallist": "^3.0.2" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -2642,6 +2905,27 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -2837,6 +3121,12 @@ "node": ">= 0.8.0" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -2899,6 +3189,44 @@ "node": ">=0.10.0" } }, + "node_modules/react-router": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.8.2.tgz", + "integrity": "sha512-7M2fR1JbIZ/jFWqelpvSZx+7vd7UlBTfdZqf6OSdF9g6+sfdqJDAWcak6ervbHph200ePlu+7G8LdoiC3ReyAQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.8.2.tgz", + "integrity": "sha512-Z4VM5mKDipal2jQ385H6UBhiiEDlnJPx6jyWsTYoZQdl5TrjxEV2a9yl3Fi60NBJxYzOTGTTHXPi0pdizvTwow==", + "license": "MIT", + "dependencies": { + "react-router": "7.8.2" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", @@ -3000,6 +3328,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-cookie-parser": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz", + "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==", + "license": "MIT" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index dbf9194..90e5315 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,8 +10,10 @@ "preview": "vite preview" }, "dependencies": { + "axios": "^1.11.0", "react": "^19.1.1", - "react-dom": "^19.1.1" + "react-dom": "^19.1.1", + "react-router-dom": "^7.8.2" }, "devDependencies": { "@eslint/js": "^9.33.0", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3d7ded3..6ab88db 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,35 +1,42 @@ -import { useState } from 'react' -import reactLogo from './assets/react.svg' -import viteLogo from '/vite.svg' import './App.css' +import axios from "axios"; +import {useEffect, useState} from "react"; +import {Route, Routes } from "react-router-dom"; +import Dashboard from "../components/Dashboard.tsx"; +import ProtectedRoute from "../components/ProtectedRoute.tsx"; +import {Navbar} from "../components/Navbar.tsx"; +import type {userInfoType} from "../type/UserInfoType.ts"; -function App() { - const [count, setCount] = useState(0) +export default function App() { + const [user,setUser]=useState(null) + + const loadUser =()=>{ + axios.get("/api/auth/me") + .then(response=>{ + console.log(response.data); + setUser(response.data) + }).catch(()=>setUser(null)) + } + + useEffect(() => { + loadUser() + }, []); return ( <>
- - Vite logo - - - React logo - + + {/**/} + + }> + }/> + + }/> + }> + }/> + +
-

Vite + React

-
- -

- Edit src/App.tsx and save to test HMR -

-
-

- Click on the Vite and React logos to learn more -

) -} - -export default App +} \ No newline at end of file diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index bef5202..a24970e 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -2,9 +2,12 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import App from './App.tsx' +import {BrowserRouter} from "react-router-dom"; createRoot(document.getElementById('root')!).render( - + + + , ) diff --git a/frontend/type/UserInfoType.ts b/frontend/type/UserInfoType.ts new file mode 100644 index 0000000..0edb414 --- /dev/null +++ b/frontend/type/UserInfoType.ts @@ -0,0 +1,5 @@ +export type userInfoType={ + id:string, + userName: string, + avatarUrl: string +} \ No newline at end of file From 26cd0cffee763eec3eb804ff4a1b7bad207efb87 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Tue, 16 Sep 2025 21:51:40 +0200 Subject: [PATCH 02/11] Fast search added --- .../controller/DiscountsController.java | 39 +++++ .../org/example/backend/model/Discount.java | 22 +++ .../repository/DiscountRepository.java | 12 ++ .../backend/service/DiscountsService.java | 23 +++ .../src/main/resources/application.properties | 3 + frontend/components/Dashboard.tsx | 14 -- frontend/components/Navbar.tsx | 64 -------- frontend/src/App.css | 152 +++++++++++++++--- frontend/src/App.tsx | 40 +++-- frontend/src/components/Card.tsx | 16 ++ frontend/src/components/Dashboard.tsx | 48 ++++++ frontend/src/components/Login.tsx | 32 ++++ frontend/src/components/Navbar.tsx | 48 ++++++ .../{ => src}/components/ProtectedRoute.tsx | 0 frontend/src/components/SearchBar.tsx | 26 +++ frontend/src/index.css | 2 +- frontend/src/type/DiscountInfoType.ts | 7 + frontend/{ => src}/type/UserInfoType.ts | 0 frontend/tsconfig.app.json | 2 +- 19 files changed, 433 insertions(+), 117 deletions(-) create mode 100644 backend/src/main/java/org/example/backend/controller/DiscountsController.java create mode 100644 backend/src/main/java/org/example/backend/model/Discount.java create mode 100644 backend/src/main/java/org/example/backend/repository/DiscountRepository.java create mode 100644 backend/src/main/java/org/example/backend/service/DiscountsService.java delete mode 100644 frontend/components/Dashboard.tsx delete mode 100644 frontend/components/Navbar.tsx create mode 100644 frontend/src/components/Card.tsx create mode 100644 frontend/src/components/Dashboard.tsx create mode 100644 frontend/src/components/Login.tsx create mode 100644 frontend/src/components/Navbar.tsx rename frontend/{ => src}/components/ProtectedRoute.tsx (100%) create mode 100644 frontend/src/components/SearchBar.tsx create mode 100644 frontend/src/type/DiscountInfoType.ts rename frontend/{ => src}/type/UserInfoType.ts (100%) diff --git a/backend/src/main/java/org/example/backend/controller/DiscountsController.java b/backend/src/main/java/org/example/backend/controller/DiscountsController.java new file mode 100644 index 0000000..67de2e5 --- /dev/null +++ b/backend/src/main/java/org/example/backend/controller/DiscountsController.java @@ -0,0 +1,39 @@ +package org.example.backend.controller; + +import lombok.RequiredArgsConstructor; +import org.example.backend.model.Discount; +import org.example.backend.service.DiscountsService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api") +@RequiredArgsConstructor +public class DiscountsController { +// private final MongoRepository repository; + private final DiscountsService service; +// @GetMapping("/data") +// public List DbData(){ +// return repository.allDocuments(); +// } + @GetMapping("/data" ) + public List getAllDiscounts(){ + return service.getAllDiscounts(); + } + + @GetMapping("/edeka" ) + public List getEdeka(){ + return service.findByStore("Edeka"); + } + @GetMapping("/lidl" ) + public List getLidl(){ + return service.findByStore("Lidl"); + } + @GetMapping("/aldinord" ) + public List getAldiNord(){ + return service.findByStore("AldiNord"); + } +} diff --git a/backend/src/main/java/org/example/backend/model/Discount.java b/backend/src/main/java/org/example/backend/model/Discount.java new file mode 100644 index 0000000..cc7c6c9 --- /dev/null +++ b/backend/src/main/java/org/example/backend/model/Discount.java @@ -0,0 +1,22 @@ +package org.example.backend.model; + +//import org.bson.Document; + +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "Discounters") +public record Discount(String id, String name, String image, String price,String provider) { +// public static Discount fromDocument(Document doc) { +// // map fields from doc to Discount +// if (doc == null) { +// return null; +// } +// return new Discount( +// doc.getObjectId("_id").toString(), +// doc.getString("Image"), +// doc.getString("Name"), +// doc.getString("Price"), +// doc.getString("Provider") +// ); +// } +} diff --git a/backend/src/main/java/org/example/backend/repository/DiscountRepository.java b/backend/src/main/java/org/example/backend/repository/DiscountRepository.java new file mode 100644 index 0000000..cbf1d52 --- /dev/null +++ b/backend/src/main/java/org/example/backend/repository/DiscountRepository.java @@ -0,0 +1,12 @@ +package org.example.backend.repository; + +import org.example.backend.model.Discount; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface DiscountRepository extends MongoRepository { + List findDiscountByProvider(String provider); +} diff --git a/backend/src/main/java/org/example/backend/service/DiscountsService.java b/backend/src/main/java/org/example/backend/service/DiscountsService.java new file mode 100644 index 0000000..3e91ee6 --- /dev/null +++ b/backend/src/main/java/org/example/backend/service/DiscountsService.java @@ -0,0 +1,23 @@ +package org.example.backend.service; + +import org.example.backend.model.Discount; +import org.example.backend.repository.DiscountRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class DiscountsService { + private final DiscountRepository repo; + + public DiscountsService(DiscountRepository repo) { + this.repo = repo; + } + + public List getAllDiscounts() { + return repo.findAll(); + } + public List findByStore(String Provider) { + return repo.findDiscountByProvider(Provider); + } +} diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties index b993a7e..54630b6 100644 --- a/backend/src/main/resources/application.properties +++ b/backend/src/main/resources/application.properties @@ -10,6 +10,9 @@ spring.security.oauth2.client.registration.facebook.client-secret=${FACEBOOK_SEC spring.security.oauth2.client.registration.facebook.scope=public_profile app.url=${APP_URL} +DatabaseName=${DatabaseName} +Collectionname=${Collectionname} + # Facebook Provider Customization spring.security.oauth2.client.provider.facebook.authorization-uri=https://www.facebook.com/v18.0/dialog/oauth spring.security.oauth2.client.provider.facebook.token-uri=https://graph.facebook.com/v18.0/oauth/access_token diff --git a/frontend/components/Dashboard.tsx b/frontend/components/Dashboard.tsx deleted file mode 100644 index 1e34234..0000000 --- a/frontend/components/Dashboard.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import type {userInfoType} from "../type/UserInfoType.ts"; - -type DashboardProps = { - user:userInfoType|null -} -export default function Dashboard(props:Readonly) { - - return ( -
-

Welcome {props.user?.userName}

- {props.user?.userName}/ -
- ); -} \ No newline at end of file diff --git a/frontend/components/Navbar.tsx b/frontend/components/Navbar.tsx deleted file mode 100644 index c2dbdb8..0000000 --- a/frontend/components/Navbar.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import axios from "axios"; -import type {userInfoType} from "../type/UserInfoType.ts"; - -interface NavbarProps { - user: userInfoType | null - setUser: (user: userInfoType | null) => void -} - -export function Navbar({user, setUser}: NavbarProps) { - - const loginParams = () => { - axios.get("/api/auth/params") - .then(response => { - console.log(response.data); - }).catch(e => console.error(e)) - } - - function loginWithGithub() { - const host: string = window.location.host === "localhost:5173" ? - "http://localhost:8080" : - window.location.origin; - //from video - // window.open(host + "/login/oauth2/code/github","_self"); - //universal login page for all providers - // window.open(host + "/login/","_self"); - //for GitHub - window.open(host + "/oauth2/authorization/github", "_self"); - } - - function loginWithGoogle() { - const host: string = window.location.host === "localhost:5173" ? - "http://localhost:8080" : - window.location.origin; - window.open(host + "/oauth2/authorization/google", "_self"); - } - function loginWithFacebook() { - const host: string = window.location.host === "localhost:5173" ? - "http://localhost:8080" : - window.location.origin; - window.open(host + "/oauth2/authorization/facebook", "_self"); - } - - function logout() { - const host: string = window.location.host === "localhost:5173" ? - "http://localhost:8080" : - window.location.origin; - window.open(host + "/logout", "_self"); - setUser(null) - } - - return ( -
- - {user ? () : - ( -
- - - -
- )} -
- ); -} \ No newline at end of file diff --git a/frontend/src/App.css b/frontend/src/App.css index b9d355d..f6b2381 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -4,39 +4,143 @@ padding: 2rem; text-align: center; } +.app-container { + margin: 2rem; + padding: 2rem; + max-width: 100%; + overflow-x: hidden; +} +nav { + transition: top 0.3s; +} +.login-buttons{ + display: grid; + grid-template-columns: 1fr; + justify-items: stretch; + row-gap: 1rem; + margin: 2rem; + .button{ + padding: 2rem; + } +} +.card { + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + border-radius: 2rem; + box-shadow: 2px 5px 1px rgba(0,0,0,0); + /*border-style: solid;*/ + background: rgba(250, 250, 250, 0.9); + width: 100%; + max-width: 20rem; + word-wrap: anywhere; + color: #1a1a1a; + .price{ + color: red; + } +} +.card-image { + position: relative; + background: white; + border-radius: 2rem; + display: flex; + justify-content: center; + align-items: center; + width: 100%; + max-width: 100%; + max-height: 100%; +} + -.logo { - height: 6em; - padding: 1.5em; - will-change: filter; - transition: filter 300ms; +.card-grid { + display: grid; + /* 6 columns on large screens */ + max-width: 1600px; /* Optional: sets a max-width for the grid on very large screens */ + margin: 0 auto; /* Centers the grid container */ + grid-template-columns: repeat(5, 1fr); + gap: 1.5rem; /* Adjust the space between cards */ + padding: 1.5rem; + justify-items: center; /* Center cards within their grid cell */ } -.logo:hover { - filter: drop-shadow(0 0 2em #646cffaa); + +nav { + display: flex; + gap: 1rem; + position: fixed; + left: 0; + width: 100%; + background: rgba(35, 35, 35, 0.9); + color: white; + padding: 1rem 0 1rem 0; + text-align: center; + z-index: 1000; + top: 0; + bottom: auto; + justify-content: space-evenly; } -.logo.react:hover { - filter: drop-shadow(0 0 2em #61dafbaa); +.search-bar{ + .search-input{ + padding: 0.8em 1.5em; + border-radius: 25px; + border: 1px solid transparent; + font-size: 1em; + width: 20rem; + transition: border-color 0.25s; + } } -@keyframes logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } +.navbar-avatar{ + width: 2rem; + height: 2rem; + border-radius: 10%; + margin-right: 1rem; + vertical-align: middle; +} +/*buttons*/ +button{ + transition: transform 0.4s ease, box-shadow 0.2s; } -@media (prefers-reduced-motion: no-preference) { - a:nth-of-type(2) .logo { - animation: logo-spin infinite 20s linear; - } +button:hover{ + box-shadow: 0 0 1rem rgba(0, 0, 0, 50%); + transform: scale(1.1); + cursor: pointer; } +/* --- Responsive Adjustments --- */ -.card { - padding: 2em; +/* For large tablets and small laptops */ +@media (max-width: 1680px) { + .card-grid { + grid-template-columns: repeat(4, 1fr); + } +} +@media (max-width: 1280px) { + .card-grid { + grid-template-columns: repeat(3, 1fr); + } +} + +/* For tablets */ +@media (max-width: 1024px) { + .card-grid { + grid-template-columns: repeat(2, 1fr); + } } -.read-the-docs { - color: #888; +/* For mobile phones */ +@media (max-width: 768px) { + .card-grid { + grid-template-columns: repeat(1, 1fr); + } + .search-bar{ + .search-input{ + padding: 0.8em 1.5em; + border-radius: 2rem; + border: 1px solid transparent; + font-size: 1em; + width: auto; + transition: border-color 0.25s; + } + } } diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6ab88db..f78d523 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,40 +2,54 @@ import './App.css' import axios from "axios"; import {useEffect, useState} from "react"; import {Route, Routes } from "react-router-dom"; -import Dashboard from "../components/Dashboard.tsx"; -import ProtectedRoute from "../components/ProtectedRoute.tsx"; -import {Navbar} from "../components/Navbar.tsx"; -import type {userInfoType} from "../type/UserInfoType.ts"; +import Dashboard from "./components/Dashboard.tsx"; +import ProtectedRoute from "./components/ProtectedRoute.tsx"; +import {Navbar} from "./components/Navbar.tsx"; +import type {userInfoType} from "./type/UserInfoType.ts"; +import type {DiscountInfoType} from "./type/DiscountInfoType.ts"; +import Login from "./components/Login.tsx"; export default function App() { const [user,setUser]=useState(null) + const [discounts,setDiscounts]=useState([]) + const [filteredDiscounts,setFilteredDiscounts]=useState([]) const loadUser =()=>{ axios.get("/api/auth/me") .then(response=>{ console.log(response.data); - setUser(response.data) + setUser(response.data); + DbData(); }).catch(()=>setUser(null)) } + const DbData = () => { + axios.get("/api/data") + .then(response => { + console.log(response.data); + setDiscounts(response.data); + }).catch(e => console.error(e)) + } useEffect(() => { loadUser() }, []); + return ( <> -
- - {/**/} +
+ + {!user&& } }> - }/> - - }/> - }> - }/> + }/> + }/> + {/*}>*/} + {/* }/>*/} + {/**/} +
) diff --git a/frontend/src/components/Card.tsx b/frontend/src/components/Card.tsx new file mode 100644 index 0000000..d503616 --- /dev/null +++ b/frontend/src/components/Card.tsx @@ -0,0 +1,16 @@ +import type {DiscountInfoType} from "../type/DiscountInfoType.ts"; + +export default function Card(props:Readonly) { + return ( +
+
+ {props.name}/ +

{props.name}

+
+
+

{props.price}

+

{props.provider}

+
+
+ ); +} \ No newline at end of file diff --git a/frontend/src/components/Dashboard.tsx b/frontend/src/components/Dashboard.tsx new file mode 100644 index 0000000..2e70d39 --- /dev/null +++ b/frontend/src/components/Dashboard.tsx @@ -0,0 +1,48 @@ +import type {userInfoType} from "../type/UserInfoType.ts"; +import Login from "./Login.tsx"; +import type {DiscountInfoType} from "../type/DiscountInfoType.ts"; +import Card from "./Card.tsx"; + +type DashboardProps = { + user: userInfoType | null, + discounts: DiscountInfoType[], + filteredDiscounts: DiscountInfoType[] +} + +export default function Dashboard({user,discounts,filteredDiscounts}: Readonly) { + + return ( +
+ {user ? +
+

Welcome {user?.userName}

+ {user?.userName}/ +

This weeks discounts:

+ +
+ {filteredDiscounts.length>0 ? + filteredDiscounts.map( + (discount: DiscountInfoType)=>( + )): + discounts.length>0&& + discounts.map( + (discount: DiscountInfoType)=>( + )) + } +
+
: + () + } +
+ ); +} \ No newline at end of file diff --git a/frontend/src/components/Login.tsx b/frontend/src/components/Login.tsx new file mode 100644 index 0000000..efe7927 --- /dev/null +++ b/frontend/src/components/Login.tsx @@ -0,0 +1,32 @@ +function loginWithGithub() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/oauth2/authorization/github", "_self"); +} + +function loginWithGoogle() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/oauth2/authorization/google", "_self"); +} +function loginWithFacebook() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/oauth2/authorization/facebook", "_self"); +} + +export default function Login() { + return ( +
+

Please login

+
+ + + +
+
+ ); +} \ No newline at end of file diff --git a/frontend/src/components/Navbar.tsx b/frontend/src/components/Navbar.tsx new file mode 100644 index 0000000..c9e77ee --- /dev/null +++ b/frontend/src/components/Navbar.tsx @@ -0,0 +1,48 @@ +import type {userInfoType} from "../type/UserInfoType.ts"; +import type {DiscountInfoType} from "../type/DiscountInfoType.ts"; +import {useEffect, useState} from "react"; +import SearchBar from "./SearchBar.tsx"; + + +interface NavbarProps { + user: userInfoType | null, + setUser: (user: userInfoType | null) => void, + discounts: DiscountInfoType[], + setDiscounts: (discounts: DiscountInfoType[]) => void, + setFilteredDiscounts:(filteredDiscounts: DiscountInfoType[]) => void +} + + +export function Navbar({user, setUser, discounts, setFilteredDiscounts}: NavbarProps) { +//scroll animation + const [prevScrollPosition, setPrevScrollPosition] = useState(0); + const [visible, setVisible] = useState(true); + useEffect(() => { + function handleScroll() { + const currentScrollPosition = window.pageYOffset; + setVisible(prevScrollPosition > currentScrollPosition || currentScrollPosition < 10); + setPrevScrollPosition(currentScrollPosition); + } + + window.addEventListener("scroll", handleScroll); + return () => window.removeEventListener("scroll", handleScroll); + }, [prevScrollPosition]); + + function logout() { + const host: string = window.location.host === "localhost:5173" ? + "http://localhost:8080" : + window.location.origin; + window.open(host + "/logout", "_self"); + setUser(null) + } + + return ( +
+ +
+ ); +} \ No newline at end of file diff --git a/frontend/components/ProtectedRoute.tsx b/frontend/src/components/ProtectedRoute.tsx similarity index 100% rename from frontend/components/ProtectedRoute.tsx rename to frontend/src/components/ProtectedRoute.tsx diff --git a/frontend/src/components/SearchBar.tsx b/frontend/src/components/SearchBar.tsx new file mode 100644 index 0000000..5c850cd --- /dev/null +++ b/frontend/src/components/SearchBar.tsx @@ -0,0 +1,26 @@ +import type {DiscountInfoType} from "../type/DiscountInfoType.ts"; + +type SearchBarProps = { + discounts: DiscountInfoType[], + setFilteredDiscounts: (filteredDiscounts: DiscountInfoType[]) => void +} +export default function SearchBar({discounts, setFilteredDiscounts}: Readonly) { + function filterDiscounts(e:string){ + const searchArray: DiscountInfoType[] = []; + if(e.trim().length>0){ + discounts.map((discount:DiscountInfoType)=>(discount.name.toLowerCase().includes(e.toLowerCase()) && searchArray.push(discount))); + setFilteredDiscounts(searchArray); + }else{ + setFilteredDiscounts(discounts); + } + + } + return ( +
+ {discounts.length > 0 && ( + filterDiscounts(e.target.value) }/> + )} +
+ ); +} \ No newline at end of file diff --git a/frontend/src/index.css b/frontend/src/index.css index 08a3ac9..bf4f166 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -57,7 +57,7 @@ button:focus-visible { @media (prefers-color-scheme: light) { :root { color: #213547; - background-color: #ffffff; + background-color: lightgray; } a:hover { color: #747bff; diff --git a/frontend/src/type/DiscountInfoType.ts b/frontend/src/type/DiscountInfoType.ts new file mode 100644 index 0000000..2484c14 --- /dev/null +++ b/frontend/src/type/DiscountInfoType.ts @@ -0,0 +1,7 @@ +export type DiscountInfoType={ + id: string, + image: string, + name: string, + price: string, + provider: string +} \ No newline at end of file diff --git a/frontend/type/UserInfoType.ts b/frontend/src/type/UserInfoType.ts similarity index 100% rename from frontend/type/UserInfoType.ts rename to frontend/src/type/UserInfoType.ts diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json index 227a6c6..68735d8 100644 --- a/frontend/tsconfig.app.json +++ b/frontend/tsconfig.app.json @@ -23,5 +23,5 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["src"] + "include": ["src/**/*"] } From 41d06828634094a442d8302a9bc13390739c3d84 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Tue, 16 Sep 2025 22:57:07 +0200 Subject: [PATCH 03/11] Tests added --- .../controller/DiscountsController.java | 20 +- .../org/example/backend/model/Discount.java | 18 +- .../backend/security/AuthController.java | 6 - .../security/CustomOAuth2UserService.java | 28 ++- .../security/CustomOidcUserService.java | 13 +- .../backend/BackendApplicationTests.java | 4 +- .../controller/DiscountsControllerTest.java | 56 +++++ .../example/backend/model/DiscountTest.java | 57 +++++ .../security/CustomOAuth2UserServiceTest.java | 200 ++++++++++++++++++ .../security/CustomOidcUserServiceTest.java | 121 +++++++++++ .../backend/security/CustomOidcUserTest.java | 81 +++++++ 11 files changed, 541 insertions(+), 63 deletions(-) create mode 100644 backend/src/test/java/org/example/backend/controller/DiscountsControllerTest.java create mode 100644 backend/src/test/java/org/example/backend/model/DiscountTest.java create mode 100644 backend/src/test/java/org/example/backend/security/CustomOAuth2UserServiceTest.java create mode 100644 backend/src/test/java/org/example/backend/security/CustomOidcUserServiceTest.java create mode 100644 backend/src/test/java/org/example/backend/security/CustomOidcUserTest.java diff --git a/backend/src/main/java/org/example/backend/controller/DiscountsController.java b/backend/src/main/java/org/example/backend/controller/DiscountsController.java index 67de2e5..a2e1448 100644 --- a/backend/src/main/java/org/example/backend/controller/DiscountsController.java +++ b/backend/src/main/java/org/example/backend/controller/DiscountsController.java @@ -13,27 +13,11 @@ @RequestMapping("/api") @RequiredArgsConstructor public class DiscountsController { -// private final MongoRepository repository; + private final DiscountsService service; -// @GetMapping("/data") -// public List DbData(){ -// return repository.allDocuments(); -// } + @GetMapping("/data" ) public List getAllDiscounts(){ return service.getAllDiscounts(); } - - @GetMapping("/edeka" ) - public List getEdeka(){ - return service.findByStore("Edeka"); - } - @GetMapping("/lidl" ) - public List getLidl(){ - return service.findByStore("Lidl"); - } - @GetMapping("/aldinord" ) - public List getAldiNord(){ - return service.findByStore("AldiNord"); - } } diff --git a/backend/src/main/java/org/example/backend/model/Discount.java b/backend/src/main/java/org/example/backend/model/Discount.java index cc7c6c9..fcd50e6 100644 --- a/backend/src/main/java/org/example/backend/model/Discount.java +++ b/backend/src/main/java/org/example/backend/model/Discount.java @@ -1,22 +1,6 @@ package org.example.backend.model; -//import org.bson.Document; - import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "Discounters") -public record Discount(String id, String name, String image, String price,String provider) { -// public static Discount fromDocument(Document doc) { -// // map fields from doc to Discount -// if (doc == null) { -// return null; -// } -// return new Discount( -// doc.getObjectId("_id").toString(), -// doc.getString("Image"), -// doc.getString("Name"), -// doc.getString("Price"), -// doc.getString("Provider") -// ); -// } -} +public record Discount(String id, String name, String image, String price,String provider) {} diff --git a/backend/src/main/java/org/example/backend/security/AuthController.java b/backend/src/main/java/org/example/backend/security/AuthController.java index 315ebf6..97a26e3 100644 --- a/backend/src/main/java/org/example/backend/security/AuthController.java +++ b/backend/src/main/java/org/example/backend/security/AuthController.java @@ -2,7 +2,6 @@ import lombok.RequiredArgsConstructor; import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -19,9 +18,4 @@ public AppUserDto getMe(@AuthenticationPrincipal AppUserPrincipal user){ AppUser appUser=user.getAppUser(); return new AppUserDto(appUser.id(),appUser.userName(),appUser.avatarUrl()); } - - @GetMapping("/params") - public String getParams(@AuthenticationPrincipal OAuth2User userParams){ - return userParams.getAttributes().keySet().toString(); - } } diff --git a/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java b/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java index a55f384..d9b6f72 100644 --- a/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java +++ b/backend/src/main/java/org/example/backend/security/CustomOAuth2UserService.java @@ -3,6 +3,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; @@ -11,13 +12,16 @@ @Service @RequiredArgsConstructor -public class CustomOAuth2UserService extends DefaultOAuth2UserService { +public class CustomOAuth2UserService implements OAuth2UserService { private final AppUserRepository userRepo; + // Package-private for easy testing + OAuth2UserService delegate = new DefaultOAuth2UserService(); + @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { - OAuth2User oAuth2User = super.loadUser(userRequest); + OAuth2User oAuth2User = delegate.loadUser(userRequest); String provider = userRequest.getClientRegistration().getRegistrationId(); String providerId = oAuth2User.getName(); String uniqueId = provider + ":" + providerId; @@ -29,14 +33,11 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic return new CustomOAuth2User(oAuth2User, appUser); } - @SuppressWarnings("unchecked") - private AppUser createAppUser(OAuth2User oAuth2User, String uniqueId, String provider,String providerId) throws OAuth2AuthenticationException { - + private AppUser createAppUser(OAuth2User oAuth2User, String uniqueId, String provider, String providerId) { String name = null; String avatarUrl = null; - //Switch case - switch (provider){ + switch (provider) { case "github": name = oAuth2User.getAttribute("login"); avatarUrl = oAuth2User.getAttribute("avatar_url"); @@ -47,19 +48,18 @@ private AppUser createAppUser(OAuth2User oAuth2User, String uniqueId, String pro break; case "facebook": name = oAuth2User.getAttribute("name"); - Map picture=oAuth2User.getAttribute("picture"); - if(picture!=null){ + Map picture = oAuth2User.getAttribute("picture"); + if (picture != null) { @SuppressWarnings("unchecked") - Map data = (Map) picture.get("data"); + Map data = (Map) picture.get("data"); if (data != null) { avatarUrl = (String) data.get("url"); } } break; } - // GitHub user attributes - AppUser newUser= AppUser.builder() + AppUser newUser = AppUser.builder() .id(uniqueId) .provider(provider) .providerId(providerId) @@ -67,8 +67,6 @@ private AppUser createAppUser(OAuth2User oAuth2User, String uniqueId, String pro .avatarUrl(avatarUrl) .build(); - userRepo.save(newUser); - System.out.println("Saved user:"+ newUser); - return newUser; + return userRepo.save(newUser); } } diff --git a/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java b/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java index 0aeb666..d3b3bf0 100644 --- a/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java +++ b/backend/src/main/java/org/example/backend/security/CustomOidcUserService.java @@ -3,6 +3,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.stereotype.Service; @@ -11,12 +12,16 @@ @Service @RequiredArgsConstructor -public class CustomOidcUserService extends OidcUserService { +public class CustomOidcUserService implements OAuth2UserService { private final AppUserRepository userRepo; + // Package-private for easy testing + OidcUserService delegate = new OidcUserService(); + + @Override public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { - OidcUser oidcUser = super.loadUser(userRequest); + OidcUser oidcUser = delegate.loadUser(userRequest); String provider = userRequest.getClientRegistration().getRegistrationId(); // 'sub' is the standard OIDC claim for user's unique ID @@ -42,7 +47,7 @@ private AppUser createAppUser(OidcUser oidcUser, String uniqueId, String provide .avatarUrl(avatarUrl) .build(); - System.out.println("Saved user:"+ newUser); + System.out.println("Saved user:" + newUser); return userRepo.save(newUser); } -} \ No newline at end of file +} diff --git a/backend/src/test/java/org/example/backend/BackendApplicationTests.java b/backend/src/test/java/org/example/backend/BackendApplicationTests.java index a12e3fb..9a46eef 100644 --- a/backend/src/test/java/org/example/backend/BackendApplicationTests.java +++ b/backend/src/test/java/org/example/backend/BackendApplicationTests.java @@ -3,11 +3,9 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -@SpringBootTest +@SpringBootTest(properties = "app.url=http://localhost") class BackendApplicationTests { - @Test void contextLoads() { } - } diff --git a/backend/src/test/java/org/example/backend/controller/DiscountsControllerTest.java b/backend/src/test/java/org/example/backend/controller/DiscountsControllerTest.java new file mode 100644 index 0000000..391a9c2 --- /dev/null +++ b/backend/src/test/java/org/example/backend/controller/DiscountsControllerTest.java @@ -0,0 +1,56 @@ +package org.example.backend.controller; + +import org.example.backend.model.Discount; +import org.example.backend.service.DiscountsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.Arrays; +import java.util.List; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@ExtendWith(MockitoExtension.class) +class DiscountsControllerTest { + + private MockMvc mockMvc; + + @Mock + private DiscountsService discountsService; + + @InjectMocks + private DiscountsController discountsController; + + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(discountsController).build(); + } + + @Test + void getAllDiscounts_shouldReturnListOfDiscounts() throws Exception { + // Given + Discount discount1 = new Discount("1", "Sale 1", "image1.jpg", "10.00", "ProviderA"); + Discount discount2 = new Discount("2", "Sale 2", "image2.jpg", "20.00", "ProviderB"); + List discounts = Arrays.asList(discount1, discount2); + + when(discountsService.getAllDiscounts()).thenReturn(discounts); + + // When & Then + mockMvc.perform(get("/api/data")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json")) + .andExpect(jsonPath("$.length()").value(2)) + .andExpect(jsonPath("$[0].id").value("1")) + .andExpect(jsonPath("$[0].name").value("Sale 1")) + .andExpect(jsonPath("$[1].id").value("2")) + .andExpect(jsonPath("$[1].name").value("Sale 2")); + } +} diff --git a/backend/src/test/java/org/example/backend/model/DiscountTest.java b/backend/src/test/java/org/example/backend/model/DiscountTest.java new file mode 100644 index 0000000..06be959 --- /dev/null +++ b/backend/src/test/java/org/example/backend/model/DiscountTest.java @@ -0,0 +1,57 @@ +package org.example.backend.model; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class DiscountTest { + + @Test + void testDiscountRecord_ConstructorAndAccessors() { + // Given + String id = "1"; + String name = "Super Sale"; + String image = "image.jpg"; + String price = "19.99"; + String provider = "TestProvider"; + + // When + Discount discount = new Discount(id, name, image, price, provider); + + // Then + assertEquals(id, discount.id()); + assertEquals(name, discount.name()); + assertEquals(image, discount.image()); + assertEquals(price, discount.price()); + assertEquals(provider, discount.provider()); + } + + @Test + void testDiscountRecord_EqualsAndHashCode() { + // Given + Discount discount1 = new Discount("1", "Super Sale", "image.jpg", "19.99", "TestProvider"); + Discount discount2 = new Discount("1", "Super Sale", "image.jpg", "19.99", "TestProvider"); + Discount discount3 = new Discount("2", "Different Sale", "image2.jpg", "29.99", "AnotherProvider"); + + // Then + assertEquals(discount1, discount2); + assertEquals(discount1.hashCode(), discount2.hashCode()); + + assertNotEquals(discount1, discount3); + assertNotEquals(discount1.hashCode(), discount3.hashCode()); + assertNotEquals(null, discount1); + assertNotEquals(new Object(),discount1); + } + + @Test + void testDiscountRecord_ToString() { + // Given + Discount discount = new Discount("1", "Super Sale", "image.jpg", "19.99", "TestProvider"); + String expectedString = "Discount[id=1, name=Super Sale, image=image.jpg, price=19.99, provider=TestProvider]"; + + // When + String actualString = discount.toString(); + + // Then + assertEquals(expectedString, actualString); + } +} diff --git a/backend/src/test/java/org/example/backend/security/CustomOAuth2UserServiceTest.java b/backend/src/test/java/org/example/backend/security/CustomOAuth2UserServiceTest.java new file mode 100644 index 0000000..71b86db --- /dev/null +++ b/backend/src/test/java/org/example/backend/security/CustomOAuth2UserServiceTest.java @@ -0,0 +1,200 @@ +package org.example.backend.security; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; +import org.springframework.security.oauth2.core.user.DefaultOAuth2User; +import org.springframework.security.oauth2.core.user.OAuth2User; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CustomOAuth2UserServiceTest { + + @Mock + private AppUserRepository userRepo; + + @InjectMocks + private CustomOAuth2UserService customOAuth2UserService; + + @Mock + private OAuth2UserService delegate; + + @Mock + private OAuth2UserRequest userRequest; + + @Mock + private ClientRegistration clientRegistration; + + private AutoCloseable closeable; + + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); + customOAuth2UserService.delegate = delegate; + when(userRequest.getClientRegistration()).thenReturn(clientRegistration); + } + + @AfterEach + void tearDown() throws Exception { + closeable.close(); + } + + @Test + void loadUser_whenUserExists() { + // Given + String provider = "github"; + String providerId = "12345"; + String uniqueId = provider + ":" + providerId; + + // Correctly set up the mock OAuth2User to use the 'id' attribute for getName() + Map attributes = Map.of("login", "testuser", "id", 12345); + OAuth2User oAuth2User = new DefaultOAuth2User(Collections.emptyList(), attributes, "id"); + + AppUser existingUser = AppUser.builder().id(uniqueId).userName("testuser").build(); + + when(clientRegistration.getRegistrationId()).thenReturn(provider); + when(delegate.loadUser(userRequest)).thenReturn(oAuth2User); + when(userRepo.findById(uniqueId)).thenReturn(Optional.of(existingUser)); + + // When + OAuth2User result = customOAuth2UserService.loadUser(userRequest); + + // Then + assertInstanceOf(CustomOAuth2User.class, result); + assertEquals(existingUser.id(), result.getName()); + verify(userRepo, never()).save(any(AppUser.class)); + } + + @Test + void loadUser_whenNewGitHubUser() { + // Given + String provider = "github"; + String providerId = "12345"; + String uniqueId = provider + ":" + providerId; + String name = "githubuser"; + String avatarUrl = "https://example.com/avatar.jpg"; + + Map attributes = Map.of("login", name, "avatar_url", avatarUrl, "id", 12345); + OAuth2User oAuth2User = new DefaultOAuth2User(Collections.emptyList(), attributes, "id"); + + when(clientRegistration.getRegistrationId()).thenReturn(provider); + when(delegate.loadUser(userRequest)).thenReturn(oAuth2User); + when(userRepo.findById(uniqueId)).thenReturn(Optional.empty()); + when(userRepo.save(any(AppUser.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + // When + customOAuth2UserService.loadUser(userRequest); + + // Then + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(AppUser.class); + verify(userRepo).save(userCaptor.capture()); + AppUser savedUser = userCaptor.getValue(); + + assertEquals(uniqueId, savedUser.id()); + assertEquals(name, savedUser.userName()); + assertEquals(avatarUrl, savedUser.avatarUrl()); + } + + @Test + void loadUser_whenNewGoogleUser() { + // Given + String provider = "google"; + String providerId = "123456789"; + String uniqueId = provider + ":" + providerId; + String name = "Google User"; + String avatarUrl = "https://example.com/google.jpg"; + + Map attributes = Map.of("sub", providerId, "name", name, "picture", avatarUrl); + OAuth2User oAuth2User = new DefaultOAuth2User(Collections.emptyList(), attributes, "sub"); + + when(clientRegistration.getRegistrationId()).thenReturn(provider); + when(delegate.loadUser(userRequest)).thenReturn(oAuth2User); + when(userRepo.findById(uniqueId)).thenReturn(Optional.empty()); + when(userRepo.save(any(AppUser.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + // When + customOAuth2UserService.loadUser(userRequest); + + // Then + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(AppUser.class); + verify(userRepo).save(userCaptor.capture()); + AppUser savedUser = userCaptor.getValue(); + + assertEquals(uniqueId, savedUser.id()); + assertEquals(name, savedUser.userName()); + assertEquals(avatarUrl, savedUser.avatarUrl()); + } + + @Test + void loadUser_whenNewFacebookUser() { + // Given + String provider = "facebook"; + String providerId = "987654321"; + String uniqueId = provider + ":" + providerId; + String name = "Facebook User"; + String avatarUrl = "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=123"; + + Map pictureData = Map.of("url", avatarUrl); + Map picture = Map.of("data", pictureData); + Map attributes = Map.of("id", providerId, "name", name, "picture", picture); + OAuth2User oAuth2User = new DefaultOAuth2User(Collections.emptyList(), attributes, "id"); + + when(clientRegistration.getRegistrationId()).thenReturn(provider); + when(delegate.loadUser(userRequest)).thenReturn(oAuth2User); + when(userRepo.findById(uniqueId)).thenReturn(Optional.empty()); + when(userRepo.save(any(AppUser.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + // When + customOAuth2UserService.loadUser(userRequest); + + // Then + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(AppUser.class); + verify(userRepo).save(userCaptor.capture()); + AppUser savedUser = userCaptor.getValue(); + + assertEquals(uniqueId, savedUser.id()); + assertEquals(name, savedUser.userName()); + assertEquals(avatarUrl, savedUser.avatarUrl()); + } + + @Test + void loadUser_whenFacebookUserWithNoPictureData() { + // Given + String provider = "facebook"; + String providerId = "987654321"; + String uniqueId = provider + ":" + providerId; + String name = "Facebook User"; + + Map picture = Map.of("data", Collections.emptyMap()); + Map attributes = Map.of("id", providerId, "name", name, "picture", picture); + OAuth2User oAuth2User = new DefaultOAuth2User(Collections.emptyList(), attributes, "id"); + + when(clientRegistration.getRegistrationId()).thenReturn(provider); + when(delegate.loadUser(userRequest)).thenReturn(oAuth2User); + when(userRepo.findById(uniqueId)).thenReturn(Optional.empty()); + when(userRepo.save(any(AppUser.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + // When + customOAuth2UserService.loadUser(userRequest); + + // Then + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(AppUser.class); + verify(userRepo).save(userCaptor.capture()); + AppUser savedUser = userCaptor.getValue(); + + assertNull(savedUser.avatarUrl()); + } +} diff --git a/backend/src/test/java/org/example/backend/security/CustomOidcUserServiceTest.java b/backend/src/test/java/org/example/backend/security/CustomOidcUserServiceTest.java new file mode 100644 index 0000000..45b85f1 --- /dev/null +++ b/backend/src/test/java/org/example/backend/security/CustomOidcUserServiceTest.java @@ -0,0 +1,121 @@ +package org.example.backend.security; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; + +import java.time.Instant; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CustomOidcUserServiceTest { + + @Mock + private AppUserRepository userRepo; + + @InjectMocks + private CustomOidcUserService customOidcUserService; + + @Mock + private OidcUserService oidcUserServiceDelegate; + + @Mock + private OidcUserRequest oidcUserRequest; + + @Mock + private ClientRegistration clientRegistration; + + private AutoCloseable closeable; + + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); + customOidcUserService.delegate = oidcUserServiceDelegate; // Replace the real delegate with our mock + when(oidcUserRequest.getClientRegistration()).thenReturn(clientRegistration); + when(clientRegistration.getRegistrationId()).thenReturn("google"); + } + + @AfterEach + void tearDown() throws Exception { + closeable.close(); + } + + @Test + void loadUser_whenUserExists() { + // Given + String providerId = "12345"; + String uniqueId = "google:" + providerId; + Map claims = Map.of("sub", providerId, "name", "Test User", "picture", "https://example.com/pic.jpg"); + OidcIdToken idToken = new OidcIdToken("token-value", Instant.now(), Instant.now().plusSeconds(60), claims); + OidcUser oidcUser = new DefaultOidcUser(null, idToken); + + AppUser existingUser = AppUser.builder() + .id(uniqueId) + .userName("Test User") + .provider("google") + .providerId(providerId) + .build(); + when(oidcUserServiceDelegate.loadUser(oidcUserRequest)).thenReturn(oidcUser); + when(userRepo.findById(uniqueId)).thenReturn(Optional.of(existingUser)); + + // When + OidcUser result = customOidcUserService.loadUser(oidcUserRequest); + + // Then + assertInstanceOf(CustomOidcUser.class, result); + CustomOidcUser customOidcUser = (CustomOidcUser) result; + assertEquals(existingUser.id(), customOidcUser.getName()); + assertEquals(existingUser, customOidcUser.getAppUser()); + verify(userRepo, never()).save(any(AppUser.class)); + } + + @Test + void loadUser_whenNewUser() { + // Given + String providerId = "54321"; + String uniqueId = "google:" + providerId; + Map claims = Map.of("sub", providerId, "name", "New User", "picture", "https://example.com/new.jpg"); + OidcIdToken idToken = new OidcIdToken("token-value", Instant.now(), Instant.now().plusSeconds(60), claims); + OidcUser oidcUser = new DefaultOidcUser(null, idToken); + + ArgumentCaptor appUserCaptor = ArgumentCaptor.forClass(AppUser.class); + + when(oidcUserServiceDelegate.loadUser(oidcUserRequest)).thenReturn(oidcUser); + when(userRepo.findById(uniqueId)).thenReturn(Optional.empty()); + when(userRepo.save(any(AppUser.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + // When + OidcUser result = customOidcUserService.loadUser(oidcUserRequest); + + // Then + assertInstanceOf(CustomOidcUser.class, result); + CustomOidcUser customOidcUser = (CustomOidcUser) result; + + verify(userRepo, times(1)).save(appUserCaptor.capture()); + AppUser savedUser = appUserCaptor.getValue(); + + assertEquals(uniqueId, savedUser.id()); + assertEquals("New User", savedUser.userName()); + assertEquals("https://example.com/new.jpg", savedUser.avatarUrl()); + assertEquals("google", savedUser.provider()); + assertEquals(providerId, savedUser.providerId()); + + assertEquals(savedUser.id(), customOidcUser.getName()); + assertEquals(savedUser, customOidcUser.getAppUser()); + } +} diff --git a/backend/src/test/java/org/example/backend/security/CustomOidcUserTest.java b/backend/src/test/java/org/example/backend/security/CustomOidcUserTest.java new file mode 100644 index 0000000..e9fb198 --- /dev/null +++ b/backend/src/test/java/org/example/backend/security/CustomOidcUserTest.java @@ -0,0 +1,81 @@ +package org.example.backend.security; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.OidcUserInfo; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; + +import java.util.Collections; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +class CustomOidcUserTest { + + @Mock + private OidcUser oidcUser; + + @Mock + private AppUser appUser; + + private CustomOidcUser customOidcUser; + + private AutoCloseable closeable; + + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); + customOidcUser = new CustomOidcUser(oidcUser, appUser); + } + + @AfterEach + void tearDown() throws Exception { + closeable.close(); + } + + @Test + void getClaims() { + Map claims = Collections.singletonMap("claim", "value"); + when(oidcUser.getClaims()).thenReturn(claims); + assertEquals(claims, customOidcUser.getClaims()); + } + + @Test + void getUserInfo() { + OidcUserInfo userInfo = new OidcUserInfo(Collections.singletonMap("info", "value")); + when(oidcUser.getUserInfo()).thenReturn(userInfo); + assertEquals(userInfo, customOidcUser.getUserInfo()); + } + + @Test + void getIdToken() { + OidcIdToken idToken = new OidcIdToken("tokenValue", null, null, Collections.singletonMap("claim", "value")); + when(oidcUser.getIdToken()).thenReturn(idToken); + assertEquals(idToken, customOidcUser.getIdToken()); + } + + @Test + void getAttributes() { + Map attributes = Collections.singletonMap("attribute", "value"); + when(oidcUser.getAttributes()).thenReturn(attributes); + assertEquals(attributes, customOidcUser.getAttributes()); + } + + + @Test + void getName() { + String userId = "testUserId"; + when(appUser.id()).thenReturn(userId); + assertEquals(userId, customOidcUser.getName()); + } + + @Test + void getAppUser() { + assertEquals(appUser, customOidcUser.getAppUser()); + } +} From 12af9aed6521c95101cc4b65f1eedd02fdcc927b Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 11:22:04 +0200 Subject: [PATCH 04/11] Tests changed --- .../java/org/example/backend/security/SecurityConfig.java | 2 +- .../java/org/example/backend/BackendApplicationTests.java | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/backend/src/main/java/org/example/backend/security/SecurityConfig.java b/backend/src/main/java/org/example/backend/security/SecurityConfig.java index 5e1c31f..6fb382c 100644 --- a/backend/src/main/java/org/example/backend/security/SecurityConfig.java +++ b/backend/src/main/java/org/example/backend/security/SecurityConfig.java @@ -24,7 +24,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(a-> a - .requestMatchers("/api/auth/params").permitAll() +// .requestMatchers("/api/auth/params").permitAll() .requestMatchers("/api/auth/me").authenticated() .requestMatchers("/api/secured").authenticated() // .requestMatchers("/api/discounts").authenticated() diff --git a/backend/src/test/java/org/example/backend/BackendApplicationTests.java b/backend/src/test/java/org/example/backend/BackendApplicationTests.java index 9a46eef..7cccfe9 100644 --- a/backend/src/test/java/org/example/backend/BackendApplicationTests.java +++ b/backend/src/test/java/org/example/backend/BackendApplicationTests.java @@ -3,7 +3,11 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -@SpringBootTest(properties = "app.url=http://localhost") +@SpringBootTest(properties = { + "app.url=http://localhost", + "spring.security.oauth2.client.registration.github.client-id=test-id", + "spring.security.oauth2.client.registration.github.client-secret=test-secret" +}) class BackendApplicationTests { @Test void contextLoads() { From 2247fd56c20d8314d766c3e20b858715e15014c7 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 11:26:58 +0200 Subject: [PATCH 05/11] Tests changed 2 --- backend/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/pom.xml b/backend/pom.xml index 521960a..a9a359e 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -36,7 +36,7 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo.spring3x - 4.21.0 + 4.20.0 test From b2b1c779aab4cfb90e1c5bce2601df413a9a419a Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 11:31:40 +0200 Subject: [PATCH 06/11] Tests changed 3 --- backend/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/pom.xml b/backend/pom.xml index a9a359e..7661e5c 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -36,7 +36,7 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo.spring3x - 4.20.0 + 4.18.0 test From 489fd2d2913fdd07e30c97d1572f4c06af3a1bb5 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 11:37:23 +0200 Subject: [PATCH 07/11] Tests changed 4 --- .../org/example/backend/BackendApplicationTests.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/backend/src/test/java/org/example/backend/BackendApplicationTests.java b/backend/src/test/java/org/example/backend/BackendApplicationTests.java index 7cccfe9..7bedce0 100644 --- a/backend/src/test/java/org/example/backend/BackendApplicationTests.java +++ b/backend/src/test/java/org/example/backend/BackendApplicationTests.java @@ -3,11 +3,13 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -@SpringBootTest(properties = { - "app.url=http://localhost", - "spring.security.oauth2.client.registration.github.client-id=test-id", - "spring.security.oauth2.client.registration.github.client-secret=test-secret" -}) +@SpringBootTest( +// properties = { +// "app.url=http://localhost", +// "spring.security.oauth2.client.registration.github.client-id=test-id", +// "spring.security.oauth2.client.registration.github.client-secret=test-secret" +//} +) class BackendApplicationTests { @Test void contextLoads() { From 4fa2fe34994e3902d2f38ff8ac793f3c2cc55c5e Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 12:03:08 +0200 Subject: [PATCH 08/11] Tests changed 6 --- backend/src/main/resources/application.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties index 54630b6..4433ce9 100644 --- a/backend/src/main/resources/application.properties +++ b/backend/src/main/resources/application.properties @@ -10,8 +10,8 @@ spring.security.oauth2.client.registration.facebook.client-secret=${FACEBOOK_SEC spring.security.oauth2.client.registration.facebook.scope=public_profile app.url=${APP_URL} -DatabaseName=${DatabaseName} -Collectionname=${Collectionname} +#DatabaseName=${DatabaseName} +#Collectionname=${Collectionname} # Facebook Provider Customization spring.security.oauth2.client.provider.facebook.authorization-uri=https://www.facebook.com/v18.0/dialog/oauth From 27a5273a986d4c3e50a270fd7c4c7fda74f3c544 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 12:04:42 +0200 Subject: [PATCH 09/11] Tests changed 6 --- .../src/test/resources/application.properties | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 backend/src/test/resources/application.properties diff --git a/backend/src/test/resources/application.properties b/backend/src/test/resources/application.properties new file mode 100644 index 0000000..49d68c7 --- /dev/null +++ b/backend/src/test/resources/application.properties @@ -0,0 +1,19 @@ +spring.application.name=backend +de.flapdoodle.mongodb.embedded.version=7.0.4 + +app.url=http://localhost + +spring.security.oauth2.client.registration.github.client-id=123456 +spring.security.oauth2.client.registration.github.client-secret=123456 +spring.security.oauth2.client.registration.github.scope=none +spring.security.oauth2.client.registration.google.client-id=123456 +spring.security.oauth2.client.registration.google.client-secret=123456 +spring.security.oauth2.client.registration.facebook.client-id=123456 +spring.security.oauth2.client.registration.facebook.client-secret=123456 +spring.security.oauth2.client.registration.facebook.scope=public_profile + +spring.security.oauth2.client.provider.facebook.authorization-uri=https://www.facebook.com/v18.0/dialog/oauth +spring.security.oauth2.client.provider.facebook.token-uri=https://graph.facebook.com/v18.0/oauth/access_token +# This URI is crucial. It explicitly asks Facebook for the id, name, email, and a large picture. +spring.security.oauth2.client.provider.facebook.user-info-uri=https://graph.facebook.com/me?fields=id,name,email,picture.type(large) +spring.security.oauth2.client.provider.facebook.user-name-attribute=name \ No newline at end of file From 7892b4b1ef1ea6099e23c0011a37711f351f8e82 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 12:09:44 +0200 Subject: [PATCH 10/11] Tests COvarage --- sonar-project.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index 319b37d..5145477 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -8,8 +8,8 @@ sonar.organization=defhex # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. -sonar.sources=./frontend/src -sonar.coverage.exclusions=./frontend/src/** +sonar.sources=frontend/src +sonar.coverage.exclusions=frontend/src/** # Encoding of the source code. Default is default system encoding #sonar.sourceEncoding=UTF-8 \ No newline at end of file From 5f56c8f50a4b1c2b0e1a796c6b6b2306f74fbce0 Mon Sep 17 00:00:00 2001 From: Roottoot Date: Wed, 17 Sep 2025 12:17:18 +0200 Subject: [PATCH 11/11] Changed map function to forEach in front end to speed up the system. --- frontend/src/components/SearchBar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/SearchBar.tsx b/frontend/src/components/SearchBar.tsx index 5c850cd..4073728 100644 --- a/frontend/src/components/SearchBar.tsx +++ b/frontend/src/components/SearchBar.tsx @@ -8,7 +8,7 @@ export default function SearchBar({discounts, setFilteredDiscounts}: Readonly0){ - discounts.map((discount:DiscountInfoType)=>(discount.name.toLowerCase().includes(e.toLowerCase()) && searchArray.push(discount))); + discounts.forEach((discount:DiscountInfoType)=>(discount.name.toLowerCase().includes(e.toLowerCase()) && searchArray.push(discount))); setFilteredDiscounts(searchArray); }else{ setFilteredDiscounts(discounts);