public bool Update(long Id, CareersBE Be) { try { if (Be == null) { throw new ApiBusinessException(007, "La entidad no está completa.", System.Net.HttpStatusCode.NotFound, "Http"); } Careers entity = _unitOfWork.CareersRepository.GetAllByFilters(t => t.name.ToLower() == Be.name.ToLower(), null).FirstOrDefault(); if (entity != null && entity.idcareers != Id) { throw new ApiBusinessException(005, "Ya existe una carrera con ese nombre, por favor elija otro nombre.", System.Net.HttpStatusCode.BadRequest, "Http"); } Mapper.Initialize(cfg => { cfg.CreateMap <CareersBE, Careers>(); }); Careers myentity = Mapper.Map <CareersBE, Careers>(Be); _unitOfWork.CareersRepository.Update(myentity, new List <String> { "name", "state" }); _unitOfWork.Commit(); return(true); } catch (Exception ex) { throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } }
public List <CareersBE> GetAll(int state, int page, int pageSize, string orderBy, string ascending, string name, ref int count) { try { Expression <Func <Careers, Boolean> > exp = t => (t.name.ToLower().Contains(name.ToLower()) || String.IsNullOrEmpty(name)) && (t.state == state || state == 0); IQueryable <Careers> entities = _unitOfWork.CareersRepository.GetAllByFilters(exp, null); count = entities.Count(); var skipAmount = 0; if (page > 0) { skipAmount = pageSize * (page - 1); } entities = entities .OrderByPropertyOrField(orderBy, ascending) .Skip(skipAmount) .Take(pageSize); List <CareersBE> ColBe; Mapper.Initialize(cfg => { cfg.CreateMap <List <Careers>, List <CareersBE> >(); cfg.CreateMap <Careers, CareersBE>(); }); ColBe = Mapper.Map <IEnumerable <Careers>, IEnumerable <CareersBE> >(entities.ToList()).ToList(); return(ColBe); } catch (Exception ex) { throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } }
public CareersBE GetById(long Id) { try { Expression <Func <Careers, Boolean> > predicate = u => u.idcareers == Id; Careers entity = _unitOfWork.CareersRepository.GetOneByFilters(predicate, null); if (entity == null) { throw new ApiBusinessException(006, "No existe la carrera.", System.Net.HttpStatusCode.NotFound, "Http"); } Mapper.Initialize(cfg => { cfg.CreateMap <Careers, CareersBE>(); }); CareersBE be = Mapper.Map <Careers, CareersBE>(entity); return(be); } catch (Exception ex) { throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } }
public async Task <IHttpActionResult> RequestResetPassword(ResetPasswordBindingModel resetmodel) { using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { resetmodel.token = RandomLink.getVerifyPathResetPsw() + resetmodel.token; var resetpass = dataContext.ResetPasswords.FirstOrDefault(t => t.email.Equals(resetmodel.email) && t.token.Equals(resetmodel.token)); if (resetpass == null) { throw new ApiDataException(16, "No existe una confirmación en el sistema para confirmar" , System.Net.HttpStatusCode.NotFound, "Http://"); } if (resetpass.state == (Int32)StatesEnum.Confirmed) { throw new ApiBusinessException(0006, "El link ya fue utilizado", System.Net.HttpStatusCode.NotFound, "Http"); } if (resetpass.state == (Int32)StatesEnum.Annulled) { throw new ApiDataException(18, "La confirmación fue reemplazada por una nueva o ya expiró" , System.Net.HttpStatusCode.NotFound, "Http://"); } if (resetpass.expiredate < DateTime.Now) { throw new ApiBusinessException(17, "Esta solicitud ya expiró, mande una nueva solicitud." , System.Net.HttpStatusCode.NotFound, "Http://"); } var user = await this.AppUserManager.FindByEmailAsync(resetpass.email); if (user == null) { throw new ApiDataException(15, "No existe ese email en nuestro sistema", System.Net.HttpStatusCode.NotFound, "Http://"); } user.PasswordHash = this.AppUserManager.PasswordHasher.HashPassword(resetmodel.newpassword); this.AppUserManager.UpdateSecurityStamp(user.Id); resetpass.state = (Int32)StatesEnum.Confirmed; dataContext.SaveChanges(); trans.Commit(); return(Ok()); } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }
public async Task <IHttpActionResult> CreateAdmin(CreateUserBindingModel createUserModel) { //throw new ApiBusinessException(0002, "Nombre de usuario duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { var user = new ApplicationUser() { UserName = createUserModel.Username, Email = createUserModel.Email, Name = createUserModel.Name, //LastName = createUserModel.LastName, //Level = 3, //JoinDate = DateTime.Now.Date, EmailConfirmed = true }; var role = new CreateRoleBindingModel() { Name = createUserModel.RoleName }; IdentityResult addUserResult = await this.AppUserManager .CreateAsync(user, createUserModel.Password); if (!addUserResult.Succeeded) { trans.Rollback(); return(GetErrorResult(addUserResult)); } IdentityResult addUserToRoleResult = await this.AppUserManager. AddToRoleAsync(user.Id, role.Name); if (!addUserToRoleResult.Succeeded) { trans.Rollback(); return(GetErrorResult(addUserResult)); } trans.Commit(); Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id })); return(Created(locationHeader, TheModelFactory.Create(user))); } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }
public bool Delete(long Id) { try { Cycles entity = _unitOfWork.CyclesRepository.GetById(Id); entity.state = (Int32)StatesEnum.Annulled; _unitOfWork.CyclesRepository.Delete(entity, new List <String>() { "state" }); _unitOfWork.Commit(); return(true); } catch (Exception ex) { throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } }
public async Task <IHttpActionResult> GetClaim(long id) { using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { //var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); //ApplicationUser user = await userManager.FindByNameAsync(User.Identity.Name); //var employee=dataContext.EmployeeAccounts.First(t => t.idemployeeaccount == id); //List<ClaimBindingModel> claims = new List<ClaimBindingModel>(); //foreach (var claim in user.Claims) //{ // if (claim.ClaimType.Equals("iss") || claim.ClaimType.Equals("aud") || claim.ClaimType.Equals("nbf") || // claim.ClaimType.Equals("exp") || claim.ClaimType.Equals("nameid") || // claim.ClaimType.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider") // || claim.ClaimType.Equals("role") // || claim.ClaimType.Equals("AspNet.Identity.SecurityStamp") || claim.ClaimType.Equals("exp") // || claim.ClaimType.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier") // || claim.ClaimType.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name") // || claim.ClaimType.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider") // || claim.ClaimType.Equals("AspNet.Identity.SecurityStamp") // || claim.ClaimType.Equals("http://schemas.microsoft.com/ws/2008/06/identity/claims/role") // ) // continue; // else if (claim.ClaimValue==employee.username) // { // claims.Add(new ClaimBindingModel() { Type = claim.ClaimType, Value = claim.ClaimValue }); // } //} //trans.Commit(); //return Ok(claims); return(Ok()); } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }
public long Create(CyclesBE Be) { try { if (_unitOfWork.CyclesRepository.GetOneByFilters(t => t.name == Be.name, null) != null) { throw new ApiBusinessException(005, "Ya existe un ciclo con ese nombre, por favor elija otro nombre", System.Net.HttpStatusCode.BadRequest, "Http"); } Mapper.Initialize(cfg => { cfg.CreateMap <CyclesBE, Cycles>(); }); Cycles entity = Mapper.Map <CyclesBE, Cycles>(Be); _unitOfWork.CyclesRepository.Insert(entity); _unitOfWork.Commit(); return(entity.idcycle); } catch (Exception ex) { throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } }
public async Task <IHttpActionResult> PostClaims(List <PostClaimBindingModel> permisionss) { //throw new ApiBusinessException(0002, "Nombre de usuario duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { //List<Claim> NewClaims = new List<Claim>(); //foreach (var claim in permisionss) //{ //NewClaims.Add(new Claim(claim.Type, claim.Value)); //} //var identity = User.Identity as ClaimsIdentity; //var claims = identity.Claims.ToList(); //foreach (var claim in claims) //{ // if (claim.Type.Equals("iss") || claim.Type.Equals("aud") || claim.Type.Equals("nbf") || // claim.Type.Equals("exp") || claim.Type.Equals("nameid") || // claim.Type.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider") // || claim.Type.Equals("role") // || claim.Type.Equals("AspNet.Identity.SecurityStamp") || claim.Type.Equals("exp") // || claim.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier") // || claim.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name") // || claim.Type.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider") // || claim.Type.Equals("AspNet.Identity.SecurityStamp") // || claim.Type.Equals("http://schemas.microsoft.com/ws/2008/06/identity/claims/role") // ) // continue; // else // claims.Remove(claim); //} //identity.AddClaims(NewClaims); var appUser = Request.GetOwinContext().GetUserManager <ApplicationUserManager>().FindByNameAsync(User.Identity.Name); //var appUser = await this.AppUserManager.FindByIdAsync(id); if (appUser == null) { return(NotFound()); } Claim iuc; var realclaims = Request.GetOwinContext().GetUserManager <ApplicationUserManager>().GetClaimsAsync(appUser.Result.Id); foreach (PostClaimBindingModel claimModel in permisionss) { iuc = new Claim(claimModel.Type, claimModel.Value); if (claimModel.ischecked) { //iuc = new IdentityUserClaim() //{ // ClaimType = claimModel.Type, // ClaimValue = claimModel.Value //}; //if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type)) if (realclaims.Result.FirstOrDefault(t => t.Type == iuc.Type && t.Value == claimModel.Value) != null) { await Request.GetOwinContext().GetUserManager <ApplicationUserManager>().RemoveClaimAsync(appUser.Result.Id, iuc); } //await Request.GetOwinContext().GetUserManager<ApplicationUserManager>().AddClaimAsync(appUser.Result.Id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value)); await Request.GetOwinContext().GetUserManager <ApplicationUserManager>().AddClaimAsync(appUser.Result.Id, iuc); } else { //if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type)) if (realclaims.Result.FirstOrDefault(t => t.Type == iuc.Type && t.Value == claimModel.Value) != null) { await Request.GetOwinContext().GetUserManager <ApplicationUserManager>().RemoveClaimAsync(appUser.Result.Id, iuc); } } } //ClaimsIdentity oAuthIdentity = await appUser.Result.GenerateUserIdentityAsync(Request.GetOwinContext().GetUserManager<ApplicationUserManager>(), "JWT"); //HttpContext.Current.GetOwinContext().Authentication.User.AddIdentity(oAuthIdentity); //Request.GetOwinContext().Environment. //var ticket = new AuthenticationTicket(oAuthIdentity, properties); //Request.GetOwinContext().Authentication. //OAuthGrantResourceOwnerCredentialsContext //context.Validated(ticket); trans.Commit(); return(Ok()); //identity.AddClaim } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }
public async Task <IHttpActionResult> UpdateUser(UpdateUserBindingModel createUserModel) { //throw new ApiBusinessException(0002, "Nombre de usuario duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { var user = this.AppUserManager.FindById(User.Identity.GetUserId()); var userduplicate = this.AppUserManager.FindByName(user.UserName); if (userduplicate != null && userduplicate.Id != user.Id) { throw new ApiBusinessException(0002, "Nombre de usuario duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); } userduplicate = this.AppUserManager.FindByEmail(user.Email); if (userduplicate != null && userduplicate.Id != user.Id) { throw new ApiBusinessException(0003, "Email duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); } //var userdniduplicate = dataContext.PeatonUsers.Where(t => t.dni.Equals(createUserModel.dni)).FirstOrDefault(); //if (userdniduplicate != null && userdniduplicate.Id != user.Id) // throw new ApiBusinessException(0004, "Dni duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); //var userdniduplicateplayer = dataContext.PlayerUsers.Where(t => t.dni.Equals(createUserModel.dni)).FirstOrDefault(); //if (userdniduplicateplayer != null) // throw new ApiBusinessException(0004, "Dni duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); user.UserName = createUserModel.Username; user.Email = createUserModel.Email; user.Name = createUserModel.Name; var passwordResult = this.AppUserManager.CheckPassword(user, createUserModel.OldPassword); if (!passwordResult) { throw new ApiBusinessException(0008, "La contraseña actual no es correcta", System.Net.HttpStatusCode.BadRequest, "Http"); } if (!String.IsNullOrEmpty(createUserModel.Password) && !String.IsNullOrEmpty(createUserModel.ConfirmPassword) && createUserModel.Password.Equals(createUserModel.ConfirmPassword)) { IdentityResult addUserResult = this.AppUserManager .ChangePassword(User.Identity.GetUserId(), createUserModel.OldPassword, createUserModel.Password); if (!addUserResult.Succeeded) { if (addUserResult.Errors.Contains("Incorrect password.")) { throw new ApiBusinessException(0008, "La contraseña actual no es correcta", System.Net.HttpStatusCode.BadRequest, "Http"); } trans.Rollback(); return(GetErrorResult(addUserResult)); } } //var userpeaton = dataContext.PeatonUsers.FirstOrDefault(t => t.idpeatonusers == createUserModel.idpeatonusers); //userpeaton.address = createUserModel.address; //userpeaton.addressnumber = createUserModel.addressnumber; //userpeaton.phonenumber = createUserModel.phonenumber; ////userpeaton.age = createUserModel.age; //userpeaton.dni = createUserModel.dni; //userpeaton.genre = createUserModel.genre; //userpeaton.idlocation = createUserModel.idlocation; //userpeaton.name = createUserModel.FirstName; //userpeaton.lastname = createUserModel.LastName; //userpeaton.profession = createUserModel.profession.Replace(" / ", "_"); ////userpeaton.profilephoto = Cryptography.Decrypt(createUserModel.profilephoto); //userpeaton.profilephoto = createUserModel.profilephoto; //userpeaton.civilstatus = createUserModel.civilstatus; //userpeaton.apartment = createUserModel.apartment; //userpeaton.floor = createUserModel.floor; //dataContext.SaveChanges(); //Points Security //SetFullProfilePoints(user, dataContext); //End Points trans.Commit(); Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id })); return(Created(locationHeader, TheModelFactory.Create(user))); } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }
public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>()) { using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { try { var user = new ApplicationUser() { UserName = createUserModel.Username, Email = createUserModel.Email, Name = createUserModel.Name, //Level = 3, //JoinDate = DateTime.Now.Date, EmailConfirmed = true, }; //var userpeaton = new PeatonUser() //{ // address = createUserModel.address, // addressnumber = createUserModel.addressnumber, // //age = createUserModel.age, // dni = createUserModel.dni, // genre = createUserModel.genre, // idlocation = createUserModel.idlocation, // name = createUserModel.FirstName, // lastname = createUserModel.LastName, // profession = createUserModel.profession, // //profilephoto = Cryptography.Decrypt(createUserModel.profilephoto), // profilephoto =createUserModel.profilephoto, // state = (Int32)StatesEnum.Valid, // Id = user.Id, // birthdate = createUserModel.birthdate, // apartment=createUserModel.apartment, // civilstatus=createUserModel.civilstatus, // floor=createUserModel.floor, // phonenumber = createUserModel.phonenumber //}; //String randomLink = RandomLink.GetRandomLink(); //var confirmregistration = new ConfirmRegistrations() //{ // dateup = DateTime.Now, // Id = user.Id, // state = (Int32)StatesEnum.NotConfirmed, // randomkey = randomLink, // expiredate = DateTime.Now.AddDays(1), //}; var userduplicate = this.AppUserManager.FindByName(user.UserName); if (userduplicate != null) { throw new ApiBusinessException(0002, "Nombre de usuario duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); } userduplicate = this.AppUserManager.FindByEmail(user.Email); if (userduplicate != null) { throw new ApiBusinessException(0003, "Email duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); } //var userdniduplicate = dataContext.PeatonUsers.Where(t => t.dni.Equals(userpeaton.dni)).FirstOrDefault(); //if (userdniduplicate != null) // throw new ApiBusinessException(0004, "Dni duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); //var userdniduplicateplayer = dataContext.PlayerUsers.Where(t => t.dni.Equals(userpeaton.dni)).FirstOrDefault(); //if (userdniduplicateplayer != null) // throw new ApiBusinessException(0004, "Dni duplicado", System.Net.HttpStatusCode.BadRequest, "Http"); var role = new CreateRoleBindingModel() { Name = createUserModel.RoleName }; IdentityResult addUserResult = await this.AppUserManager .CreateAsync(user, createUserModel.Password); if (!addUserResult.Succeeded) { trans.Rollback(); return(GetErrorResult(addUserResult)); } IdentityResult addUserToRoleResult = await this.AppUserManager. AddToRoleAsync(user.Id, role.Name); if (!addUserToRoleResult.Succeeded) { trans.Rollback(); return(GetErrorResult(addUserResult)); } //dataContext.PeatonUsers.Add(userpeaton); //dataContext.SaveChanges(); //dataContext.ConfirmRegsitrations.Add(confirmregistration); //dataContext.SaveChanges(); //RegisterUserStateMail registerUserMail = //new RegisterUserStateMail(user.FirstName + " " + user.LastName, user.UserName, randomLink, createUserModel.Password, createUserModel.Email); //new SimpleMail().SendMail(registerUserMail); trans.Commit(); Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id })); return(Created(locationHeader, TheModelFactory.Create(user))); } catch (Exception ex) { trans.Rollback(); throw HandlerExceptions.GetInstance().RunCustomExceptions(ex); } } } }