mvc.CheckUserController.java Source code

Java tutorial

Introduction

Here is the source code for mvc.CheckUserController.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 mvc;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import mvc.parent.WebController;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *  ?  ?
 *
 * @author Rice Pavel
 */
@Controller
public class CheckUserController extends WebController {

    @RequestMapping("/CheckUser")
    @ResponseBody
    public Map<String, Object> checkUser(HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        map.put("anonymous", isAnonymous());
        map.put("userName", getUserName());
        return map;
    }

    private boolean isAnonymous() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return (auth instanceof AnonymousAuthenticationToken);
    }

    private String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken) && authentication != null) {
            String currentUserName = authentication.getName();
            return currentUserName;
        }
        return "";
    }

}