Skip to content
Merged
Show file tree
Hide file tree
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 Apr 11, 2026
b0bd309
feat: Implement GitHub OAuth2 authentication with user registration a…
PasinduOG Apr 11, 2026
d3fd966
feat: Implement JWT authentication with login functionality and secur…
PasinduOG Apr 12, 2026
76999cc
feat: Add OAuth2 callback handling and validation for user authentica…
PasinduOG Apr 13, 2026
a054335
feat: Enhance API security with OpenAPI configuration and role-based …
PasinduOG Apr 13, 2026
d8fc344
feat: Enhance GitHub OAuth2 user authentication by fetching email and…
PasinduOG Apr 13, 2026
962d916
fix: Correct casing for Gemini API key and URL configuration properties
PasinduOG Apr 13, 2026
40a0e79
feat: Add user retrieval by ID with role-based access control and res…
PasinduOG Apr 13, 2026
1f8eaae
Potential fix for pull request finding
PasinduOG Apr 13, 2026
1d05a88
Potential fix for pull request finding
PasinduOG Apr 13, 2026
4c0e08b
Potential fix for pull request finding
PasinduOG Apr 13, 2026
d7f7ed5
Potential fix for pull request finding
PasinduOG Apr 13, 2026
1c6149a
fix: default role to ATTENDEE when null in getAuthorities(), fix from…
Copilot Apr 13, 2026
7a7a3b5
Potential fix for pull request finding
PasinduOG Apr 13, 2026
0fa650e
fix: remove final from adminEmails for @Value field injection; add er…
Copilot Apr 13, 2026
c372f04
fix: use generic error message and log exception in fetchEmailFromGitHub
Copilot Apr 13, 2026
82d5d29
feat: update application configuration and enhance user authenticatio…
PasinduOG Apr 14, 2026
24c4cb9
feat: update application configuration and enhance user authenticatio…
PasinduOG Apr 14, 2026
2590284
Remove redundant null check in getAuthorities() — role is non-null un…
Copilot Apr 14, 2026
0fc10b0
fix: simplify role assignment in getAuthorities method
PasinduOG Apr 14, 2026
8ca30b6
Merge remote-tracking branch 'origin/feature/auth' into feature/auth
PasinduOG Apr 14, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@
<artifactId>spring-boot-starter-flyway</artifactId>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-oauth2-client -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/org.flywaydb/flyway-mysql -->
<dependency>
<groupId>org.flywaydb</groupId>
Expand Down Expand Up @@ -88,6 +100,30 @@
<artifactId>og4dev-spring-response</artifactId>
<version>1.4.0</version>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.13.0</version>
<scope>compile</scope>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-jackson -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>

</project>
34 changes: 34 additions & 0 deletions src/main/java/dev/pasinduog/eventsphere/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package dev.pasinduog.eventsphere.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestClient;

import java.net.http.HttpClient;
Expand Down Expand Up @@ -34,4 +41,31 @@ public RestClient restClient() {
public Logger logger() {
return Logger.getLogger("dev.pasinduog.eventsphere.config");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public OpenAPI openApiConfig() {
final String securitySchemeName = "bearerAuth";

return new OpenAPI().info(
new Info()
.title("EventSphere API")
.description("This is the EventSphere API Documentation")
.version("1.0.0")
.termsOfService("https://github.com/pasinduog/eventsphere"))
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.description("Enter your JWT token. You can obtain it from the /api/v1/auth/login endpoint.")
));
}
}
97 changes: 97 additions & 0 deletions src/main/java/dev/pasinduog/eventsphere/config/SecurityConfig.java
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
Comment thread
PasinduOG marked this conversation as resolved.
.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
Comment thread
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"));
}
Comment thread
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();
Comment thread
PasinduOG marked this conversation as resolved.
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import dev.pasinduog.eventsphere.service.AiMatchmakingService;
import dev.pasinduog.eventsphere.service.EventService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -23,21 +24,25 @@ List<Event> getUpcomingEvents() {
}

@GetMapping("/{eventId}/matches")
@PreAuthorize("isAuthenticated()")
List<MatchSuggestionResponse> getMatchSuggestions(@PathVariable String eventId, @RequestParam String userId) {
return aiMatchmakingService.getMatchSuggestions(eventId, userId);
}
Comment thread
PasinduOG marked this conversation as resolved.

@PostMapping
@PreAuthorize("hasAuthority('ORGANIZER') or hasAuthority('ADMIN')")
boolean createEvent(@RequestBody Event event){
return eventService.createEvent(event);
}

@PostMapping("/{eventId}/register")
@PreAuthorize("isAuthenticated()")
boolean registerEvent(@PathVariable String eventId, @RequestParam String userId){
return eventService.registerUserForEvent(eventId, userId);
}

@PostMapping("/{eventId}/matchmaking")
@PreAuthorize("isAuthenticated()")
AiMatchResult generateNetworkingMatches(@PathVariable String eventId, @RequestParam String userId){
return aiMatchmakingService.generateMatchesForUser(eventId, userId);
Comment thread
PasinduOG marked this conversation as resolved.
}
Expand Down
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 src/main/java/dev/pasinduog/eventsphere/dto/LoginRequest.java
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
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package dev.pasinduog.eventsphere.dto;

public record LoginResponse(String token) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package dev.pasinduog.eventsphere.dto;

public record OAuth2CallbackRequest(String code) {
}
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
) {
}
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);
}
}
Loading