com.github.jens_meiss.blog.server.service.json.user.UserController.java Source code

Java tutorial

Introduction

Here is the source code for com.github.jens_meiss.blog.server.service.json.user.UserController.java

Source

/*
 * 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.server.service.json.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.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.RestController;

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;

/**
 * Handles requests for the application user page.
 */
@RestController
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 validate.
     *
     * @param userAddDTO the user add dto
     * @param result the result
     * @return the string
     */
    @RequestMapping(value = UserRequest.USER_ADD_VALIDATE, method = RequestMethod.POST)
    public boolean addValidate(@ModelAttribute(MODEL_USER) final UserAddDTOImpl userAddDTO,
            final BindingResult result) {

        logger.debug("addValidate");

        final String name = userAddDTO.getName();

        if (userService.existsUserName(name)) {
            // todo throw user not found exception
            return false;
        }

        return userService.add(userAddDTO);
    }

    @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 UserUpdateDTO edit(final Locale locale, final Model model) {

        logger.debug("edit");

        return userService.getCurrentUser();
    }

    /**
     * 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 boolean editValidate(@ModelAttribute(MODEL_USER) final UserUpdateDTOImpl userUpdateDTO,
            final BindingResult result) {

        logger.debug("editValidate");

        return userService.update(userUpdateDTO);
    }

    @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);

    }

    /**
     * Removes the confirmed.
     *
     * @return the string
     */
    @RequestMapping(value = UserRequest.USER_REMOVE_CONFIRMED, method = RequestMethod.POST)
    public void removeConfirmed() {

        logger.debug("removeConfirmed");

        userService.removeCurrentUser();
    }

    /**
     * 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;
    }
}