<commit_before>/** 
 * DNet eBusiness Suite
 * Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
 * Use is subject to license terms.
 */
package ro.seava.j4e.web.controller.session;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.seava.j4e.api.Constants;
import ro.seava.j4e.api.enums.DateFormatAttribute;
import ro.seava.j4e.api.security.IChangePasswordService;
import ro.seava.j4e.api.security.ILoginParams;
import ro.seava.j4e.api.security.LoginParamsHolder;
import ro.seava.j4e.api.session.ISessionUser;
import ro.seava.j4e.api.session.IUser;
import ro.seava.j4e.api.session.IUserSettings;
import ro.seava.j4e.api.session.Session;
import ro.seava.j4e.web.controller.AbstractBaseController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
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.servlet.ModelAndView;

@RequestMapping(value = Constants.CTXPATH_SESSION)
public class SessionController extends AbstractBaseController {

	final static Logger logger = LoggerFactory
			.getLogger(SessionController.class);

	private AuthenticationManager authenticationManager;

	/**
	 * Login page view
	 */
	private String loginViewName;

	/**
	 * Show login page
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/" + Constants.SESSION_ACTION_SHOW_LOGIN)
	public ModelAndView showLogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// if user already authenticated redirect
		SecurityContext ctx = (SecurityContext) request
				.getSession()
				.getAttribute(
						HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
		if (ctx != null && ctx.getAuthentication() != null) {
			response.sendRedirect(this.getSettings()
					.get(Constants.PROP_CTXPATH));
			return null;
		}

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("loginPageCss",
				this.getSettings().get(Constants.PROP_LOGIN_PAGE_CSS));
		model.put("loginPageLogo",
				this.getSettings().get(Constants.PROP_LOGIN_PAGE_LOGO));
		model.put("currentYear", Calendar.getInstance().get(Calendar.YEAR) + "");

		model.put("productName", this.getSettings().getProductName());
		model.put("productDescription", this.getSettings()
				.getProductDescription());
		model.put("productVersion", this.getSettings().getProductVersion());
		model.put("productUrl", this.getSettings().getProductUrl());
		model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH));
		
		return new ModelAndView(this.loginViewName, model);

	}

	/**
	 * Process login action
	 * 
	 * @param username
	 * @param password
	 * @param clientCode
	 * @param language
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGIN, method = RequestMethod.POST)
	public ModelAndView login(
			@RequestParam(value = "user", required = true) String username,
			@RequestParam(value = "pswd", required = true) String password,
			@RequestParam(value = "client", required = true) String clientCode,
			@RequestParam(value = "lang", required = false) String language,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {

			if (logger.isInfoEnabled()) {
				logger.info("Session request: -> login ");
			}

			if (logger.isDebugEnabled()) {
				logger.debug(
						"  --> request-params: user={}, client={}, pswd=*** ",
						new String[] { username, clientCode });
			}

			request.getSession().invalidate();
			request.getSession();

			prepareLoginParamsHolder(clientCode, language, request);

			String hashedPass = get<PASSWORD>Password(password);

			Authentication authRequest = new UsernamePasswordAuthenticationToken(
					username, hashedPass);
			Authentication authResponse = this.getAuthenticationManager()
					.authenticate(authRequest);
			SecurityContextHolder.getContext().setAuthentication(authResponse);

			response.sendRedirect(this.getSettings()
					.get(Constants.PROP_CTXPATH) + Constants.URL_UI_EXTJS);
			return null;
		} catch (Exception e) {
			ModelAndView err = this.showLogin(request, response);
			String msg = "Authentication failed. ";
			if (e.getMessage() != null && !"".equals(e.getMessage())) {
				msg += e.getMessage();
			}
			err.getModel().put("error", msg);
			return err;
		}
	}

	/**
	 * Process login action from an AJAX context
	 * 
	 * @param username
	 * @param password
	 * @param clientCode
	 * @param language
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "="
			+ Constants.SESSION_ACTION_LOGIN)
	public String loginExtjs(
			@RequestParam(value = "user", required = true) String username,
			@RequestParam(value = "pswd", required = true) String password,
			@RequestParam(value = "client", required = true) String clientCode,
			@RequestParam(value = "lang", required = false) String language,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {<commit_msg>Login error message<commit_after>/** 
 * DNet eBusiness Suite
 * Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
 * Use is subject to license terms.
 */
package ro.seava.j4e.web.controller.session;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.seava.j4e.api.Constants;
import ro.seava.j4e.api.enums.DateFormatAttribute;
import ro.seava.j4e.api.security.IChangePasswordService;
import ro.seava.j4e.api.security.ILoginParams;
import ro.seava.j4e.api.security.LoginParamsHolder;
import ro.seava.j4e.api.session.ISessionUser;
import ro.seava.j4e.api.session.IUser;
import ro.seava.j4e.api.session.IUserSettings;
import ro.seava.j4e.api.session.Session;
import ro.seava.j4e.web.controller.AbstractBaseController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
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.servlet.ModelAndView;

@RequestMapping(value = Constants.CTXPATH_SESSION)
public class SessionController extends AbstractBaseController {

	final static Logger logger = LoggerFactory
			.getLogger(SessionController.class);

	private AuthenticationManager authenticationManager;

	/**
	 * Login page view
	 */
	private String loginViewName;

	/**
	 * Show login page
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/" + Constants.SESSION_ACTION_SHOW_LOGIN)
	public ModelAndView showLogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// if user already authenticated redirect
		SecurityContext ctx = (SecurityContext) request
				.getSession()
				.getAttribute(
						HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
		if (ctx != null && ctx.getAuthentication() != null) {
			response.sendRedirect(this.getSettings()
					.get(Constants.PROP_CTXPATH));
			return null;
		}

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("loginPageCss",
				this.getSettings().get(Constants.PROP_LOGIN_PAGE_CSS));
		model.put("loginPageLogo",
				this.getSettings().get(Constants.PROP_LOGIN_PAGE_LOGO));
		model.put("currentYear", Calendar.getInstance().get(Calendar.YEAR) + "");

		model.put("productName", this.getSettings().getProductName());
		model.put("productDescription", this.getSettings()
				.getProductDescription());
		model.put("productVersion", this.getSettings().getProductVersion());
		model.put("productUrl", this.getSettings().getProductUrl());
		model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH));
		
		return new ModelAndView(this.loginViewName, model);

	}

	/**
	 * Process login action
	 * 
	 * @param username
	 * @param password
	 * @param clientCode
	 * @param language
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGIN, method = RequestMethod.POST)
	public ModelAndView login(
			@RequestParam(value = "user", required = true) String username,
			@RequestParam(value = "pswd", required = true) String password,
			@RequestParam(value = "client", required = true) String clientCode,
			@RequestParam(value = "lang", required = false) String language,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {

			if (logger.isInfoEnabled()) {
				logger.info("Session request: -> login ");
			}

			if (logger.isDebugEnabled()) {
				logger.debug(
						"  --> request-params: user={}, client={}, pswd=*** ",
						new String[] { username, clientCode });
			}

			request.getSession().invalidate();
			request.getSession();

			prepareLoginParamsHolder(clientCode, language, request);

			String hashedPass = <PASSWORD>(password);

			Authentication authRequest = new UsernamePasswordAuthenticationToken(
					username, hashedPass);
			Authentication authResponse = this.getAuthenticationManager()
					.authenticate(authRequest);
			SecurityContextHolder.getContext().setAuthentication(authResponse);

			response.sendRedirect(this.getSettings()
					.get(Constants.PROP_CTXPATH) + Constants.URL_UI_EXTJS);
			return null;
		} catch (Exception e) {
			ModelAndView err = this.showLogin(request, response);
			String msg = "Access denied. ";
			if (e.getMessage() != null && !"".equals(e.getMessage())) {
				msg += e.getMessage();
			}
			err.getModel().put("error", msg);
			return err;
		}
	}

	/**
	 * Process login action from an AJAX context
	 * 
	 * @param username
	 * @param password
	 * @param clientCode
	 * @param language
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "="
			+ Constants.SESSION_ACTION_LOGIN)
	public String loginExtjs(
			@RequestParam(value = "user", required = true) String username,
			@RequestParam(value = "pswd", required = true) String password,
			@RequestParam(value = "client", required = true) String clientCode,
			@RequestParam(value = "lang", required = false) String language,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
{'fraction_non_alphanumeric': 0.11758768609639163, 'fraction_numerical': 0.003196231810917655, 'mean_word_length': 4.977878330819507, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4560215', 'n_tokens_mistral': 3752, 'n_tokens_neox': 3357, 'n_words': 694}