<commit_before>package com.ilearnrw.app.usermanager;

import ilearnrw.user.profile.UserProfile;
import ilearnrw.utils.LanguageCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ilearnrw.api.datalogger.model.LogEntryResult;
import com.ilearnrw.api.profileAccessUpdater.IProfileProvider;
import com.ilearnrw.api.profileAccessUpdater.IProfileProvider.ProfileProviderException;
import com.ilearnrw.app.usermanager.form.RolePermissionsForm;
import com.ilearnrw.app.usermanager.form.TeacherStudentForm;
import com.ilearnrw.app.usermanager.form.UserNewForm;
import com.ilearnrw.app.usermanager.form.UserRolesForm;
import com.ilearnrw.common.AuthenticatedRestClient;
import com.ilearnrw.common.security.Tokens;
import com.ilearnrw.common.security.users.model.Permission;
import com.ilearnrw.common.security.users.model.Role;
import com.ilearnrw.common.security.users.model.User;
import com.ilearnrw.common.security.users.services.PermissionService;
import com.ilearnrw.common.security.users.services.RoleService;
import com.ilearnrw.common.security.users.services.TeacherStudentService;
import com.ilearnrw.common.security.users.services.UserService;

@Controller
public class UserManagerController {

	private static Logger LOG = Logger.getLogger(UserManagerController.class);

	@Autowired
	@Qualifier("usersDataSource")
	private DataSource dSource;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private TeacherStudentService teacherStudentService;

	@Autowired
	IProfileProvider profileProvider;

	@Autowired
	private AuthenticatedRestClient restClient;

	@RequestMapping(value = "/panel", method = RequestMethod.GET)
	public String panel(ModelMap modelMap) {
		modelMap.addAttribute("teachers",
				teacherStudentService.getTeacherList());
		modelMap.addAttribute("users", userService.getUserList());
		modelMap.addAttribute("roles", roleService.getRoleList());
		modelMap.addAttribute("permissions",
				permissionService.getPermissionList());
		return "statistics/stats";
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request) {
		SecurityContextHolder.getContext().setAuthentication(null);
		request.getSession().invalidate();
		return "redirect:/apps/login";
	}

	@RequestMapping(value = "/login")
	public String login() {
		return "main/login";
	}

	@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
		model.addAttribute("error", "true");
		return "main/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username,
			@RequestParam("pass") String pass, ModelMap model,
			HttpServletRequest request) {

		try {
			Tokens tokens = restClient.getTokens(username, pass);

			List<String> roles = restClient.getRoles(tokens.getAuthToken());

			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			for (String role : roles) {
				authorities.add(new SimpleGrantedAuthority(role));
			}
			Authentication userAuthentication = new UsernamePasswordAuthenticationToken(
					username, tokens.getAuthToken(), authorities);

			SecurityContextHolder.getContext().setAuthentication(
					userAuthentication);

			request.getSession().setAttribute("username", username);
			User user = userService.getUserByUsername(username);
			request.getSession().setAttribute("userid", user.getId());
			request.getSession().setAttribute("students", teacherStudentService.getStudentList(user));

		} catch (Exception e) {
			model.addAttribute("error", e.getMessage());
			return "main/login";
		}
		return "redirect:/apps/panel";
	}

	/* Users logs */
	
	@RequestMapping(value = "users/manage")
	public String manageUsers(ModelMap modelMap) {
		modelMap.addAttribute("users", userService.getUserList());
		return "users/manage";
	}

	@RequestMapping(value = "users/{username}/logs/page/{page}", method = RequestMethod.GET)
	public String viewLogs(@PathVariable String username,
			@PathVariable String page, ModelMap model,
			HttpServletRequest request) {

		Map<String, String> args = new HashMap<String, String>();
		args.put("username", username);
		args.put("page", page);
		for (String param : Arrays.asList("timestart", "timeend", "tags",
				"applicationId"))
			if (request.getSession().getAttribute(param) != null)
				args.put(param,
						(String) request.getSession().getAttribute(param));
		LogEntryResult result = restClient.getLogs(args);
		model.addAttribute("logEntryResult", result);
		return "users/logs";
	}

	@RequestMapping(value = "users/{username}/logs/page/{page}", method = RequestMethod.POST)
	public String viewLogsFiltered(
			@PathVariable String username,
			@PathVariable String page,
			@RequestParam(value = "timestart", required = false) String timestart,
			@RequestParam(value = "timeend", required = false) String timeend,
			@RequestParam(value = "tags", required = false) String tags,
			@RequestParam(value = "applicationId", required = false) String applicationId,
			ModelMap model, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("timestart", timestart);
		map.put("timeend", timeend);
		map.put("tags", tags);
		map.put("applicationId", applicationId);
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (entry.getValue() != null && !entry.getValue().isEmpty())
				request.getSession().setAttribute(entry.getKey(),
						entry.getValue());
			else
				request.getSession().removeAttribute(entry.getKey());
		}

		return viewLogs(username, page, model, request);
	}

	/* Users profile */

	@RequestMapping(value = "users/{id}/profile", method = RequestMethod.GET)
	@Transactional(readOnly = true)
	public String viewProfile(@PathVariable int id, ModelMap model)
			throws ProfileProviderException, Exception {<commit_msg>View logs by user id instead of username.<commit_after>package com.ilearnrw.app.usermanager;

import ilearnrw.user.profile.UserProfile;
import ilearnrw.utils.LanguageCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ilearnrw.api.datalogger.model.LogEntryResult;
import com.ilearnrw.api.profileAccessUpdater.IProfileProvider;
import com.ilearnrw.api.profileAccessUpdater.IProfileProvider.ProfileProviderException;
import com.ilearnrw.app.usermanager.form.RolePermissionsForm;
import com.ilearnrw.app.usermanager.form.TeacherStudentForm;
import com.ilearnrw.app.usermanager.form.UserNewForm;
import com.ilearnrw.app.usermanager.form.UserRolesForm;
import com.ilearnrw.common.AuthenticatedRestClient;
import com.ilearnrw.common.security.Tokens;
import com.ilearnrw.common.security.users.model.Permission;
import com.ilearnrw.common.security.users.model.Role;
import com.ilearnrw.common.security.users.model.User;
import com.ilearnrw.common.security.users.services.PermissionService;
import com.ilearnrw.common.security.users.services.RoleService;
import com.ilearnrw.common.security.users.services.TeacherStudentService;
import com.ilearnrw.common.security.users.services.UserService;

@Controller
public class UserManagerController {

	private static Logger LOG = Logger.getLogger(UserManagerController.class);

	@Autowired
	@Qualifier("usersDataSource")
	private DataSource dSource;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private TeacherStudentService teacherStudentService;

	@Autowired
	IProfileProvider profileProvider;

	@Autowired
	private AuthenticatedRestClient restClient;

	@RequestMapping(value = "/panel", method = RequestMethod.GET)
	public String panel(ModelMap modelMap) {
		modelMap.addAttribute("teachers",
				teacherStudentService.getTeacherList());
		modelMap.addAttribute("users", userService.getUserList());
		modelMap.addAttribute("roles", roleService.getRoleList());
		modelMap.addAttribute("permissions",
				permissionService.getPermissionList());
		return "statistics/stats";
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request) {
		SecurityContextHolder.getContext().setAuthentication(null);
		request.getSession().invalidate();
		return "redirect:/apps/login";
	}

	@RequestMapping(value = "/login")
	public String login() {
		return "main/login";
	}

	@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
		model.addAttribute("error", "true");
		return "main/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username,
			@RequestParam("pass") String pass, ModelMap model,
			HttpServletRequest request) {

		try {
			Tokens tokens = restClient.getTokens(username, pass);

			List<String> roles = restClient.getRoles(tokens.getAuthToken());

			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			for (String role : roles) {
				authorities.add(new SimpleGrantedAuthority(role));
			}
			Authentication userAuthentication = new UsernamePasswordAuthenticationToken(
					username, tokens.getAuthToken(), authorities);

			SecurityContextHolder.getContext().setAuthentication(
					userAuthentication);

			request.getSession().setAttribute("username", username);
			User user = userService.getUserByUsername(username);
			request.getSession().setAttribute("userid", user.getId());
			request.getSession().setAttribute("students", teacherStudentService.getStudentList(user));

		} catch (Exception e) {
			model.addAttribute("error", e.getMessage());
			return "main/login";
		}
		return "redirect:/apps/panel";
	}

	/* Users logs */
	
	@RequestMapping(value = "users/manage")
	public String manageUsers(ModelMap modelMap) {
		modelMap.addAttribute("users", userService.getUserList());
		return "users/manage";
	}

	@RequestMapping(value = "users/{id}/logs/page/{page}", method = RequestMethod.GET)
	public String viewLogs(@PathVariable int id,
			@PathVariable String page, ModelMap model,
			HttpServletRequest request) {

		Map<String, String> args = new HashMap<String, String>();
		User user = userService.getUser(id);
		args.put("username", user.getUsername());
		args.put("page", page);
		for (String param : Arrays.asList("timestart", "timeend", "tags",
				"applicationId"))
			if (request.getSession().getAttribute(param) != null)
				args.put(param,
						(String) request.getSession().getAttribute(param));
		LogEntryResult result = restClient.getLogs(args);
		model.addAttribute("logEntryResult", result);
		return "users/logs";
	}

	@RequestMapping(value = "users/{id}/logs/page/{page}", method = RequestMethod.POST)
	public String viewLogsFiltered(
			@PathVariable int id,
			@PathVariable String page,
			@RequestParam(value = "timestart", required = false) String timestart,
			@RequestParam(value = "timeend", required = false) String timeend,
			@RequestParam(value = "tags", required = false) String tags,
			@RequestParam(value = "applicationId", required = false) String applicationId,
			ModelMap model, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("timestart", timestart);
		map.put("timeend", timeend);
		map.put("tags", tags);
		map.put("applicationId", applicationId);
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (entry.getValue() != null && !entry.getValue().isEmpty())
				request.getSession().setAttribute(entry.getKey(),
						entry.getValue());
			else
				request.getSession().removeAttribute(entry.getKey());
		}

		return viewLogs(id, page, model, request);
	}

	/* Users profile */

	@RequestMapping(value = "users/{id}/profile", method = RequestMethod.GET)
	@Transactional(readOnly = true)
	public String viewProfile(@PathVariable int id, ModelMap model)
			throws ProfileProviderException, Exception {
{'fraction_non_alphanumeric': 0.11925838154317976, 'fraction_numerical': 0.0001394019655677145, 'mean_word_length': 6.092436974789916, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, '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': '830270', 'n_tokens_mistral': 4325, 'n_tokens_neox': 4063, 'n_words': 774}