Skip to content

Commit

Permalink
Merge pull request #40 from Informatik-Projekt-Kurs/IPK-107-Implement…
Browse files Browse the repository at this point in the history
…-GraphQL

Ipk 107 implement graph ql
  • Loading branch information
Gugi-Games authored May 19, 2024
2 parents 57174c4 + 2bdabba commit 5a6d330
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 46 deletions.
24 changes: 9 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.release>17</maven.compiler.release>
<maven.compiler.verbose>true</maven.compiler.verbose>
<maven.compiler.verbose>true</maven.compiler.verbose>
</properties>

<distributionManagement>
Expand Down Expand Up @@ -55,18 +55,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
Expand Down Expand Up @@ -97,13 +85,11 @@
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
Expand All @@ -119,6 +105,14 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/com/MeetMate/experiments/TestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.MeetMate.experiments;

import com.MeetMate.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

@Controller
@RequiredArgsConstructor
public class TestController {

private final TestService testService;

@QueryMapping
public User getUsers(@Argument Long id) {
return testService.getUsers(id);
}

@MutationMapping
public ResponseEntity<?> UpdateUser(@Argument String name, @Argument String email, @Argument String password) {
testService.updateUser(name, email, password);
return ResponseEntity.ok().build();
}

@MutationMapping
public ResponseEntity<?> CreateUser(@Argument String name, @Argument String email, @Argument String password) {
testService.createUser(name, email, password);
return ResponseEntity.status(201).build();
}
}
40 changes: 40 additions & 0 deletions src/main/java/com/MeetMate/experiments/TestService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.MeetMate.experiments;

import com.MeetMate.user.User;
import com.MeetMate.user.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;


@RequiredArgsConstructor
@Service
public class TestService {

private final UserRepository userRepository;

public User getUsers(long id) {
return userRepository.findUserById(id)
.orElseThrow(() -> new IllegalStateException("User not found"));
}

@Transactional
public void updateUser(String name, String email, String password) {
User user =
userRepository
.findUserByEmail(email)
.orElseThrow(() -> new EntityNotFoundException("User does not exist."));

if (password != null) user.setPassword(password);
if (name != null) user.setName(name);
}

public void createUser(String name, String email, String password) {
User user = new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userRepository.save(user);
}
}
11 changes: 5 additions & 6 deletions src/main/java/com/MeetMate/security/JwtAuthenticationFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,20 @@ protected void doFilterInternal(
@NotNull HttpServletResponse response,
@NotNull FilterChain filterChain)
throws ServletException, IOException {

final String authHeader = request.getHeader("Authorization");
final String jwt;
final String userEmail;

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
// extract jwt token
// beginIndex is 7 bc "Bearer " is 7
jwt = authHeader.substring(7);

jwt = authHeader.substring(7);// beginIndex is 7 bc "Bearer " is 7
userEmail = jwtService.extractUserEmail(jwt);

if (userEmail != null
&& SecurityContextHolder.getContext().getAuthentication()
== null) { // check f if user is already authenticated
&& SecurityContextHolder.getContext().getAuthentication() == null) { // check f if user is already authenticated
UserDetails userDetails = userDetailsService.loadUserByUsername(userEmail);

if (jwtService.isTokenValid(jwt, userDetails)) {
Expand All @@ -56,6 +54,7 @@ protected void doFilterInternal(
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}

filterChain.doFilter(request, response);
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/MeetMate/security/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public boolean isTokenValid(String token, UserDetails userDetails) {
return email.equals(userDetails.getUsername()) && !isTokenExpired(token);
}

public boolean isTokenExpired(String token) {
private boolean isTokenExpired(String token) {
long expirationDate = extractClaim(token, Claims::getExpiration).getTime();
return expirationDate < System.currentTimeMillis();
}
Expand Down
46 changes: 23 additions & 23 deletions src/main/java/com/MeetMate/security/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
Expand All @@ -15,28 +16,27 @@
@RequiredArgsConstructor
public class SecurityConfig {

private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final AuthenticationProvider authenticationProvider;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final AuthenticationProvider authenticationProvider;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(
authorizeRequests ->
authorizeRequests
.requestMatchers("/api/user/login", "/api/user/signup", "/test/test")
// .requestMatchers("/**")
.permitAll() // Whitelist
.anyRequest()
.authenticated() // Everything else should be authenticated
)
.sessionManagement(
sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

return httpSecurity.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(
authorizeRequests ->
authorizeRequests
.requestMatchers("/api/user/login", "/api/user/signup", "/test/test", "/graphql/**")
// .requestMatchers("/**")
.permitAll() // Whitelist
.anyRequest().authenticated() // Everything else should be authenticated
)
.sessionManagement(
sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/MeetMate/throttle/IPRateLimiter.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
public class IPRateLimiter extends OncePerRequestFilter {

private final HashMap<String, LinkedList<Long>> requests = new HashMap<>();
private final int maxRequests = 2;
private final int maxRequests = 5;
private final long refreshTime = 1000 * 10; // 10 seconds

@Override
Expand Down
17 changes: 17 additions & 0 deletions src/main/resources/graphql/schema.graphqls
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#graphqls for graphql scema

type Query {
getUsers(id: ID!): User
}

type Mutation {
updateUser(name: String, email: String!, password: String): String
createUser(name: String!, email: String!, password: String!): String
}

type User {
id: ID
name: String
email: String
password: String
}

0 comments on commit 5a6d330

Please sign in to comment.