springit icon indicating copy to clipboard operation
springit copied to clipboard

User is not set on a new Link entity

Open boser87 opened this issue 7 years ago • 5 comments

Current user should be set on a newly created Link entity. This is done manually in the DatabaseLoader, but it's not done when the link is created through the UI.

boser87 avatar Dec 13 '18 15:12 boser87

I don't have access to push otherwise I would create a PR for a fix

boser87 avatar Dec 13 '18 16:12 boser87

I don't have access to push otherwise I would create a PR for a fix

i found that too, could you please tell me how to fix that?

313183373 avatar Jul 17 '19 07:07 313183373

I have solved this . Please insert this in your LinkController . `@PostMapping("/link/submit") public String createLink(@Valid Link link, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) { User user = null; Optional<String> optionalemail = BeanUtil.getBean(AuditorAwareImpl.class).getCurrentAuditor(); if(optionalemail.isPresent()) { Optional<User> optionalUser = userRepository.findByEmail(optionalemail.get()); user = (optionalUser.isPresent())?optionalUser.get():null; } if(bindingResult.hasErrors()) { logger.info("Validation Errors were found while submiting a new link"); link.setUser(user); model.addAttribute("link", link); return "link/submit"; }else { link.setUser(user); linkService.save(link); logger.info("New Link Saved Successfully"); redirectAttributes.addAttribute("id", link.getId()).addFlashAttribute("success", true); return "redirect:/link/{id}"; }

}`

sreekanthmcit avatar Dec 04 '19 08:12 sreekanthmcit

Thank you. Your suggestion solves the problem so far. For everyone else; You find the code above as a gist here: https://gist.github.com/duese22/4a07d5e0306aaade89cdde9920c9660f

I tried improving it withe the Spring security way, following: https://www.mkyong.com/spring-security/get-current-logged-in-username-in-spring-security/ You find this also in the https://gist.github.com/duese22/4a07d5e0306aaade89cdde9920c9660f#file-improved-code

Please correct me if i am wrong!

What I wonder: Everyone should have this problem right? i did not find any mentions in the comments under the sessions.

duese22 avatar Dec 04 '19 11:12 duese22

Everyone should have got this . In your tutorials "Getting started with Spring Boot 2" on your lecture number 84 a user has commented and mentioned this .

sreekanthmcit avatar Dec 05 '19 04:12 sreekanthmcit