public Status <bool> DeleteProperty(long buildingId) { var ident = CustomAuthentication.GetIdentity(); if (!ident.IsAuthenticated) { return(Status.UnAuthorized <bool>()); } using (var data = this.service.Get()) { // get the building and make sure the user owns it var preview = data.Building.GetBuildingPreviewById(buildingId); if (preview == null) { return(Status.NotFound <bool>()); } if (preview.UserId != ident.UserId) { return(Status.UnAuthorized <bool>()); } // delete the building data.Building.DeleteBuilding(buildingId); data.Save(); return(Status.OK <bool>(true)); } }
public ActionResult Checkout(int id, Guid?token) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); return(RedirectToAction("checkout")); } } var status = this.orderAdapter.GetOrderForCheckout(User.Identity.Name, id); if (status.StatusCode != 200) { return(this.NotFoundException()); } Rentler.Web.Models.OrderCheckoutModel model = new Rentler.Web.Models.OrderCheckoutModel() { Order = status.Result, Input = new Rentler.Web.Models.OrderCheckoutInputModel() }; // auto-select the first payment method if (status.Result.User.UserCreditCards.Count > 0) { model.Input.SelectedPaymentMethod = status.Result.User.UserCreditCards.First(); } return(View(model)); }
public ActionResult List(long?id, Guid?token) { if (!id.HasValue) { return(this.NotFoundException()); } if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); return(RedirectToAction("list", new { id = id })); } } var status = this.propertyAdapter.GetPropertyListingInfo(id.Value, User.Identity.Name); if (status.StatusCode != 200) { return(this.NotFoundException()); } Rentler.Web.Models.PropertyListModel model = new Models.PropertyListModel(status.Result); model.StepsAvailable = GetStepsAvailable(status.Result); return(View(model)); }
public ActionResult Register(AccountRegisterInputModel input, string returnUrl) { if (ModelState.IsValid) { var result = this.accountAdapter.RegisterUser(new User() { Username = input.UserName, Email = input.Email, FirstName = input.FirstName, LastName = input.LastName }, input.Password); if (result.StatusCode == 200) { CustomAuthentication.SetAuthCookie(result.Result.Username, result.Result.UserId, false); // redirect the user if (String.IsNullOrEmpty(returnUrl)) { return(Redirect("/")); } else { return(Redirect(returnUrl)); } } HandleErrors(result); } return(View(new AccountRegisterModel() { Input = input })); }
public ActionResult Edit(long id, Guid?token) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); return(RedirectToAction("edit")); } } var request = this.propertyAdapter.GetProperty(id, User.Identity.Name); if (request.StatusCode != 200) { return(this.NotFoundException()); } PropertyEditModel model = new PropertyEditModel( new PropertyEditInputModel(request.Result) ); return(View(model)); }
/// <summary> /// Entry point for landlord to manage a single property. /// </summary> /// <param name="id">the property identifier</param> /// <returns></returns> public ActionResult Manage(long id, Guid?token) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); } return(Redirect("/property/manage/" + id)); } if (!User.Identity.IsAuthenticated) { return(Redirect("/account/login?returnUrl=" + "/property/manage/" + id)); } var listing = this.propertyFacade.ManageListingById(id); if (listing.StatusCode != 200) { throw new HttpException(404, "Not Found"); } PropertyManageModel model = new PropertyManageModel(); model.Listing = listing.Result; if (!model.Listing.IsValidListing) { return(View("Manage-NotValid", model)); } return(View(model)); }
public ActionResult Login(AccountLoginInputModel input, string returnUrl) { if (ModelState.IsValid) { var result = this.accountAdapter.LoginUser(input.UserName, input.Password); if (result.StatusCode == 200) { // set auth cookie CustomAuthentication.SetAuthCookie(result.Result.Username, result.Result.UserId, input.RememberMe); // allow cross-browser auth cookie (IE8) Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""); // redirect the user if (String.IsNullOrEmpty(returnUrl)) { return(Redirect("/")); } else { return(Redirect(returnUrl)); } } // process failure var error = result.Errors.First(); ModelState.AddModelError(error.MemberNames.First(), error.ErrorMessage); } return(View(new AccountLoginModel() { Input = input })); }
public Status <PropertySearch> SearchForUserProperty(PropertySearch search) { var ident = CustomAuthentication.GetIdentity(); if (!ident.IsAuthenticated) { return(Status.UnAuthorized <PropertySearch>()); } // if it is null create a new one if (search == null) { search = new PropertySearch(); } if (search.Page < 1) { search.Page = 1; } if (search.ResultsPerPage < 5) { search.ResultsPerPage = 25; } if (string.IsNullOrEmpty(search.OrderBy)) { search.OrderBy = "CreateDate"; } using (var data = this.service.Get()) { var result = data.Building.SearchUserBuildings(ident.UserId, search); search.Results = result; return(Status.OK <PropertySearch>(search)); } }
public Status <Listing> ManageListingById(long listingId) { var ident = CustomAuthentication.GetIdentity(); if (!ident.IsAuthenticated) { return(Status.UnAuthorized <Listing>()); } using (var data = this.service.Get()) { var result = data.Listing.GetListingById(listingId); if (result == null) { return(Status.NotFound <Listing>()); } if (result.UserId == ident.UserId) { result.IsOwnedByCurrentUser = true; } if (!result.IsOwnedByCurrentUser) { return(Status.UnAuthorized <Listing>()); } // get the stats var connection = ConnectionGateway.Current.GetReadConnection(); try { var listingViewTask = connection.Hashes.GetString(App.RedisDatabase, CacheKeys.LISTING_VIEWS, listingId.ToString()); string listingViewResult = connection.Wait(listingViewTask); if (string.IsNullOrEmpty(listingViewResult)) { result.PageViews = 0; } result.PageViews = long.Parse(listingViewResult); var listingSearchTask = connection.Hashes.GetString(App.RedisDatabase, CacheKeys.LISTING_SEARCH_VIEWS, listingId.ToString()); string listingSearchResult = connection.Wait(listingSearchTask); if (string.IsNullOrEmpty(listingSearchResult)) { result.SearchViews = 0; } result.SearchViews = long.Parse(listingSearchResult); } catch (Exception) { result.PageViews = 0; result.SearchViews = 0; } return(Status.OK <Listing>(result)); } }
public void GetIdentityUnauthenticatedUser() { var identity = CustomAuthentication.GetIdentity(); Assert.IsNotNull(identity); Assert.AreEqual(identity.IsAuthenticated, false); Assert.AreEqual(identity.Username, string.Empty); Assert.AreEqual(identity.UserId, 0); }
public ActionResult Index(long?ad, Guid?token) { if (!ad.HasValue) { return(this.NotFoundException()); } RedisPublisher.Publish("token", "Listing page " + ad.Value + " token: " + token.HasValue.ToString()); if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); } return(Redirect("/ksl/listing/index?ad=" + ad.Value)); } var status = this.listingAdapter.GetListing(ad.Value); // this is ok because the adapter will return 0 if count cannot // be retrieved var viewCount = this.listingAdapter.GetListingViews(ad.Value).Result; var userHasSaved = this.listingAdapter.ListingWasSavedBy(ad.Value, User.Identity.Name).Result; if (status.StatusCode != 200) { return(this.NotFoundException()); } this.listingAdapter.IncrementListingViews(ad.Value); var model = new ListingIndexModel(); model.Listing = status.Result; model.ListingViews = viewCount; model.UserHasSaved = userHasSaved; //set the login url to Ksl model.LoginUrl = string.Format("{0}{1}?login_forward=", Rentler.Web.Config.KslDomain, Rentler.Web.Config.KslLoginPath); model.LoginUrl += Url.Encode(string.Format("{0}{1}{2}", Rentler.Web.Config.KslDomain, Rentler.Web.Config.KslListingPath, status.Result.BuildingId)); return(View(model)); }
protected virtual void InitAuth(StandardKernel kernel) { kernel.Bind <HttpCookieCollection>().To <HttpCookieCollection>(); kernel.Bind <IAuthCookieProvider>().To <FakeAuthCookieProvider>().InSingletonScope(); kernel.Bind <IAuthentication>().ToMethod <CustomAuthentication>(c => { var auth = new CustomAuthentication(); auth.AuthCookieProvider = kernel.Get <IAuthCookieProvider>(); return(auth); }); }
public IHttpActionResult GetUser(int id) { var auth = new CustomAuthentication(ControllerContext); if (!auth.AuthenticateUser(User.Identity as ClaimsIdentity, id, out IHttpActionResult result)) { return(result); } var user = _userManager.GetUser(id); return(Ok(user)); }
/// <summary> /// Gets the saved listings for user. /// </summary> /// <param name="username">The username to get the saved listings for.</param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <returns> /// A list of saved listings for a user. /// </returns> public Status <PaginatedList <BuildingPreview> > GetFavoritesForUser( string username, int?pageNumber, int?pageSize) { var identity = CustomAuthentication.GetIdentity(); if (!identity.IsAuthenticated) { return(Status.UnAuthorized <PaginatedList <BuildingPreview> >()); } if (!pageNumber.HasValue) { pageNumber = 0; } if (!pageSize.HasValue || pageSize.Value > 100) { pageSize = 25; } if (string.IsNullOrWhiteSpace(username)) { return(Status.ValidationError <PaginatedList <BuildingPreview> >(null, "username", "username is required")); } using (var context = new RentlerContext()) { var props = (from sb in context.SavedBuildings join b in context.Buildings on sb.BuildingId equals b.BuildingId where sb.UserId == identity.UserId && b.IsActive == true && b.IsRemovedByAdmin == false orderby b.CreateDateUtc descending select b).ToList(); var queryableProps = props.Select(b => new BuildingPreview() { Bathrooms = b.Bathrooms.Value, Bedrooms = b.Bedrooms.Value, BuildingId = b.BuildingId, City = b.City, IsFeatured = false, Price = b.Price, PrimaryPhotoExtension = b.PrimaryPhotoExtension, PrimaryPhotoId = b.PrimaryPhotoId, State = b.State, Title = string.IsNullOrWhiteSpace(b.Title) ? b.Address1 : b.Title, Address1 = b.Address1 }).AsQueryable <BuildingPreview>(); return(Status.OK <PaginatedList <BuildingPreview> >( new PaginatedList <BuildingPreview>(queryableProps, pageNumber.Value, pageSize.Value))); } }
public void GetIdentityInvalidIdentity() { HttpContext.Current.User = new GenericPrincipal( new FakeIdentity("cyberkruz"), new string[0]); try { CustomAuthentication.GetIdentity(); } catch (InvalidCastException) { Assert.IsTrue(true); } }
public IHttpActionResult UpdateUser(int id, UserDisplayDto user) { //authentication var auth = new CustomAuthentication(ControllerContext); if (!auth.AuthenticateUser(User.Identity as ClaimsIdentity, id, out IHttpActionResult result)) { return(result); } var updatedUser = _userManager.UpdateUser(id, user); return(Ok(updatedUser)); }
public void GetIdentityIsAuthenticated() { // unauthenticated user FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, "cyberkruz", DateTime.Now, DateTime.Now.AddDays(30), true, "4", FormsAuthentication.FormsCookiePath); FormsIdentity ident = new FormsIdentity(ticket); HttpContext.Current.User = new GenericPrincipal(ident, new string[0]); var identity = CustomAuthentication.GetIdentity(); Assert.IsTrue(identity.IsAuthenticated); Assert.AreEqual(identity.Username, "cyberkruz"); Assert.AreEqual(identity.UserId, 4); }
/// <summary> /// Removes a Saved Listing for a particular User /// </summary> /// <param name="listingId">listing identifier</param> /// <param name="username">user identifier</param> /// <returns> /// A status with the saved building /// </returns> public Status <bool> DeleteSavedBuilding(long listingId, string username) { var identity = CustomAuthentication.GetIdentity(); if (!identity.IsAuthenticated) { return(Status.UnAuthorized <bool>()); } if (listingId == 0) { return(Status.ValidationError <bool>(false, "listingId", "listingId is required")); } if (string.IsNullOrWhiteSpace(username)) { return(Status.ValidationError <bool>(false, "username", "username is required")); } using (var context = new RentlerContext()) { try { SavedBuilding save = (from s in context.SavedBuildings where s.BuildingId == listingId && s.UserId == identity.UserId select s).SingleOrDefault(); if (save == null) { return(Status.NotFound <bool>()); } context.SavedBuildings.Remove(save); context.SaveChanges(); InvalidateCache(save.BuildingId); return(Status.OK <bool>(true)); } catch (Exception ex) { return(Status.Error <bool>(ex.Message, false)); } } }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the /*MembershipCreateStatus createStatus; * Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus); * * if (createStatus == MembershipCreateStatus.Success) * { * FormsAuthentication.SetAuthCookie(model.UserName, false); * return RedirectToAction("Index", "Home"); * } * else * { * ModelState.AddModelError("", ErrorCodeToString(createStatus)); * }*/ /*var anyUser = Repository.Users.Any(p => string.Compare(p.Email, userView.Email) == 0); * if (anyUser) * { * ModelState.AddModelError("Email", "Пользователь с таким email уже зарегистрирован"); * }*/ if (ModelState.IsValid) { //var user = (User)ModelMapper.Map(userView, typeof(UserView), typeof(User)); Repository = new SqlRepository(); Auth = new CustomAuthentication() { Repository = Repository }; Repository.CreateUser(new Entities.GlUser() { Name = model.UserName, Password = model.Password }); //Repository.CreateUser(user); return(RedirectToAction("Index", "Home")); } } // If we got this far, something failed, redisplay form return(View(model)); }
public IHttpActionResult DeleteUser(int id) { //authentication var auth = new CustomAuthentication(ControllerContext); if (!auth.AuthenticateUser(User.Identity as ClaimsIdentity, id, out IHttpActionResult result)) { return(result); } bool deleted = _userManager.DeleteUser(id); if (deleted) { return(Ok("deleted")); } return(Ok()); }
public ActionResult Index(Search search, Guid?token) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); } } // Fix for php sending goofy data to us. if (Request["Amenities[]"] != null) { if (search.Amenities == null) { List <string> strings = new List <string>( Request["Amenities[]"].Split(",".ToCharArray())); search.Amenities = strings.ToArray(); } } // Fix for php sending goofy data to us. if (Request["Terms[]"] != null) { if (search.Terms == null) { List <string> strings = new List <string>( Request["Terms[]"].Split(",".ToCharArray())); search.Terms = strings.ToArray(); } } var result = this.searchAdapter.Search(search); if (Request.IsAjaxRequest()) { return(PartialView("SearchResults", result.Result)); } return(View(result.Result)); }
private void InitializeComponent() { this.module1 = new DevExpress.ExpressApp.SystemModule.SystemModule(); this.module2 = new DevExpress.ExpressApp.Web.SystemModule.SystemAspNetModule(); this.module3 = new UserTest.Module.UserTestModule(); this.module4 = new UserTest.Module.Web.UserTestAspNetModule(); this.securityModule1 = new DevExpress.ExpressApp.Security.SecurityModule(); this.securityStrategyComplex1 = new DevExpress.ExpressApp.Security.SecurityStrategyComplex(); this.objectsModule = new DevExpress.ExpressApp.Objects.BusinessClassLibraryCustomizationModule(); this.validationModule = new DevExpress.ExpressApp.Validation.ValidationModule(); this.validationAspNetModule = new DevExpress.ExpressApp.Validation.Web.ValidationAspNetModule(); this.customAuthentication1 = new UserTest.Module.CustomAuthentication(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // securityStrategyComplex1 // this.securityStrategyComplex1.AllowAnonymousAccess = false; this.securityStrategyComplex1.Authentication = this.customAuthentication1; this.securityStrategyComplex1.RoleType = typeof(DevExpress.Persistent.BaseImpl.PermissionPolicy.PermissionPolicyRole); this.securityStrategyComplex1.SupportNavigationPermissionsForTypes = false; this.securityStrategyComplex1.UserType = typeof(UserTest.Module.BusinessObjects.Employee); // // validationModule // this.validationModule.AllowValidationDetailsAccess = true; this.validationModule.IgnoreWarningAndInformationRules = false; // // UserTestAspNetApplication // this.ApplicationName = "UserTest"; this.CheckCompatibilityType = DevExpress.ExpressApp.CheckCompatibilityType.DatabaseSchema; this.Modules.Add(this.module1); this.Modules.Add(this.module2); this.Modules.Add(this.objectsModule); this.Modules.Add(this.validationModule); this.Modules.Add(this.module3); this.Modules.Add(this.validationAspNetModule); this.Modules.Add(this.module4); this.Modules.Add(this.securityModule1); this.Security = this.securityStrategyComplex1; this.DatabaseVersionMismatch += new System.EventHandler <DevExpress.ExpressApp.DatabaseVersionMismatchEventArgs>(this.UserTestAspNetApplication_DatabaseVersionMismatch); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); }
public ActionResult Search(PropertySearch search, Guid?token) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); } return(Redirect("/property/search")); } var result = this.propertyFacade.SearchForUserProperty(search); if (Request.IsAjaxRequest()) { return(PartialView("SearchResults", result.Result)); } return(View(result.Result)); }
public ActionResult Create(Guid?token, int?PropertyTypeCode) { if (!User.Identity.IsAuthenticated && token.HasValue) { var user = authAdapter.ValidateAuthToken(token.Value); if (user.StatusCode == 200) { CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true); return(RedirectToAction("create")); } } Rentler.Web.Models.PropertyCreateModel model = new Models.PropertyCreateModel(); model.IsKsl = true; // set property type from ksl from user selection model.Input.PropertyTypeCode = PropertyTypeCode.HasValue ? PropertyTypeCode.Value : 0; return(View(model)); }
public Status <string[]> GetOrderedPhotoIds(long buildingId) { var identity = CustomAuthentication.GetIdentity(); if (!identity.IsAuthenticated) { return(Status.UnAuthorized <string[]>()); } if (buildingId == 0) { return(Status.ValidationError <string[]>(null, "buildingId", "buildingId cannot be empty")); } using (RentlerContext context = new RentlerContext()) { try { var building = (from b in context.Buildings.Include("Photos") where b.BuildingId == buildingId select b).SingleOrDefault(); if (building == null) { return(Status.NotFound <string[]>()); } var photoIds = building.Photos .OrderBy(p => p.SortOrder) .Select(p => p.PhotoId.ToString()) .ToArray(); return(Status.OK <string[]>(photoIds)); } catch (Exception ex) { return(Status.Error <string[]>(ex.Message, null)); } } }
public void SetAuthCookieNoException() { CustomAuthentication.SetAuthCookie("cyberkruz", 4, true); }
public void SignOutNoException() { CustomAuthentication.SignOut(); }
/// <summary> /// Page to logout the user. /// </summary> /// <returns>Redirection to the home page.</returns> public ActionResult Logout() { CustomAuthentication.SignOut(); return(Redirect("/")); }
/// <summary> /// Sets the application for user. /// </summary> /// <param name="username">The username of the user to set the application for.</param> /// <param name="userApplication">The user's application.</param> /// <returns> /// The user application that was saved. /// </returns> public Status <UserApplication> SaveApplicationForUser( string username, UserApplication userApplication) { var identity = CustomAuthentication.GetIdentity(); if (!identity.IsAuthenticated) { return(Status.UnAuthorized <UserApplication>()); } using (var context = new RentlerContext()) { try { bool isNew = false; var application = (from u in context.UserApplications where u.UserId == identity.UserId select u).SingleOrDefault(); if (application == null) { application = new UserApplication { UserId = identity.UserId }; isNew = true; } application.ConvictedExplaination = userApplication.ConvictedExplaination; application.EmergencyContact = userApplication.EmergencyContact; application.EmergencyContactAddressLine1 = userApplication.EmergencyContactAddressLine1; application.EmergencyContactAddressLine2 = userApplication.EmergencyContactAddressLine2; application.EmergencyContactCity = userApplication.EmergencyContactCity; application.EmergencyContactPhone = userApplication.EmergencyContactPhone; application.EmergencyContactState = userApplication.EmergencyContactState; application.EmergencyContactZip = userApplication.EmergencyContactZip; application.FirstName = userApplication.FirstName; application.HasBeenConvicted = userApplication.HasBeenConvicted; application.HasEverBeenUnlawfulDetainer = userApplication.HasEverBeenUnlawfulDetainer; application.LastName = userApplication.LastName; application.PresentAddressLine1 = userApplication.PresentAddressLine1; application.PresentAddressLine2 = userApplication.PresentAddressLine2; application.PresentCity = userApplication.PresentCity; application.PresentEmployer = userApplication.PresentEmployer; application.PresentEmployerPhone = userApplication.PresentEmployerPhone; application.PresentLandlord = userApplication.PresentLandlord; application.PresentLandlordPhone = userApplication.PresentLandlordPhone; application.PresentPhone = userApplication.PresentPhone; application.PresentState = userApplication.PresentState; application.PresentZip = userApplication.PresentZip; application.PreviousAddressLine1 = userApplication.PreviousAddressLine1; application.PreviousAddressLine2 = userApplication.PreviousAddressLine2; application.PreviousCity = userApplication.PreviousCity; application.PreviousEmployer = userApplication.PreviousEmployer; application.PreviousEmployerPhone = userApplication.PreviousEmployerPhone; application.PreviousLandlord = userApplication.PreviousLandlord; application.PreviousLandlordPhone = userApplication.PreviousLandlordPhone; application.PreviousState = userApplication.PreviousState; application.PreviousZip = userApplication.PreviousZip; application.Ssn = userApplication.Ssn; application.UpdateDateUtc = DateTime.UtcNow; application.UpdatedBy = "accountadapter"; application.VehicleColor = userApplication.VehicleColor; application.VehicleLicenseNumber = userApplication.VehicleLicenseNumber; application.VehicleMake = userApplication.VehicleMake; application.VehicleModel = userApplication.VehicleModel; application.VehicleState = userApplication.VehicleState; application.VehicleYear = userApplication.VehicleYear; // new applications need to be added to the context if (isNew) { context.UserApplications.Add(application); } context.SaveChanges(); return(Status.OK <UserApplication>(application)); } catch (Exception ex) { // TODO: log exception return(Status.Error <UserApplication>("System was unable to create/update application", null)); } } }
private static NewClientCredentials Authenticate(NetStream stream) { var ncc = CustomAuthentication.CustomAuth(stream); return(ncc ?? ConfigAuth(stream)); }