com.sf.springsecurityregistration1.web.controllers.RegistrationController.java Source code

Java tutorial

Introduction

Here is the source code for com.sf.springsecurityregistration1.web.controllers.RegistrationController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sf.springsecurityregistration1.web.controllers;

/**
 *
 * @author sf
 */
import com.sf.springsecurityregistration1.core.entities.UserRoles;
import com.sf.springsecurityregistration1.core.entities.Users;
import com.sf.springsecurityregistration1.core.services.IUserService;
import com.sf.springsecurityregistration1.core.services.UserExistsException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
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.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
//@PropertySource("classpath:encoding.properties")
public class RegistrationController {
    //    @Value("${page.encoding}")
    //    private String pageEncoding = "ISO-8859-1";
    //    @Value("${db.encoding}")
    //    private String dbEncoding = "UTF8";    
    @Autowired
    private IUserService userService;

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        System.out.println("setUserService");
        this.userService = userService;
    }

    /**
     * Method used to fill welcome page.
     *
     * @return model of view
     */
    @RequestMapping(value = { "/", "/welcome**", "/logout**", "/index**" }, method = RequestMethod.GET)
    public ModelAndView welcomePage() {

        System.out.println("welcomePage");
        ModelAndView model = new ModelAndView();
        //        "? ?";
        String titleStr = "Доска о"
                + "бъявлени" + "й";
        //        "? ?   ?. "
        //                + "  ?? \"??\""
        String messageStr = "Для дос"
                + "тупа нео"
                + "бходимо "
                + "пройти р"
                + "егистрац"
                + "ию. Перей"
                + "дите по с"
                + "сылке ";
        //        "??"
        String registrationRefStr = "Регист"
                + "рация.";
        model.addObject("title", titleStr);
        model.addObject("message", messageStr);
        model.addObject("registrationRef", registrationRefStr);
        String logoutRef = "Выход";
        model.addObject("logoutRef", logoutRef);
        String userTitle = "Пользов"
                + "атель";
        model.addObject("userTitle", userTitle);
        //        ? ??
        String announcementsRef = "Посмот"
                + "реть объ"
                + "явления";
        model.addObject("announcementsRef", announcementsRef);
        model.setViewName("hello");
        return model;

    }

    /**
     * Method used to create a new user for registration page.
     *
     * @return model of the registration page
     */
    @RequestMapping(value = { "/registration" }, method = RequestMethod.GET)
    public ModelAndView registrationPage() {
        //        System.out.println("registrationPage");
        Users user = new Users();
        ModelAndView model = new ModelAndView();
        model.addObject("user", user);
        model.setViewName("registration");
        return model;

    }

    /**
     * Method used to check and persist a new user data.
     *
     * @param accountDto user to be persisted
     * @param result used to detect errors in form
     * @param request for future code
     * @param errors for future code
     * @return model of the success view or that of the registration page
     */
    @RequestMapping(value = "/user/**/registration", method = RequestMethod.POST)
    public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid Users accountDto, BindingResult result,
            WebRequest request, Errors errors) {
        System.out.println("/user/registration");
        Users registered = new Users();
        //        accountDto.setUsername(changeEncoding(accountDto.getUsername(),
        //                pageEncoding, dbEncoding));
        if (!result.hasErrors()) {
            System.out.println("!result.hasErrors()");
            registered = createUserAccount(accountDto, result);
        }
        if (registered == null) {
            System.out.println("registered == null");
            result.rejectValue("username", "message.regError");
        }
        if (result.hasErrors()) {
            System.out.println("result.hasErrors()");
            ModelAndView model = new ModelAndView("registration");
            model.addObject("user", accountDto);
            return model;
        } else {
            ModelAndView model = new ModelAndView("successRegister");
            model.addObject("user", accountDto);
            return model;
        }
    }

    /**
     * Method used to create a new user .
     *
     * @param accountDto user to be persisted
     * @param result for future code
     * @return null for error and created user for success
     */
    private Users createUserAccount(Users accountDto, BindingResult result) {
        Users registered = null;
        try {
            registered = userService.registerNewUserAccount(accountDto);
            System.out.println("createUserAccount: " + registered.getUsername());
        } catch (UserExistsException e) {
            System.out.println("createUserAccount: UserExistsException");
            return null;
        }
        return registered;
    }

    /**
     * Method will be used to secure administrative actions.
     * 
     * @return model of the administrator page
     */
    @RequestMapping(value = "/admin**", method = RequestMethod.GET)
    public ModelAndView adminPage() {

        System.out.println("adminPage");
        ModelAndView model = new ModelAndView();
        //        model.addObject("title", "Spring Security Hello World");
        //        model.addObject("message", "This is protected page - Admin Page!");
        model.addObject("title", "Spring Security Login Form - Database Authentication");
        model.addObject("message", "This page is for ROLE_ADMIN only!");
        model.setViewName("admin");

        return model;

    }

    /**
     * Method will be used to secure administrative actions.
     *
     * @return model of the administrator page
     */
    @RequestMapping(value = "/dba**", method = RequestMethod.GET)
    public ModelAndView dbaPage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Hello World");
        model.addObject("message", "This is protected page - Database Page!");
        model.setViewName("admin");

        return model;

    }

    /**
    * Method is used to support login page.
    *
    * @param error
    * @param logout
    * @return model of the login page
    */
    @RequestMapping(value = { "/login", "/user/**/login" }, method = RequestMethod.GET)
    public ModelAndView login(@RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {

        System.out.println("login: logout = " + logout);
        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("login");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //get logged in username

        return model;

    }

    //for 403 access denied page
    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public ModelAndView accesssDenied() {

        ModelAndView model = new ModelAndView();

        //check if user is login
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            UserDetails userDetail = (UserDetails) auth.getPrincipal();
            model.addObject("username", userDetail.getUsername());
        }

        model.setViewName("403");
        return model;

    }
}