Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package net.nan21.dnet.core.web.controller.session;
  
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.Set;
 
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 
 
 import  org.springframework.security.authentication.AuthenticationManager;
 import  org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import  org.springframework.security.core.Authentication;
 import  org.springframework.security.core.GrantedAuthority;
 import  org.springframework.security.core.context.SecurityContext;
 import  org.springframework.security.core.context.SecurityContextHolder;
 import  org.springframework.security.web.context.HttpSessionSecurityContextRepository;
 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.bind.annotation.ResponseBody;
 import  org.springframework.web.context.WebApplicationContext;
 import  org.springframework.web.servlet.ModelAndView;
 
 @Scope(value = "request")
 @RequestMapping(value = "/session")
 public class SessionController {
 
 	protected WebApplicationContext webappContext;
 
 	private AuthenticationManager authenticationManager;
 
 	// ************* HTML LOGIN *************
 
Show login page

Returns:
Throws:
Exception
 
 	@RequestMapping(value = "/login")
 	public ModelAndView showLogin() throws Exception {
 		return new ModelAndView("login");
 
 	}

Process login action

Parameters:
username
password
clientCode
language
request
response
Returns:
Throws:
Exception
 
 	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
 	public ModelAndView doLogin(
 			@RequestParam(value = "user", required = trueString username,
 			@RequestParam(value = "pswd", required = trueString password,
 			@RequestParam(value = "client", required = trueString clientCode,
 			@RequestParam(value = "lang", required = falseString language,
 			HttpServletRequest request, HttpServletResponse response)
 			throws Exception {
 		try {
 			request.getSession().invalidate();
 			request.getSession();
 
 			String thePassword = password;
 			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
 			messageDigest.update(thePassword.getBytes(), 0, thePassword
 					.length());
 			String hashedPass = new BigInteger(1, messageDigest.digest())
 					.toString(16);
 			if (hashedPass.length() < 32) {
 				hashedPass = "0" + hashedPass;
 			}
 
 			Authentication authRequest = new UsernamePasswordAuthenticationToken(
					usernamehashedPass);
			Authentication authResponse = this.
					.authenticate(authRequest);
			SecurityContextHolder.getContext().setAuthentication(authResponse);
			this.auditLogin((SessionUserauthResponse.getPrincipal(), request);
			response.sendRedirect("/nan21.dnet.core.web/ui/extjs/");
			return null;
catch (Exception e) {
			Map<StringStringmodel = new HashMap<StringString>();
			model.put("error""Invalid credentials. Authentication failed.");
			return new ModelAndView("login"model);
		}
	}
	@ResponseBody
	@RequestMapping(params = "action=login")
			@RequestParam(value = "user", required = trueString username,
			@RequestParam(value = "pswd", required = trueString password,
			@RequestParam(value = "client", required = trueString clientCode,
			@RequestParam(value = "lang", required = falseString language,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			// TODO: copy attributes ? 
			request.getSession().invalidate();
			request.getSession();
			Authentication authRequest = new UsernamePasswordAuthenticationToken(
					usernamepassword);
			Authentication authResponse = this.
					.authenticate(authRequest);
			SecurityContextHolder.getContext().setAuthentication(authResponse);
			SessionUser su = (SessionUser) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
			this.auditLogin(surequest);
			User u = su.getUser();
			Params params = su.getParams();
			StringBuffer sb = new StringBuffer();
			String userRolesStr = null;
			sb.append(",\"extjsDateFormat\":\"" + prefs.getExtjsDateFormat()
"\"");
			sb.append(" , \"extjsTimeFormat\": \"" + prefs.getExtjsTimeFormat()
"\"");
			sb.append(" , \"extjsDateTimeFormat\": \""
prefs.getExtjsDateTimeFormat() + "\"");
			sb.append(" , \"extjsAltFormats\": \"" + prefs.getExtjsAltFormats()
"\"");
			sb.append(" , \"decimalSeparator\": \""
prefs.getDecimalSeparator() + "\"");
			sb.append(" , \"thousandSeparator\": \""
prefs.getThousandSeparator() + "\"");
			Set<GrantedAuthority> roles = su.getAuthorities();
			StringBuffer sbroles = new StringBuffer();
			int i = 0;
			for (GrantedAuthority role : roles) {
				if (i > 0) {
					sbroles.append(",");
				}
				sbroles.append("\"" + role.getAuthority() + "\"");
				i++;
			}
			userRolesStr = sbroles.toString();
			sb.append(" , \"roles\": [" + userRolesStr + "]");
			request
					.getSession()
					.setAttribute(
							HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
							SecurityContextHolder.getContext());
			return "{ \"success\": true , \"data\": { \"name\":\""
u.getDisplayName() + "\",\"code\":\"" + u.getUsername()
"\", \"clientId\":\"" + u.getClientId()
"\" , \"systemClient\":" + params.isSystemClient()
sb.toString() + "  }  }";
catch (Exception e) {
			return this.handleException(eresponse);
		}
	}
	@ResponseBody
	@RequestMapping(value = "/doLogout")
	public String doLogout(HttpServletRequest request,
			HttpServletResponse responsethrows Exception {
		SecurityContextHolder.getContext().setAuthentication(null);
		request.getSession().invalidate();
		// .removeAttribute(
		// HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
		return "";
	}
	// ************* EXTJS LOGIN *************
	@ResponseBody
	@RequestMapping(params = "action=lock")
	public String lock(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return "";
	}
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, params = "action=unlock")
	public String unlock(
			@RequestParam(value = "pswd", required = trueString pswd,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return "";
	}
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, params = "action=changePassword")
			@RequestParam(value = "opswd", required = trueString oldPassword,
			@RequestParam(value = "npswd", required = trueString newPassword,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
					.getBean(IChangePasswordService.class);
			SecurityContext ctx = (SecurityContext) request
					.getSession()
					.getAttribute(
							HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
			if (ctx == null || ctx.getAuthentication() == null) {
				throw new Exception("Not authenticated");
			}
			User user = ((SessionUserctx.getAuthentication().getPrincipal())
			service.changePassword(user.getUsername(), newPassword,
					oldPassworduser.getClientId(), user.getClientCode());
			return "{success: true}";
catch (Exception e) {
			return this.handleException(eresponse);
		}
	}
	public WebApplicationContext getWebappContext() {
	}
	public void setWebappContext(WebApplicationContext webappContext) {
		this. = webappContext;
	}
	public AuthenticationManager getAuthenticationManager() {
	}
			AuthenticationManager authenticationManager) {
		this. = authenticationManager;
	}
	private void auditLogin(SessionUser su, HttpServletRequest request) {
		su.setClientIp(request.getRemoteAddr());
		su.setUserAgent(request.getHeader("User-Agent"));
		//su.setClientHost(request.getRemoteHost());
		su.setLoginDate(new Date());
	}
	protected String handleException(Exception e, HttpServletResponse response)
			throws IOException {
		response.setStatus(403);
		// response.getOutputStream().print(e.getLocalizedMessage());
	}
New to GrepCode? Check out our FAQ X