public async Task <IActionResult> RemoveImage(int?id) { if (id == null) { return(NotFound()); } var profile = await _context.UserProfiles.FindAsync(id); if (profile == null) { return(NotFound()); } //if (profile.Image != null) //{ // string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "Upload/images"); // System.IO.File.Delete(Path.Combine(uploadsFolder, profile.Image)); //} profile.Image = null; _context.SaveChanges(); return(Content("")); }
public IActionResult Update(List <UserServicesViewModel> data) { foreach (var item in data) { var US = _context.UserServices.Where(s => s.Id == item.Id) .Include(s => s.Service.WorkShop.User) .FirstOrDefault(); US.Finished = item.Finished; if (US.Finished) { //send notification to user _context.Notifications.Add(new Notification { ReceiverId = US.UserId, Type = "FinishService", SenderID = US.Service.WorkShop.UserId, ContentId = US.ServiceId, }); } } _context.SaveChanges(); return(RedirectToAction(nameof(RequestedServices))); }
public async Task <IActionResult> ReadNotification(int?id) { if (id == null) { return(NotFound()); } var userID = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); //get user notifications var notification = await _context.Notifications.Where(n => n.Id == id && n.ReceiverId == userID) .FirstOrDefaultAsync(); if (notification == null) { return(NotFound()); } else { if (notification.Unread) { notification.Unread = false; _context.SaveChanges(); } } return(Content("")); }
public string Execute(string[] arguments) { int argsCount = arguments.Length; if (argsCount < 2 || argsCount > 3) { throw new FormatException(Constants.ErrorMessages.InvalidArgumentsCount); } this.authenticationManager.Authorize(); User user = this.authenticationManager.GetCurrentUser(); string teamName = arguments[0]; if (teamName.Length > 25) { throw new ArgumentException("Team name should be up to 25 characters long!"); } if (CommandHelper.IsTeamExisting(teamName)) { throw new ArgumentException(string.Format(Constants.ErrorMessages.TeamExists, teamName)); } string acronym = arguments[1]; if (acronym.Length != 3) { throw new ArgumentException(string.Format(Constants.ErrorMessages.InvalidAcronym, acronym)); } string description = argsCount == 3 ? arguments[2] : null; if (description != null && description.Length > 32) { throw new ArgumentException("Team description should be up to 32 characters long!"); } using (WorkShopDbContext context = new WorkShopDbContext()) { Team currentTeam = new Team() { Name = teamName, Acronym = acronym, Description = description, CreatorId = user.Id }; context.Teams.Add(currentTeam); context.SaveChanges(); } return($"Team {teamName} successfully created!"); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); var userid = _userManager.GetUserId(User); var userprofile = _context.UserProfiles.Where(u => u.UserId == userid).FirstOrDefault(); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); var government = userprofile.Government; var city = userprofile.City; var fName = userprofile.FirstName; var lName = userprofile.LastName; var brand = userprofile.CarBrand; var model = userprofile.CarModel; var img = userprofile.Image; if (Input.Government != government) { userprofile.Government = Input.Government; } if (Input.City != city) { userprofile.City = Input.City; } if (Input.CarBrand != brand) { userprofile.CarBrand = Input.CarBrand; } if (Input.CarModel != model) { userprofile.CarModel = Input.CarModel; } _context.SaveChanges(); await _signInManager.RefreshSignInAsync(user); TempData["Done"] = "Updated Sucessfully"; StatusMessage = "Your data has been updated"; return(RedirectToPage()); }
public string Execute(string[] arguments) { Check.CheckLenght(6, arguments); this.authenticationManager.Authorize(); User user = this.authenticationManager.GetCurrentUser(); string eventName = arguments[0]; if (eventName.Length > Constants.MaxEventNameLength) { throw new ArgumentException("Event name should be up to 25 characters long!"); } var eventDescription = arguments[1]; if (eventDescription.Length > Constants.MaxEventDescriptionLength) { throw new ArgumentException("Event description should bet up to 250 characters long!"); } string startDateString = $"{arguments[2]} {arguments[3]}"; DateTime startDate; string endDateString = $"{arguments[4]} {arguments[5]}"; DateTime endDate; bool endDateIsValid = DateTime.TryParseExact(endDateString, Constants.DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate); bool startDateIsValid = DateTime.TryParseExact(startDateString, Constants.DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate); if (!startDateIsValid || !endDateIsValid) { throw new ArgumentException(Constants.ErrorMessages.InvalidDateFormat); } using (WorkShopDbContext context = new WorkShopDbContext()) { Event currentEvent = new Event() { Name = eventName, Description = eventDescription, StartDate = startDate, EndDate = endDate, CreatorId = user.Id }; context.Events.Add(currentEvent); context.SaveChanges(); } return($"Event {eventName} was created successfully!"); }
public IActionResult CreateGovernment(Government government) { if (government == null) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Governments.Add(government); _context.SaveChanges(); TempData["Done"] = "New government created sucessfully"; } catch { TempData["Done"] = "The new government doesn't created, something went wrong"; } } return(RedirectToAction("Locations")); }
public async Task <IActionResult> AddUserService(int?id) { if (id == null) { return(NotFound()); } var service = await _context.Services.Where(s => s.Id == id) .Include(s => s.WorkShop) .FirstOrDefaultAsync(); if (service == null) { return(NotFound()); } var userID = _httpContext.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); await _context.UserServices.AddAsync( new UserServices { UserId = userID, ServiceId = service.Id, }); //send notification to workshop _context.Notifications.Add(new Notification { ReceiverId = service.WorkShop.UserId, Type = "RequestService", SenderID = userID, ContentId = service.Id, }); _context.SaveChanges(); var userServices = await _context.UserServices.Where(s => s.UserId == userID && s.Finished == false) .Include(s => s.Service) .Include(s => s.Service.WorkShop) .OrderByDescending(s => s.Date) .ToListAsync(); return(PartialView("_ServiceNotifiPartial", userServices)); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "Incorrect password."); return(Page()); } } var profile = _context.UserProfiles.Where(p => p.UserId == user.Id).FirstOrDefault(); _context.UserProfiles.Remove(profile); _context.SaveChanges(); var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return(Redirect("~/")); }
public IActionResult Register([FromForm] UserModel userModel) { using (var db = new WorkShopDbContext()) { var user = db.Users.FirstOrDefault(u => u.UserName == userModel.UserName); if (user != null) { return(BadRequest("this username is alrady exist")); } else { db.Users.Add(new UserEntity() { FirstName = userModel.FirstName, LastName = userModel.LastName, UserName = userModel.UserName, Password = userModel.Password }); db.SaveChanges(); return(Ok()); } } }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); #region assign to role if (await _roleManager.FindByNameAsync("User") == null) { result = await _roleManager.CreateAsync(new IdentityRole("User")); } if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "User"); } #endregion assign to role #region create user profile await _context.UserProfiles.AddAsync(new UserProfile { UserId = user.Id }); _context.SaveChanges(); #endregion create user profile if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); var pathToFile = _env.WebRootPath + Path.DirectorySeparatorChar.ToString() + "Templates" + Path.DirectorySeparatorChar.ToString() + "EmailTemplate" + Path.DirectorySeparatorChar.ToString() + "RegisterConfirmationEmail.html"; var builder = new BodyBuilder(); using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile)) { builder.HtmlBody = SourceReader.ReadToEnd(); } //use string.Format(format item, dynamic values as parameters) In our case, {x} //values in Templates are to replace by dynamic values. string messageBody = string.Format(builder.HtmlBody, "", HtmlEncoder.Default.Encode(callbackUrl)); await _emailSender.SendEmailAsync(user.Email, "Confirm your email", messageBody); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { Input.Username = UsernameInput; Input.Email = EmailInput; IdentityUser user = new() { UserName = Input.Username, Email = Input.Email, PhoneNumber = Input.Phone, }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { #region assign to role if (await _roleManager.FindByNameAsync("User") == null) { result = await _roleManager.CreateAsync(new IdentityRole("User")); } if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "User"); } #endregion assign to role #region create user profile _context.UserProfiles.Add(new UserProfile { //FirstName = Input.FirstName, //LastName = Input.LastName, UserId = user.Id }); _context.SaveChanges(); #endregion create user profile _logger.LogInformation("User created a new account with password."); #region Email confirmation var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); var pathToFile = _env.WebRootPath + Path.DirectorySeparatorChar.ToString() + "Templates" + Path.DirectorySeparatorChar.ToString() + "EmailTemplate" + Path.DirectorySeparatorChar.ToString() + "RegisterConfirmationEmail.html"; var builder = new BodyBuilder(); using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile)) { builder.HtmlBody = SourceReader.ReadToEnd(); } //use string.Format(format item, dynamic values as parameters) In our case, {x} //values in Templates are to replace by dynamic values. string messageBody = string.Format(builder.HtmlBody, "", HtmlEncoder.Default.Encode(callbackUrl)); await _emailSender.SendEmailAsync(user.Email, "Confirm your email", messageBody); #endregion Email confirmation if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); var userid = _userManager.GetUserId(User); var userprofile = _context.UserProfiles.Where(u => u.UserId == userid).FirstOrDefault(); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); var fName = userprofile.FirstName; var lName = userprofile.LastName; if (Input.PhoneNumber != phoneNumber) { var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { StatusMessage = "Unexpected error when trying to set phone number."; return(RedirectToPage()); } } if (Input.FirstName != fName) { userprofile.FirstName = Input.FirstName; } if (Input.LastName != lName) { userprofile.LastName = Input.LastName; } string fileName = string.Empty; string uploads = Path.Combine(hosting.WebRootPath, "Upload/images"); if (ImageFile != null) { fileName = Guid.NewGuid().ToString() + "_" + ImageFile.FileName; //image path string Fullpath = Path.Combine(uploads, fileName); //copy (upload) image to that path ImageFile.CopyTo(new FileStream(Fullpath, FileMode.Create)); //if (userprofile.Image != null) //{ // string OldImgPath = Path.Combine(uploads, userprofile.Image); // try // { // System.IO.File.Delete(OldImgPath); // } // catch // { // StatusMessage = "Unexpected error when trying to set Photo."; // } //} userprofile.Image = fileName; } else { if (RemoveImage == "true") { if (userprofile.Image != null) { System.IO.File.Delete(Path.Combine(uploads, userprofile.Image)); } userprofile.Image = null; } } _context.SaveChanges(); await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your profile has been updated"; return(RedirectToPage()); }