Skip to content
Snippets Groups Projects
Commit d129e39b authored by Richard Githuba's avatar Richard Githuba
Browse files

Merge branch 'release/Sprint-4' into 'main'

Release/sprint 4

See merge request c24108486/team-11-polish-community-group!58
parents 2f0154cb 15bb682d
No related branches found
No related tags found
No related merge requests found
Showing
with 875 additions and 26 deletions
......@@ -27,8 +27,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // Thymeleaf dependency
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // Thymeleaf dependency
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.2.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-json'
......@@ -59,7 +58,6 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.mockito:mockito-core:4.0.0' // Mocking library
testImplementation 'org.mockito:mockito-junit-jupiter:4.0.0' // JUnit 5 support for Mockito
......
package polish_community_group_11.polish_community.admin.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import polish_community_group_11.polish_community.admin.services.AdminService;
import polish_community_group_11.polish_community.register.models.User;
import polish_community_group_11.polish_community.register.services.UserService;
@RestController
public class AdminApiController {
private final AdminService adminService;
private final UserService userService;
private Authentication authentication;
public AdminApiController(AdminService adminService, UserService userService) {
this.adminService = adminService;
this.userService = userService;
}
@PutMapping("/admin/edit/{user_id}/role")
public ResponseEntity<Void> changeUserRole(@PathVariable("user_id") int user_id,
@RequestBody String role_name) {
authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream().anyMatch(
a -> a.getAuthority().equals("ROLE_ADMIN"))) {
if (role_name == null || role_name.trim().isEmpty()) {
return ResponseEntity.badRequest().build();
}
try {
User user = userService.findById(user_id);
if (user == null) {
return ResponseEntity.notFound().build();
}
adminService.updateUserRole(user, role_name);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.internalServerError().build();
}
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
@PutMapping("/admin/edit/{user_id}/enabled")
public ResponseEntity<Void> enableOrDisableUser(
@PathVariable("user_id") int user_id, @RequestParam Boolean enabled) {
authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream().anyMatch(
a -> a.getAuthority().equals("ROLE_ADMIN"))) {
try {
User user = userService.findById(user_id);
if (user == null) {
return ResponseEntity.notFound().build(); // User not found
}
adminService.enableOrDisableUser(user, enabled);
return ResponseEntity.ok().build();
} catch (IllegalArgumentException e) {
// Invalid boolean or other illegal arguments
return ResponseEntity.badRequest().build();
} catch (Exception e) {
return ResponseEntity.internalServerError().build();
}
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
@GetMapping("/admin/get/{user_id}")
public ResponseEntity<User> getUser(@PathVariable("user_id") int user_id) {
try {
User user = userService.findById(user_id);
if (user == null) {
return ResponseEntity.notFound().build(); // User not found
}
return ResponseEntity.ok(user);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
}
package polish_community_group_11.polish_community.admin.controllers;
import org.apache.coyote.BadRequestException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import polish_community_group_11.polish_community.admin.services.AdminService;
import polish_community_group_11.polish_community.register.services.RoleService;
import java.sql.SQLException;
@Controller
public class AdminController {
private final AdminService adminService;
private final RoleService roleService;
private Authentication authentication;
public AdminController(AdminService adminService, RoleService roleService) {
this.adminService = adminService;
this.roleService = roleService;
}
@GetMapping("admin/userInfo")
public ModelAndView getFirstAdminUsers() throws SQLException, BadRequestException {
ModelAndView mav = new ModelAndView("admin/userManage");
authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream().anyMatch(
a -> a.getAuthority().equals("ROLE_ADMIN")))
{
mav.addObject("usersAdminInfo",adminService.getUserManagementInfo());
mav.addObject("roles",roleService.findAllRoles());
}
else{
throw new BadRequestException("User is not admin");
}
return mav;
}
@GetMapping("admin")
public ModelAndView getAdminDashboard() throws SQLException, BadRequestException {
ModelAndView mav = new ModelAndView("admin/adminBoard");
authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream().anyMatch(
a -> a.getAuthority().equals("ROLE_ADMIN"))){
mav.addObject("adminBoard",adminService.getBoardManagementInfo());
}
else{
throw new BadRequestException("User is not admin");
}
return mav;
}
}
package polish_community_group_11.polish_community.admin.dao;
import polish_community_group_11.polish_community.admin.models.AdminBoard;
import polish_community_group_11.polish_community.admin.models.ManageUser;
import polish_community_group_11.polish_community.register.models.User;
import java.sql.SQLException;
import java.util.List;
public interface AdminRepository {
List<ManageUser> getUserManagementInfo() throws SQLException;
AdminBoard getBoardManagementInfo() throws SQLException;
int updateUserRole(User user);
}
package polish_community_group_11.polish_community.admin.dao;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.admin.models.AdminBoard;
import polish_community_group_11.polish_community.admin.models.ManageUser;
import polish_community_group_11.polish_community.register.models.User;
import java.sql.SQLException;
import java.time.DateTimeException;
import java.util.List;
@Repository
public class AdminRepositoryImpl implements AdminRepository {
private JdbcTemplate jdbc; // JdbcTemplate instance for performing database operations
private RowMapper<ManageUser> adminManageUserMapper; // RowMapper to map rows of the database result set to Manage User objects
private RowMapper<AdminBoard> adminBoardMapper;
public AdminRepositoryImpl(JdbcTemplate aJdbc){
this.jdbc = aJdbc;
setAdminManageUserMapper();
setAdminBoardMapper();
}
public void setAdminManageUserMapper(){
adminManageUserMapper = (rs, i) ->{
return new ManageUser(
rs.getInt("id"),
rs.getString("fullname"),
rs.getString("email"),
rs.getBoolean("enabled"),
rs.getInt("role_id"),
rs.getString("role_name")
);
};
}
public void setAdminBoardMapper(){
adminBoardMapper = (rs, i) ->{
return new AdminBoard(
rs.getInt("total_users"),
rs.getInt("total_posts"),
rs.getInt("upcoming_events"),
rs.getInt("new_comments")
);
};
}
public List<ManageUser> getUserManagementInfo() throws SQLException {
String sql="select u.id, u.fullname, u.email, u.enabled,u.role_id, rol.role_name from users u" +
" left join user_roles u_rol" +
" on u.id = u_rol.user_id" +
" join roles rol" +
" on u.role_id = rol.id" +
" order by u.id asc";
// +
// " limit 10";
List<ManageUser> users=null;
try{
users=jdbc.query(sql, adminManageUserMapper);
}
catch(EmptyResultDataAccessException ex){
// Handle case where no records were found
throw new EmptyResultDataAccessException("Did not find any records with selected id", 0);
}
catch (IncorrectResultSizeDataAccessException ex) {
// Handle case where multiple results were found
throw new IncorrectResultSizeDataAccessException("Multiple records generated, only one record expected",1);
}
catch (DataAccessException e) {
// Handle other database-related exceptions
throw new SQLException("Some unexpected database error occured.");
}
return users;
}
public AdminBoard getBoardManagementInfo() throws SQLException {
String sql="SELECT" +
"(SELECT COUNT(id) FROM users) AS total_users," +
"(SELECT COUNT(post_id) FROM feed) AS total_posts," +
"(SELECT COUNT(event_id) FROM event WHERE event_date > CURRENT_DATE) AS upcoming_events," +
"(SELECT COUNT(id) FROM comment WHERE DATEDIFF(CURRENT_DATE, created_date) <= 3) AS new_comments";
AdminBoard dashboard=null;
try{
dashboard=jdbc.queryForObject(sql, adminBoardMapper);
}
catch (IncorrectResultSizeDataAccessException ex) {
// Handle case where multiple results were found
throw new IncorrectResultSizeDataAccessException("Multiple records generated, only one record expected",1);
}
catch (DataAccessException e) {
// Handle other database-related exceptions
throw new SQLException("Some unexpected database error occured.");
}
return dashboard;
}
public int updateUserRole(User user){
// Validate input to ensure no null values are passed
if (user == null || user.getId() <= 0 || user.getRoleId() <= 0) {
throw new IllegalArgumentException("Invalid user or role details.");
}
// SQL query for updating the user's role and enabled status
String sql = "UPDATE users SET role_id = ?, enabled = ? WHERE id = ?";
try {
// Perform the update operation
int rowsUpdated = jdbc.update(sql, user.getRoleId(), user.getEnabled(), user.getId());
return rowsUpdated;
} catch (DataAccessException e) {
throw new RuntimeException("Database error occurred while updating user role.", e);
}
}
}
package polish_community_group_11.polish_community.admin.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AdminBoard {
private int totalNoOfUsers;
private int totalPosts;
private int upcomingEvents;
private int newComments;
}
package polish_community_group_11.polish_community.admin.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ManageUser {
private int id;
private String fullName;
private String email;
private Boolean enabled;
private int role_id;
private String role;
}
package polish_community_group_11.polish_community.admin.services;
import polish_community_group_11.polish_community.admin.models.AdminBoard;
import polish_community_group_11.polish_community.admin.models.ManageUser;
import polish_community_group_11.polish_community.register.models.User;
import java.sql.SQLException;
import java.util.List;
public interface AdminService {
List<ManageUser> getUserManagementInfo() throws SQLException;
AdminBoard getBoardManagementInfo() throws SQLException;
void updateUserRole(User user, String roleName);
void enableOrDisableUser(User user, Boolean enabled);
}
package polish_community_group_11.polish_community.admin.services;
import org.springframework.stereotype.Service;
import polish_community_group_11.polish_community.admin.dao.AdminRepository;
import polish_community_group_11.polish_community.admin.models.AdminBoard;
import polish_community_group_11.polish_community.admin.models.ManageUser;
import polish_community_group_11.polish_community.register.models.User;
import java.sql.SQLException;
import java.util.List;
@Service
public class AdminServiceImpl implements AdminService {
private final AdminRepository adminRepository;
public AdminServiceImpl(AdminRepository adminRepository) {
this.adminRepository = adminRepository;
}
public List<ManageUser> getUserManagementInfo() throws SQLException {
return adminRepository.getUserManagementInfo();
}
public AdminBoard getBoardManagementInfo() throws SQLException{
return adminRepository.getBoardManagementInfo();
}
public void updateUserRole(User user, String roleName){
int newRoleId=roleName.toLowerCase().contains("admin")?1:2;
boolean needsUpdate=user.getRoleId()==newRoleId?false:true;
if(needsUpdate){
user.setRoleId(newRoleId);
adminRepository.updateUserRole(user);
}
}
public void enableOrDisableUser(User user, Boolean enabled){
boolean needsUpdate=(enabled==user.getEnabled())?false:true;
if(needsUpdate){
user.setEnabled(enabled);
adminRepository.updateUserRole(user);
}
}
}
package polish_community_group_11.polish_community.contact.Controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
@Controller
public class Contact {
@GetMapping("/contactus")
public ModelAndView home(){
ModelAndView modelAndView = new ModelAndView("contact/contact");
return modelAndView;
}
}
package polish_community_group_11.polish_community.event.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import polish_community_group_11.polish_community.event.services.EventRepository;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import polish_community_group_11.polish_community.event.models.viewmodel.EventForm;
import org.springframework.web.bind.annotation.*;
import polish_community_group_11.polish_community.event.models.Event;
import polish_community_group_11.polish_community.event.models.EventImpl;
import polish_community_group_11.polish_community.event.services.EventService;
import polish_community_group_11.polish_community.register.services.UserService;
import java.security.Principal;
import java.sql.SQLException;
@Controller
public class EventController {
// Inject the EventRepository service to handle event-related data operations
private EventRepository eventService;
private EventService eventService;
private UserService userService;
@Autowired
// Constructor-based dependency injection for EventRepository
public EventController(EventRepository eventService){
public EventController(EventService eventService, UserService userService) {
this.eventService = eventService;
this.userService = userService;
}
// Controller method to handle GET requests for the "/event" URL
......@@ -50,4 +67,65 @@ public class EventController {
// Return the populated ModelAndView object, which will render the event details view
return modelAndView;
}
//Controller Method to load create new event page
@GetMapping("event/add")
public ModelAndView addEvent() {
ModelAndView modelAndView = new ModelAndView("event/add-event");
//Passing Form object for validation
modelAndView.addObject("event", new EventForm());
/* Form action string to check the type of action to perform and dynamically
use the same form for both create and update */
modelAndView.addObject("formAction", "/event/add");
return modelAndView;
}
@PostMapping("event/add")
public ModelAndView addEvent(@Valid @ModelAttribute("event") EventForm event,
BindingResult bindingResult, Model model,
Principal principal, RedirectAttributes redirectAttributes) throws SQLException {
ModelAndView modelAndView = new ModelAndView("event/add-event");
if(bindingResult.hasErrors()) {
modelAndView.addObject(model.asMap());
/* Form action string to check the type of action to perform and dynamically
use the same form for both create and update */
modelAndView.addObject("formAction", "/event/add");
}
else{
if(event==null){
throw new NullPointerException("New event is empty or null");
}
eventService.addNewEvent(event.processEventForm(),principal.getName());
redirectAttributes.addFlashAttribute("successMessage", "Event created successfully!");
modelAndView.setViewName("redirect:/event");
}
return modelAndView;
}
//Update Events
@GetMapping("event/edit/{id}")
public ModelAndView editEvent(@PathVariable int id) {
EventForm event = eventService.getEventById(id).processEventToEventForm();
ModelAndView modelAndView = new ModelAndView("event/add-event");
modelAndView.addObject("event", event);
modelAndView.addObject("formAction", "/event/edit");
return modelAndView;
}
@PostMapping("/event/edit")
public ModelAndView editEvent(@Valid @ModelAttribute("event") EventForm event,
BindingResult bindingResult, Model model) throws SQLException {
ModelAndView modelAndView = new ModelAndView("event/add-event");
if (bindingResult.hasErrors()) {
modelAndView.addObject(model.asMap());
modelAndView.addObject("formAction", "/event/edit");
} else {
eventService.getEditEvent(event.processEventForm());
modelAndView.setViewName("redirect:/event");
}
return modelAndView;
}
}
package polish_community_group_11.polish_community.event.services;
package polish_community_group_11.polish_community.event.dao;
import polish_community_group_11.polish_community.event.models.Event;
import java.sql.SQLException;
import java.util.List;
public interface EventRepository {
......@@ -8,4 +10,6 @@ public interface EventRepository {
List<Event> getAllEvents();
Event getEventById(int id);
void addNewEvent(Event newEvent) throws SQLException;
Event editEvent(Event event)throws SQLException;
}
package polish_community_group_11.polish_community.event.services;
package polish_community_group_11.polish_community.event.dao;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.event.models.Event;
import polish_community_group_11.polish_community.event.models.EventImpl;
import java.sql.SQLException;
import java.util.List;
@Repository // Marks this class as a Spring Data repository for database interaction
public class EventRepositoryImpl implements EventRepository {
// JdbcTemplate instance for executing SQL queries
private JdbcTemplate jdbc;
private final JdbcTemplate jdbc;
// RowMapper to map SQL result set rows to Event objects
private RowMapper<Event> eventItemMapper;
......@@ -52,7 +55,7 @@ public class EventRepositoryImpl implements EventRepository {
// Method to retrieve all events from the database
public List<Event> getAllEvents() {
String sql = "select * from event";
String sql = "select * from event order by event_id desc";
return jdbc.query(sql, eventItemMapper);
}
......@@ -74,4 +77,64 @@ public class EventRepositoryImpl implements EventRepository {
return event;
}
public void addNewEvent(Event newEvent) throws SQLException, NullPointerException{
if(newEvent==null){
throw new NullPointerException("Event cannot be null");
}
String dbInsertSql =
"insert into event " +
"(event_title, event_description, location, " +
"event_date, event_time,user_id, event_poster_url,whyJoin,benefits)" +
" values (?,?,?,?,?,?,?,?,?)";
try{
jdbc.update(dbInsertSql,
newEvent.getEvent_title(),
newEvent.getDescription(),
newEvent.getDescription(),
newEvent.getEvent_date(),
newEvent.getEvent_time(),
newEvent.getUser_id(),
newEvent.getImageUrl(),
newEvent.getWhyJoin(),
newEvent.getBenefits()
);
}
catch (DataAccessException e) {
throw new SQLException("Failed to insert new information record", e);
}
}
// Updates selected record with new updated information
public Event editEvent(Event event)throws SQLException {
String updateSql = "UPDATE event " +
"SET event_title = ?, event_description = ?, " +
"event_date = ?, event_time = ?, " +
"location = ?, user_id = ?, event_poster_url = ?, " +
"whyJoin = ?, benefits = ? " +
"WHERE event_id = ?";
try {
// jdbc.update() is a method that will execute the sql query
// replaces the ? with the actual values from the news object
int rowsAffected = jdbc.update(updateSql,
event.getEvent_title(),
event.getDescription(),
event.getEvent_date(),
event.getEvent_time(),
event.getLocation(),
event.getUser_id(),
event.getImageUrl(),
event.getWhyJoin(),
event.getBenefits(),
event.getEvent_id()
);
// error handling
if (rowsAffected == 0) {
throw new SQLException("No event item was updated. Check the ID provided.");
}
} catch (DataAccessException e) {
throw new SQLException("Error updating event with ID: " + event.getEvent_id(), e);
}
return event;
}
}
package polish_community_group_11.polish_community.event.models;
import polish_community_group_11.polish_community.event.models.viewmodel.EventForm;
import java.time.LocalDate;
import java.time.LocalTime;
......@@ -27,4 +29,5 @@ public interface Event {
public String getBenefits();
public void setBenefits(String benefits);
EventForm processEventToEventForm();
}
package polish_community_group_11.polish_community.event.models;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import polish_community_group_11.polish_community.event.models.viewmodel.EventForm;
import java.time.LocalDate;
import java.time.LocalTime;
......@@ -20,4 +26,12 @@ public class EventImpl implements Event{
private String whyJoin;
private String benefits;
public EventForm processEventToEventForm(){
EventForm eventForm = new EventForm(
event_id, event_title, description, event_date, event_time,
location, user_id, imageUrl, whyJoin, benefits
);
return eventForm;
}
}
package polish_community_group_11.polish_community.event.models.viewmodel;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.URL;
import polish_community_group_11.polish_community.event.models.Event;
import polish_community_group_11.polish_community.event.models.EventImpl;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EventForm {
private int event_id;
@NotEmpty(message = "Please enter the event title")
private String event_title;
@NotEmpty(message = "Please enter the event description")
private String description;
@FutureOrPresent(message = "The date cannot be in the past")
@NotNull(message = "Please enter the event date")
private LocalDate event_date;
@NotNull(message = "Please enter the time of the event")
private LocalTime event_time;
@NotEmpty(message = "Please provide the location of event")
private String location;
private int user_id;
@NotEmpty(message = "Please provide event image url")
@Pattern(regexp = ".*\\.(png|jpg|jpeg|gif).*", message = "Must be a valid image (png, jpg, jpeg, gif).")
@URL(message = "Not a valid image url")
private String imageUrl;
private String whyJoin;
private String benefits;
public Event processEventForm(){
if (event_title == null || event_title.isEmpty()) {
throw new IllegalArgumentException("Event title is required");
}
if (event_date == null) {
throw new IllegalArgumentException("Event date is required");
}
if (event_time == null) {
throw new IllegalArgumentException("Event time is required");
}
if (location == null || location.isEmpty()) {
throw new IllegalArgumentException("Location is required");
}
Event event = new EventImpl(
event_id, event_title, description, event_date, event_time,
location, user_id, imageUrl, whyJoin, benefits
);
return event;
}
}
package polish_community_group_11.polish_community.event.services;
import polish_community_group_11.polish_community.event.models.Event;
import java.sql.SQLException;
import java.util.List;
public interface EventService {
List<Event> getAllEvents();
Event getEventById(int id);
void addNewEvent(Event newEvent, String email) throws SQLException;
Event getEditEvent(Event event) throws SQLException;
}
\ No newline at end of file
package polish_community_group_11.polish_community.event.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import polish_community_group_11.polish_community.event.dao.EventRepository;
import polish_community_group_11.polish_community.event.models.Event;
import polish_community_group_11.polish_community.register.services.UserService;
import java.sql.SQLException;
import java.util.List;
@Service
public class EventServiceImpl implements EventService {
private final EventRepository eventRepository;
private final UserService userService;
@Autowired
public EventServiceImpl(EventRepository eventRepository, UserService userService) {
this.eventRepository = eventRepository;
this.userService=userService;
}
public List<Event> getAllEvents(){
return eventRepository.getAllEvents();
}
public Event getEventById(int id){
return eventRepository.getEventById(id);
}
public void addNewEvent(Event newEvent, String email) throws SQLException {
newEvent.setUser_id(userService.findUserIdByEmail(email));
eventRepository.addNewEvent(newEvent);
}
public Event getEditEvent(Event event) throws SQLException {
return eventRepository.editEvent(event);
}
}
package polish_community_group_11.polish_community.feed;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${file.upload-dir}")
private String uploadDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:" + uploadDir + "/");
}
}
\ No newline at end of file
package polish_community_group_11.polish_community.feed.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import polish_community_group_11.polish_community.feed.repository.FeedRepository;
import polish_community_group_11.polish_community.feed.services.FeedService;
import polish_community_group_11.polish_community.feed.services.FileStorageService;
import polish_community_group_11.polish_community.register.models.User;
import polish_community_group_11.polish_community.register.services.UserService;
import java.util.List;
......@@ -14,18 +23,53 @@ import java.util.List;
public class FeedApisController {
private final FeedRepository feedRepository;
private final UserService userService;
private final FeedService feedService;
private final FileStorageService fileStorageService;
private static final Logger log = LoggerFactory.getLogger(FeedApisController.class);
public FeedApisController(FeedRepository feedRepository, FeedService feedService) {
public FeedApisController(FeedRepository feedRepository, FeedService feedService, UserService userService, FileStorageService fileStorageService) {
this.feedService = feedService;
this.feedRepository = feedRepository;
this.userService = userService;
this.fileStorageService = fileStorageService;
}
// getting all posts
@GetMapping
public List<FeedImpl> getAllPosts() {
return feedRepository.getAllPosts();
log.info("Fetching all posts");
// getting current user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = null;
if (auth != null && auth.isAuthenticated() && !auth.getPrincipal().equals("anonymousUser")) {
String email = auth.getName();
log.info("User Email: " + email);
currentUser = userService.findByEmail(email);
log.info("Current User: " + currentUser);
}
List<FeedImpl> posts = feedRepository.getAllPosts();
if (currentUser != null){
// set isDeletable flag and isEditable flag for each post depedant on whether they are an admin or own the post
for (FeedImpl post : posts) {
log.info("Role ID: " + currentUser.getRoleId());
boolean isSuperAdmin = currentUser != null && currentUser.getRoleId() == 1;
log.info("IsSuperAdmin: " + isSuperAdmin);
boolean isOwner = currentUser != null && post.getUserId() == currentUser.getId();
log.info("IsPostOwner: " + isOwner);
post.setIsDeletable(isSuperAdmin || isOwner);
post.setIsEditable( isOwner);
log.info("PostIsEditable: " + post.getIsDeletable());
}
}
return posts;
}
//getting them by id
......@@ -40,70 +84,127 @@ public class FeedApisController {
}
// creating a new post
@PostMapping("/add")
public ResponseEntity<?> addNewPost(@RequestBody FeedImpl feed) {
public ResponseEntity<?> addNewPost(
@RequestPart("post") FeedImpl feed,
@RequestPart(value = "image", required = false) MultipartFile image) {
try {
if (image != null && !image.isEmpty()) {
String imageUrl = fileStorageService.storeFile(image);
feed.setPostImageUrl(imageUrl);
}
feedService.addNewFeedPost(feed);
return ResponseEntity.ok().body("Post created successfully");
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating post: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error creating post: " + e.getMessage());
}
}
// updating the post
@PutMapping("/{postId}")
public ResponseEntity<Void> updatePost(@PathVariable int postId, @RequestBody FeedImpl feed) {
@PatchMapping("/{postId}")
public ResponseEntity<?> updatePost(
@PathVariable int postId,
@RequestPart("post") FeedImpl feed,
@RequestPart(value = "image", required = false) MultipartFile image) {
try {
if (image != null && !image.isEmpty()) {
String imageUrl = fileStorageService.storeFile(image);
feed.setPostImageUrl(imageUrl);
} else {
FeedImpl existingPost = feedRepository.getPostById(postId);
if (existingPost != null) {
feed.setPostImageUrl(existingPost.getPostImageUrl());
}
}
feedRepository.updatePost(postId, feed);
return ResponseEntity.ok().build();
return ResponseEntity.ok().body("Post updated successfully");
} catch (Exception e) {
return ResponseEntity.notFound().build();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error updating post: " + e.getMessage());
}
}
// deleting a post
@DeleteMapping("/{postId}")
public ResponseEntity<Void> deletePost(@PathVariable int postId) {
try {
// get logged in user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
FeedImpl post = feedRepository.getPostById(postId);
if (post == null) {
return ResponseEntity.notFound().build();
}
// get current user
UserDetails userDetails = (UserDetails) auth.getPrincipal();
User currentUser = userService.findByEmail(userDetails.getUsername());
// check if admin or post owner
boolean isSuperAdmin = currentUser.getRoleId() == 1;
boolean isPostOwner = post.getUserId() == currentUser.getId();
if (!isSuperAdmin && !isPostOwner) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
feedRepository.deletePost(postId);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.notFound().build();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
// liking a post
@PostMapping("/{postId}/like")
public ResponseEntity<Void> likePost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Void> likePost(@PathVariable int postId) {
try {
feedRepository.likePost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
feedRepository.likePost(postId, currentUser.getId());
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// removing a like from post
// remove like from post
@DeleteMapping("/{postId}/like")
public ResponseEntity<Void> unlikePost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Void> unlikePost(@PathVariable int postId) {
try {
feedRepository.unlikePost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
feedRepository.unlikePost(postId, currentUser.getId());
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// getting list of likes from a post
// check if already liked
@GetMapping("/{postId}/hasLiked")
public ResponseEntity<Boolean> hasUserLikedPost(@PathVariable int postId, @RequestParam int userId) {
public ResponseEntity<Boolean> hasUserLikedPost(@PathVariable int postId) {
try {
boolean hasLiked = feedRepository.hasUserLikedPost(postId, userId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findByEmail(auth.getName());
boolean hasLiked = feedRepository.hasUserLikedPost(postId, currentUser.getId());
return ResponseEntity.ok(hasLiked);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment