From 1739e4347ef70f6d591b9367ab21d4046037b282 Mon Sep 17 00:00:00 2001 From: Andrew-Bernhardt Date: Sun, 27 Mar 2022 02:41:42 -0400 Subject: [PATCH 1/3] working on sending verification emails --- backend/pom.xml | 10 ++ .../backend/controller/AuthController.java | 72 +++++++- .../backend/controller/UserController.java | 155 +++++++++++------- .../recipes/fridger/backend/crud/Users.java | 4 + .../backend/mail/RegistrationListener.java | 2 +- .../recipes/fridger/backend/mail/Utility.java | 10 ++ .../recipes/fridger/backend/model/User.java | 3 + .../backend/model/VerificationToken.java | 4 +- .../fridger/backend/service/UserService.java | 12 +- .../backend/service/UserServiceImpl.java | 114 +++++++++++-- frontend/src/components/RegistrationForm.tsx | 2 +- 11 files changed, 300 insertions(+), 88 deletions(-) create mode 100644 backend/src/main/java/recipes/fridger/backend/mail/Utility.java diff --git a/backend/pom.xml b/backend/pom.xml index 919b4d83..3c823d1a 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -105,6 +105,16 @@ modelmapper 2.3.5 + + org.springframework + spring-webmvc + 5.3.10 + + + javax.servlet + javax.servlet-api + 4.0.1 + diff --git a/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java b/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java index 09036bc1..59f517f0 100644 --- a/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java +++ b/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java @@ -2,25 +2,30 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.repository.query.Param; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; import recipes.fridger.backend.dto.CreateAuthRequestDTO; import recipes.fridger.backend.dto.CreateUserDTO; import recipes.fridger.backend.dto.JwtTokenDTO; +import recipes.fridger.backend.mail.OnRegistrationCompleteEvent; +import recipes.fridger.backend.mail.Utility; +import recipes.fridger.backend.model.User; import recipes.fridger.backend.security.jwt.JwtUtils; import recipes.fridger.backend.security.services.UserDetailsImpl; import recipes.fridger.backend.service.UserService; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.List; +import java.util.UUID; import java.util.stream.Collectors; @RestController @@ -28,6 +33,9 @@ @RequestMapping(path = "/v1/auth") public class AuthController { + @Autowired + ApplicationEventPublisher eventPublisher; + @Autowired private UserService userService; @@ -40,6 +48,7 @@ public class AuthController { @Autowired JwtUtils jwtUtils; + //used to verifiy if user has an account @PostMapping(path = "/login") public ResponseEntity authenticateUser(@RequestBody CreateAuthRequestDTO u) { @@ -62,7 +71,7 @@ public class AuthController { @PostMapping(path = "/register") public ResponseEntity - createUser(@RequestBody @Valid CreateUserDTO u) { + createUser(@RequestBody @Valid CreateUserDTO u, HttpServletRequest request) { // Ensure email is unique log.info("attempting user create"); if(userService.getUserByEmail(u.getEmail()) != null) { @@ -70,9 +79,16 @@ public class AuthController { return ResponseEntity.badRequest().body("Account already exists"); } try { - log.info("halfway there to user creation"); - userService.createUser(u); + //Create user + User registered = userService.registerNewUserAccount(u, request); log.info("Successful creation of user"); + + //Send Verification Email To that user +// String siteURL = Utility.getSiteURL(request); //get site for verification email +// userService.createVerificationToken(registered, UUID.randomUUID().toString()); +// userService.sendVerificationEmail(registered,siteURL); +// log.info("Sent email to "+u.getEmail()); + return ResponseEntity.ok("Created user"); } catch (Exception e) { log.warn("Unable to create user\n" + e.getMessage()); @@ -80,4 +96,46 @@ public class AuthController { "Unable to create user\n" + e.getMessage()); } } + + @GetMapping("/verify") + public String verifyUser(@Param("code") String code) { + if (userService.verify(code)) { + return "verify_success"; + } else { + return "verify_fail"; + } + } + +// @PostMapping(path = "/register") +// public ResponseEntity +// createUser(@RequestBody @Valid CreateUserDTO u, HttpServletRequest request, Errors errors) { +// // Ensure email is unique +// log.info("attempting user create"); +// if(userService.getUserByEmail(u.getEmail()) != null) { +// log.info("already exists user" + u.getEmail()); +// return ResponseEntity.badRequest().body("Account already exists"); +// } +// try { +// log.info("Entering User Creation"); +// User registered = userService.registerNewUserAccount(u); +// +// String appURL = request.getContextPath(); +// eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered,request.getLocale(),appURL)); +// +// log.info("Successful creation of user"); +// return ResponseEntity.ok("Created user"); +// } catch (Exception e) { +// log.warn("Unable to create user\n" + e.getMessage()); +// return ResponseEntity.internalServerError().body( +// "Unable to create user\n" + e.getMessage()); +// } +// } + + @DeleteMapping(path = "/deleteUserAcct") + public void deleteUser(@RequestBody @Valid String email) { + if(userService.emailExistsPub(email)) { + log.info("user exists at this email: "+email); + userService.deleteUserByEmail(email); + } + } } diff --git a/backend/src/main/java/recipes/fridger/backend/controller/UserController.java b/backend/src/main/java/recipes/fridger/backend/controller/UserController.java index ede01a68..f247ab2e 100644 --- a/backend/src/main/java/recipes/fridger/backend/controller/UserController.java +++ b/backend/src/main/java/recipes/fridger/backend/controller/UserController.java @@ -103,46 +103,107 @@ public class UserController { */ //no verification -> this works and is tested - @PostMapping(path = "/") - public ResponseEntity - createUser(@RequestBody @Valid CreateUserDTO u) { - try { - userService.createUser(u); - log.info("Successful creation of user"); - return ResponseEntity.ok("Created user"); - } catch (Exception e) { - log.warn("Unable to create user\n" + e.getMessage()); - return ResponseEntity.internalServerError().body( - "Unable to create user\n" + e.getMessage()); - } - } +// @PostMapping(path = "/") +// public ResponseEntity +// createUser(@RequestBody @Valid CreateUserDTO u) { +// try { +// userService.createUser(u); +// log.info("Successful creation of user"); +// return ResponseEntity.ok("Created user"); +// } catch (Exception e) { +// log.warn("Unable to create user\n" + e.getMessage()); +// return ResponseEntity.internalServerError().body( +// "Unable to create user\n" + e.getMessage()); +// } +// } - //account verification of user - @PostMapping("/user/registration") - public ModelAndView registerUserAccount( - @ModelAttribute("user") @Valid CreateUserDTO userDto, - HttpServletRequest request, Errors errors) { - try { - User registered = userService.registerNewUserAccount(userDto); - log.info("inside registerUserAccount"); - - String appUrl = request.getContextPath(); - eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, - request.getLocale(), appUrl)); - } catch (UserAlreadyExistException uaeEx) { - ModelAndView mav = new ModelAndView("registration", "user", userDto); - mav.addObject("message", "An account for that username/email already exists."); - log.info("1st catch"); - return mav; - - } catch (RuntimeException ex) { - log.info("2nd catch"); - return new ModelAndView("emailError", "user", userDto); + //register user is in auth controller!! + + +// @PostMapping(path = "/register") +// public ResponseEntity +// createUser(@RequestBody @Valid CreateUserDTO u, HttpServletRequest request) { +// // Ensure email is unique +// log.info("attempting user create"); +// if(userService.getUserByEmail(u.getEmail()) != null) { +// log.info("already exists user" + u.getEmail()); +// return ResponseEntity.badRequest().body("Account already exists"); +// } +// try { +// //Create user +// User registered = userService.registerNewUserAccount(u); +// log.info("Successful creation of user"); +// +// //Send Verification Email To that user +// String siteURL = Utility.getSiteURL(request); //get site for verification email +// userService.sendVerificationEmail(registered,siteURL); +// log.info("Sent email to "+u.getEmail()); +// +// return ResponseEntity.ok("Created user"); +// } catch (Exception e) { +// log.warn("Unable to create user\n" + e.getMessage()); +// return ResponseEntity.internalServerError().body( +// "Unable to create user\n" + e.getMessage()); +// } +// } + +// //account verification of user +// @PostMapping("/user/registration") +// public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid CreateUserDTO userDto) { +// +// try { +//// if(userService.getUserByEmail(userDto.getEmail()) != null) { +//// log.info("already exists user" + userDto.getEmail()); +//// return new ModelAndView("registration","user",userDto); +//// } +// //This creates a new user, but the user's attribute "enabled" is set to false. +// //This must be set to true in order to sign in +// User registered = userService.registerNewUserAccount(userDto); +// log.info("Registered New Account"); +// +//// String appUrl = request.getContextPath(); +//// eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, +//// request.getLocale(), appUrl)); +// } catch (UserAlreadyExistException uaeEx) { +// ModelAndView mav = new ModelAndView("registration", "user", userDto); +// mav.addObject("message", "An account for that username/email already exists."); +// log.info("1st catch"); +// return mav; +// +// } catch (RuntimeException ex) { +// log.info("2nd catch"); +// return new ModelAndView("emailError", "user", userDto); +// +// } +// +// return new ModelAndView("successRegister", "user", userDto); +// } + + @GetMapping("/registrationConfirm") + public String confirmRegistration + (WebRequest request, Model model, @RequestParam("token") String token) { + Locale locale = request.getLocale(); + + VerificationToken verificationToken = userService.getVerificationToken(token); + if (verificationToken == null) { + String message = messages.getMessage("auth.message.invalidToken", null, locale); + model.addAttribute("message", message); + return "redirect:/badUser.html?lang=" + locale.getLanguage(); } - return new ModelAndView("successRegister", "user", userDto); + User user = verificationToken.getUser(); + Calendar cal = Calendar.getInstance(); + if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) { + String messageValue = messages.getMessage("auth.message.expired", null, locale); + model.addAttribute("message", messageValue); + return "redirect:/badUser.html?lang=" + locale.getLanguage(); + } + + user.setEnabled(true); + userService.saveRegisteredUser(user); + return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); } @PreAuthorize("hasAnyRole('USER', 'ADMIN')") @@ -219,31 +280,7 @@ public ResponseEntity deleteUser(@PathVariable Long id) { } } - @GetMapping("/registrationConfirm") - public String confirmRegistration - (WebRequest request, Model model, @RequestParam("token") String token) { - - Locale locale = request.getLocale(); - - VerificationToken verificationToken = userService.getVerificationToken(token); - if (verificationToken == null) { - String message = messages.getMessage("auth.message.invalidToken", null, locale); - model.addAttribute("message", message); - return "redirect:/badUser.html?lang=" + locale.getLanguage(); - } - - User user = verificationToken.getUser(); - Calendar cal = Calendar.getInstance(); - if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) { - String messageValue = messages.getMessage("auth.message.expired", null, locale); - model.addAttribute("message", messageValue); - return "redirect:/badUser.html?lang=" + locale.getLanguage(); - } - user.setEnabled(true); - userService.saveRegisteredUser(user); - return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); - } //@PreAuthorization("hasRole('USER') or hasRole(‘ADMIN’)") diff --git a/backend/src/main/java/recipes/fridger/backend/crud/Users.java b/backend/src/main/java/recipes/fridger/backend/crud/Users.java index 6d2c4dc3..fcc81389 100644 --- a/backend/src/main/java/recipes/fridger/backend/crud/Users.java +++ b/backend/src/main/java/recipes/fridger/backend/crud/Users.java @@ -19,4 +19,8 @@ public interface Users extends CrudRepository { @Query("select u from User u where (u.email = :email)") User findByEmailAuth(String email); + + @Query("SELECT u FROM User u WHERE u.verificationCode = ?1") + public User findByVerificationCode(String code); + } diff --git a/backend/src/main/java/recipes/fridger/backend/mail/RegistrationListener.java b/backend/src/main/java/recipes/fridger/backend/mail/RegistrationListener.java index ad1ac48a..794f0fce 100644 --- a/backend/src/main/java/recipes/fridger/backend/mail/RegistrationListener.java +++ b/backend/src/main/java/recipes/fridger/backend/mail/RegistrationListener.java @@ -45,7 +45,7 @@ private void confirmRegistration(OnRegistrationCompleteEvent event) { userService.createVerificationToken(user, token); String recipientAddress = user.getEmail(); - String subject = "Fridger Registration Confirmation"; + String subject = "Fridger New Account Confirmation"; String confirmationUrl = event.getAppUrl() + "/registrationConfirm.html?token=" + token; String message = messages.getMessage("message.regSucc", null, event.getLocale()); diff --git a/backend/src/main/java/recipes/fridger/backend/mail/Utility.java b/backend/src/main/java/recipes/fridger/backend/mail/Utility.java new file mode 100644 index 00000000..a452b895 --- /dev/null +++ b/backend/src/main/java/recipes/fridger/backend/mail/Utility.java @@ -0,0 +1,10 @@ +package recipes.fridger.backend.mail; + +import javax.servlet.http.HttpServletRequest; + +public class Utility { + public static String getSiteURL(HttpServletRequest request) { + String siteURL = request.getRequestURL().toString(); + return siteURL.replace(request.getServletPath(),""); + } +} diff --git a/backend/src/main/java/recipes/fridger/backend/model/User.java b/backend/src/main/java/recipes/fridger/backend/model/User.java index 99be4a7f..c2907b49 100644 --- a/backend/src/main/java/recipes/fridger/backend/model/User.java +++ b/backend/src/main/java/recipes/fridger/backend/model/User.java @@ -33,6 +33,9 @@ public class User { @Column(name = "enabled") private boolean enabled; + @Column(name = "verification_code", length = 64) + private String verificationCode; + @Size(min = 0, max = 100) @Column(name = "password") private String password; diff --git a/backend/src/main/java/recipes/fridger/backend/model/VerificationToken.java b/backend/src/main/java/recipes/fridger/backend/model/VerificationToken.java index 134b6333..d568a89b 100644 --- a/backend/src/main/java/recipes/fridger/backend/model/VerificationToken.java +++ b/backend/src/main/java/recipes/fridger/backend/model/VerificationToken.java @@ -26,9 +26,9 @@ public class VerificationToken { public VerificationToken() { //default contructor } - public VerificationToken(User u, String tokn) { + public VerificationToken(User u, String tok) { user = u; - token = tokn; + token = tok; } private Date calculateExpiryDate(int expiryTimeInMinutes) { diff --git a/backend/src/main/java/recipes/fridger/backend/service/UserService.java b/backend/src/main/java/recipes/fridger/backend/service/UserService.java index dae9aab3..30e4b4cf 100644 --- a/backend/src/main/java/recipes/fridger/backend/service/UserService.java +++ b/backend/src/main/java/recipes/fridger/backend/service/UserService.java @@ -5,17 +5,25 @@ import recipes.fridger.backend.model.User; import recipes.fridger.backend.model.VerificationToken; +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import java.io.UnsupportedEncodingException; + public interface UserService { public void createUser(CreateUserDTO dto); public void deleteUser(Long id); public User getUser(Long id); public void updateUser(Long id, UpdateUserDTO u) throws Exception; - + public boolean emailExistsPub(String email); public Iterable getUsersByIdAndEmail(Long id, String email); public Iterable getUsers(Long userId); + public void testSendEmail(CreateUserDTO dto); + public void sendVerificationEmail(User user, String url) throws MessagingException, UnsupportedEncodingException; + public boolean verify(String verificationCode); + public void deleteUserByEmail(String email); public User getUserByEmail(String email); public void saveRegisteredUser(User user); public void createVerificationToken(User user, String token); VerificationToken getVerificationToken(String token); - public User registerNewUserAccount(CreateUserDTO dto); + public User registerNewUserAccount(CreateUserDTO dto, HttpServletRequest request) throws MessagingException, UnsupportedEncodingException; } diff --git a/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java b/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java index f66742e3..58fd6990 100644 --- a/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java +++ b/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java @@ -1,9 +1,11 @@ package recipes.fridger.backend.service; import lombok.extern.slf4j.Slf4j; +import net.bytebuddy.utility.RandomString; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -13,16 +15,22 @@ import recipes.fridger.backend.dto.CreateUserDTO; import recipes.fridger.backend.mail.UserAlreadyExistException; import recipes.fridger.backend.dto.UpdateUserDTO; +import recipes.fridger.backend.mail.Utility; import recipes.fridger.backend.model.Role; import recipes.fridger.backend.model.RoleEnum; import recipes.fridger.backend.model.User; import recipes.fridger.backend.model.VerificationToken; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; +import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Optional; import java.util.Set; +import java.util.UUID; @Slf4j @Service @@ -51,7 +59,7 @@ public void createUser(CreateUserDTO dto) { User u = new User(); u.setEmail(dto.getEmail()); - sendVerificationEmail(dto); + testSendEmail(dto); u.setEnabled(true); //make the account not true until user registers with email u.setPassword(passwordEncoder.encode(dto.getPassword())); @@ -69,27 +77,18 @@ public void createUser(CreateUserDTO dto) { users.save(u); } - public void sendVerificationEmail(CreateUserDTO dto) { - SimpleMailMessage email = new SimpleMailMessage(); - email.setFrom("noreplyfridger@gmail.com"); - email.setTo(dto.getEmail()); - email.setSubject("Welcome To Fridger!"); - email.setText("Dear" + dto.getName() + ",\n" + - "We are excited to have you join our fridger community! Thank you " + - "for signing up with us!"); - mailSender.send(email); - log.info("Sending confirmation email to " + dto.getEmail()); - } - - //still under testing @Override - public User registerNewUserAccount(CreateUserDTO dto) { + public User registerNewUserAccount(CreateUserDTO dto, HttpServletRequest request) + throws MessagingException, UnsupportedEncodingException { if (emailExists(dto.getEmail())) { - throw new UserAlreadyExistException("There is an account with this email address: " + dto.getEmail()); + throw new UserAlreadyExistException( + "There is an account with this email address: " + + dto.getEmail()); } User u = new User(); u.setEmail(dto.getEmail()); u.setEnabled(false); + u.setVerificationCode(RandomString.make(64)); u.setPassword(passwordEncoder.encode(dto.getPassword())); u.setName(dto.getName()); u.setBio(dto.getBio()); @@ -97,6 +96,7 @@ public User registerNewUserAccount(CreateUserDTO dto) { u.setHeight_in(dto.getHeight_in()); u.setWeight_lb(dto.getWeight_lb()); + Set userRoles = new HashSet<>(); userRoles.add(roles.findByName(RoleEnum.ROLE_USER).orElseThrow( () -> new RuntimeException("Role not found") @@ -104,10 +104,81 @@ public User registerNewUserAccount(CreateUserDTO dto) { u.setRoles(userRoles); log.info(dto.getEmail()); log.info("RegisterNewAccountRAN!"); + + //Send Verification Email To that user + String siteURL = Utility.getSiteURL(request); //get site for verification email + //createVerificationToken(u, UUID.randomUUID().toString()); + sendVerificationEmail(u,siteURL); + log.info("Sent email to "+u.getEmail()); + return users.save(u); + + } + + public void sendVerificationEmail(User user, String siteURL) + throws MessagingException, UnsupportedEncodingException { + SimpleMailMessage email = new SimpleMailMessage(); + + String subject = "Fridger: Email Verification"; + String senderName = "Fridger team"; + String mailContent = "

Hello " + user.getName() + "!" + + "\nWe are excited to have you join the Fridger community! Thank you " + + "for signing up with us! But before you can do that, we need you to " + + "confirm your email for us! Go ahead and click the link below!"; + + String verifyURL = siteURL + "/verify?token=" + user.getVerificationCode(); //pass verification token for user + + mailContent += "

VERIFY

"; + mailContent += "

Thank you
The Fridger Team

"; + + MimeMessage message = mailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(message); + + helper.setFrom("noreplyfridger@gmail.com",senderName); + helper.setTo(user.getEmail()); + helper.setSubject(subject); + helper.setText(mailContent,true); + + mailSender.send(message); + } + + public boolean verify(String verificationCode) { + User user = users.findByVerificationCode(verificationCode); + + if (user == null || user.isEnabled()) { + return false; + } else { + user.setVerificationCode(null); + user.setEnabled(true); + users.save(user); + + return true; + } + + } + + public void testSendEmail(CreateUserDTO dto) { + SimpleMailMessage email = new SimpleMailMessage(); + email.setFrom("noreplyfridger@gmail.com"); + email.setTo(dto.getEmail()); + email.setSubject("Welcome To Fridger!"); + email.setText("Dear" + dto.getName() + ",\n" + + "We are excited to have you join our fridger community! Thank you " + + "for signing up with us!"); + mailSender.send(email); + log.info("Sending confirmation email to " + dto.getEmail()); + } + + //still under testing + //TODO + private boolean emailExists(String email) { + return users.findByEmail(email).isPresent(); + } + + public boolean emailExistsPub(String email) { if(users.findByEmail(email)!=null) return true; return false; @@ -117,6 +188,17 @@ public void saveRegisteredUser(User user) { users.save(user); } + public void deleteUserByEmail(String email) { + log.info("tyring to delete this "+email); + User u = users.findByEmailAuth(email); + //log.info(u.getEmail()); + + if(u!=null) { + users.delete(u); + log.info("deleted user at "+u.getEmail()); + } + } + //TODO DONE? @Override public void createVerificationToken(User user, String token) { diff --git a/frontend/src/components/RegistrationForm.tsx b/frontend/src/components/RegistrationForm.tsx index c27e6dae..cd408665 100644 --- a/frontend/src/components/RegistrationForm.tsx +++ b/frontend/src/components/RegistrationForm.tsx @@ -47,7 +47,7 @@ const RegistrationForm: React.FC = () => { }; const body = JSON.stringify(getValues()); axios.post( - `https://api.fridger.recipes/v1/auth/register`, + `https://api.fridger.recipes/v1/user/user/registration`, // `http://localhost:8080/v1/auth/register`, //sending test From 420d5019018188b8d3eedd5eb0b5d4804bc2ac43 Mon Sep 17 00:00:00 2001 From: Andrew-Bernhardt Date: Sun, 27 Mar 2022 02:54:49 -0400 Subject: [PATCH 2/3] todo add setenabled and check allow link to be clicked on --- .../recipes/fridger/backend/controller/AuthController.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java b/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java index 59f517f0..e19fbc4e 100644 --- a/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java +++ b/backend/src/main/java/recipes/fridger/backend/controller/AuthController.java @@ -52,6 +52,10 @@ public class AuthController { @PostMapping(path = "/login") public ResponseEntity authenticateUser(@RequestBody CreateAuthRequestDTO u) { + //TODO add + // if(user.getEnabled()==false) + // -->don't allow + Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(u.getEmail(), u.getPassword())); From a5d622329e499a6f832df80bebd16eab3a077913 Mon Sep 17 00:00:00 2001 From: Andrew-Bernhardt Date: Sun, 3 Apr 2022 00:43:15 -0400 Subject: [PATCH 3/3] changed some api headers --- .../backend/controller/UserController.java | 79 +------------------ .../fridger/backend/service/UserService.java | 1 + .../backend/service/UserServiceImpl.java | 17 +++- frontend/src/App.tsx | 3 + frontend/src/components/RegistrationForm.tsx | 4 +- 5 files changed, 20 insertions(+), 84 deletions(-) diff --git a/backend/src/main/java/recipes/fridger/backend/controller/UserController.java b/backend/src/main/java/recipes/fridger/backend/controller/UserController.java index 9316ffbe..32d4573d 100644 --- a/backend/src/main/java/recipes/fridger/backend/controller/UserController.java +++ b/backend/src/main/java/recipes/fridger/backend/controller/UserController.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.MessageSource; +import org.springframework.data.repository.query.Param; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.GrantedAuthority; @@ -94,84 +95,6 @@ public class UserController { * USER API */ - //no verification -> this works and is tested -// @PostMapping(path = "/") -// public ResponseEntity -// createUser(@RequestBody @Valid CreateUserDTO u) { -// try { -// userService.createUser(u); -// log.info("Successful creation of user"); -// return ResponseEntity.ok("Created user"); -// } catch (Exception e) { -// log.warn("Unable to create user\n" + e.getMessage()); -// return ResponseEntity.internalServerError().body( -// "Unable to create user\n" + e.getMessage()); -// } -// } - - - //register user is in auth controller!! - - -// @PostMapping(path = "/register") -// public ResponseEntity -// createUser(@RequestBody @Valid CreateUserDTO u, HttpServletRequest request) { -// // Ensure email is unique -// log.info("attempting user create"); -// if(userService.getUserByEmail(u.getEmail()) != null) { -// log.info("already exists user" + u.getEmail()); -// return ResponseEntity.badRequest().body("Account already exists"); -// } -// try { -// //Create user -// User registered = userService.registerNewUserAccount(u); -// log.info("Successful creation of user"); -// -// //Send Verification Email To that user -// String siteURL = Utility.getSiteURL(request); //get site for verification email -// userService.sendVerificationEmail(registered,siteURL); -// log.info("Sent email to "+u.getEmail()); -// -// return ResponseEntity.ok("Created user"); -// } catch (Exception e) { -// log.warn("Unable to create user\n" + e.getMessage()); -// return ResponseEntity.internalServerError().body( -// "Unable to create user\n" + e.getMessage()); -// } -// } - -// //account verification of user -// @PostMapping("/user/registration") -// public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid CreateUserDTO userDto) { -// -// try { -//// if(userService.getUserByEmail(userDto.getEmail()) != null) { -//// log.info("already exists user" + userDto.getEmail()); -//// return new ModelAndView("registration","user",userDto); -//// } -// //This creates a new user, but the user's attribute "enabled" is set to false. -// //This must be set to true in order to sign in -// User registered = userService.registerNewUserAccount(userDto); -// log.info("Registered New Account"); -// -//// String appUrl = request.getContextPath(); -//// eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, -//// request.getLocale(), appUrl)); -// } catch (UserAlreadyExistException uaeEx) { -// ModelAndView mav = new ModelAndView("registration", "user", userDto); -// mav.addObject("message", "An account for that username/email already exists."); -// log.info("1st catch"); -// return mav; -// -// } catch (RuntimeException ex) { -// log.info("2nd catch"); -// return new ModelAndView("emailError", "user", userDto); -// -// } -// -// return new ModelAndView("successRegister", "user", userDto); -// } - @GetMapping("/registrationConfirm") public String confirmRegistration (WebRequest request, Model model, @RequestParam("token") String token) { diff --git a/backend/src/main/java/recipes/fridger/backend/service/UserService.java b/backend/src/main/java/recipes/fridger/backend/service/UserService.java index 30e4b4cf..2b84f3cc 100644 --- a/backend/src/main/java/recipes/fridger/backend/service/UserService.java +++ b/backend/src/main/java/recipes/fridger/backend/service/UserService.java @@ -15,6 +15,7 @@ public interface UserService { public User getUser(Long id); public void updateUser(Long id, UpdateUserDTO u) throws Exception; public boolean emailExistsPub(String email); + public boolean isEnabled(String email); public Iterable getUsersByIdAndEmail(Long id, String email); public Iterable getUsers(Long userId); public void testSendEmail(CreateUserDTO dto); diff --git a/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java b/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java index 58fd6990..a30d78ef 100644 --- a/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java +++ b/backend/src/main/java/recipes/fridger/backend/service/UserServiceImpl.java @@ -106,8 +106,10 @@ public User registerNewUserAccount(CreateUserDTO dto, HttpServletRequest request log.info("RegisterNewAccountRAN!"); //Send Verification Email To that user - String siteURL = Utility.getSiteURL(request); //get site for verification email + //String siteURL = Utility.getSiteURL(request); //get site for verification email //createVerificationToken(u, UUID.randomUUID().toString()); + //TODO CHANGE BEFORE GOING LIVE + String siteURL="https://fridger.recipes"; sendVerificationEmail(u,siteURL); log.info("Sent email to "+u.getEmail()); @@ -117,7 +119,6 @@ public User registerNewUserAccount(CreateUserDTO dto, HttpServletRequest request public void sendVerificationEmail(User user, String siteURL) throws MessagingException, UnsupportedEncodingException { - SimpleMailMessage email = new SimpleMailMessage(); String subject = "Fridger: Email Verification"; String senderName = "Fridger team"; @@ -126,10 +127,10 @@ public void sendVerificationEmail(User user, String siteURL) "for signing up with us! But before you can do that, we need you to " + "confirm your email for us! Go ahead and click the link below!"; - String verifyURL = siteURL + "/verify?token=" + user.getVerificationCode(); //pass verification token for user + String verifyURL = siteURL + "/verify?code=" + user.getVerificationCode(); //pass verification token for user mailContent += "

VERIFY

"; - mailContent += "

Thank you
The Fridger Team

"; + mailContent += "

Thank you,
The Fridger Team

"; MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); @@ -158,6 +159,14 @@ public boolean verify(String verificationCode) { } + //This method will see if the user is enabled yet + public boolean isEnabled(String email) { + Optional u = users.findByEmail(email); + if(!u.isPresent()) + return false; + return u.get().isEnabled(); + } + public void testSendEmail(CreateUserDTO dto) { SimpleMailMessage email = new SimpleMailMessage(); email.setFrom("noreplyfridger@gmail.com"); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 04542f05..fa4361ad 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -19,6 +19,8 @@ import AddComplaint from './pages/AddComplaint'; import Complaint from './pages/Complaint'; import Favorite from './pages/Favorite'; import Loading from './pages/Loading'; + +import Verify from './pages/Verify'; //import Recipe from './pages/Recipe'; /* Core CSS required for Ionic components to work properly */ import '@ionic/react/css/core.css'; @@ -103,6 +105,7 @@ import myReviews from './pages/myReviews'; + diff --git a/frontend/src/components/RegistrationForm.tsx b/frontend/src/components/RegistrationForm.tsx index 61eefaf1..8e1c11a2 100644 --- a/frontend/src/components/RegistrationForm.tsx +++ b/frontend/src/components/RegistrationForm.tsx @@ -47,11 +47,11 @@ const RegistrationForm: React.FC = () => { }; const body = JSON.stringify(getValues()); axios.post( - `https://api.fridger.recipes/v1/auth/register`, + // `https://api.fridger.recipes/v1/auth/register`, // `https://api.fridger.recipes/v1/auth/register`, //sending test - // 'http://localhost:8080/v1/user/user/registration', + 'http://localhost:8080/v1/auth/register', body, config ).then( res => {