public bool AddReadStatus(PostUserModel model) { try { if (!_db.PostStatInfoes.Any(x => x.PostId == model.PostId && x.UserId == model.UserId)) { var newPostStat = new PostStatInfo() { UserId = model.UserId, PostId = model.PostId, IsLiked = false, IsRead = true }; _db.PostStatInfoes.Add(newPostStat); _db.SaveChanges(); } return(true); } catch (Exception ex) { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(model); Log.Error("Post Like - Add- " + json, ex); throw; } }
public IActionResult Create([FromBody] PostUserModel user) { _usersLogic.CreateANewUser(user); var userToReturn = _usersLogic.GetByUserName(user.UserName); return(CreatedAtRoute("GetByUserName", new { username = user.UserName }, userToReturn)); }
public ActionResult <ApiMethodResponse <int> > Post([FromBody] PostUserModel userModel) { var validationResult = _postUserModelValidator.Validate(userModel); if (!validationResult.IsValid) { return(BadRequest(new ApiMethodResponse <int> { Errors = validationResult.Errors.Select(error => error.ToString()).ToArray() })); } var salt = _credentialService.GenerateRandomSalt(); var hashedPassword = _credentialService.HashPassword(userModel.Password, salt); try { var newId = _userRepository.CreateUser(userModel.Username, hashedPassword, Convert.ToBase64String(salt)); _logger.LogInformation($"Created new user. Username {userModel.Username} ID {newId}"); return(Ok(new ApiMethodResponse <int> { Data = newId })); } catch (Exception e) { _logger.LogError($"User creation failed - {e.Message}"); return(BadRequest(new ApiMethodResponse <int> { Errors = new [] { "User account creation failed" } })); } }
public async Task <IHttpActionResult> PostUser(PostUserModel userModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = db.Users.Add(MapToDbo <User>(userModel)); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = user.Id }, user)); }
public async Task <ActionResult <GetUserModel> > PostUser(PostUserModel postUserModel) { try { GetUserModel user = await _userRepository.PostUser(postUserModel); return(CreatedAtAction(nameof(GetUser), new { id = user.Id }, user)); } catch (DatabaseException e) { return(BadRequest(e.MovieMindError)); } }
public void CreateAUserWithNullsDoesNotGetCreated(string user, string email, string password) { var mock = new Mock <IUserRepository>(); var postModel = new PostUserModel { UserName = user, EmailAddress = email, Active = true, PassWord = password }; var service = new UsersLogic(mock.Object); Assert.Throws <ArgumentException>(() => service.CreateANewUser(postModel)); }
[ValidateAntiForgeryToken] // Prevents XSRF/CSRF attacks public async Task <IActionResult> Index(PostUserModel postUserModel, string rememberMe) { if (postUserModel.Password != postUserModel.ConfirmPassword) { ModelState.AddModelError("ConfirmPassword", _localizer["Passwords are not the same"]); } if (ModelState.IsValid) { try { if (postUserModel.Roles == null) { postUserModel.Roles = new List <String> { "Guest" }; } else if (postUserModel.Roles.Count == 0) { postUserModel.Roles.Add("Guest"); } // Send an API request to create the new user GetUserModel getUserModel = await _moviemindAPIService.PostModel <PostUserModel, GetUserModel>(postUserModel, "users"); // When the user was successfully created send an API request to authenticate the new user PostAuthenticateRequestModel postAuthenticateRequestModel = new PostAuthenticateRequestModel { UserName = postUserModel.UserName, Password = postUserModel.Password, }; PostAuthenticateResponseModel postAuthenticateResponseModel = await _moviemindAPIService.Authenticate(postAuthenticateRequestModel); _stateManagementService.SetState(postAuthenticateResponseModel); // Redirect to the home page return(RedirectToRoute(new { action = "Index", controller = "Home" })); } catch (MovieMindException e) { TempData["ApiError"] = e.Message; } } return(View(postUserModel)); }
public async Task <GetUserModel> PostUser(PostUserModel postUserModel) { User user = new User { UserName = postUserModel.UserName, FirstName = postUserModel.FirstName, LastName = postUserModel.LastName, Email = postUserModel.Email, Description = postUserModel.Description }; IdentityResult result = await _userManager.CreateAsync(user, postUserModel.Password); if (!result.Succeeded) { string description = result.Errors.First().Description; if (description.Contains("is already taken")) { description = "This username or email is already in use"; } throw new IdentityException(description, this.GetType().Name, "PostUser", "400"); } try { if (postUserModel.Roles == null) { await _userManager.AddToRoleAsync(user, "Guest"); } else { await _userManager.AddToRolesAsync(user, postUserModel.Roles); } } catch (Exception e) { await _userManager.DeleteAsync(user); throw new IdentityException(e.Message, this.GetType().Name, "PostUser", "400"); } return(await GetUser(user.Id.ToString())); }
public void CreateANewUser(PostUserModel user) { this.CheckForNulls(user.UserName, user.EmailAddress, user.PassWord); CheckIfUserExists(user.UserName); CheckIfEmailExists(user.EmailAddress); var hashedPassword = PasswordHasher.SetPassword(user.PassWord); var userToPost = new UserModel { UserName = user.UserName.ToLowerInvariant(), Active = true, EmailAddress = user.EmailAddress, PassWord = hashedPassword, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }; _userRepository.Add(userToPost); }
public async Task <JsonResult> CreateAsync1(PostUserModel user) { var applicationUser = new ApplicationUser() { UserName = user.UserName, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, BirthDate = System.DateTime.Now }; IdentityResult result = await AppUserManager.CreateAsync(applicationUser, user.Password); var returnAction = new JsonResult(); returnAction.JsonRequestBehavior = JsonRequestBehavior.AllowGet; string responseJson = ""; if (result.Succeeded) { responseJson = JsonConvert.SerializeObject(JsonConvert.SerializeObject(result), new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); HttpContext.Response.StatusDescription = "OK"; //HttpContext.Response.StatusCode = 200; } else { responseJson = JsonConvert.SerializeObject(JsonConvert.SerializeObject(result.Errors), new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); HttpContext.Response.StatusDescription = "OK"; HttpContext.Response.StatusCode = 404; } returnAction.ContentType = "application/json"; returnAction.ContentEncoding = System.Text.Encoding.UTF8; returnAction.Data = responseJson; return(returnAction); }
public void CreateANewUserWithAllFieldsGetsAdded() { var mock = new Mock <IUserRepository>(); var username = "******"; var password = "******"; var email = "*****@*****.**"; var postModel = new PostUserModel { UserName = username, EmailAddress = email, Active = true, PassWord = password }; var service = new UsersLogic(mock.Object); service.CreateANewUser(postModel); mock.Verify(x => x.Add(It.IsAny <UserModel>()), Times.Exactly(1)); }
public async Task <ActionResult> CreateAsync(PostUserModel user) { var applicationUser = new ApplicationUser() { UserName = user.UserName, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, BirthDate = System.DateTime.Now }; IdentityResult result = await AppUserManager.CreateAsync(applicationUser, user.Password); if (!result.Succeeded) { throw new Exception("ERROR:" + result.Errors.FirstOrDefault()); } return(View()); }
public void CreateANewUserWithEmailThatDoesExistThrowsArgumentException() { var mock = new Mock <IUserRepository>(); var username = "******"; var password = "******"; var email = "*****@*****.**"; var postModel = new PostUserModel { UserName = username, EmailAddress = email, Active = true, PassWord = password }; mock.Setup(e => e.CheckIfEmailExists(email)).Returns(true); var service = new UsersLogic(mock.Object); Assert.Throws <ArgumentException>(() => service.CreateANewUser(postModel)); }
public void CreateANewEmailWithUserThatDoesNotExistPasses() { var mock = new Mock <IUserRepository>(); var username = "******"; var password = "******"; var email = "*****@*****.**"; var postModel = new PostUserModel { UserName = username, EmailAddress = email, Active = true, PassWord = password }; mock.Setup(e => e.CheckIfEmailExists(email)).Returns(false); var service = new UsersLogic(mock.Object); service.CreateANewUser(postModel); mock.Verify(x => x.Add(It.IsAny <UserModel>()), Times.Exactly(1)); }
public bool AddLikedStatus(PostUserModel model) { try { if (!_db.PostStatInfoes.Any(x => x.PostId == model.PostId && x.UserId == model.UserId)) { var newPostStat = new PostStatInfo() { UserId = model.UserId, PostId = model.PostId, IsLiked = true, IsRead = true }; _db.PostStatInfoes.Add(newPostStat); _db.SaveChanges(); return(true); } var postStat = _db.PostStatInfoes.First(x => x.PostId == model.PostId && x.UserId == model.UserId); postStat.IsLiked = true; postStat.IsRead = true; _db.Entry(postStat).State = EntityState.Modified; _db.SaveChanges(); return(true); } catch (Exception ex) { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(model); Log.Error("Post Like - Add- " + json, ex); throw; } }