-
Notifications
You must be signed in to change notification settings - Fork 0
Add user registration and GitHub OAuth2 authentication features #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
0f8cb64
feat: Add user registration functionality with password encoding and …
PasinduOG b0bd309
feat: Implement GitHub OAuth2 authentication with user registration a…
PasinduOG d3fd966
feat: Implement JWT authentication with login functionality and secur…
PasinduOG 76999cc
feat: Add OAuth2 callback handling and validation for user authentica…
PasinduOG a054335
feat: Enhance API security with OpenAPI configuration and role-based …
PasinduOG d8fc344
feat: Enhance GitHub OAuth2 user authentication by fetching email and…
PasinduOG 962d916
fix: Correct casing for Gemini API key and URL configuration properties
PasinduOG 40a0e79
feat: Add user retrieval by ID with role-based access control and res…
PasinduOG 1f8eaae
Potential fix for pull request finding
PasinduOG 1d05a88
Potential fix for pull request finding
PasinduOG 4c0e08b
Potential fix for pull request finding
PasinduOG d7f7ed5
Potential fix for pull request finding
PasinduOG 1c6149a
fix: default role to ATTENDEE when null in getAuthorities(), fix from…
Copilot 7a7a3b5
Potential fix for pull request finding
PasinduOG 0fa650e
fix: remove final from adminEmails for @Value field injection; add er…
Copilot c372f04
fix: use generic error message and log exception in fetchEmailFromGitHub
Copilot 82d5d29
feat: update application configuration and enhance user authenticatio…
PasinduOG 24c4cb9
feat: update application configuration and enhance user authenticatio…
PasinduOG 2590284
Remove redundant null check in getAuthorities() — role is non-null un…
Copilot 0fc10b0
fix: simplify role assignment in getAuthorities method
PasinduOG 8ca30b6
Merge remote-tracking branch 'origin/feature/auth' into feature/auth
PasinduOG File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
src/main/java/dev/pasinduog/eventsphere/config/SecurityConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| package dev.pasinduog.eventsphere.config; | ||
|
|
||
| import dev.pasinduog.eventsphere.filter.JwtAuthFilter; | ||
| import dev.pasinduog.eventsphere.service.CustomOAuth2UserService; | ||
| import dev.pasinduog.eventsphere.service.OAuth2CodeService; | ||
| 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.security.config.annotation.method.configuration.EnableMethodSecurity; | ||
| 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.config.http.SessionCreationPolicy; | ||
| import org.springframework.security.oauth2.core.user.DefaultOAuth2User; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.web.cors.CorsConfiguration; | ||
| import org.springframework.web.cors.CorsConfigurationSource; | ||
| import org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
| import org.springframework.web.util.UriComponentsBuilder; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| @EnableMethodSecurity | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
| private final CustomOAuth2UserService customOAuth2UserService; | ||
| private final JwtAuthFilter jwtAuthFilter; | ||
| private final OAuth2CodeService oAuth2CodeService; | ||
|
|
||
| @Value("${app.frontend.base-url}") | ||
| private String frontendBaseUrl; | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) { | ||
| http | ||
| .cors(cors -> cors.configurationSource(corsConfigurationSource())) // අනිවාර්යයි! | ||
| .csrf(AbstractHttpConfigurer::disable) | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers( | ||
| "/api/v1/auth/**", | ||
| "/api/v1/users/register", | ||
| "/swagger-ui/**", | ||
| "/v3/api-docs/**", | ||
| "/swagger-ui.html", | ||
| "/ws-event-chat/**", | ||
| "/oauth2/authorization/**", | ||
| "/login/oauth2/code/**" | ||
| ).permitAll() | ||
| .anyRequest().authenticated() | ||
| ) | ||
| .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)) | ||
| .addFilterBefore(jwtAuthFilter, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class) | ||
| .oauth2Login(oauth2 -> oauth2 | ||
|
PasinduOG marked this conversation as resolved.
|
||
| .userInfoEndpoint(userInfo -> userInfo | ||
| .userService(customOAuth2UserService) | ||
| ) | ||
| .successHandler((request, response, authentication) -> { | ||
| DefaultOAuth2User oauthUser = (DefaultOAuth2User) authentication.getPrincipal(); | ||
| if (oauthUser != null && oauthUser.getAttribute("email") != null) { | ||
| String email = oauthUser.getAttribute("email"); | ||
| String code = oAuth2CodeService.generateCode(email); | ||
| response.sendRedirect(buildFrontendLoginRedirect("code", code)); | ||
| } else { | ||
| response.sendRedirect(buildFrontendLoginRedirect("error", "github_email_missing")); | ||
| } | ||
|
PasinduOG marked this conversation as resolved.
|
||
| }) | ||
| ) | ||
| .logout(logout -> logout | ||
| .logoutUrl("/api/v1/auth/logout") | ||
| .logoutSuccessHandler((request, response, authentication) -> response.setStatus(200)) | ||
| ); | ||
| return http.build(); | ||
| } | ||
|
|
||
| private String buildFrontendLoginRedirect(String parameterName, String parameterValue) { | ||
| return UriComponentsBuilder.fromUriString(frontendBaseUrl) | ||
| .path("/login") | ||
| .queryParam(parameterName, parameterValue) | ||
| .build() | ||
| .toUriString(); | ||
| } | ||
|
|
||
| @Bean | ||
| public CorsConfigurationSource corsConfigurationSource() { | ||
| CorsConfiguration configuration = new CorsConfiguration(); | ||
| configuration.setAllowedOrigins(List.of(frontendBaseUrl)); | ||
| configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); | ||
| configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type")); | ||
| configuration.setAllowCredentials(true); | ||
| UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
|
PasinduOG marked this conversation as resolved.
|
||
| source.registerCorsConfiguration("/**", configuration); | ||
| return source; | ||
| } | ||
| } | ||
53 changes: 53 additions & 0 deletions
53
src/main/java/dev/pasinduog/eventsphere/controller/AuthController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| package dev.pasinduog.eventsphere.controller; | ||
|
|
||
| import dev.pasinduog.eventsphere.dto.LoginRequest; | ||
| import dev.pasinduog.eventsphere.dto.LoginResponse; | ||
| import dev.pasinduog.eventsphere.dto.OAuth2CallbackRequest; | ||
| import dev.pasinduog.eventsphere.exception.InvalidAuthCodeException; | ||
| import dev.pasinduog.eventsphere.exception.UserNotFoundException; | ||
| import dev.pasinduog.eventsphere.model.User; | ||
| import dev.pasinduog.eventsphere.repository.UserRepository; | ||
| import dev.pasinduog.eventsphere.service.JwtService; | ||
| import dev.pasinduog.eventsphere.service.OAuth2CodeService; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.authentication.BadCredentialsException; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/v1/auth") | ||
| @RequiredArgsConstructor | ||
| public class AuthController { | ||
|
|
||
| private final UserRepository userRepository; | ||
| private final JwtService jwtService; | ||
| private final PasswordEncoder passwordEncoder; | ||
| private final OAuth2CodeService oAuth2CodeService; | ||
|
|
||
| @PostMapping("/login") | ||
| public LoginResponse login(@RequestBody LoginRequest request) { | ||
| User user = userRepository.findByEmail(request.email()) | ||
| .orElseThrow(() -> new UserNotFoundException("User not found")); | ||
|
|
||
| if (!passwordEncoder.matches(request.password(), user.getPasswordHash())) { | ||
| throw new BadCredentialsException("Invalid credentials"); | ||
| } | ||
| String token = jwtService.generateToken(user); | ||
| return new LoginResponse(token); | ||
| } | ||
|
|
||
| @PostMapping("/oauth2/callback") | ||
| public LoginResponse oauth2Callback(@RequestBody OAuth2CallbackRequest request) { | ||
| String email = oAuth2CodeService.validateCodeAndGetEmail(request.code()); | ||
|
|
||
| if (email == null) { | ||
| throw new InvalidAuthCodeException("Invalid or expired authorization code"); | ||
| } | ||
|
|
||
| User user = userRepository.findByEmail(email) | ||
| .orElseThrow(() -> new UserNotFoundException("User not found")); | ||
|
|
||
| String token = jwtService.generateToken(user); | ||
| return new LoginResponse(token); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 33 additions & 5 deletions
38
src/main/java/dev/pasinduog/eventsphere/controller/UserController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,54 @@ | ||
| package dev.pasinduog.eventsphere.controller; | ||
|
|
||
| import dev.pasinduog.eventsphere.dto.RegisterRequest; | ||
| import dev.pasinduog.eventsphere.dto.UserResponse; | ||
| import dev.pasinduog.eventsphere.model.User; | ||
| import dev.pasinduog.eventsphere.service.UserService; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.security.access.prepost.PreAuthorize; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| import java.security.Principal; | ||
| import java.util.Map; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/v1/users") | ||
| @RequiredArgsConstructor | ||
| public class UserController { | ||
| private final UserService userService; | ||
|
|
||
| @GetMapping("/by-email") | ||
| @PreAuthorize("hasAuthority('ADMIN')") | ||
| UserResponse getUserByEmail(@RequestParam String email) { | ||
| return userService.getUserByEmail(email); | ||
| } | ||
|
|
||
| @GetMapping | ||
| @PreAuthorize("hasAuthority('ADMIN')") | ||
| UserResponse getUserById(@RequestParam String userId) { | ||
| return userService.getUserById(userId); | ||
| } | ||
|
|
||
| @GetMapping("/me") | ||
| @PreAuthorize("isAuthenticated()") | ||
| UserResponse getCurrentUser(Principal principal) { | ||
| String email = principal.getName(); | ||
| return userService.getUserByEmail(email); | ||
| } | ||
|
|
||
| @PostMapping("/register") | ||
| @ResponseStatus(HttpStatus.CREATED) | ||
| boolean registerUser(@RequestBody User user) { | ||
| return userService.registerUser(user); | ||
| boolean registerUser(@RequestBody RegisterRequest request) { | ||
| return userService.registerUser(request); | ||
| } | ||
|
|
||
| @GetMapping("/by-email") | ||
| UserResponse getUserByEmail(@RequestParam String email) { | ||
| return userService.getUserByEmail(email); | ||
| @PutMapping("/me/profile") | ||
| @PreAuthorize("isAuthenticated()") | ||
| boolean updateProfile(Principal principal, @RequestBody Map<String, String> updates){ | ||
| User user = userService.getUserEntityByEmail(principal.getName()); | ||
| if (updates.containsKey("skillsAndInterests")) user.setSkillsAndInterests(updates.get("skillsAndInterests")); | ||
| if (updates.containsKey("fullName")) user.setFullName(updates.get("fullName")); | ||
| return userService.updateUser(user); | ||
| } | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/main/java/dev/pasinduog/eventsphere/dto/LoginRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package dev.pasinduog.eventsphere.dto; | ||
|
|
||
| public record LoginRequest( | ||
| String email, | ||
| String password | ||
| ) {} |
4 changes: 4 additions & 0 deletions
4
src/main/java/dev/pasinduog/eventsphere/dto/LoginResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package dev.pasinduog.eventsphere.dto; | ||
|
|
||
| public record LoginResponse(String token) { | ||
| } |
4 changes: 4 additions & 0 deletions
4
src/main/java/dev/pasinduog/eventsphere/dto/OAuth2CallbackRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package dev.pasinduog.eventsphere.dto; | ||
|
|
||
| public record OAuth2CallbackRequest(String code) { | ||
| } |
9 changes: 9 additions & 0 deletions
9
src/main/java/dev/pasinduog/eventsphere/dto/RegisterRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| package dev.pasinduog.eventsphere.dto; | ||
|
|
||
| public record RegisterRequest( | ||
| String fullName, | ||
| String email, | ||
| String password, | ||
| String skillsAndInterests | ||
| ) { | ||
| } |
10 changes: 10 additions & 0 deletions
10
src/main/java/dev/pasinduog/eventsphere/exception/InvalidAuthCodeException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package dev.pasinduog.eventsphere.exception; | ||
|
|
||
| import io.github.og4dev.exception.ApiException; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| public class InvalidAuthCodeException extends ApiException { | ||
| public InvalidAuthCodeException(String message) { | ||
| super(message, HttpStatus.UNAUTHORIZED); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.