public async Task<IHttpActionResult> Post(CreateProfileRequest request) { var passphrase = ""; if (request.Passphrase == null) { // Old way passphrase = Passphrase; } else { // New way // If the model state is invalid, return bad request if (!ModelState.IsValid) { return BadRequest(ModelState); } passphrase = request.Passphrase; } // Check passphrase against our password rules var result = await UserManager.PasswordValidator.ValidateAsync(passphrase); if (!result.Succeeded) { // Add errors to the model state foreach (var error in result.Errors) { ModelState.AddModelError("Errors", error); } return BadRequest(ModelState); } // Create context using (var ctx = new ApplicationDbContext()) { // Find the user var user = ctx.Users.Find(UserId); if (user == null) { return BadRequest("User not found."); } // Generate a random salt for the profile var saltBytes = Encryption.GenerateSalt(); // Create profile object to store in DB var profile = new Profile() { User = user, Name = request.Name, Key1 = Convert.ToBase64String(saltBytes), Key2 = Encryption.Hash(passphrase, saltBytes) }; // Add the profile to the context ctx.Profiles.Add(profile); // Save changes await ctx.SaveChangesAsync(); // Ok return Ok(profile.Id); } }
/// <summary> /// Verifies the supplied passphrase /// </summary> /// <param name="passphrase"></param> /// <returns></returns> private bool VerifyPassphrase(Profile profile, string passphrase) { // If there is no salt, set empty var salt = profile.Key1 ?? string.Empty; // Get the salt var saltBytes = Convert.FromBase64String(salt); // Verify the supplied passphrase var hashedPassphrase = Encryption.Hash(Passphrase, saltBytes); // Compare the hashes return hashedPassphrase.Equals(profile.Key2); }
public async Task<IHttpActionResult> Upload(Profile profile) { using (var ctx = new ApplicationDbContext()) { // Find the user var user = ctx.Users.Find(UserId); if (user == null) { return BadRequest("User not found"); } //// Look for a profile with the same name, if there are one or more, count them and add a (n) to the name //var dupes = (from p in ctx.Profiles // where p.User.Id == user.Id // && p.Name == profile.Name // select p).Count(); //// Add dupe count to profile name //if (dupes > 0) //{ // profile.Name = profile.Name + $" ({dupes})"; //} // Create a profile profile.Id = 0; profile.User = user; // Add the profile to the context ctx.Profiles.Add(profile); // Save new profile await ctx.SaveChangesAsync(); // Ok return Ok(profile.Id); } }