Skip to content

Sign up #231

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

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ dependency-reduced-pom.xml
.factorypath
.project
.settings/
application.yml
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Acebook

https://trello.com/b/VidgaAkH/acebook-engineering-project-2

The application uses:
- `maven` to build the project
- `thymeleaf` for templating
Expand Down
3 changes: 3 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<scope>provided</scope>
</dependency>
<dependency>
Expand Down Expand Up @@ -102,6 +103,7 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand All @@ -114,6 +116,7 @@
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
</annotationProcessorPaths>
</configuration>
Expand Down
Binary file added src/.DS_Store
Binary file not shown.
Binary file added src/main/.DS_Store
Binary file not shown.
Binary file added src/main/java/.DS_Store
Binary file not shown.
Binary file added src/main/java/com/.DS_Store
Binary file not shown.
Binary file added src/main/java/com/makersacademy/.DS_Store
Binary file not shown.
Binary file not shown.
15 changes: 15 additions & 0 deletions src/main/java/com/makersacademy/acebook/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.makersacademy.acebook.config;

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 {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/user_profile/**")
.addResourceLocations("file:uploads/user_profile/");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.makersacademy.acebook.controller;

import com.makersacademy.acebook.model.Friend;
import com.makersacademy.acebook.model.FriendRequest;
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.FriendRepository;
import com.makersacademy.acebook.repository.FriendRequestRepository;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
public class FriendsController {

@Autowired
FriendRequestRepository friendRequestRepository;
@Autowired
FriendRepository friendRepository;
@Autowired
UserRepository userRepository;

@GetMapping("/friends")
public ModelAndView friendList(@AuthenticationPrincipal(expression = "attributes['email']") String email) {
ModelAndView modelAndView = new ModelAndView("friends/friends");

// User!
Optional<User> userOptional = userRepository.findUserByUsername(email);

User currentUser = userOptional.get();
Long userId = currentUser.getId();

// Friends!
List<Friend> friendsList = friendRepository.findAllByMainUserId(userId);

// Objectify!
List<User> friendUsers = new ArrayList<>();
for (Friend friend : friendsList) {
Long friendId = friend.getFriendUserId();
Optional<User> friendUser = userRepository.findById(friendId);
if (friendUser.isPresent()) {
friendUsers.add(friendUser.get());
}
}

// Friend Requests!
List<FriendRequest> pendingRequests = friendRequestRepository.findAllByReceiverIdAndStatus(userId, "pending");

// Objectify!
List<User> requesterUsers = new ArrayList<>();
for (FriendRequest request : pendingRequests) {
Long requesterId = request.getRequesterId();
Optional<User> requesterUser = userRepository.findById(requesterId);
if (requesterUser.isPresent()) {
requesterUsers.add(requesterUser.get());
}
}

modelAndView.addObject("friendUsers", friendUsers);
modelAndView.addObject("requesterUsers", requesterUsers);

return modelAndView;

// @PostMapping("/friends")
// public RedirectView create(@ModelAttribute Friend friend, @AuthenticationPrincipal(expression = "attributes['email']") String email) {
// Optional<User> user = userRepository.findUserByUsername(email);
// if (user.isPresent()) {
// Long id = user.get().getId();
// }
// return new RedirectView("friends/friends");
// }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

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

@Controller
public class HomeController {
@RequestMapping(value = "/")
public RedirectView index() {
return new RedirectView("/posts");
public ModelAndView index() {
return new ModelAndView("/landing");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.makersacademy.acebook.controller;

import com.makersacademy.acebook.model.Notification;
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.NotificationRepository;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.*;

@Controller
public class NotificationsController {

@Autowired
NotificationRepository notificationRepository;
@Autowired
UserRepository userRepository;

@GetMapping("/notifications")
public String index(Model model) {
List<Notification> notifications = new ArrayList<>();
notificationRepository.findAll().forEach(notifications::add);
Collections.reverse(notifications);
Map<Long, String> senderNames = new HashMap<>();
for (Notification notification : notifications) {
Optional<User> sender = userRepository.findById(notification.getSending_user_id());
sender.ifPresent(user -> senderNames.put(notification.getId(), user.getUsername())); //needs updated with proper User getFirstName
}
model.addAttribute("notifications", notifications);
model.addAttribute("senderNames", senderNames);
return "notifications/index";
}
//
// @PostMapping("/notifications")
// public RedirectView markAsRead(@ModelAttribute Notification notification) {
// Optional<Notification> readNotification = notificationRepository.findById(1L);
// if (readNotification.isPresent()) {
// Notification notif = readNotification.get();
// notif.set_read(true);
// notificationRepository.save(notif);
// }
//// notification.set_read(true);
// return new RedirectView("/notifications");
// }
}
Original file line number Diff line number Diff line change
@@ -1,32 +1,56 @@
package com.makersacademy.acebook.controller;

import com.makersacademy.acebook.model.Post;
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.PostRepository;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

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

@Controller
public class PostsController {

@Autowired
PostRepository repository;
PostRepository postRepository;

@Autowired
UserRepository userRepository;

@GetMapping("/posts")
public String index(Model model) {
Iterable<Post> posts = repository.findAll();
Iterable<Post> posts = postRepository.findAll();
model.addAttribute("posts", posts);
model.addAttribute("post", new Post());

DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();

String username = (String) principal.getAttributes().get("email");
User user = userRepository.findUserByUsername(username).get();
model.addAttribute("user", user);

return "posts/index";
}

@PostMapping("/posts")
public RedirectView create(@ModelAttribute Post post) {
repository.save(post);
public RedirectView create(@ModelAttribute Post post, @AuthenticationPrincipal(expression = "attributes['email']") String email) {
Optional<User> user = userRepository.findUserByUsername(email);
if (user.isPresent()) {
post.setUser_id(user.get().getId());
postRepository.save(post);
}
return new RedirectView("/posts");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,31 @@
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Optional;

@RestController
public class UsersController {
@Autowired
UserRepository userRepository;

@Value("${file.upload-dir}")
private String uploadDir;

@GetMapping("/users/after-login")
public RedirectView afterLogin() {
DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder
Expand All @@ -21,10 +36,90 @@ public RedirectView afterLogin() {
.getPrincipal();

String username = (String) principal.getAttributes().get("email");
String first_name = (String) principal.getAttributes().get("given_name");
String last_name = (String) principal.getAttributes().get("family_name");
String profile_pic = "/images/profile/default.jpg";
userRepository
.findUserByUsername(username)
.orElseGet(() -> userRepository.save(new User(username)));
.orElseGet(() -> userRepository.save(new User(username, first_name, last_name, profile_pic)));

return new RedirectView("/posts");
}

@GetMapping("/settings")
public ModelAndView settings(){
DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();

String username = (String) principal.getAttributes().get("email");
User userByEmail = userRepository.findUserByUsername(username).get();
// Optional<User> user = userRepository.findById(userByEmail.getId());
ModelAndView settings = new ModelAndView("/users/settings");
settings.addObject("user", userByEmail);
return settings;
}

@PostMapping("/settings")
public RedirectView update(@ModelAttribute User userFromForm, @RequestParam("file") MultipartFile file) {
DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();

String email = (String) principal.getAttributes().get("email");

User userInDb = userRepository.findUserByUsername(email)
.orElseThrow(() -> new IllegalArgumentException("User not found"));

try {
if (!file.isEmpty()) {
String fileName = saveImage(file, userInDb.getId().toString()); // Save to disk
userInDb.setProfile_pic("/images/user_profile/" + fileName); // Or adjust path
}
} catch (IOException e) {
e.printStackTrace(); // optionally log it
return new RedirectView("/settings?error=file");
}

userInDb.setFirst_name(userFromForm.getFirst_name());
userInDb.setLast_name(userFromForm.getLast_name());

userRepository.save(userInDb);

return new RedirectView("/settings");
}


private String saveImage(MultipartFile file, String userId) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}

String contentType = file.getContentType();
if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
throw new IllegalArgumentException("Only JPEG or PNG images are allowed");
}

String fileName = file.getOriginalFilename();
String extension = getFileExtension(fileName);
String newFileName = userId + extension;
Path filePath = uploadPath.resolve(newFileName);
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

return newFileName;
}

public static String getFileExtension(String fileName) {
Path path = Paths.get(fileName);
return Optional.ofNullable(path.getFileName())
.map(Path::toString)
.filter(f -> f.contains("."))
.map(f -> f.substring(f.lastIndexOf(".")))
.orElse("");
}


}
Loading