public async Task <IActionResult> Add() { ViewData["Title"] = _localizer["PageTitleAdd"]; ViewData["PageDesc"] = _localizer["PageDescAdd"]; var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); var batchVolumeQuery = _journalQueryFactory.CreateBatchVolumeUOMQuery(); var uomVolumeList = await batchVolumeQuery.ExecuteAsync().ConfigureAwait(false); var getCategoriesQuery = _recipeQueryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var varietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var vList = await varietiesQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); var addBatchModel = _modelFactory.CreateBatchViewModel(null, null, vList, cList, yList, null, uomVolumeList, uomSugarList, uomTempList); // validate with User (ApplicationUser) var appUser = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); addBatchModel.BatchJwt = await CreateJwtTokenAsync(appUser, 15).ConfigureAwait(false); return(View(addBatchModel)); }
public async Task <IActionResult> SendPasswordResetLink(RequestPasswordResetViewModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var user = await UserManagerAgent.FindByNameAsync(model.UserName).ConfigureAwait(false); if (user == null || !await UserManagerAgent.IsEmailConfirmedAsync(user).ConfigureAwait(false)) { ViewBag.Message = "Error while resetting your password!"; return(View("Error")); } var token = await UserManagerAgent.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false); var resetLink = Url.Action("ResetPassword", "Account", new { token }, protocol: HttpContext.Request.Scheme); // code to email the above link string[] emailAddresses = { _appSettings.SMTP.AdminEmail, user.Email }; await _emailAgent.SendEmailAsync(_appSettings.SMTP.FromEmail, _appSettings.SMTP.FromEmail, emailAddresses, "Winemakers Software - Password Reset.", CreatePasswordResetEmail(resetLink), true, null).ConfigureAwait(false); // redirect to limbo page return(RedirectToAction("PasswordLimbo", "Account")); }
/// <summary> /// Opening Page for Entering New Recipes /// </summary> public async Task <IActionResult> Add() { ViewData["Title"] = _localizer["PageTitleAdd"]; ViewData["PageDesc"] = _localizer["PageDescAdd"]; var getCategoriesQuery = _queryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var getVarietiesQuery = _queryFactory.CreateVarietiesQuery(); var vList = await getVarietiesQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); var addRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList); addRecipeModel.User = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); return(View(addRecipeModel)); }
public async Task <IActionResult> Register(RegisterViewModel model, Uri returnUrl = null) { ViewData["Title"] = "Register"; // ViewData["Menu"] = "navAccount"; ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model?.UserName, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email }; var result = await UserManagerAgent.CreateAsync(user, model.Password).ConfigureAwait(false); if (result.Succeeded) { if (!await RoleManagerAgent.RoleExistsAsync(_appSettings.SecRole.Level1).ConfigureAwait(false)) { ApplicationRole role = new ApplicationRole { Name = _appSettings.SecRole.Level1, Description = "Perform basic operations." }; IdentityResult roleResult = await RoleManagerAgent.CreateAsync(role).ConfigureAwait(false); if (!roleResult.Succeeded) { ModelState.AddModelError(string.Empty, "Error while creating role!"); return(View(model)); } } UserManagerAgent.AddToRoleAsync(user, _appSettings.SecRole.Level1).Wait(); // send confirmation email string confirmationToken = await UserManagerAgent.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false); string confirmationLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = confirmationToken }, protocol: HttpContext.Request.Scheme); string[] emailAddresses = { _appSettings.SMTP.AdminEmail, user.Email }; var emailName = string.IsNullOrWhiteSpace(user.FirstName) ? user.UserName : $"{user.FirstName} {user.LastName}".Trim(); await _emailAgent.SendEmailAsync(_appSettings.SMTP.FromEmail, _appSettings.SMTP.FromEmail, emailAddresses, "Welcome to Winemakers Software - Please verify your email.", CreateVerifyEmail(confirmationLink, emailName), true, null).ConfigureAwait(false); // redirect to limbo page return(RedirectToAction("RegisterLimbo", "Account")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Index() { ViewData["Title"] = _localizer["PageTitle"]; ViewData["PageDesc"] = _localizer["PageDesc"]; var submittedBy = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); var model = _modelFactory.CreateContactModel(); model.User = submittedBy; return(View(model)); }
public async Task <IActionResult> EditUser(UserViewModel model) { ViewData["Title"] = "Edit a User"; var user = await UserManagerAgent.FindByNameAsync(model?.UserName).ConfigureAwait(false); model = _mapper.Map <UserViewModel>(user); model.MemberRoles.AddRange(await UserManagerAgent.GetRolesAsync(user).ConfigureAwait(false)); model.AllRoles.AddRange(GetAllRolesAsSelectList()); return(View(model)); }
public async Task <IActionResult> DeleteUser(string UserName) { var user = await UserManagerAgent.FindByNameAsync(UserName).ConfigureAwait(false); if (user != null) { if (!await UserManagerAgent.IsInRoleAsync(user, _appSettings.SecRole.Admin).ConfigureAwait(false)) { await UserManagerAgent.DeleteAsync(user).ConfigureAwait(false); } } return(RedirectToAction("Index", "Admin", new { id = "users" })); }
/// <summary> /// Create a roles based access token with roles assigned by user /// </summary> /// <param name="user">User as <see cref="ApplicationUser"/></param> /// <param name="expireMinutes">Minutes Token will remain alive as <see cref="double?"/></param> /// <returns>JWT Token as <see cref="string"/></returns> protected async Task <string> CreateJwtTokenAsync(ApplicationUser user, double?expireMinutes = null) { if (string.IsNullOrWhiteSpace(user?.UserName)) { return(null); } var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var userClaims = await UserManagerAgent.GetClaimsAsync(user).ConfigureAwait(false); var userRoles = await UserManagerAgent.GetRolesAsync(user).ConfigureAwait(false); claims.AddRange(userClaims); foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); var role = await RoleManagerAgent.FindByNameAsync(userRole).ConfigureAwait(false); if (role != null) { var roleClaims = await RoleManagerAgent.GetClaimsAsync(role).ConfigureAwait(false); foreach (Claim roleClaim in roleClaims) { claims.Add(roleClaim); } } } double expirationMinutes = expireMinutes ?? double.Parse(ConfigurationAgent["JwtToken:ExpireMinutes"], CultureInfo.CurrentCulture); var token = new JwtSecurityToken ( issuer: ConfigurationAgent["JwtToken:Issuer"], audience: ConfigurationAgent["JwtToken:Audience"], claims: claims, expires: DateTime.UtcNow.AddMinutes(expirationMinutes), notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationAgent["JwtToken:Key"])), SecurityAlgorithms.HmacSha256) ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task <IActionResult> UnlockUser(string UserName) { var user = await UserManagerAgent.FindByNameAsync(UserName).ConfigureAwait(false); if (await UserManagerAgent.IsLockedOutAsync(user).ConfigureAwait(false)) { var result = await UserManagerAgent.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow).ConfigureAwait(false); if (result.Succeeded) { await UserManagerAgent.ResetAccessFailedCountAsync(user).ConfigureAwait(false); } } return(RedirectToAction("Index", "Admin", new { id = "users" })); }
public async Task <IActionResult> DeleteUserRole(UserViewModel model) { ViewData["Title"] = "Edit a User"; var user = await UserManagerAgent.FindByNameAsync(model?.UserName).ConfigureAwait(false); if (await RoleManagerAgent.RoleExistsAsync(model.NewRole).ConfigureAwait(false) && await UserManagerAgent.IsInRoleAsync(user, model.NewRole).ConfigureAwait(false)) { await UserManagerAgent.RemoveFromRoleAsync(user, model.NewRole).ConfigureAwait(false); } model = _mapper.Map <UserViewModel>(user); model.MemberRoles.AddRange(await UserManagerAgent.GetRolesAsync(user).ConfigureAwait(false)); model.AllRoles.AddRange(GetAllRolesAsSelectList()); return(View("EditUser", model)); }
public async Task <IActionResult> ConfirmEmail(string userid, string token) { ApplicationUser user = await UserManagerAgent.FindByIdAsync(userid).ConfigureAwait(false); IdentityResult result = await UserManagerAgent.ConfirmEmailAsync(user, token).ConfigureAwait(false); if (result.Succeeded) { Success(_localizer["EmailConfirmSuccess"], true); return(View("Login")); } else { Danger(_localizer["EmailConfirmFail"]); return(View("Register")); } }
public async Task <IActionResult> Login(LoginViewModel model, Uri returnUrl = null) { ViewData["Title"] = "Login"; // ViewData["Menu"] = "navAccount"; ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = await UserManagerAgent.FindByNameAsync(model?.UserName).ConfigureAwait(false); if (user != null) { // check that user has validated email address if (!await UserManagerAgent.IsEmailConfirmedAsync(user).ConfigureAwait(false)) { ModelState.AddModelError(string.Empty, "Email has not yet been verified! Please check your Email Inbox and click Verify."); return(View(model)); } var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent : true, lockoutOnFailure : false).ConfigureAwait(false); if (result.Succeeded) { await UserManagerAgent.ResetAccessFailedCountAsync(user).ConfigureAwait(false); return(RedirectToLocal(returnUrl?.ToString())); } if (result.IsLockedOut) { var availableNext = user.LockoutEnd.Value.ToLocalTime().ToString("g", CultureInfo.CurrentCulture); ModelState.AddModelError("", string.Format(CultureInfo.CurrentCulture, "Due to multiple failed login attempts, your account has been locked out until {0}", availableNext)); } else { await UserManagerAgent.AccessFailedAsync(user).ConfigureAwait(false); ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View(model)); } } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> EditBatch(int id) { ViewData["Title"] = _localizer["PageTitleDetails"]; ViewData["PageDesc"] = _localizer["PageDescDetails"]; var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); var batchVolumeQuery = _journalQueryFactory.CreateBatchVolumeUOMQuery(); var uomVolumeList = await batchVolumeQuery.ExecuteAsync().ConfigureAwait(false); var getCategoriesQuery = _recipeQueryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var varietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var vList = await varietiesQuery.ExecuteAsync().ConfigureAwait(false); var cultureQuery = _maloCultureQueryFactory.CreateMaloCulturesQuery(); var cultureList = await cultureQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); var batchQuery = _journalQueryFactory.CreateBatchesQuery(); var batchDto = await batchQuery.ExecuteAsync(id).ConfigureAwait(false); var entriesQuery = _journalQueryFactory.CreateBatchEntriesQuery(); var entriesDto = await entriesQuery.ExecuteByFKAsync(id).ConfigureAwait(true); var batchEntriesDto = entriesDto .OrderByDescending(e => e.ActionDateTime) .ThenByDescending(e => e.EntryDateTime).ToList(); var model = _modelFactory.CreateBatchViewModel(batchDto, batchEntriesDto, vList, cList, yList, cultureList, uomVolumeList, uomSugarList, uomTempList); // validate with User (ApplicationUser) var appUser = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); model.BatchJwt = await CreateJwtTokenAsync(appUser, 15).ConfigureAwait(false); return(View("UpdateBatch", model)); }
/// <summary> /// Details Page of a Single Recipe /// </summary> /// <param name="id">Primary Key of Recipe as <see cref="int"/></param> public async Task <IActionResult> Recipe(int id) { ViewData["Title"] = _localizer["PageTitleDetails"]; ViewData["PageDesc"] = _localizer["PageDescDetails"]; var getRecipesQuery = _queryFactory.CreateRecipesQuery(); var recipeDto = await getRecipesQuery.ExecuteAsync(id).ConfigureAwait(false); var submittedBy = await UserManagerAgent.FindByIdAsync(recipeDto.SubmittedBy).ConfigureAwait(false); var recipeModel = _modelFactory.CreateRecipeModel(recipeDto); recipeModel.User = submittedBy; recipeModel.HitCounterJwt = CreateJwtToken("Guest", 5); recipeModel.RatingJwt = CreateJwtToken("Guest", 15); return(View(recipeModel)); }
public async Task <IActionResult> AddFromRecipe(int?recipeId, int?yeastId, int?varietyId, int?targetId) { ViewData["Title"] = _localizer["PageTitleAdd"]; ViewData["PageDesc"] = _localizer["PageDescAdd"]; var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); var batchVolumeQuery = _journalQueryFactory.CreateBatchVolumeUOMQuery(); var uomVolumeList = await batchVolumeQuery.ExecuteAsync().ConfigureAwait(false); var getCategoriesQuery = _recipeQueryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var varietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var vList = await varietiesQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); BatchDto batch = new BatchDto(); if (targetId.HasValue) { var getTargetsQuery = _journalQueryFactory.CreateTargetsQuery(); batch.Target = getTargetsQuery.Execute(targetId.Value); } var addBatchModel = _modelFactory.CreateBatchViewModel(batch, null, vList, cList, yList, null, uomVolumeList, uomSugarList, uomTempList); addBatchModel.VarietyId = varietyId; addBatchModel.RecipeId = recipeId; addBatchModel.YeastId = yeastId; // validate with User (ApplicationUser) var appUser = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); addBatchModel.BatchJwt = await CreateJwtTokenAsync(appUser, 15).ConfigureAwait(false); return(View("Add", addBatchModel)); }
/// <summary> /// Main Landing Page for Journals /// </summary> public async Task <IActionResult> Index() { ViewData["Title"] = _localizer["PageTitle"]; ViewData["PageDesc"] = _localizer["PageDesc"]; var submittedBy = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); var varietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var vList = await varietiesQuery.ExecuteAsync().ConfigureAwait(false); var entriesQuery = _journalQueryFactory.CreateBatchEntriesQuery(); var getBatchesQuery = _journalQueryFactory.CreateBatchesQuery(); var batchesDto = await getBatchesQuery.ExecuteByUserAsync(submittedBy.Id).ConfigureAwait(false); foreach (var b in batchesDto) { var entriesDto = await entriesQuery.ExecuteByFKAsync(b.Id.Value).ConfigureAwait(true); b.Entries.AddRange(entriesDto.OrderByDescending(e => e.ActionDateTime).ThenByDescending(e => e.EntryDateTime)); b.Variety.Literal = vList.FirstOrDefault(v => v.Id == b.Variety.Id).Literal; } var journalModel = _modelFactory.CreateJournalModel(); var batchItemsModel = _modelFactory.BuildBatchListItemModels(batchesDto); journalModel.Batches = batchItemsModel .OrderBy(r => r.BatchComplete) .ThenByDescending(r => r.Vintage) .ThenBy(r => r.Variety); // validate with User (ApplicationUser) var appUser = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); journalModel.BatchJwt = await CreateJwtTokenAsync(appUser, 15).ConfigureAwait(false); return(View(journalModel)); }
public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var user = await UserManagerAgent.FindByNameAsync(model.UserName).ConfigureAwait(false); IdentityResult result = await UserManagerAgent.ResetPasswordAsync(user, model.Token, model.Password).ConfigureAwait(false); if (result.Succeeded) { Success(_localizer["PasswordResetSuccess"], true); return(View("Login")); } else { Danger(_localizer["PasswordResetFail"]); return(View("RequestNewPassword")); } }
public async Task <IActionResult> EditJournal(int id) { ViewData["Title"] = "Edit a Batch"; var qry = _journalQueryFactory.CreateBatchesQuery(); var dto = await qry.ExecuteAsync(id).ConfigureAwait(false); var entriesQuery = _journalQueryFactory.CreateBatchEntriesQuery(); var entriesDto = await entriesQuery.ExecuteByFKAsync(id).ConfigureAwait(true); var batchEntriesDto = entriesDto .OrderByDescending(e => e.ActionDateTime) .ThenByDescending(e => e.EntryDateTime).ToList(); dto.Entries.AddRange(batchEntriesDto); var user = await UserManagerAgent.FindByIdAsync(dto.SubmittedBy).ConfigureAwait(false); var userVms = _mapper.Map <UserViewModel>(user); var model = _modelFactory.CreateJournalViewModel(dto, userVms); return(View("UpdateJournal", model)); }
public async Task <IActionResult> EditRecipe(int Id) { ViewData["Title"] = "Edit a Recipe"; var recipeQry = _recipeQueryFactory.CreateRecipesQuery(); var dto = await recipeQry.ExecuteAsync(Id).ConfigureAwait(false); if (dto.Target != null) { var targetQry = _journalQueryFactory.CreateTargetsQuery(); var targetDto = await targetQry.ExecuteAsync(dto.Target.Id.Value).ConfigureAwait(false); dto.Target = targetDto; } var model = _modelFactory.CreateRecipeViewModel(dto); var user = await UserManagerAgent.FindByIdAsync(dto.SubmittedBy).ConfigureAwait(false); model.SubmittedBy = string.Concat(user.FirstName, " ", user.LastName, " (", user.Email, ")"); return(View("UpdateRecipe", model)); }
public async Task <IActionResult> LockUser(string UserName, DateTimeOffset?timeOut = null) { var user = await UserManagerAgent.FindByNameAsync(UserName).ConfigureAwait(false); if (!await UserManagerAgent.IsLockedOutAsync(user).ConfigureAwait(false)) { var result = await UserManagerAgent.SetLockoutEnabledAsync(user, true).ConfigureAwait(false); if (result.Succeeded) { if (timeOut.HasValue) { await UserManagerAgent.SetLockoutEndDateAsync(user, timeOut).ConfigureAwait(false); } else { await UserManagerAgent.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false); } } } return(RedirectToAction("Index", "Admin", new { id = "users" })); }
public async Task <IActionResult> Index(string id) { ViewData["Title"] = _localizer["PageTitle"]; ViewData["PageDesc"] = _localizer["PageDesc"]; var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var getYeastPairs = _yeastQueryFactory.CreateYeastPairQuery(); var getCategoriesQuery = _recipeQueryFactory.CreateCategoriesQuery(); var getVarietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var getRecipesQuery = _recipeQueryFactory.CreateRecipesQuery(); var getMaloCulturesQuery = _maloQueryFactory.CreateMaloCulturesQuery(); var getJournalsQuery = _journalQueryFactory.CreateBatchesQuery(); // using TPL to parallel call gets List <Task> tasks = new List <Task>(); var categoryTask = Task.Run(async() => await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(categoryTask); var cList = await categoryTask.ConfigureAwait(false); var varietyTask = Task.Run(async() => await getVarietiesQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(varietyTask); var vList = await varietyTask.ConfigureAwait(false); var yeastTask = Task.Run(async() => await getYeastQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(yeastTask); var yList = await yeastTask.ConfigureAwait(false); var pairsTask = Task.Run(async() => await getYeastPairs.ExecuteAsync().ConfigureAwait(false)); tasks.Add(pairsTask); var ypList = await pairsTask.ConfigureAwait(false); var recipeTask = Task.Run(async() => await getRecipesQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(recipeTask); var rList = await recipeTask.ConfigureAwait(false); var maloTask = Task.Run(async() => await getMaloCulturesQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(maloTask); var mList = await maloTask.ConfigureAwait(false); var journalTask = Task.Run(async() => await getJournalsQuery.ExecuteAsync().ConfigureAwait(false)); tasks.Add(journalTask); var jList = await journalTask.ConfigureAwait(false); Task.WaitAll(tasks.ToArray()); // build model var model = _modelFactory.CreateAdminModel(id); // make sure admin security role exist if (!await RoleManagerAgent.RoleExistsAsync(_appSettings.SecRole.Admin).ConfigureAwait(false)) { ApplicationRole role = new ApplicationRole { Name = _appSettings.SecRole.Admin, Description = "Perform all operations." }; IdentityResult roleResult = await RoleManagerAgent.CreateAsync(role).ConfigureAwait(false); if (!roleResult.Succeeded) { ModelState.AddModelError(string.Empty, "Error while creating role!"); return(View(model)); } } // gather users data var users = UserManagerAgent.Users.ToList(); var userVms = _mapper.Map <List <UserViewModel> >(users); model.UsersViewModel.Users.Clear(); model.UsersViewModel.Users.AddRange(userVms); foreach (var user in model.UsersViewModel.Users) { user.IsAdmin = await UserManagerAgent.IsInRoleAsync(user, _appSettings.SecRole.Admin).ConfigureAwait(false); user.IsLockedOut = await UserManagerAgent.IsLockedOutAsync(user).ConfigureAwait(false); } // gather roles data var roles = await RoleManagerAgent.Roles.OrderBy(r => r.Name).ToListAsync().ConfigureAwait(false); var roleVms = _mapper.Map <List <RoleViewModel> >(roles); model.RolesViewModel.Roles.Clear(); model.RolesViewModel.Roles.AddRange(roleVms); // gather category / variety data model.CategoriesViewModel.Categories.Clear(); model.CategoriesViewModel.Categories.AddRange(_modelFactory.CreateCategoryViewModel(cList)); model.VarietiesViewModel.Varieties.Clear(); model.VarietiesViewModel.Varieties.AddRange(_modelFactory.CreateVarietyViewModel(vList)); // gather yeast data model.YeastsViewModel.Yeasts.Clear(); model.YeastsViewModel.Yeasts.AddRange(_modelFactory.CreateYeastViewModel(yList)); // gather malolactic data model.MaloCulturesViewModel.Cultures.Clear(); model.MaloCulturesViewModel.Cultures.AddRange(_modelFactory.CreateMaloCultureViewModel(mList)); // gather recipe data model.RecipesViewModel.Recipes.Clear(); model.RecipesViewModel.Recipes.AddRange(_modelFactory.CreateRecipeViewModel(rList)); // gather journal data model.JournalsViewModel.Journals.Clear(); model.JournalsViewModel.Journals.AddRange(_modelFactory.CreateJournalViewModel(jList, userVms)); return(View(model)); }
public async Task <IActionResult> Add(AddRecipeViewModel model) { ViewData["Title"] = _localizer["PageTitle"]; ViewData["PageDesc"] = _localizer["PageDesc"]; var getCategoriesQuery = _queryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var getVarietiesQuery = _queryFactory.CreateVarietiesQuery(); var vList = await getVarietiesQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); // must be logged in to continue var submittedBy = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); if (submittedBy == null) { var addRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList, model); Warning(_localizer["NoLogIn"], false); return(View(addRecipeModel)); } // using model validation attributes, if model state says errors do nothing if (!ModelState.IsValid) { var addRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList, model); Warning(_localizer["AddGeneralError"], true); return(View(addRecipeModel)); } ICode variety = null; if (int.TryParse(model?.VarietyId, out int varietyId)) { variety = vList.FirstOrDefault(c => c.Id == varietyId); } ICode category = null; if (variety != null && variety.ParentId.HasValue) { category = cList.FirstOrDefault(c => c.Id == variety.ParentId.Value); } YeastDto yeast = null; if (int.TryParse(model?.YeastId, out int yeastId)) { yeast = yList.FirstOrDefault(y => y.Id == yeastId); } Business.Journal.Dto.TargetDto target = null; if (model.Target.HasTargetData()) { target = new Business.Journal.Dto.TargetDto { EndSugar = model.Target.EndingSugar, pH = model.Target.pH, StartSugar = model.Target.StartingSugar, TA = model.Target.TA, Temp = model.Target.FermentationTemp, }; if (model.Target.StartSugarUOM.HasValue) { target.StartSugarUom = uomSugarList.FirstOrDefault(u => u.Id == model.Target.StartSugarUOM.Value); } if (model.Target.EndSugarUOM.HasValue) { target.EndSugarUom = uomSugarList.FirstOrDefault(u => u.Id == model.Target.EndSugarUOM.Value); } if (model.Target.TempUOM.HasValue) { target.TempUom = uomTempList.FirstOrDefault(u => u.Id == model.Target.TempUOM.Value); } } // convert add model to recipe dto var recipeDto = new Business.Recipe.Dto.RecipeDto { Description = model.Description, Enabled = false, Hits = 0, Ingredients = model.Ingredients, Instructions = model.Instructions, NeedsApproved = true, Rating = null, SubmittedBy = submittedBy.Id, Target = target, Title = model.Title, Yeast = yeast, Variety = variety }; //recipeDto.Id = 1; // for testing only var updateRecipesCommand = _commandsFactory.CreateRecipesCommand(); recipeDto = await updateRecipesCommand.AddAsync(recipeDto).ConfigureAwait(false); // process uploaded files if (model.Images != null) { var updateImageCommand = _commandsFactory.CreateImageCommand(); long maxFileSizeBytes = 512000; List <string> allowedExtensions = new List <string> { ".jpg", ".jpeg", ".bmp", ".png", ".gif" }; int maxUploads = 4; int uploadCount = 1; foreach (FormFile file in model.Images) { // Max File Size per Image: 500 KB if (file.Length > maxFileSizeBytes) { continue; } // Allowed Image Extensions: .jpg | .gif | .bmp | .jpeg | .png ONLY var ext = Path.GetExtension(file.FileName); if (!allowedExtensions.Any(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase))) { continue; } // Pictures Max 4 if (uploadCount > maxUploads) { break; } using MemoryStream ms = new MemoryStream(); file.OpenReadStream().CopyTo(ms); var imageData = await ResizeImage(ms.ToArray(), 360, 480).ConfigureAwait(false); var thumbData = await ResizeImage(ms.ToArray(), 100, 150).ConfigureAwait(false); var imageDto = _dtoFactory.CreateNewImageFile(recipeDto.Id, file.FileName, file.Name, imageData, thumbData, file.Length, file.ContentType); await updateImageCommand.AddAsync(imageDto).ConfigureAwait(false); uploadCount++; } } var subjectLine = "There is a new recipe is in the approval queue."; var bodyContent = "A new recipe has been submitted and needs approved."; // notify admin that new recipe is in the approval queue await _emailAgent.SendEmailAsync(_appSettings.SMTP.FromEmail, _appSettings.SMTP.FromEmail, _appSettings.SMTP.AdminEmail, subjectLine, bodyContent, false, null).ConfigureAwait(false); // tell user good job and clear or go to thank you page ModelState.Clear(); var addNewRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList); addNewRecipeModel.User = submittedBy; Success(_localizer["AddSuccess"], true); return(View(addNewRecipeModel)); }
public async Task <IActionResult> Add(BatchViewModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } ViewData["Title"] = _localizer["PageTitle"]; ViewData["PageDesc"] = _localizer["PageDesc"]; var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery(); var uomTempList = await batchTempQuery.ExecuteAsync().ConfigureAwait(false); var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery(); var uomSugarList = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false); var batchVolumeQuery = _journalQueryFactory.CreateBatchVolumeUOMQuery(); var uomVolumeList = await batchVolumeQuery.ExecuteAsync().ConfigureAwait(false); var getCategoriesQuery = _recipeQueryFactory.CreateCategoriesQuery(); var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false); var varietiesQuery = _recipeQueryFactory.CreateVarietiesQuery(); var vList = await varietiesQuery.ExecuteAsync().ConfigureAwait(false); var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery(); var yList = await getYeastQuery.ExecuteAsync().ConfigureAwait(false); // must be logged in to continue var submittedBy = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); if (submittedBy == null) { var addModel = _modelFactory.CreateBatchViewModel(null, null, vList, cList, yList, null, uomVolumeList, uomSugarList, uomTempList); Warning(_localizer["AddGeneralError"], false); return(View(addModel)); } // using model validation attributes, if model state says errors do nothing if (!ModelState.IsValid) { var addModel = _modelFactory.CreateBatchViewModel(null, null, vList, cList, yList, null, uomVolumeList, uomSugarList, uomTempList); Warning(_localizer["AddGeneralError"], true); return(View(addModel)); } TargetDto targetDto; if (model.Target.Id.HasValue) { var targetQuery = _journalQueryFactory.CreateTargetsQuery(); targetDto = targetQuery.Execute(model.Target.Id.Value); } else { targetDto = new TargetDto(); } if (model.Target.HasTargetData()) { // convert add model to batch and target dto targetDto.Temp = model.Target.FermentationTemp; targetDto.pH = model.Target.pH; targetDto.TA = model.Target.TA; targetDto.StartSugar = model.Target.StartingSugar; targetDto.EndSugar = model.Target.EndingSugar; if (model.Target.TempUOM.HasValue) { targetDto.TempUom = new UnitOfMeasure { Id = model.Target.TempUOM.Value } } ; if (model.Target.StartSugarUOM.HasValue) { targetDto.StartSugarUom = new UnitOfMeasure { Id = model.Target.StartSugarUOM.Value } } ; if (model.Target.EndSugarUOM.HasValue) { targetDto.EndSugarUom = new UnitOfMeasure { Id = model.Target.EndSugarUOM.Value } } ; var updateTargetCommand = _journalCommandFactory.CreateTargetsCommand(); if (targetDto.Id.HasValue) { targetDto = await updateTargetCommand.UpdateAsync(targetDto).ConfigureAwait(false); } else { targetDto = await updateTargetCommand.AddAsync(targetDto).ConfigureAwait(false); } } var batchDto = new BatchDto { Description = model.Description, Vintage = model.Vintage, Volume = model.Volume, Complete = false, SubmittedBy = submittedBy?.Id, Title = model.Title, Yeast = yList.FirstOrDefault(y => y.Id == model.YeastId.Value), RecipeId = model.RecipeId, Target = targetDto, VolumeUom = new UnitOfMeasure { Id = model.VolumeUOM.Value }, Variety = new Code { Id = model.VarietyId.Value } }; var updateBatchCommand = _journalCommandFactory.CreateBatchesCommand(); await updateBatchCommand.AddAsync(batchDto).ConfigureAwait(false); // tell user good job and clear or go to thank you page ModelState.Clear(); var addBatchModel = _modelFactory.CreateBatchViewModel(null, null, vList, cList, yList, null, uomVolumeList, uomSugarList, uomTempList); Success(_localizer["AddSuccess"], true); // validate with User (ApplicationUser) var appUser = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false); addBatchModel.BatchJwt = await CreateJwtTokenAsync(appUser, 15).ConfigureAwait(false); return(View(addBatchModel)); }