public async Task <ActionResult> QueryUsers(UserFilter filter) { try { var res = filter.BuildQuery(_context.Users).Include(x => x.UserRoles).ToList(); var total = res.Count(); if (filter.Pager.Page > 0) { res = res.Skip(filter.Pager.Skip()).Take(filter.Pager.Size).ToList(); } if (!res.Any()) { return(NotFound(new { Message = "No User Found" })); } var data = res.Select(x => new { x.Id, x.Name, x.Email, x.PhoneNumber, x.UserName, Role = new RoleRepository(_context).GetById(x.UserRoles.First().RoleId)?.Name, }).ToList(); return(Ok(data)); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> Query(AppSettingsFilter filter) { using (var db = _repository._context) { using (var transaction = db.Database.BeginTransaction()) { try { var query = _repository.Query(filter); var data = query.OrderBy(x => x.Name).ToList(); var total = data.Count(); if (filter.Pager.Page > 0) { data = data.Skip(filter.Pager.Skip()).Take(filter.Pager.Size).ToList(); } if (!data.Any()) { return(Ok("No data found")); } transaction.Commit(); return(Ok(new { data, total, message = "Loaded Successfully" })); } catch (Exception ex) { transaction.Rollback(); return(BadRequest(WebHelpers.ProcessException(ex))); } } } }
public async Task <ActionResult> CreateRole(Role model) { try { model.NormalizedName = model.Name; var claims = model.Claims; var existingRole = _context.Roles.FirstOrDefault(x => x.Name == model.Name); if (existingRole == null) { var res = roleManager.CreateAsync(model); if (res.Result.Succeeded) { //var role = _context.Roles.First(x => x.Name == model.Name); foreach (var c in claims) { roleManager.AddClaimAsync(model, new Claim(GenericProperties.Privilege, c)).Wait(); } } } else { return(BadRequest("There is an existing role with the same name. Consider updating the role.")); } _context.SaveChanges(); return(Created("CreateRole", new { model.Id, Message = "Role has been created successfully" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> UpdateUser(User model) { try { var roleRepo = new RoleRepository(_context); var user = new UserRepository(_context).Get(model.UserName); var role = roleRepo.GetByName(model.Role); if (user == null) { return(NotFound("Updating user not found. Please update an existing user")); } user.Name = model.Name; user.UpdatedAt = DateTime.Now.ToUniversalTime(); user.PhoneNumber = model.PhoneNumber; user.Email = model.Email; //user.Locked = false; new UserRepository(_context).Update(user); //Remove old role roleRepo.RemoveFromAllRoles(user.Id); //Add to role roleRepo.AddToRole(user.Id, role.Name); return(Created("UpdateUser", new { user.Id, Message = "User has been updated successfully" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> UpdateProfile(User model) { try { var uId = User.FindFirst("Id")?.Value; var db = _context; var user = db.Users.FirstOrDefault(x => x.Id == uId); if (user == null) { throw new Exception("Could not find user"); } user.Name = model.Name; user.UpdatedAt = DateTime.UtcNow; user.PhoneNumber = model.PhoneNumber; user.Email = model.Email; db.SaveChanges(); return(Created("UpdateProfile", new { model.Id, Message = "Profile has been updated successfully" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> DeleteRole(string id) { try { _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var role = _context.Roles.FirstOrDefault(x => x.Id == id); if (role != null) { var roleClaims = _context.RoleClaims.Where(x => x.RoleId == id); _context.RoleClaims.RemoveRange(roleClaims); _context.Roles.Remove(role); } else { return(NotFound("Please check the role id.")); } _context.SaveChanges(); return(Ok(new { Message = "Role Deleted Successful" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> ResetPassword(ResetPasswordModel model) { try { var us = _context.Users.FirstOrDefault(x => x.UserName == model.UserName && !x.Hidden && !x.IsDeleted); if (us == null) { return(NotFound("Unknown Username")); } var result = await userManager.RemovePasswordAsync(us); if (result.Succeeded) { var res = await userManager.AddPasswordAsync(us, model.Password); if (!res.Succeeded) { return(BadRequest(WebHelpers.ProcessException(res))); } } else { return(BadRequest(WebHelpers.ProcessException(result))); } _context.SaveChanges(); return(Ok(new { Message = "Password Reset Successful" })); } catch (Exception e) { return(BadRequest(WebHelpers.ProcessException(e))); } }
public ResultObj UpdateProfile(Profile profile) { ResultObj results; try { if (!IsValidProfile(profile)) { return(WebHelpers.BuildResponse(profile, "Role must have a name and at least one profile.", false, 1)); } var oldRoles = new BaseRepository <Profile>().Get(profile.Id).Privileges.Split(','); var newRoles = profile.Privileges.Split(','); var users = _userRepo.Get(new UserFilter { ProfileId = profile.Id }); foreach (var user in users) { UserManager.RemoveFromRoles(user.Id, oldRoles); var user1 = user; newRoles.ForEach(r => UserManager.AddToRole(user1.Id, r.Trim())); } new BaseRepository <Profile>().Update(profile); results = WebHelpers.BuildResponse(profile, "Role Update Successfully.", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public async Task <ActionResult> CreateUser(User model) { try { var roleRepo = new RoleRepository(_context); var role = roleRepo.GetByName(model.Role); //todo: do validations model.Id = Guid.NewGuid().ToString(); model.Locked = false; var result = await userManager.CreateAsync(model, model.Password).ConfigureAwait(true); if (result.Succeeded) { var user = userManager.FindByNameAsync(model.UserName).Result; //Add to role roleRepo.AddToRole(user.Id, role.Name); //var rslt = userManager.AddToRoleAsync(user, model.Role); } else { return(BadRequest(WebHelpers.ProcessException(result))); } return(Created("CreateUser", new { model.Id, Message = "User has been created Successfully" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ResultObj> UpdateUser(UpdateUserModel model) { try { if (!ModelState.IsValid) { return(WebHelpers.ProcessException(ModelState.Values)); } var user = _userRepo.Get(model.UserName); var role = new ProfileRepository().Get(model.RoleId); if (user == null) { return(WebHelpers.BuildResponse(null, "Updating user not found. Please update an existing user", false, 0)); } var oldRoles = user.Profile.Privileges.Split(','); user.ProfileId = role.Id; user.Name = model.Name; user.UpdatedAt = DateTime.UtcNow; user.PhoneNumber = model.PhoneNumber; user.Email = model.Email; _userRepo.Update(user); //Remove old reles oldRoles.ForEach(x => UserManager.RemoveFromRole(user.Id, x)); //Add Roles in selected Role to user if (!string.IsNullOrEmpty(role.Privileges)) { role.Privileges.Split(',').ForEach(r => UserManager.AddToRole(user.Id, r.Trim())); } //Change Password if (!string.IsNullOrEmpty(model.Password)) { UserManager.RemovePassword(user.Id); UserManager.AddPassword(user.Id, model.Password); } var data = new { user.Id, user.Name, user.Email, user.PhoneNumber, user.UserName, RoleId = user.ProfileId, Role = new { user.Profile.Id, user.Profile.Name }, }; return(WebHelpers.BuildResponse(data, "User Created Successfully", true, 1)); } catch (Exception ex) { return(WebHelpers.ProcessException(ex)); } }
public async Task <ActionResult> DeleteUser(string id) { try { new UserRepository(_context).Delete(id); return(Ok(new { Message = "User Deleted Successfully." })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public virtual async Task <ActionResult> Post(T model) { try { _repository.Insert(SetAudit(model, true)); return(Created($"Create{_klassName}", new { Message = $"{_klassName} Saved Successful" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> GetClaims() { try { var data = _context.RoleClaims.Select(x => x.ClaimValue).Distinct().ToList(); return(Ok(data)); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> Logout() { try { await signInManager.SignOutAsync(); return(Ok(new { Message = "User Logged Out" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public ResultObj GetRoles() { ResultObj results; try { var data = new AppDbContext().Roles.Select(x => x.Name).ToList(); results = WebHelpers.BuildResponse(data, "", true, data.Count()); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public virtual ResultObj Get(long id) { ResultObj results; try { var data = Repository.Get(id); results = WebHelpers.BuildResponse(data, "", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public virtual ResultObj Get() { ResultObj results; try { var data = Repository.Get(); results = WebHelpers.BuildResponse(data, "Records Loaded", true, data.Count()); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public async Task <ResultObj> Login(LoginModel model) { try { if (!ModelState.IsValid) { throw new Exception("Please check the login details"); } var user = await UserManager.FindAsync(model.UserName, model.Password); if (user == null) { throw new Exception("Invalid Username or Password"); } var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); var data = new { user.Id, Username = user.UserName, user.Name, Role = new { user.Profile.Id, user.Profile.Name, Privileges = user.Profile.Privileges.Split(',') }, token }; return(WebHelpers.BuildResponse(data, "Login Successfull", true, 0)); } catch (Exception e) { return(WebHelpers.ProcessException(e)); } }
public virtual ResultObj Delete(long id) { ResultObj results; try { Repository.Delete(id); results = WebHelpers.BuildResponse(id, $"{_klassName} Deleted Successfully.", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public ResultObj DeleteUser(string id) { ResultObj results; try { _userRepo.Delete(id); results = WebHelpers.BuildResponse(id, "User Deleted Successfully.", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public virtual ResultObj Put(T record) { ResultObj results; try { Repository.Update(SetAudit(record)); results = WebHelpers.BuildResponse(record, $"{_klassName} Update Successfully.", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public virtual ResultObj Post(T record) { ResultObj results; try { Repository.Insert(SetAudit(record, true)); results = WebHelpers.BuildResponse(record, $"New {_klassName} Saved Successfully.", true, 1); } catch (Exception ex) { results = WebHelpers.ProcessException(ex); } return(results); }
public virtual async Task <ActionResult> Delete(long id) { try { var res = _repository.Get(id); if (res == null) { return(NotFound($"Could not find the {_klassName}")); } _repository.Delete(id); return(Ok(new { Message = $"{_klassName} Deleted Successful" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> GetRole(string id) { try { var data = _context.Roles.Where(x => x.Id == id).Include(x => x.RoleClaims).ToList().Select(x => new Role { Id = x.Id, Name = x.Name, NormalizedName = x.NormalizedName, Claims = x.RoleClaims.Select(c => c.ClaimValue).ToList() }).FirstOrDefault(); return(Ok(data)); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public ResultObj Reset(string email) { try { using (var db = new AppDbContext()) { var existing = db.Users.FirstOrDefault(x => x.UserName == email && !x.Hidden && !x.Locked); if (existing == null) { throw new Exception("Sorry email is not valid. Enjoy!!"); } var newRecord = new ResetRequest { Email = email, Token = StringHelpers.GenerateRandomString(32), Date = DateTime.Now, Ip = Request.Headers.Referrer.AbsoluteUri, IsActive = true }; db.ResetRequests.Add(newRecord); // create a password reset entry var link = Request.Headers.Referrer.AbsoluteUri + "#/resetpassword/" + newRecord.Token; var emailMsg = new EmailOutboxEntry { Message = $"<h3>Password Reset Request</h3> <br/><br/> Please follow the link below to change your password. <br/><br/><b><a href='{link}'>Click here</a></b> to reset your password.<br/><br/><br/><br/>Please ignore this message if you did not make this request.<br/><br/>Thank you. <br/>", Subject = "Password Reset", Sender = "*****@*****.**", Receiver = newRecord.Email, Created = DateTime.Now }; db.EmailOutboxEntries.Add(emailMsg); db.SaveChanges(); MessageHelpers.SendEmailMessage(emailMsg.Id); return(WebHelpers.BuildResponse(null, "Password reset link has been sent to your email.", true, 1)); } } catch (Exception e) { return(WebHelpers.ProcessException(e)); } }
public async Task <ResultObj> SignUp(RegisterBindingModel model) { try { if (!ModelState.IsValid) { return(WebHelpers.ProcessException(ModelState.Values)); } var role = new ProfileRepository().Get(model.ProfileId); //Todo: Check Code Validation Somehow var user = new User { UserName = model.UserName, ProfileId = model.ProfileId, Name = model.Name, PhoneNumber = model.PhoneNumber, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; var identityResult = await UserManager.CreateAsync(user, model.Password); if (!identityResult.Succeeded) { return(WebHelpers.ProcessException(identityResult)); } //Add Roles in selected Role to user if (!string.IsNullOrEmpty(role.Privileges)) { role.Privileges.Split(',').ForEach(r => UserManager.AddToRole(user.Id, r.Trim())); } return(WebHelpers.BuildResponse(null, "Registration Successful", true, 1)); } catch (Exception ex) { return(WebHelpers.ProcessException(ex)); } }
public async Task <ResultObj> ChangePassword(ChangePasswordBindingModel model) { try { if (!ModelState.IsValid) { return(WebHelpers.ProcessException(ModelState.Values)); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); return(!result.Succeeded ? WebHelpers.ProcessException(result) : WebHelpers.BuildResponse(model, "Password changed sucessfully.", true, 1)); } catch (Exception exception) { return(WebHelpers.ProcessException(exception)); } }
public async Task <ActionResult> UpdateRole(Role model) { try { _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var claims = model.Claims; var role = _context.Roles.FirstOrDefault(x => x.Id == model.Id); if (role != null) { var roleClaims = _context.RoleClaims.Where(x => x.RoleId == model.Id); _context.RoleClaims.RemoveRange(roleClaims); _context.SaveChanges(); foreach (var c in claims) { _context.RoleClaims.Add(new RoleClaim { ClaimType = GenericProperties.Privilege, ClaimValue = c, RoleId = model.Id }); } role.Name = model.Name; role.NormalizedName = model.Name; role.UpdatedAt = DateTime.Now.ToUniversalTime(); _context.SaveChanges(); } else { return(NotFound("Please check the role id.")); } _context.SaveChanges(); return(Created("UpdateRole", new { model.Id, Message = "Role has been updated successfully" })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> GetUsers() { try { var res = _context.Users.Include(x => x.UserRoles).ToList(); var data = res.Select(x => new { x.Id, x.Name, x.Email, x.PhoneNumber, x.UserName, Role = new RoleRepository(_context).GetById(x.UserRoles.FirstOrDefault()?.RoleId)?.Name, }).OrderBy(x => x.Name).ToList(); return(Ok(data)); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }
public async Task <ActionResult> ChangePassword(ChangePasswordModel model) { try { var uId = User.FindFirst("Id")?.Value; var db = _context; var user = db.Users.AsNoTracking().FirstOrDefault(x => x.Id == uId); var result = await userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!result.Succeeded) { return(BadRequest(WebHelpers.ProcessException(result))); } return(Ok(new { Message = "Password changed sucessfully." })); } catch (Exception ex) { return(BadRequest(WebHelpers.ProcessException(ex))); } }