Java tutorial
/* * This file is part of blog (https://github.com/jens-meiss/blog). * * blog is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * blog is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with blog. If not, see <http://www.gnu.org/licenses/>. */ package com.github.jens_meiss.blog.web.user; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.github.jens_meiss.blog.service.UserService; import com.github.jens_meiss.blog.service.dto.impl.user.UserAddDTOImpl; import com.github.jens_meiss.blog.service.dto.impl.user.UserUpdateDTOImpl; import com.github.jens_meiss.blog.service.dto.user.UserDetailsDTO; import com.github.jens_meiss.blog.service.dto.user.UserUpdateDTO; import com.github.jens_meiss.blog.web.RequestRedirect; /** * Handles requests for the application user page. */ @Controller public class UserController implements AuthenticationProvider, UserDetailsService { /** The Constant logger. */ private static final Logger logger = LoggerFactory.getLogger(UserController.class); /** The Constant MODEL_USER. */ private static final String MODEL_USER = "user"; /** The user service. */ @Autowired private UserService userService; /** * Adds the. * * @param locale the locale * @param model the model * @return the model and view */ @RequestMapping(value = UserRequest.USER_ADD, method = RequestMethod.GET) public ModelAndView add(final Locale locale, final Model model) { logger.debug("add"); return new ModelAndView(UserResponse.USER_ADD, MODEL_USER, new UserAddDTOImpl()); } /** * Adds the validate. * * @param userAddDTO the user add dto * @param result the result * @return the string */ @RequestMapping(value = UserRequest.USER_ADD_VALIDATE, method = RequestMethod.POST) public String addValidate(@ModelAttribute(MODEL_USER) final UserAddDTOImpl userAddDTO, final BindingResult result) { logger.debug("addValidate"); final String name = userAddDTO.getName(); if (userService.existsUserName(name)) return UserResponse.USER_ADD_INVALID; userService.add(userAddDTO); return RequestRedirect.DASHBOARD; } @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final String userName = authentication.getName(); final UserDetailsDTO userDetailsDTO = userService.findByUserName(userName); if (userDetailsDTO == null) { logger.error("username not found"); return null; } final String crendentials = authentication.getCredentials().toString(); if (crendentials.equals(userDetailsDTO.getPassword()) == false) { logger.error("password mismatch"); return null; } logger.debug("user successfully authenticated"); return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<GrantedAuthority>()); } /** * Edits the. * * @param locale the locale * @param model the model * @return the string */ @RequestMapping(value = UserRequest.USER_EDIT, method = RequestMethod.GET) public String edit(final Locale locale, final Model model) { logger.debug("edit"); final UserUpdateDTO userDTO = userService.getCurrentUser(); final UserUpdateDTOImpl updateDTO = new UserUpdateDTOImpl(); updateDTO.setEmail(userDTO.getEmail()); updateDTO.setPassword(userDTO.getPassword()); updateDTO.setUserId(userDTO.getUserId()); updateDTO.setName(userDTO.getName()); model.addAttribute(MODEL_USER, updateDTO); return UserResponse.USER_EDIT; } /** * Edits the validate. * * @param userUpdateDTO the user update dto * @param result the result * @return the string */ @RequestMapping(value = UserRequest.USER_EDIT_VALIDATE, method = RequestMethod.POST) public String editValidate(@ModelAttribute(MODEL_USER) final UserUpdateDTOImpl userUpdateDTO, final BindingResult result) { logger.debug("editValidate"); userService.update(userUpdateDTO); return RequestRedirect.DASHBOARD; } @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.debug("loadUserByUsername"); final UserDetailsDTO userDetailsDTO = userService.findByUserName(username); if (userDetailsDTO == null) throw new UsernameNotFoundException("Username Not Found"); final List<SimpleGrantedAuthority> roles = new LinkedList<SimpleGrantedAuthority>(); roles.add(new SimpleGrantedAuthority("ROLE_USER")); return new User(userDetailsDTO.getUserName(), userDetailsDTO.getPassword(), true, true, true, true, roles); } /** * Login. * * @param error the error * @param logout the logout * @return the model and view */ @RequestMapping(value = UserRequest.USER_LOGIN, method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) final String error, @RequestParam(value = "logout", required = false) final String logout) { logger.debug("login"); final ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("msg", "You've been logged out successfully."); } model.setViewName(UserResponse.USER_LOGIN); return model; } /** * Logout. * * @param locale the locale * @param model the model * @return the string */ @RequestMapping(value = UserRequest.USER_LOGOUT_SUCESSFULLY, method = RequestMethod.GET) public String logout(final Locale locale, final Model model) { logger.debug("logout"); return UserResponse.USER_LOGOUT; } /** * Removes the. * * @param locale the locale * @param model the model * @return the string */ @RequestMapping(value = UserRequest.USER_REMOVE, method = RequestMethod.GET) public String remove(final Locale locale, final Model model) { logger.debug("remove"); return UserResponse.USER_REMOVE_CONFIRM; } /** * Removes the confirmed. * * @return the string */ @RequestMapping(value = UserRequest.USER_REMOVE_CONFIRMED, method = RequestMethod.POST) public String removeConfirmed() { logger.debug("removeConfirmed"); userService.removeCurrentUser(); return UserResponse.USER_REMOVE_CONFIRMED; } /** * Sets the user service. * * @param userService the new user service */ public void setUserService(final UserService userService) { this.userService = userService; } @Override public boolean supports(final Class<?> authentication) { if (authentication == UsernamePasswordAuthenticationToken.class) return true; return false; } }