/// <summary> /// Attempts authentication through AD and then adds the user to the DB if they do not already exist with the /// "Authorized User" role added as a default. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public IUserDto Login(string username, string password) { AdUser adUser = new AdUser(); if (adUser.AuthenticateUser(username, password)) { using (var context = new PrometheusContext()) { //See if the user exists already IUserDto user = null; try { user = GetUser(adUser.UserGuid); } catch (Exception) { /* user does not exist */ } if (user != null) { //If they existed retrun them user.Name = GetDisplayName(user.AdGuid); return(user); } else { //Otherwise add them with the authenticated role var newUser = new UserDto { AdGuid = adUser.UserGuid }; //Get the role that is to be added to the user var authenticatedRole = context.Roles.FirstOrDefault(x => x.Name == AuthorizedUserRoleName); //get the user's department var id = int.Parse(ConfigurationManager.AppSettings["GetDepartmentScriptId"]); var scriptGuid = _departmentController.GetDepartmentScriptFromId(id); string departmentName = _scriptExecutor.GetUserDepartment(newUser.AdGuid, scriptGuid); if (string.IsNullOrEmpty(departmentName)) { throw new Exception("Login failure: no department available for this account"); } try { newUser.DepartmentId = (from d in _departmentController.GetDepartments(newUser.Id) where d.Name == departmentName select d.Id).FirstOrDefault(); if (newUser.DepartmentId < 1) //somewhere invalid departments are not getting thrown... { throw new Exception("Login failure: no department configured for this account"); } } catch (Exception) { throw new Exception("Login failure: no department configured for this account"); } //Add them and their role to the database var savedUser = context.Users.Add(ManualMapper.MapDtoToUser(newUser)); savedUser.Roles = new List <Role> { authenticatedRole }; context.SaveChanges(); newUser = (UserDto)ManualMapper.MapUserToDto(savedUser); newUser.Department = new DepartmentDto { Name = departmentName, Id = newUser.DepartmentId }; //attach the department newUser.Name = GetDisplayName(newUser.AdGuid); //Name resolution return(newUser); } } } //failed login if there is no AD Authentication return(new UserDto { Name = "failed" }); }