private object DeleteDeveloper(dynamic arg)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response { StatusCode = HttpStatusCode.Unauthorized };

                int id = Convert.ToInt32(arg.id.Value);
                using (var context = new EstateAgencyEntities())
                {
                    var company = context.DeveloperCompanies.FirstOrDefault(c => c.Id == id);
                    if (company == null)
                        return new Response { StatusCode = HttpStatusCode.NotFound };
                    if (company.Houses.Any())
                        return new Response { StatusCode = HttpStatusCode.Conflict };
                    context.DeveloperCompanies.Remove(company);
                    context.SaveChanges();
                }
                return new Response { StatusCode = HttpStatusCode.NoContent };
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
 public void ConfigureObjects(DevelopersPOCO putted, EstateAgencyEntities context)
 {
     Address = string.IsNullOrEmpty(putted.Address) ? null : Address.Parse(putted.Address, context);
     if (Houses == null)
         Houses = new List<House>();
     else
         Houses.Clear();
     foreach (var house in context.Houses.Join(putted.Houses, h => h.Id, h => h, (h, _) => h))
         Houses.Add(house);
 }
示例#3
0
        public void ConfigureObjects(HousePOCO house, EstateAgencyEntities context)
        {
            Price = context.Prices.FirstOrDefault(x => x.Rent == house.Rent && x.Sale == house.Sale)
                    ?? context.Prices.Add(new Price { Sale = house.Sale, Rent = house.Rent });

            DeveloperCompany = house.DeveloperCompanyId == null
                ? null
                : context.DeveloperCompanies.FirstOrDefault(a => a.Id == house.DeveloperCompanyId);

            Address = string.IsNullOrEmpty(house.Address) ? null : Address.Parse(house.Address, context);
        }
示例#4
0
        public static Address Parse(string address, EstateAgencyEntities context)
        {
            var match = Regex.Match(address, @"(?<City>\w+),\s*(?<Street>\w+),\s*(?<HomeNumber>\d+)/?(?<Corps>\w+)?$");
            if (!match.Success)
                return null;

            var city = match.Groups["City"].Value;
            return new Address
            {
                City = context.Cities.FirstOrDefault(x => x.Name == city) ?? context.Cities.Add(new City { Name = city }),
                Street = match.Groups["Street"].Value,
                HomeNumber = int.Parse(match.Groups["HomeNumber"].Value),
                Corps = string.IsNullOrWhiteSpace(match.Groups["Corps"].Value) ? null : match.Groups["Corps"].Value.ToLower()[0].ToString()
            };
        }
示例#5
0
        private object GetHouse(dynamic arg)
        {
            try
            {
                int id = Convert.ToInt32(arg.id.Value);
                HousePOCO house;
                using (var context = new EstateAgencyEntities())
                    house = Mapper.Map<HousePOCO>(context.Houses.AsNoTracking().FirstOrDefault(h => h.Id == id));

                return house != null
                    ? Response.AsJson(house)
                    : new Response { StatusCode = HttpStatusCode.NotFound };
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
示例#6
0
        //проверка валидности токена
        public static bool CheckPermitions(Request req)
        {
            var authorization = req.Headers.Authorization;

            TokenResponseBase token;
            if (!TokenResponseBase.TryParse(authorization, out token)) //парсим токен из строки
                return false;

            using (var context = new EstateAgencyEntities())
            {
                var dbToken = context.Tokens.FirstOrDefault(t => t.AccessToken == token.AccessToken); // ищем в базе токен с таким же AccessToken
                if (dbToken == null || dbToken.ExpiresIn < DateTime.Now) //если токена нет или он протух
                    return false;
                dbToken.ExpiresIn = DateTime.Now + TimeSpan.FromDays(7); //продление токена на неделю
                context.SaveChanges();
            }
            return true;
        }
示例#7
0
        //отправление логина и пароля
        private dynamic PostLogin(object _)
        {
            try
            {
                var model = this.Bind<LoginModel>(); //привязка параметров формы
                if (model.IsEmpty())
                    return new Response {StatusCode = HttpStatusCode.UnprocessableEntity};

                using (var context = new EstateAgencyEntities())
                {
                    context.Configuration.AutoDetectChangesEnabled = false;

                    var app = context.Applications.FirstOrDefault(a => a.ClientId == model.ClientId); //находим приложение по clientId
                    if (app == null || app.RedirectUri != model.RedirectUri)
                        return new Response {StatusCode = HttpStatusCode.BadRequest};

                    var user = context.Users.FirstOrDefault(a => a.Login == model.Login); //находим пользователя по Login
                    if (user == null)
                        return new Response {StatusCode = HttpStatusCode.Unauthorized};

                    var enc = Encoding.UTF8;
                    string hashString;

                    using (var sha1 = SHA1.Create())
                    {
                        var hash = sha1.ComputeHash(enc.GetBytes(model.Password + user.Solt));
                        hashString = string.Join("", hash.Select(x => x.ToString("x")));
                    }

                    if (user.PasswordHash == hashString) //сравнение паролей
                    {
                        var code = new OAuthCode {Application = app, User = user, Code = Guid.NewGuid()};
                        context.OAuthCodes.Add(code);
                        context.SaveChanges();

                        return Response.AsRedirect(
                            new UriBuilder(app.RedirectUri)
                            {
                                Query = $"code={code.Code}{(model.State == null ? "" : $"&state={model.State}")}"
                            }.Uri.AbsoluteUri, RedirectResponse.RedirectType.Permanent);
                    }
                    return new Response {StatusCode = HttpStatusCode.Unauthorized};
                }
            }
        private object GetDeveloper(dynamic arg)
        {
            try
            {
                int id = Convert.ToInt32(arg.id.Value);
                DevelopersPOCO company;
                using (var context = new EstateAgencyEntities())
                    company =
                        Mapper.Map<DevelopersPOCO>(
                            context.DeveloperCompanies.AsNoTracking().FirstOrDefault(h => h.Id == id));

                return company != null
                    ? Response.AsJson(company)
                    : new Response { StatusCode = HttpStatusCode.NotFound };
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
示例#9
0
        private object GetMe(object _)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response {StatusCode = HttpStatusCode.Unauthorized};

                AuthModule.TokenResponseBase token;
                AuthModule.TokenResponseBase.TryParse(Request.Headers.Authorization, out token); //парсим токениз строки

                using (var context = new EstateAgencyEntities())
                {
                    var user = context.OAuthCodes.AsNoTracking().FirstOrDefault(x => x.Tokens.Any(t => t.AccessToken == token.AccessToken))?.User;
                    return user != null ? Response.AsJson(new {user.Login, user.PhoneNumber}) : new Response {StatusCode = HttpStatusCode.NotFound};
                }
            }
            catch
            {
                return new Response {StatusCode = HttpStatusCode.InternalServerError};
            }
        }
示例#10
0
        private object DeleteHouse(dynamic arg)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response { StatusCode = HttpStatusCode.Unauthorized };

                int id = Convert.ToInt32(arg.id.Value);
                int result;
                using (var context = new EstateAgencyEntities())
                    result = context.Houses.Where(h => h.Id == id).Delete();

                return new Response
                {
                    StatusCode = result == 0 ? HttpStatusCode.NotFound : HttpStatusCode.NoContent
                };
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
        private object GetDeveloperHouses(dynamic arg)
        {
            try
            {
                DynamicDictionaryValue pageParam = Request.Query["page"]; //получение номера запрашиваемой страницы
                var page = pageParam.HasValue ? Convert.ToInt32(pageParam.Value) : 1;

                DynamicDictionaryValue sizeParam = Request.Query["page_size"]; //получение кол-ва отображаемых эл-том на странице
                var pageSize = sizeParam.HasValue ? Convert.ToInt32(sizeParam.Value) : Bootstrapper.DefaultPageCount;
                int startPage = (page - 1) * pageSize;

                int id = Convert.ToInt32(arg.id.Value);

                Response resp;
                using (var context = new EstateAgencyEntities()) {
                    var company = context.DeveloperCompanies.FirstOrDefault(h => h.Id == id);

                    var pages = Bootstrapper.GetPage(company.Houses
                        .OrderBy(x => x.Id)
                        .Skip(startPage)
                        .Take(pageSize)
                        .Select(Mapper.Map<SimpleHousePOCO>)
                        .ToList(),
                        company.Houses.Count(),
                        new UriBuilder(Request.Url.SiteBase)
                        {
                            Path = Request.Url.Path,
                            Query = $"page={page + 1}&page_size={pageSize}"
                        }.Uri.AbsoluteUri);

                    resp = Response.AsJson(pages);
                }
                return resp;
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
        private object PutDeveloper(dynamic arg)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response { StatusCode = HttpStatusCode.Unauthorized };

                var putted = this.Bind<DevelopersPOCO>();
                putted.Id = Convert.ToInt32(arg.id.Value);
                using (var context = new EstateAgencyEntities())
                {
                    var company = context.DeveloperCompanies.FirstOrDefault(h => h.Id == putted.Id);

                    if (company == null)
                        return new Response { StatusCode = HttpStatusCode.NotFound };

                    Mapper.Map(putted, company);
                    company.ConfigureObjects(putted, context);

                    context.SaveChanges();
                }

                return new Response { StatusCode = HttpStatusCode.NoContent };
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
        private object PostDeveloper(object _)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response { StatusCode = HttpStatusCode.Unauthorized };

                var company = this.Bind<DevelopersPOCO>();
                DeveloperCompany added;
                using (var context = new EstateAgencyEntities())
                {
                    context.Configuration.AutoDetectChangesEnabled = false;

                    var developerCompany = Mapper.Map<DeveloperCompany>(company);
                    developerCompany.ConfigureObjects(company, context);

                    added = context.DeveloperCompanies.Add(developerCompany);
                    context.SaveChanges();
                }

                return Response.AsJson(Mapper.Map<DevelopersPOCO>(added)).WithStatusCode(HttpStatusCode.Created);
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
示例#14
0
        private object PostHouse(object _)
        {
            try
            {
                if (!AuthModule.CheckPermitions(Request))
                    return new Response { StatusCode = HttpStatusCode.Unauthorized };

                var house = this.Bind<HousePOCO>();
                House added;
                using (var context = new EstateAgencyEntities())
                {
                    context.Configuration.AutoDetectChangesEnabled = false;

                    var entity = Mapper.Map<House>(house);
                    entity.ConfigureObjects(house, context);

                    added = context.Houses.Add(entity);
                    context.SaveChanges();
                }

                return Response.AsJson(Mapper.Map<HousePOCO>(added)).WithStatusCode(HttpStatusCode.Created);
            }
            catch
            {
                return new Response { StatusCode = HttpStatusCode.InternalServerError };
            }
        }