Skip to content

Commit

Permalink
Merge pull request #31 from AcebookRedPanda/feature/like
Browse files Browse the repository at this point in the history
Feature/like
  • Loading branch information
neily2nd authored Jun 14, 2024
2 parents e22f6b3 + 637ef6f commit 11c8087
Show file tree
Hide file tree
Showing 8 changed files with 215 additions and 159 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>


</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import com.makersacademy.acebook.model.User;
import com.makersacademy.acebook.repository.AuthoritiesRepository;
import com.makersacademy.acebook.repository.UserRepository;
import com.makersacademy.acebook.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
Expand All @@ -13,6 +15,13 @@
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;





import java.util.Objects;


@Controller
Expand All @@ -22,6 +31,8 @@ public class UsersController {
UserRepository userRepository;
@Autowired
AuthoritiesRepository authoritiesRepository;
@Autowired
EmailService emailService;

@GetMapping("/register")
public String signup(Model model) {
Expand All @@ -30,13 +41,33 @@ public String signup(Model model) {
}

@PostMapping("/users")
public RedirectView signup(@ModelAttribute User user) {
userRepository.save(user);
Authority authority = new Authority(user.getUsername(), "ROLE_USER");
authoritiesRepository.save(authority);
return new RedirectView("/login");
public String signup(@ModelAttribute User user, Model model) {
try {
userRepository.save(user);
Authority authority = new Authority(user.getUsername(), "ROLE_USER");
authoritiesRepository.save(authority);

// Send confirmation email
emailService.sendSignUpConfirmation(user.getEmailAddress(), user.getUsername());

return "redirect:/login";
} catch (DataIntegrityViolationException e) {
if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
if (Objects.requireNonNull(e.getMessage()).contains("users.username")) {
model.addAttribute("errorMessage", "Username already exists. Please choose a different username.");
} else if (e.getMessage().contains("users.emailAddress")) {
model.addAttribute("errorMessage", "Email address already exists. Please use a different email.");
} else {
model.addAttribute("errorMessage", "A database error occurred. Please try again.");
}
} else {
model.addAttribute("errorMessage", "A database error occurred. Please try again.");
}
return "users/new";
}
}


@GetMapping("/profile")
public String showProfile(Model model) {
User currentUser = getCurrentUser();
Expand All @@ -45,19 +76,21 @@ public String showProfile(Model model) {
}

@PostMapping("/profile")
public RedirectView updateProfile(@ModelAttribute User user) {
public RedirectView updateProfile(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
User currentUser = getCurrentUser();
currentUser.setMobileNumber(user.getMobileNumber());
currentUser.setEmailAddress(user.getEmailAddress());
currentUser.setGender(user.getGender());
currentUser.setCountry(user.getCountry());
currentUser.setLanguage(user.getLanguage());
userRepository.save(currentUser);
redirectAttributes.addFlashAttribute("message", "Profile updated successfully.");


return new RedirectView("/profile");
}

private User getCurrentUser() {
// Assuming you're using Spring Security to manage user authentication
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username;
if (principal instanceof UserDetails) {
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/makersacademy/acebook/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String username;
private String password;
private boolean enabled = true;
// need be int
private String mobileNumber;
@Column(unique = true)
private String emailAddress;
private String gender;
private String country;
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/com/makersacademy/acebook/service/EmailService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.makersacademy.acebook.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

@Autowired
private JavaMailSender mailSender;

public void sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}

public void sendSignUpConfirmation(String to, String username) {
String subject = "Sign Up Confirmation";
String text = "Hey " + username + ",\n\nYour signup is confirmed. Welcome to Acebook!";
sendSimpleMessage(to, subject, text);
}
}
10 changes: 10 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,13 @@ spring.data.rest.base-path=/api
spring.datasource.platform=postgres
spring.jpa.hibernate.ddl-auto=validate
logging.level.org.springframework.web=DEBUG
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=${EMAIL_USERNAME}
spring.mail.password=${EMAIL_PASSWORD}

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.devtools.restart.additional-paths=src/main/java, src/main/resources
spring.devtools.restart.exclude=**/static/**,**/public/**,**/templates/**,**/META-INF/**,**/resources/**

66 changes: 35 additions & 31 deletions src/main/resources/templates/posts/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,32 @@
e.value = tempValue;
}

<!-- // Function to hide flash message after 5 seconds-->
<script>
function hideFlashMessage(id) {
setTimeout(function() {
var flashMessage = document.getElementById(id);
if (flashMessage) {
flashMessage.style.opacity = '0';
setTimeout(function() {
flashMessage.style.display = 'none';
}, 500); // Allow time for fade out
}
}, 5000);
}
function hideFlashMessage(id) {
setTimeout(function() {
var flashMessage = document.getElementById(id);
if (flashMessage) {
flashMessage.style.opacity = '0';
setTimeout(function() {
flashMessage.style.display = 'none';
}, 500); // Allow time for fade out
}
}, 5000);
}

<!-- // Call hideFlashMessage for each flash message on page load-->
window.onload = function() {
let flashMessages = document.getElementsByClassName('flash-message');
for (var i = 0; i < flashMessages.length; i++) {
let flashMessage = flashMessages[i];
if (flashMessage.innerText.trim() !== '') {
hideFlashMessage(flashMessage.id);
} else {
flashMessage.style.display = 'none';
window.onload = function() {
let flashMessages = document.getElementsByClassName('flash-message');
for (var i = 0; i < flashMessages.length; i++) {
let flashMessage = flashMessages[i];
if (flashMessage.innerText.trim() !== '') {
hideFlashMessage(flashMessage.id);
} else {
flashMessage.style.display = 'none';
}
}
}
}
</script>

</script>



<style>
Expand Down Expand Up @@ -271,6 +268,15 @@ <h1>Posts</h1>
</form>
</div>

<!-- Flash messages -->
<div id="flash-message-[[${post.id}]]-success" class="flash-message" th:if="${message}">
<p th:text="${message}"></p>
</div>
<div id="flash-message-[[${post.id}]]-error" class="flash-message error" th:if="${error}">
<p th:text="${error}"></p>
</div>


<!-- List of posts -->
<ul th:if="${not #lists.isEmpty(posts)}">
<!-- Iterate over each post and display its content -->
Expand Down Expand Up @@ -322,14 +328,12 @@ <h1>Posts</h1>
</form>
<hr>



<div th:if="${post.user.id == currentUser.id}">
<!-- Flash messages -->
<div id="flash-message-[[${post.id}]]" class="flash-message" th:if="${message}">
<p th:text="${message}"></p>
</div>
<div id="flash-error-[[${iterStat.index}]]" class="flash-message error" th:if="${error}">
<p th:text="${error}"></p>
</div>



<!-- Conditional Edit Form -->

<form th:action="@{'/posts/' + ${post.id} + '/edit'}" method="post" th:object="${post}">
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/templates/users/new.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<body>
<form action="#" th:action="@{/users}" th:object="${user}" method="post">
<p>Username: <input type="text" th:field="*{username}" /></p>
<p>Email: <input type="text" th:field="*{emailAddress}" /></p>
<p>Password: <input type="password" th:field="*{password}" /></p>
<p><input type="submit" value="Submit" id="submit"/> <input type="reset" value="Reset" /></p>
</form>
Expand Down
Loading

0 comments on commit 11c8087

Please sign in to comment.