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 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; }
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 }; } }
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 }; } }
//отправление логина и пароля 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}; } }