public JsonResult UpdateUser(oUser uUser) { User User = db.Users.SingleOrDefault(x => x.userId == uUser.ID); User.userName = uUser.username; User.FirstName = uUser.FirstName; User.SurName = uUser.SurName; if (uUser.Password != null) { User.emailAdd = uUser.EmailAdd; } User.Pwd = MD5Crypt.Encrypt(uUser.Password, "admin", true); User.mobileNo = uUser.Mobileno; try { db.SaveChanges(); return(Json(new { isError = "F", message = "Successfully Saved." })); } catch (Exception ex) { return(Json(new { isError = "T", message = "Could not insert data." })); } }
private async Task <oUser> UpdatePassword(oUser SelectedUser) { /// find the current user details from the database oUser userDetails = DbContext.Users.Find(SelectedUser.Id); if (userDetails == null) { oAppFunc.Error(ref ErrorsList, "User not found!"); return(null); } /// generate new password reset token string passResetToken = await UserManager.GeneratePasswordResetTokenAsync(userDetails).ConfigureAwait(false); /// reset user's password IdentityResult result = await UserManager.ResetPasswordAsync( userDetails, passResetToken, SelectedUser.Password).ConfigureAwait(false); /// if result is Failed if (!result.Succeeded) { foreach (var item in result.Errors) { ErrorsList.Add(new oError(item.Code, item.Description)); } return(null); } /// else the result is a success. return(userDetails); }
[HttpPut("put/{userId}/{lockoutEnabled}")] /// Ready For Test public async Task <IActionResult> Put(int userId, bool lockoutEnabled) { try { /// if the user with the same id is not found oUser user = await DbContext.Users.FindAsync(userId).ConfigureAwait(false); if (user == null) { oAppFunc.Error(ref ErrorsList, "User not found"); return(StatusCode(412, ErrorsList)); } user.LockoutEnabled = lockoutEnabled; /// update user in the context DbContext.Users.Update(user); /// save the changes to the database await DbContext.SaveChangesAsync().ConfigureAwait(false); /// thus return 200 ok status with the updated object return(Ok(user)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
// [Authorize(oAppConst.AccessPolicies.LevelOne)] /// Ready For Test public async Task <IActionResult> Delete([FromBody] oUser thisUser) { try { /// if the User record with the same id is not found if (!DbContext.Users.Any(u => u.Id == thisUser.Id)) { oAppFunc.Error(ref ErrorsList, "User not found"); return(StatusCode(412, ErrorsList)); } /// else the User is found /// now delete the user record DbContext.Users.Remove(DbContext.Users.Find(thisUser.Id)); /// save the changes to the database await DbContext.SaveChangesAsync().ConfigureAwait(false); /// return 200 OK status return(Ok($"User ID ('{thisUser.Id}') was deleted")); } catch (Exception) { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> PutMyPassword([FromBody] oUser modifiedUser) { try { int.TryParse(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value, out int userId); if (modifiedUser.Id != userId) { oAppFunc.Error(ref ErrorsList, "Not Authorized!"); return(StatusCode(412, ErrorsList)); } oUser result = await UpdatePassword(modifiedUser).ConfigureAwait(false); if (result == null) { return(StatusCode(412, ErrorsList)); } return(Ok(result)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
/// <summary> /// This method is used to generate a URL to verify the user's request such as /// password reset and user's email validation. /// </summary> /// <param name="user">Register the token with a specific user</param> /// <param name="requestType">The type of the request </param> /// <param name="ExpiaryDate">The expiry of the token</param> /// <returns>The Generate URL</returns> private async Task <string> GetUrlWithToken(oUser user, TokenType requestType, DateTime ExpiaryDate) { /// First check if the user has a token for the requested token type IEnumerable <oToken> tokenValues = DbContext.Tokens .Where(vs => vs.User.Id == user.Id && vs.ValueType == requestType) .AsNoTracking() .AsEnumerable(); /// If the user already has a token for the requested type /// then remove all of them if (tokenValues != null) { DbContext.Tokens.RemoveRange(tokenValues); } /// Create a new token var token = new oToken { User = user, ValueType = requestType, ExpiaryDateTime = ExpiaryDate, }; token.Value = token.GetToken(); /// Add the new token the context await DbContext.AddAsync(token); /// Save the changes to the database await DbContext.SaveChangesAsync(); /// return the requested URL return(string.Format(@"{0}/{1}/{2}", DomainUrl, requestType, token.Value)); }
//[Authorize(oAppConst.AccessPolicies.LevelOne)] /// Ready For Test public async Task <IActionResult> Put([FromBody] oUser modifiedUser) { try { /// Try to validate the model TryValidateModel(modifiedUser); /// remove the passwordHash and confrimPassword since /// the password update gets handled by another method in this class ModelState.Remove("PasswordHash"); if (!ModelState.IsValid) { /// extract the errors and return bad request containing the errors oAppFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } /// if the user record with the same id is not found if (!DbContext.Users.Any(u => u.Id == modifiedUser.Id)) { oAppFunc.Error(ref ErrorsList, "User not found"); return(StatusCode(412, ErrorsList)); } /// find the current user details from the database oUser userDetails = DbContext.Users.Find(modifiedUser.Id); /// update the user details with the new details userDetails.FirstName = modifiedUser.FirstName; userDetails.Surname = modifiedUser.Surname; userDetails.Email = modifiedUser.Email; userDetails.PhoneNumber = modifiedUser.PhoneNumber; userDetails.Role = modifiedUser.Role; /// thus update user in the context DbContext.Users.Update(userDetails); /// save the changes to the database await DbContext.SaveChangesAsync().ConfigureAwait(false); /// thus return 200 ok status with the updated object return(Ok(userDetails)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
//[Authorize(oAppConst.AccessPolicies.LevelOne)] /// Ready For Test public async Task <IActionResult> Post([FromBody] oUser newCustomer) { try { newCustomer.Role = await DbContext.Roles .SingleOrDefaultAsync(r => r.AccessClaim.Equals(oAppConst.AccessClaims.Customer)) .ConfigureAwait(false); return(await CreateUser(newCustomer).ConfigureAwait(false)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
/// <summary> /// This method is used to email a token value to the user in order to rest their password /// </summary> /// <param name="user">User object</param> /// <param name="ExpiaryDate">The expiry DateTime of the token</param> /// <returns>bool: true (if email is send correctly) else false</returns> internal async Task <bool> PasswordResetAsync(oUser user, DateTime ExpiaryDate) { try { /// Create the URL for the user to go to in order to reset their password string PasswordResetUrl = await GetUrlWithToken( user, TokenType.ResetPassword, ExpiaryDate).ConfigureAwait(false); /// The following methods must be called in order to create the email. /// The order in which this methods are called will determine /// the layout of the email from top to bottom. string htmlMessage = HtmlCreator .HeaderText($"Hello {user.FirstName.FirstCap()} {user.Surname.FirstCap()} \n") .BodyText("If you have requested to reset your password, " + "please use the link below. Otherwise Ignore this email. \n") .Button("Reset Password", PasswordResetUrl) .BodyTextLight("The link will expire on " + ExpiaryDate) .FooterFinal("", "oSnack.co.uk") .GetFinalHtml(); /// pass the information to be used to send the email. await SendEmailAsync(user.Email, "Password Reset", htmlMessage).ConfigureAwait(false); /// if all goes well then return true return(true); } catch (Exception err) { /// if there are any exceptions, Log the exception error /// on the database and return false to the caller await DbContext.AppLogs.AddAsync(new oAppLog { Massage = err.Message, JsonObject = JsonConvert.SerializeObject(err), User = user }); await DbContext.SaveChangesAsync().ConfigureAwait(false); return(false); } }
//[Authorize(oAppConst.AccessPolicies.LevelOne)] /// Ready For Test public async Task <IActionResult> PostUser([FromBody] oUser newUser) { try { if (string.IsNullOrWhiteSpace(newUser.Password)) { newUser.Password = oAppFunc.passwordGenerator(); } ErrorsList.Add(new oError("1000", newUser.Password)); return(await CreateUser(newUser).ConfigureAwait(false)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
/// <summary> /// This method is used to send token to the user after registration in order to /// validate their email address. /// </summary> /// <param name="user">The user object</param> /// <param name="ExpiaryDate">The expiry date for token</param> /// <returns>bool: true (if email is send correctly) else false</returns> internal async Task <bool> EmailConfirmationAsync(oUser user, DateTime ExpiaryDate) { try { /// Create the URL for the user to go to in order to confirm email address var EmailConfirmUrl = await GetUrlWithToken(user, TokenType.ConfirmEmail, ExpiaryDate).ConfigureAwait(false); /// The following methods must be called in order to create the email. /// The order in which this methods are called will determine /// the layout of the email from top to bottom. var htmlMessage = HtmlCreator .HeaderText(string.Format("Hello {0} {1}<br />" , user.FirstName.FirstCap() , user.Surname.FirstCap())) .HeaderText("Welcome to oSnack.") .BodyText("Please use the link below to confirm your email address. <br />") .Button("Confirm Email", EmailConfirmUrl) .FooterFinal("", "oSnack.co.uk") .GetFinalHtml(); /// pass the information to be used to send the email. await SendEmailAsync(user.Email, "Confirm Email", htmlMessage); /// if all goes well then return true return(true); } catch (Exception err) { /// if there are any exceptions, Log the exception error /// on the database and return false to the caller await DbContext.AppLogs.AddAsync(new oAppLog { Massage = err.Message, JsonObject = JsonConvert.SerializeObject(err), User = user }); await DbContext.SaveChangesAsync(); return(false); } }
public async Task <IActionResult> PutPassword([FromBody] oUser modifiedUser) { try { oUser result = await UpdatePassword(modifiedUser).ConfigureAwait(false); if (result == null) { return(StatusCode(412, ErrorsList)); } return(Ok(result)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }
/// <summary> /// This method is used to send user's new password to the user after registration in order to /// validate their email address. (Employees only) /// </summary> /// <param name="user">The user object</param> /// <param name="ExpiaryDate">The expiry date for token</param> /// <returns>bool: true (if email is send correctly) else false</returns> internal async Task <bool> NewEmployeePasswordAsync(oUser user, DateTime ExpiaryDate) { try { /// The following methods must be called in order to create the email. /// The order in which this methods are called will determine /// the layout of the email from top to bottom. var htmlMessage = HtmlCreator .HeaderText(string.Format("Hello {0} {1}<br />" , user.FirstName.FirstCap() , user.Surname.FirstCap())) .HeaderText("Welcome to oSnack.") .BodyText($"Your new password is: {user.Password}<br />") .FooterFinal("", "oSnack.co.uk") .GetFinalHtml(); /// pass the information to be used to send the email. await SendEmailAsync(user.Email, "You new OSnack password.", htmlMessage); /// if all goes well then return true return(true); } catch (Exception err) { /// if there are any exceptions, Log the exception error /// on the database and return false to the caller await DbContext.AppLogs.AddAsync(new oAppLog { Massage = err.Message, JsonObject = JsonConvert.SerializeObject(err), User = user }); await DbContext.SaveChangesAsync(); return(false); } }
/// <summary> /// Create a new User /// </summary> private async Task <IActionResult> CreateUser(oUser newUser) { try { newUser.PasswordHash = newUser.Password; ModelState.Clear(); /// find the selected role object of the user newUser.Role = await DbContext.Roles.FindAsync(newUser.Role.Id).ConfigureAwait(false); /// if model validation failed if (!TryValidateModel(newUser)) { oAppFunc.ExtractErrors(ModelState, ref ErrorsList); /// return bad request with all the errors return(UnprocessableEntity(ErrorsList)); } /// check the database to see if a user with the same email exists if (DbContext.Users.Any(d => d.Email == newUser.Email)) { /// extract the errors and return bad request containing the errors oAppFunc.Error(ref ErrorsList, "Email already exists."); return(StatusCode(412, ErrorsList)); } /// Create the new user IdentityResult newUserResult = await UserManager.CreateAsync(newUser, newUser.PasswordHash) .ConfigureAwait(false); /// If result failed if (!newUserResult.Succeeded) { /// Add the error below to the error list and return bad request foreach (var error in newUserResult.Errors) { oAppFunc.Error(ref ErrorsList, error.Description, error.Code); } return(StatusCode(417, ErrorsList)); } /// else result is successful the try to add the access claim for the user IdentityResult addedClaimResult = await UserManager.AddClaimAsync( newUser, new Claim(oAppConst.AccessClaims.Type, newUser.Role.AccessClaim) ).ConfigureAwait(false); /// if claim failed to be created if (!addedClaimResult.Succeeded) { /// remove the user account and return appropriate error DbContext.Users.Remove(newUser); await DbContext.SaveChangesAsync().ConfigureAwait(false); oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } /// return 201 created status with the new object /// and success message return(Created("Success", newUser)); } catch (Exception) // DbUpdateException, DbUpdateConcurrencyException { /// Add the error below to the error list and return bad request oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError); return(StatusCode(417, ErrorsList)); } }