public async Task <IActionResult> UpdateProfile([FromRoute] string id, [FromBody] ProfileDetailsViewModel profile) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var role = ""; if (User != null) { try { role = User.Claims.Where(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").SingleOrDefault().Value; if (role == null) { errorMessage.Message = "Could not find role for user"; return(Json(error)); } } catch (Exception exception) { errorMessage.Message = "Could not get role for user"; return(Json(error)); } } if (profile == null) { errorMessage.Message = "Model is missing data"; return(Json(error)); } // Find the type of user based on the role if (role == "Personal") { // Get the personal user in the database PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (personalUser != null) { personalUser.FirstName = profile.FirstName; personalUser.LastName = profile.LastName; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } personalUser.ProfilePicture = fileName; } // Update record in the database db.Entry(personalUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(personalUser)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } else if (role == "Business") { // Get the business user in the database BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (businessUser != null) { businessUser.FirstName = profile.FirstName; businessUser.LastName = profile.LastName; businessUser.Organization = profile.Organization; businessUser.PhoneNumber = profile.PhoneNumber; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } businessUser.ProfilePicture = fileName; } // Update record in the database db.Entry(businessUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(businessUser)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } else if (role == "Employee") { // Get the employee in the database BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (employee != null) { employee.FirstName = profile.FirstName; employee.LastName = profile.LastName; employee.PhoneNumber = profile.PhoneNumber; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } employee.ProfilePicture = fileName; } // Update record in the database db.Entry(employee).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(employee)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } errorMessage.Message = "An error has occurred"; return(Json(error)); }
public async Task <IActionResult> AddEmployee([FromBody] BusinessEmployeeViewModel employee) { var id = ""; var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; try { id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "Id was not found"; return(BadRequest(error)); } // Get the employer info BusinessUsers business = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); if (business == null) { errorMessage.Message = "Could not get the employer info"; return(Json(error)); } // Check if the user exists ApplicationUser user = _userManager.Users.SingleOrDefault(e => e.Email.Equals(employee.Email, StringComparison.InvariantCultureIgnoreCase)); // If not, create the user identity profile if (user == null) { if (employee.Email != null) { ApplicationUser applicationUser = new ApplicationUser { UserName = employee.Email, Email = employee.Email }; // Set temporary password string password = String.Format("{0}{1}#{2}", employee.Email.First().ToString().ToUpper(), employee.Email.Substring(1), DateTime.Now.Year); IdentityResult result = await _userManager.CreateAsync(applicationUser, password); if (result.Succeeded) { await _userManager.AddToRoleAsync(applicationUser, "Employee"); await _signInManager.SignInAsync(applicationUser, false); // Add the new user to the database BusinessEmployees businessEmployee = new BusinessEmployees { FirstName = employee.FirstName, LastName = employee.LastName, Position = employee.Position, CanEditLibrary = employee.CanEditLibrary, PhoneNumber = employee.PhoneNumber, UserId = applicationUser.Id, BusinessUserId = business.BusinessUserId }; if (!String.IsNullOrWhiteSpace(employee.ProfilePicture)) { var fileName = await fileController.UploadImage(employee.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } businessEmployee.ProfilePicture = fileName; } db.BusinessEmployees.Add(businessEmployee); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not create the business employee"; return(Json(error)); } // model data var modelData = new BusinessEmployeeViewModel { Id = businessEmployee.UserId, FirstName = businessEmployee.FirstName, LastName = businessEmployee.LastName, Position = businessEmployee.Position, ProfilePicture = businessEmployee.ProfilePicture, PhoneNumber = businessEmployee.PhoneNumber, CanEditLibrary = businessEmployee.CanEditLibrary, Email = applicationUser.Email }; return(CreatedAtAction("AddEmployee", new { id = modelData.Id }, modelData)); } // Send an email with this link ( SET UP SENDGRID TOWARDS END OF PROJECT ) //string code = await _userManager.GeneratePasswordResetTokenAsync(applicationUser); //var callbackUrl = Url.Action("ResetPassword", "Accounts", new { userId = applicationUser.Id, code }, protocol: Request.Scheme); //// Send the email //var emailNotification = new EmailNotificationViewModel //{ // Email = applicationUser.Email, // Subject = "SPINE - Password Reset", // Content = "", // Html = "Please reset your password by clicking <a href =\"" + callbackUrl + "\">here</a>" //}; //await notificationsController.SendEmailNotification(emailNotification); } else { errorMessage.Message = "Data is missing the Email field"; return(Json(error)); } } errorMessage.Message = "An error has occurred"; return(Json(error)); }
public async Task <object> Register([FromBody] RegistrationViewModel model) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Check for the role type upon registration string[] availableRoles = { "Personal", "Business" }; if (!availableRoles.Contains(model.Role)) { errorMessage.Message = "Invalid Role"; return(Json(error)); } // Create variable for Application User var user = new ApplicationUser { Email = model.Email, UserName = model.Email }; ApplicationUser appUser = db.ApplicationUser.Where(e => e.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (appUser != null) { errorMessage.Message = "Username is already taken."; return(Json(error)); } var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, model.Role); await _signInManager.SignInAsync(user, false); // Profile Types BusinessUsers businessUser = new BusinessUsers(); PersonalUsers personalUser = new PersonalUsers(); // Create the user profile if (model == null) { errorMessage.Message = "No data was found"; return(Json(error)); } if (model.Role == availableRoles[0]) { // If the user role is a business user var profile = new PersonalUsers { FirstName = model.FirstName, LastName = model.LastName, UserId = user.Id }; // Add the user to the database db.PersonalUsers.Add(profile); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add personal user to the database"; return(Json(error)); } personalUser = profile; } else if (model.Role == availableRoles[1]) { // If the user role is a personal user var profile = new BusinessUsers { FirstName = model.FirstName, LastName = model.LastName, Organization = model.Organization, UserId = user.Id, PhoneNumber = model.PhoneNumber }; // Add the user to the database db.BusinessUsers.Add(profile); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add business user to the database"; return(Json(error)); } businessUser = profile; } // Create role list to create jwt token List <string> roleList = new List <string>() { model.Role }; var jwtToken = await GenerateJwtToken(model.Email, user, roleList); var userRoles = await _userManager.GetRolesAsync(user); // Send the user role along with the JWT Token if (model.Role == availableRoles[0]) { var response = new PersonalLoginResponse { Token = jwtToken.ToString(), Roles = userRoles.ToArray(), PersonalUser = personalUser }; return(Json(response)); } else if (model.Role == availableRoles[1]) { var response = new BusinessLoginResponse { Token = jwtToken.ToString(), Roles = userRoles.ToArray(), BusinessUser = businessUser }; return(Json(response)); } } else if (!result.Succeeded) { errorMessage.Message = "Password must have 6+ characters, at least 1 uppercase character, 1 lowercase character, 1 number, and 1 non-alphanumeric character"; return(Json(error)); } errorMessage.Message = "An error has occurred"; return(Json(error)); }
public async Task <IActionResult> AddBook([FromBody] BookDetailsViewModel book) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var id = ""; if (User == null) { errorMessage.Message = "Could not find user for claims"; return(Json(error)); } try { id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "Id was not found"; return(Json(error)); } if (book == null) { errorMessage.Message = "The book does not contain data"; return(Json(error)); } // Add the book details Documents document = new Documents { Title = book.Title, ISBN = book.ISBN, CheckedOut = book.CheckedOut, Pages = book.Pages, Publisher = book.Publisher, PublishedDate = Convert.ToDateTime(book.PublishedDate), Edition = book.Edition, Description = book.Description, UserId = id }; // Add cover image for the book if (!String.IsNullOrWhiteSpace(book.Picture)) { var fileName = await fileController.UploadImage(book.Picture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } document.CoverImage = fileName; } // Add the book to the database db.Documents.Add(document); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add book to the database"; return(Json(error)); } // Add the genres foreach (var genre in book.Genres) { // Add the document genre for each genre DocumentGenres documentGenre = new DocumentGenres { DocumentId = document.DocumentId, GenreId = genre.GenreId }; db.DocumentGenres.Add(documentGenre); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add document genre to database"; return(Json(error)); } } // Add the authors foreach (var item in book.Authors) { var dbAuthor = db.Authors.Where(e => e.Name.Equals(item.Name, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (dbAuthor == null) { // Add the author Authors author = new Authors { Name = item.Name }; db.Authors.Add(author); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add author to the database"; return(Json(error)); } // Add the author to the books list of authors DocumentAuthors documentAuthor = new DocumentAuthors { AuthorId = author.AuthorId, DocumentId = document.DocumentId }; db.DocumentAuthors.Add(documentAuthor); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add document author to the database"; return(Json(error)); } } else { // Add the author to the books list of authors DocumentAuthors documentAuthor = new DocumentAuthors { AuthorId = dbAuthor.AuthorId, DocumentId = document.DocumentId }; db.DocumentAuthors.Add(documentAuthor); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add document author to the database"; return(Json(error)); } } } BookDetailsViewModel bookDetails = new BookDetailsViewModel { Id = document.DocumentId, Title = document.Title, ISBN = document.ISBN, CheckedOut = document.CheckedOut, Picture = document.CoverImage, Pages = Convert.ToInt32(document.Pages), Publisher = document.Publisher, PublishedDate = document.PublishedDate.ToString("yyyy-MM-dd"), Edition = document.Edition, Description = document.Description }; return(Ok(bookDetails)); }