com.tsg.techsupportmvc.UserController.java Source code

Java tutorial

Introduction

Here is the source code for com.tsg.techsupportmvc.UserController.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.tsg.techsupportmvc;

import com.tsg.techsupportmvc.dao.UserDao;
import com.tsg.techsupportmvc.dto.User;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author apprentice
 */
@Controller
public class UserController {

    private final UserDao dao;

    boolean userIsLoggedIn = false;

    String error = "";

    @Inject
    public UserController(UserDao dao) {

        this.dao = dao;

    }

    @RequestMapping(value = { "/login" }, method = RequestMethod.POST)
    public String logUserIn(HttpServletRequest request, RedirectAttributes redirectAttributes,
            HttpSession session) {

        Boolean userAndPasswordAreCorrect = false;
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (dao.userExists(username)) {

            userAndPasswordAreCorrect = dao.passwordIsCorrect(username, password);

        }

        if (userAndPasswordAreCorrect) {

            userIsLoggedIn = true;

            error = "";

            User user = dao.getUserByUsername(username);

            session.setAttribute("userIsLoggedIn", userIsLoggedIn);
            session.setAttribute("user", user.getUsername());
            session.setAttribute("userRealName", user.getDisplayName());
            session.setAttribute("userSiteRole", user.getSiteRole());
            session.setAttribute("loginErrorMessage", error);
            session.setAttribute("userId", user.getUserId());

        } else {

            error = "Invalid username or password!";

        }

        return "redirect:home";

    }

    @RequestMapping(value = { "/logout" }, method = RequestMethod.POST)
    public String logUserOut(HttpServletRequest request, RedirectAttributes redirectAttributes,
            HttpSession session) {

        userIsLoggedIn = false;
        error = "";
        session.setAttribute("userIsLoggedIn", userIsLoggedIn);
        session.setAttribute("user", "");
        session.setAttribute("userRealName", "");
        session.setAttribute("userSiteRole", "");
        session.setAttribute("loginErrorMessage", error);
        return "redirect:home";

    }

}