public async Task <IActionResult> DownloadPersonalData() { PersonalDataResponse response = new PersonalDataResponse(); GoNorthUser currentUser = await _userManager.GetUserAsync(User); response.User = MapUser(currentUser); await FillModifiedData(response, currentUser); await FillAssignedTasks(response, currentUser); await FillTimelineEvents(response, currentUser); await FillTaskBoardHistory(response, currentUser); await FillLockEntries(response, currentUser); JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; MemoryStream returnStream = new MemoryStream(); StreamWriter writer = new StreamWriter(returnStream); string serializedResponse = JsonSerializer.Serialize(response, options); await writer.WriteAsync(serializedResponse); await writer.FlushAsync(); returnStream.Seek(0, SeekOrigin.Begin); return(File(returnStream, "application/json", "UserData.json")); }
/// <summary> /// Checks the lock state and locks if required /// </summary> /// <param name="category">Category of the lock</param> /// <param name="id">Id of the resource</param> /// <param name="lockIfFree">true if the resource should be locked if its free</param> /// <returns>Lock Response</returns> private async Task <IActionResult> CheckLockInternal(string category, string id, bool lockIfFree) { GoNorthUser currentUser = await _userManager.GetUserAsync(User); LockResponse response = new LockResponse(); response.LockedByOtherUser = false; response.LockValidForMinutes = LockTimespan; LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null) { if (existingLock.UserId != currentUser.Id && existingLock.ExpireDate > DateTimeOffset.UtcNow) { GoNorthUser lockedByUser = await _userManager.FindByIdAsync(existingLock.UserId); response.LockedByUserName = lockedByUser.DisplayName; response.LockedByOtherUser = true; return(Ok(response)); } } if (lockIfFree) { await _lockServiceDbAccess.LockResource(category, id, currentUser.Id, DateTimeOffset.UtcNow.AddMinutes(LockTimespan)); } return(Ok(response)); }
public async Task <IActionResult> ManageTemplate(TemplateType templateType) { GoNorthUser currentUser = await _userManager.GetUserAsync(this.User); UserPreferences userPreferences = await _userPreferencesDbAccess.GetUserPreferences(currentUser.Id); string scriptLanguage = await GetScriptLanguage(_exportDefaultTemplateProvider.IsTemplateTypeLanguage(templateType)); ManageTemplateViewModel viewModel = new ManageTemplateViewModel(); if (userPreferences != null) { viewModel.CodeEditorTheme = userPreferences.CodeEditorTheme; } if (scriptLanguage != null) { viewModel.ScriptLanguage = scriptLanguage; } viewModel.TemplateTypeUrls.Add(BuildExportTemplateTypeUrl(TemplateType.ObjectNpc, "/Kortisto/Npc?id={0}")); viewModel.TemplateTypeUrls.Add(BuildExportTemplateTypeUrl(TemplateType.ObjectItem, "/Styr/Item?id={0}")); viewModel.TemplateTypeUrls.Add(BuildExportTemplateTypeUrl(TemplateType.ObjectSkill, "/Evne/Skill?id={0}")); viewModel.DisableAutoSaving = _config.DisableAutoSaving.HasValue ? _config.DisableAutoSaving.Value : false; return(View(viewModel)); }
/// <summary> /// Sets the modified data /// </summary> /// <param name="controller">Controller that contains the Request to validate</param> /// <param name="userManager">UserManager</param> /// <param name="modifiedDataObject">Object which modified data should be set</param> /// <returns>Task</returns> public static async Task SetModifiedData(this Controller controller, UserManager <GoNorthUser> userManager, IHasModifiedData modifiedDataObject) { GoNorthUser currentUser = await userManager.GetUserAsync(controller.User); modifiedDataObject.ModifiedOn = DateTimeOffset.UtcNow; modifiedDataObject.ModifiedBy = currentUser.Id; }
public async Task <IActionResult> CreateUser([FromBody] UserCreateRequest userRequest) { if (string.IsNullOrEmpty(userRequest.Email) || string.IsNullOrEmpty(userRequest.DisplayName) || string.IsNullOrEmpty(userRequest.Password)) { return(StatusCode((int)HttpStatusCode.BadRequest)); } GoNorthUser user = new GoNorthUser { UserName = userRequest.Email, Email = userRequest.Email, DisplayName = userRequest.DisplayName }; IdentityResult result = await _userCreator.CreateUser(Url, Request.Scheme, userRequest.DisplayName, userRequest.Email, userRequest.Password, string.Empty); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); await _timelineService.AddTimelineEntry(TimelineEvent.NewUser, user.Email); return(Ok(user.Email)); } else { return(ReturnErrorResultFromIdentityResult(result)); } }
public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } GoNorthUser user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException(_localizer["UserNotFound"]); } IdentityResult changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { AddErrors(changePasswordResult); return(View(model)); } await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User changed their password successfully."); StatusMessage = _localizer["PasswordHasBeenChanged"]; return(RedirectToAction(nameof(ChangePassword))); }
public async Task <IActionResult> DeleteUser(string id) { string currentUserId = _userManager.GetUserId(User); if (currentUserId == id) { return(StatusCode((int)HttpStatusCode.BadRequest, _localizer["YouCanNotDeleteYourself"].Value)); } GoNorthUser user = await _userDbAccess.GetUserById(id); IdentityResult result = await _userManager.DeleteAsync(user); if (result.Succeeded) { _logger.LogInformation("User was deleted."); await _timelineService.AddTimelineEntry(TimelineEvent.UserDeleted, user.Email); return(Ok(id)); } else { return(ReturnErrorResultFromIdentityResult(result)); } }
/// <summary> /// Resets the assigned tasks for a user /// </summary> /// <param name="user">User</param> /// <returns>Task</returns> private async Task ResetAssignedTasks(GoNorthUser user) { List <TaskBoard> taskBoards = await _taskBoardDbAccess.GetAllTaskBoardsByAssignedUser(user.Id); foreach (TaskBoard curBoard in taskBoards) { bool changedBoard = false; foreach (TaskGroup curTaskGroup in curBoard.TaskGroups) { if (curTaskGroup.AssignedTo == user.Id) { curTaskGroup.AssignedTo = null; changedBoard = true; } foreach (GoNorthTask curTask in curTaskGroup.Tasks) { if (curTask.AssignedTo == user.Id) { curTask.AssignedTo = null; changedBoard = true; } } } if (changedBoard) { await _taskBoardDbAccess.UpdateTaskBoard(curBoard); } } }
public async Task <IActionResult> SetUserRoles(string id, [FromBody] List <string> roles) { GoNorthUser user = await _userDbAccess.GetUserById(id); List <string> rolesToRemove = user.Roles.Except(roles).ToList(); IdentityResult result = await _userManager.RemoveFromRolesAsync(user, rolesToRemove); if (!result.Succeeded) { return(ReturnErrorResultFromIdentityResult(result)); } List <string> rolesToAdd = roles.Except(user.Roles).ToList(); result = await _userManager.AddToRolesAsync(user, rolesToAdd); if (!result.Succeeded) { return(ReturnErrorResultFromIdentityResult(result)); } _logger.LogInformation("User roles were set."); await _timelineService.AddTimelineEntry(TimelineEvent.UserRolesSet, user.Email, string.Join(", ", roles)); return(Ok(id)); }
/// <summary> /// Fills the task board history /// </summary> /// <param name="response">Response to send</param> /// <param name="currentUser">Current user</param> /// <returns>Task</returns> private async Task FillTaskBoardHistory(PersonalDataResponse response, GoNorthUser currentUser) { response.TaskBoardHistory = new List <TrimmedTaskBoardHistory>(); List <UserTaskBoardHistory> taskBoardHistory = await _userTaskBoardHistoryDbAccess.GetAllOpenedBoardsOfUser(currentUser.Id); foreach (UserTaskBoardHistory curTaskBoard in taskBoardHistory) { TrimmedTaskBoardHistory curTaskBoardHistory = new TrimmedTaskBoardHistory(); curTaskBoardHistory.BoardName = "DELETED"; curTaskBoardHistory.Project = "DELETED"; TaskBoard taskBoard = await _taskBoardDbAccess.GetTaskBoardById(curTaskBoard.LastOpenBoardId); if (taskBoard != null) { curTaskBoardHistory.BoardName = taskBoard.Name; } GoNorthProject project = await _projectDbAccess.GetProjectById(curTaskBoard.ProjectId); if (project != null) { curTaskBoardHistory.Project = project.Name; } response.TaskBoardHistory.Add(curTaskBoardHistory); } }
public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } GoNorthUser user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction(nameof(ResetPasswordConfirmation))); } IdentityResult result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return(RedirectToAction(nameof(ResetPasswordConfirmation))); } AddErrors(result); return(View()); }
public async Task <IActionResult> SaveUserPreferences([FromBody] UserPreferences preferences) { GoNorthUser currentUser = await _userManager.GetUserAsync(this.User); await _userPreferencesDbAccess.SetUserCodeEditorTheme(currentUser.Id, preferences.CodeEditorTheme); return(Ok()); }
public async Task <IActionResult> GetUserPreferences() { GoNorthUser currentUser = await _userManager.GetUserAsync(this.User); UserPreferences userPreferences = await _userPreferencesDbAccess.GetUserPreferences(currentUser.Id); return(Ok(userPreferences)); }
/// <summary> /// Configures the admin account /// </summary> /// <returns>Task</returns> private static async Task ConfigureAdminAccount() { ServiceProvider serviceProvider = ServiceProviderBuilder.BuildServiceProvider(); IUserDbAccess userDbAccess = serviceProvider.GetService <IUserDbAccess>(); if (await userDbAccess.DoesAdminUserExist()) { MessageService.PrintAdminAccountExistMessage(); return; } string email; do { try { string displayName = MessageService.GetAdminAccountDisplayName(); email = MessageService.GetAdminAccountEMail(); string password = MessageService.GetAdminAccountPassword(); IUserCreator userCreator = serviceProvider.GetService <IUserCreator>(); IdentityResult result = await userCreator.CreateUser(new MockUrlHelper(), "https", displayName, email, password, RoleNames.Administrator); if (!result.Succeeded) { throw new Exception(string.Join(',', result.Errors.Select(e => e.Description))); } MessageService.PrintSuccessCreatingAdminAccount(); break; } catch (Exception ex) { MessageService.PrintErrorCreatingAdminAccount(ex); } }while(true); try { UserManager <GoNorthUser> userManager = serviceProvider.GetService <UserManager <GoNorthUser> >(); GoNorthUser adminUser = await userManager.FindByEmailAsync(email); List <string> rolesToAdd = RoleNames.GetAllRoleNames().Where(r => r != RoleNames.Administrator).ToList(); IdentityResult result = await userManager.AddToRolesAsync(adminUser, rolesToAdd); if (!result.Succeeded) { throw new Exception(string.Join(',', result.Errors.Select(e => e.Description))); } } catch (Exception ex) { MessageService.PrintErrorAssignAllRolesToUser(ex); } }
/// <summary> /// Fills the timeline events for a user /// </summary> /// <param name="response">Response to send</param> /// <param name="currentUser">Current user</param> /// <returns>Task</returns> private async Task FillTimelineEvents(PersonalDataResponse response, GoNorthUser currentUser) { List <TimelineEntry> timelineEntries = await _timelineDbAccess.GetTimelineEntriesByUser(currentUser.UserName); response.TimelineEntries = timelineEntries.Select(t => new TrimmedTimelineEntry { Event = t.Event.ToString(), Date = t.Timestamp }).ToList(); }
/// <summary> /// Lock entries /// </summary> /// <param name="response">Response to send</param> /// <param name="currentUser">Current user</param> /// <returns>Task</returns> private async Task FillLockEntries(PersonalDataResponse response, GoNorthUser currentUser) { List <LockEntry> locks = await _lockDbAccess.GetAllLocksOfUser(currentUser.Id); response.LockEntries = locks.Select(l => new TrimmedLockEntry { Id = l.Id, Category = l.Category, ResourceId = l.ResourceId, ExpireDate = l.ExpireDate }).ToList(); }
/// <summary> /// Maps a user to a response user /// </summary> /// <param name="user">User to map</param> /// <returns>User Response</returns> private TrimmedResponseUser MapUserToResponse(GoNorthUser user) { return(new TrimmedResponseUser { Id = user.Id, UserName = user.UserName, Email = user.Email, DisplayName = user.DisplayName, IsEmailConfirmed = user.EmailConfirmed, Roles = user.Roles }); }
/// <summary> /// Deletes a user and all associated data /// </summary> /// <param name="user">User</param> /// <returns>Deletion result</returns> public async Task <IdentityResult> DeleteUser(GoNorthUser user) { await DeleteModifiedData(user); await ResetAssignedTasks(user); await DeleteUserTaskBoardHistory(user); await DeleteTimelineEvents(user); await DeleteLocksOfUser(user); IdentityResult result = await _userManager.DeleteAsync(user); return(result); }
/// <summary> /// Maps a user to a return user /// </summary> /// <param name="user">User</param> /// <returns>Trimmed user</returns> private TrimmedUser MapUser(GoNorthUser user) { TrimmedUser returnUser = new TrimmedUser { Id = user.Id, Username = user.UserName, Email = user.Email, EmailIsConfirmed = user.EmailConfirmed, DisplayName = user.DisplayName, Roles = user.Roles.ToList() }; return(returnUser); }
public async Task <IActionResult> Index(IndexViewModel model) { if (!ModelState.IsValid) { return(View(model)); } GoNorthUser user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException(_localizer["UserNotFound"]); } bool userChanged = false; string email = user.Email; if (model.Email != email) { IdentityResult setEmailResult = await _userManager.SetEmailAsync(user, model.Email); if (!setEmailResult.Succeeded) { throw new ApplicationException(_localizer["ErrorOccurredWhileSaving"]); } userChanged = true; } if (model.DisplayName != user.DisplayName) { user.DisplayName = model.DisplayName; userChanged = true; } if (userChanged) { IdentityResult updateResult = await _userManager.UpdateAsync(user); if (!updateResult.Succeeded) { throw new ApplicationException(_localizer["ErrorOccurredWhileSaving"]); } await _signInManager.RefreshSignInAsync(user); } StatusMessage = _localizer["ProfileHasBeenUpdated"]; return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> DeleteLock(string category, string id, bool appendProjectIdToKey = false) { id = await AppendProjectIdIfRequired(id, appendProjectIdToKey); GoNorthUser currentUser = await _userManager.GetUserAsync(User); LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null && existingLock.UserId == currentUser.Id) { await _lockServiceDbAccess.DeleteLockById(existingLock.Id); } return(Ok()); }
/// <summary> /// Fills the assigned tasks of the user /// </summary> /// <param name="response">Response to send</param> /// <param name="currentUser">Current user</param> /// <returns>Task</returns> private async Task FillAssignedTasks(PersonalDataResponse response, GoNorthUser currentUser) { List <TaskBoard> taskBoards = await _taskBoardDbAccess.GetAllTaskBoardsByAssignedUser(currentUser.Id); response.AssignedTasks = taskBoards.SelectMany(t => t.TaskGroups.Where(tg => tg.AssignedTo == currentUser.Id)).Select(t => new TrimmedTask { Name = t.Name, Description = t.Description, IsTaskGroup = true }).ToList(); response.AssignedTasks.AddRange(taskBoards.SelectMany(t => t.TaskGroups.SelectMany(tg => tg.Tasks.Where(ta => ta.AssignedTo == currentUser.Id))).Select(t => new TrimmedTask { Name = t.Name, Description = t.Description, IsTaskGroup = false }).ToList()); }
public async Task <IActionResult> UpdateSecurityStampForUser(string id) { GoNorthUser user = await _userDbAccess.GetUserById(id); IdentityResult result = await _userManager.UpdateSecurityStampAsync(user); if (result.Succeeded) { _logger.LogInformation("User security stamp was updated."); return(Ok(id)); } else { return(ReturnErrorResultFromIdentityResult(result)); } }
public async Task <IActionResult> GetCodeEditorPreferences() { GoNorthUser currentUser = await _userManager.GetUserAsync(this.User); UserPreferences userPreferences = await _userPreferencesDbAccess.GetUserPreferences(currentUser.Id); GoNorthProject defaultProject = await _projectDbAccess.GetDefaultProject(); ExportSettings settings = await _exportSettingsDbAccess.GetExportSettings(defaultProject.Id); UserCodeEditorPreferences codeEditorPreferences = new UserCodeEditorPreferences(); codeEditorPreferences.CodeEditorTheme = userPreferences.CodeEditorTheme; codeEditorPreferences.ScriptLanguage = settings.ScriptLanguage; return(Ok(codeEditorPreferences)); }
public async Task <IActionResult> DeleteUserData() { GoNorthUser currentUser = await _userManager.GetUserAsync(User); IdentityResult result = await _userDeleter.DeleteUser(currentUser); if (result.Succeeded) { await _signInManager.SignOutAsync(); return(RedirectToAction("SignedOut", "Account")); } else { return(StatusCode((int)HttpStatusCode.InternalServerError)); } }
/// <summary> /// Removes the unused roles for the users /// </summary> /// <param name="userDbAccess">Usser Db Access</param> /// <returns>Task</returns> private async Task RemoveUnusedRolesForUsers(IUserDbAccess userDbAccess) { List <string> existingRoles = RoleNames.GetAllRoleNames(); IList <GoNorthUser> users = await userDbAccess.GetUsers(0, int.MaxValue); foreach (GoNorthUser curUser in users) { IEnumerable <string> deletedRoles = curUser.Roles.Except(existingRoles); if (deletedRoles != null && deletedRoles.Any()) { GoNorthUser user = await userDbAccess.GetUserById(curUser.Id); user.Roles = curUser.Roles.Except(deletedRoles).ToList(); await userDbAccess.UpdateUser(user); } } }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(RedirectToAction(nameof(HomeController.Index), "Home")); } GoNorthUser user = await _userManager.FindByIdAsync(userId); if (user == null) { throw new ApplicationException(_localizer["UserNotFound"]); } IdentityResult result = await _userManager.ConfirmEmailAsync(user, code); return(View(result.Succeeded ? "ConfirmEmail" : "Error")); }
public async Task <IActionResult> ConfirmEmailForUser(string id) { GoNorthUser user = await _userDbAccess.GetUserById(id); string code = await _userManager.GenerateEmailConfirmationTokenAsync(user); IdentityResult result = await _userManager.ConfirmEmailAsync(user, code); if (result.Succeeded) { _logger.LogInformation("User email was confirmed."); return(Ok(id)); } else { return(ReturnErrorResultFromIdentityResult(result)); } }
public async Task <IActionResult> Index() { GoNorthUser user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException(_localizer["UserNotFound"]); } IndexViewModel model = new IndexViewModel { Username = user.UserName, DisplayName = user.DisplayName, Email = user.Email, IsEmailConfirmed = user.EmailConfirmed, StatusMessage = StatusMessage }; return(View(model)); }
/// <summary> /// Adds a timeline event /// </summary> /// <param name="timelineEvent">Timeline Event</param> /// <param name="additionalValues">Additional Values</param> /// <returns>Task</returns> public async Task AddTimelineEntry(TimelineEvent timelineEvent, params string[] additionalValues) { Task <GoNorthUser> currentUserTask = _userManager.GetUserAsync(_httpContext.HttpContext.User); Task <GoNorthProject> projectTask = _projectDbAccess.GetDefaultProject(); Task.WaitAll(currentUserTask, projectTask); GoNorthUser currentUser = currentUserTask.Result; GoNorthProject project = projectTask.Result; TimelineEntry entry = new TimelineEntry(); entry.ProjectId = project != null ? project.Id : string.Empty; entry.Event = timelineEvent; entry.Timestamp = DateTimeOffset.UtcNow; entry.AdditionalValues = additionalValues; entry.Username = currentUser.UserName; entry.UserDisplayName = currentUser.DisplayName; await _timelineDbAccess.CreateTimelineEntry(entry); }