Skip to content

Commit

Permalink
Merge pull request #9 from The-Socialites/events
Browse files Browse the repository at this point in the history
Events
  • Loading branch information
Umi007 authored Jun 24, 2024
2 parents 793ee80 + 605d047 commit 47641aa
Show file tree
Hide file tree
Showing 21 changed files with 279 additions and 48 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,4 @@
</plugin>
</plugins>
</build>
</project>
</project>
39 changes: 9 additions & 30 deletions src/main/java/com/makersacademy/acebook/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.makersacademy.acebook.config;

import com.makersacademy.acebook.service.UserService;
import com.makersacademy.acebook.service.CustomOAuth2UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -9,31 +9,26 @@
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
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.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.SecurityFilterChain;

import java.util.HashSet;
import java.util.Set;

@EnableWebSecurity


@Configuration
public class SecurityConfig {

@Autowired
private UserService userService;
private CustomOAuth2UserService customOAuth2UserService;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors().and() // Enable CORS
.cors().and()
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/", "/login", "/register", "/users","/styles/**", "/events").permitAll()
.antMatchers("/", "/login", "/register", "/users","/styles/**", "/search", "/events", "/oauth2/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(formLogin ->
Expand All @@ -46,14 +41,14 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
oauth2Login
.loginPage("/login")
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint.userService(this.oauth2UserService())
userInfoEndpoint.userService(customOAuth2UserService)
)
.defaultSuccessUrl("/home", true)
)
.logout(logout ->
logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.logoutSuccessUrl("/login?logout")
.permitAll()
);

Expand All @@ -64,23 +59,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
public PasswordEncoder passwordEncoder() {
return new CustomPasswordEncoder();
}
}

@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();

return userRequest -> {
OAuth2User oAuth2User = delegate.loadUser(userRequest);

Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

if (oAuth2User instanceof DefaultOidcUser) {
DefaultOidcUser oidcUser = (DefaultOidcUser) oAuth2User;
return new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
} else {
return new DefaultOAuth2User(mappedAuthorities, oAuth2User.getAttributes(), "name");
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Date;
import java.util.Optional;
import java.util.List;


@Controller
public class EventsController {

Expand All @@ -45,6 +46,20 @@ public RedirectView create(@ModelAttribute Event event, Authentication authentic
return new RedirectView("/home");
}

@GetMapping("/events/details/{eventId}")
public String showEventDetails(@PathVariable Long eventId, Model model) {
// Fetch the event details from the repository
Optional<Event> optionalEvent = eventRepository.findById(eventId);

if (optionalEvent.isPresent()) {
Event event = optionalEvent.get();
model.addAttribute("event", event);
return "events/details";
} else {
// Handle the case where the event is not found
return "redirect:/error";
}

@GetMapping("/events/users")
public String userEvents(Model model,
@AuthenticationPrincipal Object principal,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.makersacademy.acebook.controller;

import com.makersacademy.acebook.model.Event;
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.EventRepository;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Expand All @@ -10,6 +12,7 @@
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class LoginController {
public String login() {
return "login";
}

@GetMapping("/loginSuccess")
public String loginSuccess() {
return "redirect:/home";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.makersacademy.acebook.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class LogoutController {
@PostMapping("/logout")
public RedirectView logout() {
return new RedirectView("/login");
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/makersacademy/acebook/model/Event.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,19 @@ public class Event {
@Getter
private String scheduledStartTime;

@Setter
@Getter
private String scheduledEndTime;

@Setter
@Getter
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createdAt;

@Setter
@Getter
private String location;

@Setter
@Getter
@ManyToOne
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/com/makersacademy/acebook/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ public class User {
@Setter
private String profilePictureUrl;

@Getter
@Setter
private String language;

@Getter
@Setter
private String city;

public User() {
this.enabled = TRUE;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
User findByEmail(String email);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
package com.makersacademy.acebook.service;
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private static final Logger logger = LoggerFactory.getLogger(CustomOAuth2UserService.class);
@Autowired
private UserRepository userRepository;
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
Map<String, Object> attributes = oAuth2User.getAttributes();
String email = (String) attributes.get("email");
logger.info("OAuth2 user attributes: {}", attributes);
if (email == null) {
logger.error("Email not found from OAuth2 provider");
throw new OAuth2AuthenticationException("Email not found from OAuth2 provider");
}
// Save or update user information in the database
User user = userRepository.findByEmail(email);
if (user == null) {
logger.info("Creating new user with email: {}", email);
user = new User();
user.setEmail(email);
user.setUsername((String) attributes.get("name"));
user.setProfilePictureUrl((String) attributes.get("picture"));
userRepository.save(user);
logger.info("New user created with email: {}", email);
} else {
logger.info("Updating existing user with email: {}", email);
user.setUsername((String) attributes.get("name"));
user.setProfilePictureUrl((String) attributes.get("picture"));
userRepository.save(user);
logger.info("Existing user updated with email: {}", email);
}
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new DefaultOAuth2User(mappedAuthorities, oAuth2User.getAttributes(), "email");
}
}
*/

package com.makersacademy.acebook.service;

import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

@Autowired
private UserRepository userRepository;

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);

Map<String, Object> attributes = oAuth2User.getAttributes();
String email = (String) attributes.get("email");

// Save or update user information in the database
User user = userRepository.findByEmail(email);
if (user == null) {
user = new User();
user.setEmail(email);
user.setUsername((String) attributes.get("name"));
user.setProfilePictureUrl((String) attributes.get("picture"));
userRepository.save(user); // Ensure user is saved here
}

Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

return new DefaultOAuth2User(mappedAuthorities, oAuth2User.getAttributes(), "name");
}
}




9 changes: 5 additions & 4 deletions src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,20 @@
##spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
##spring.security.oauth2.client.registration.google.client-name=Google

spring.datasource.url=jdbc:postgresql://socialites01.czyiqc0ga4tn.us-east-1.rds.amazonaws.com:5432/socialites_springboot_development_01
spring.datasource.url=jdbc:postgresql://socialites01.czyiqc0ga4tn.us-east-1.rds.amazonaws.com:5432/socialites01_springboot_development_01
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
flyway.baseline-on-migrate=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
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.google.scope=openid, profile, email
spring.security.oauth2.client.registration.google.scope=profile, email
spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/google
spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.google.client-name=Google
spring.security.oauth2.client.registration.google.redirect-uri=http://qxvdpmwpb4.us-east-1.awsapprunner.com/login/oauth2/code/google
spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.google.client-name=Google




5 changes: 3 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ spring.security.oauth2.client.provider.google.authorization-uri=https://accounts
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
spring.security.oauth2.client.provider.google.user-name-attribute=sub
spring.datasource.url=jdbc:postgresql://socialites.czyiqc0ga4tn.us-east-1.rds.amazonaws.com:5432/socialites_springboot_development
spring.datasource.url=jdbc:postgresql://socialites.czyiqc0ga4tn.us-east-1.rds.amazonaws.com:5432/socialites01_springboot_development_01
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
flyway.baseline-on-migrate=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
API_KEY = ${API_KEY}

logging.level.org.springframework.security=DEBUG
logging.level.com.makersacademy.acebook.service=DEBUG
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE events
ADD COLUMN location VARCHAR(250);
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE users
ADD COLUMN language VARCHAR(250);
2 changes: 2 additions & 0 deletions src/main/resources/db/migration/V12__add_city_to_users.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE users
ADD COLUMN city VARCHAR(250);
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE events
ADD COLUMN scheduled_end_time VARCHAR(250);
Loading

0 comments on commit 47641aa

Please sign in to comment.