Пример #1
0
        public IHttpActionResult PostDialogList(DialogList dialogList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, dialogList.firstUserId, "User") && !CheckAccess.IsAccess(cookie, dialogList.secondUserId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            if (db.DialogLists.FirstOrDefault(x => x.firstUserId == dialogList.firstUserId &&
                                              x.secondUserId == dialogList.secondUserId) == null)     //создаем новый диалог в списке если до этого он не был создан
            {
                db.DialogLists.Add(dialogList);
                db.SaveChanges();
            }
            else
            {
                return(BadRequest(ModelState));
            }

            return(CreatedAtRoute("DefaultApi", new { id = dialogList.id }, dialogList));
        }
        public IHttpActionResult PostFriendList(FriendList friendList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            FriendList WillReturn;
            FriendList friend = db.Friends.FirstOrDefault(x => x.who == friendList.who &&
                                                          x.with == friendList.with);

            if (friend != null)
            {
                db.Friends.Remove(friend);
                WillReturn = friend;
            }
            else
            {
                db.Friends.Add(friendList);
                WillReturn = friendList;
            }

            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = WillReturn.id }, WillReturn));
        }
        public IHttpActionResult PutAvatar([FromBody] int siteUserId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, siteUserId, "Moder"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            Avatar oldAvatar = db.Avatars.FirstOrDefault(x => x.siteUserId == siteUserId &&
                                                         x.confirmState == "PrevAva");

            if (oldAvatar != null)
            {
                db.Avatars.Remove(oldAvatar);
                File.Delete(oldAvatar.base64);
            }

            Avatar NewAva = db.Avatars.FirstOrDefault(x => x.siteUserId == siteUserId &&
                                                      x.confirmState == "Waiting");         //Если пользователь изменил мнение и решил изменить отправленный, но еще не подтвержденный аватар

            //FileInfo fileInfo = new FileInfo(NewAva.base64);
            //System.IO.File.Move(fileInfo.FullName, fileInfo.DirectoryName + "//Confirmed.jpg");

            NewAva.confirmState    = "Confirmed";
            db.Entry(NewAva).State = EntityState.Modified;
            db.SaveChanges();

            return(Ok(NewAva));
        }
Пример #4
0
        [ResponseType(typeof(Dialog))]                                  //Массовая рассылка для админа, юзеры отсылают сообщения через веб сокеты
        public IHttpActionResult PostDialog([FromBody] MassMessages mm) //MassMessages mm)//[FromBody]int[] to, [FromBody]string msg, [FromBody]int who)
        {
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}
            Dialog     msg = new Dialog();
            DialogList dl  = new DialogList();

            Filter filter = new Filter();

            string name = mm.cityForSearch;

            filter.cityForSearch = db.Cities.FirstOrDefault(x => x.cityName == name).id;
            name = mm.typeForSearch;
            filter.typeForSearch = db.TypeForSearch.FirstOrDefault(x => x.typeName == name).id;
            name = mm.ageForSearch;
            filter.ageForSearch = db.AgeForSearch.FirstOrDefault(x => x.rangeOfAge == name).id;
            filter.id           = mm.from;

            List <SiteUser> userForSend = SortWithFilter(filter, mm.gender);

            foreach (SiteUser to in userForSend)
            {
                dl = db.DialogLists.FirstOrDefault(x => x.firstUserId == mm.from && x.secondUserId == to.id);
                if (dl == null)//создаем новый диалог в списке если до этого он не был создан
                {
                    dl              = new DialogList();
                    dl.firstUserId  = mm.from;
                    dl.secondUserId = to.id;
                    db.DialogLists.Add(dl);
                    db.SaveChanges();
                }


                msg.dialogId = dl.id;
                msg.time     = DateTime.Now;
                msg.to       = to.id;
                msg.from     = mm.from;
                msg.content  = mm.content;
                msg.content  = mm.content;
                db.Dialogs.Add(msg);
                db.SaveChanges();
            }
            List <DialogList> GetAllMsg = db.DialogLists.Where(x => x.firstUserId == mm.from || x.secondUserId == mm.from).ToList();

            return(Ok(GetAllMsg));
        }
Пример #5
0
        public IHttpActionResult PutHobby(List <HobbyOfUser> hobby)//Hobby hobby)
        {
            if (hobby.Count == 0)
            {
                return(BadRequest());
            }
            int userId = hobby[0].siteUserid;

            if (hobby.FirstOrDefault(x => x.siteUserid != hobby[0].siteUserid) != null)
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }
            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, userId, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            List <HobbyOfUser> oldUserHobbies = db.HobbyOfUsers.Where(x => x.siteUserid == userId).ToList();

            foreach (HobbyOfUser oneHobby in oldUserHobbies)
            {
                int oldHobbyId = oneHobby.hobbyid;
                if (hobby.FirstOrDefault(x => x.hobbyid == oldHobbyId) == null)
                {
                    db.HobbyOfUsers.Remove(oneHobby);
                }
            }

            foreach (HobbyOfUser oneHobby in hobby)
            {
                int newHobbyId = oneHobby.hobbyid;
                if (oldUserHobbies.FirstOrDefault(x => x.hobbyid == newHobbyId) == null)
                {
                    db.HobbyOfUsers.Add(oneHobby);
                }
            }

            //db.Entry(hobby).State = EntityState.Modified;

            db.SaveChanges();

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #6
0
 public Profile Add(Profile profile)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <Profile>(profile).State = System.Data.Entity.EntityState.Added;
         _ctx.SaveChanges();
         return(profile);
     }
 }
 public FriendProfile Update(FriendProfile friend)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <FriendProfile>(friend).State = System.Data.Entity.EntityState.Modified;
         _ctx.SaveChanges();
         return(friend);
     }
 }
 public VisitorProfile Add(VisitorProfile visitorProfile)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <VisitorProfile>(visitorProfile).State = System.Data.Entity.EntityState.Added;
         _ctx.SaveChanges();
         return(visitorProfile);
     }
 }
Пример #9
0
 public ProfilePost Update(ProfilePost profilePost)
 {
     using (var _ctx = new DatingContext())
     {
         _ctx.Entry <ProfilePost>(profilePost).State = System.Data.Entity.EntityState.Modified;
         _ctx.SaveChanges();
         return(profilePost);
     }
 }
Пример #10
0
 public void Remove(long?profilePostId)
 {
     using (var _ctx = new DatingContext())
     {
         var profilePost = _ctx.Set <ProfilePost>().Where(x => x.Id == profilePostId).FirstOrDefault();
         _ctx.Entry <ProfilePost>(profilePost).State = System.Data.Entity.EntityState.Deleted;
         _ctx.SaveChanges();
     }
 }
Пример #11
0
        public IHttpActionResult PutResetPasword([FromBody] string email)
        {
            SiteUser user = db.SiteUsers.FirstOrDefault(x => x.email == email);

            if (user == null)
            {
                return(BadRequest());
            }
            string passwordGenerator;
            Guid   newPas = Guid.NewGuid();

            passwordGenerator    = newPas.ToString().Split('-')[0];
            user.password        = PasswordToMD5(passwordGenerator);
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();

            var          fromAddress  = new MailAddress("*****@*****.**", "Dating");
            var          toAddress    = new MailAddress(email, "To User");
            const string fromPassword = "******";
            const string subject      = "Reset password";
            string       body         = "Hello, it is your new password:"******"smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }
            return(Ok("OK"));
        }
Пример #12
0
        public ActionResult AcceptDecline(int FriendId, string AcceptDecline)
        {
            var UserId = _DatingContext.Profiles.SingleOrDefault(p => p.Email == User.Identity.Name).Id;
            //Hittar rätt rad i Db för att kunna uppdatera den
            var friendFound = _DatingContext.FriendRequests.FirstOrDefault
                                  (x => x.FriendReceiverId == UserId && x.FriendSenderId == FriendId);

            // Om ej null och Accept
            if (AcceptDecline == "Accept" && friendFound != null)
            {
                friendFound.Accepted = true;
                _DatingContext.SaveChanges();
            }
            // Om ej null och Decline
            else if (AcceptDecline == "Decline" && friendFound != null)
            {
                _DatingContext.Remove(friendFound);
                _DatingContext.SaveChanges();
            }
            return(RedirectToAction(nameof(Requests)));
        }
 public void DeclineFriendRequest(long friendRequestId)
 {
     using (var _ctx = new DatingContext())
     {
         var friendRequest = GetById(friendRequestId);
         if (friendRequest != null)
         {
             _ctx.Entry <FriendRequest>(friendRequest).State = System.Data.Entity.EntityState.Deleted;
             _ctx.SaveChanges();
         }
     }
 }
 public FriendProfile Add(FriendProfile friend)
 {
     using (var _ctx = new DatingContext())
     {
         var foundFriend = _ctx.Set <FriendProfile>().Any(x => x.FriendProfileId == friend.FriendProfileId && x.ProfileId == friend.ProfileId);
         if (!foundFriend)
         {
             _ctx.Entry <FriendProfile>(friend).State = System.Data.Entity.EntityState.Added;
             _ctx.SaveChanges();
         }
         return(friend);
     }
 }
        public FriendRequest AcceptFriendRequest(long friendRequestId)
        {
            using (var _ctx = new DatingContext())
            {
                var friends = _ctx.Set <FriendRequest>().Where(x => x.Id == friendRequestId);

                var friendRequest = friends.FirstOrDefault();

                friendRequest.IsFriend = true;

                _ctx.Entry(friendRequest).State = EntityState.Modified;

                _ctx.SaveChanges();

                return(friendRequest);
            }
        }
Пример #16
0
        public Profile Update(Profile profile)
        {
            using (var _ctx = new DatingContext())
            {
                var oldProfile = GetByUserId(profile.UserId);


                if (profile.Hobbies == null)
                {
                    var oldProfileHobbies = oldProfile.Hobbies.ToList();
                    foreach (var profileHobbie in oldProfileHobbies)
                    {
                        profileHobbie.Hobbie            = null;
                        profileHobbie.Profile           = null;
                        _ctx.Entry(profileHobbie).State = EntityState.Deleted;
                    }
                    oldProfile.Hobbies.Clear();
                }
                else
                {
                    profile.Hobbies.Where(r => r.Id == 0).ToList().ForEach(item => _ctx.Entry(item).State = EntityState.Added);
                    foreach (var item in profile.Hobbies.Where(r => r.Id > 0))
                    {
                        _ctx.Entry(item).State = EntityState.Modified;
                    }
                    if (oldProfile != null)
                    {
                        var oldHobbies = oldProfile.Hobbies.Where(r => !profile.Hobbies.Any(o => r.Id == o.Id)).ToList();
                        foreach (var hobbie in oldHobbies)
                        {
                            hobbie.Profile           = null;
                            _ctx.Entry(hobbie).State = EntityState.Deleted;
                        }
                    }
                }
                _ctx.Entry(oldProfile).State = EntityState.Detached;
                _ctx.Entry(profile).State    = EntityState.Modified;
                _ctx.SaveChanges();
                return(profile);
            }
        }
Пример #17
0
 public async Task <ActionResult> Edit([Bind("Id, Firstname, Lastname, Age, Email, Gender, SexualOrientation, Active, ImageFile")] Profile profile)
 {
     if (ModelState.IsValid)
     {
         try
         {
             //Uppdaterar hela profilen inklusive bild
             if (profile.ImageFile != null)
             {
                 string wwwRootPath = _hostEnvironment.WebRootPath;
                 string filename    = Path.GetFileNameWithoutExtension(profile.ImageFile.FileName);
                 string extension   = Path.GetExtension(profile.ImageFile.FileName);
                 profile.ImagePath = filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
                 string path = Path.Combine(wwwRootPath + "/Image", filename);
                 using (var fileStream = new FileStream(path, FileMode.Create))
                 {
                     await profile.ImageFile.CopyToAsync(fileStream);
                 }
                 _DatingContext.Profiles.Update(new DataLayer.Models.Profile
                 {
                     Id                = profile.Id,
                     Firstname         = profile.Firstname,
                     Lastname          = profile.Lastname,
                     Gender            = profile.Gender,
                     Active            = profile.Active,
                     Age               = profile.Age,
                     Email             = User.Identity.Name.ToString(),
                     SexualOrientation = profile.SexualOrientation,
                     ImagePath         = profile.ImagePath
                 });
                 await _DatingContext.SaveChangesAsync();
             }
             //Uppdaterar profil men behåller tidigare bild om ingen ny laddats upp
             else
             {
                 _DatingContext.Profiles.Update(new DataLayer.Models.Profile
                 {
                     Id                = profile.Id,
                     Firstname         = profile.Firstname,
                     Lastname          = profile.Lastname,
                     Gender            = profile.Gender,
                     Active            = profile.Active,
                     Age               = profile.Age,
                     Email             = profile.Email,
                     SexualOrientation = profile.SexualOrientation,
                     ImagePath         = TempData["img"] as string
                 });
                 _DatingContext.SaveChanges();
             }
             return(Redirect("/Identity/Account/Manage/ChangePassword"));
         }
         catch
         {
             return(View());
         }
     }
     else
     {
         return(View());
     }
 }
        public IHttpActionResult PutSiteUser(EditUser siteUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            using (var ldb = new DatingContext())
            {
                //находим пользователя, от корого собираемся редактировать, для того, чтобы при редактировании не потерять id сессии
                //и пароль, которые от клиента могли бы не прийти и могут обнулиться из за этого
                SiteUser user = ldb.SiteUsers.FirstOrDefault(x => x.id == siteUser.id);
                //копируем сессию и пароль(если не был отправлен новый) пришедший объект и применяем редактирование
                if (siteUser.password == null)
                {
                    siteUser.password = user.password;
                }
                else
                {
                    siteUser.password = PasswordToMD5(siteUser.password);
                }
                siteUser.sessionId  = user.sessionId;
                siteUser.online     = user.online;
                siteUser.dateOfEdit = DateTime.Now;

                int id;

                //if (siteUser.cityForSearch == "All")
                //{
                //    id = user.typeForSearchid;
                //    siteUser.typeForSearch = db.TypeForSearch.FirstOrDefault(x => x.id == id).typeName;
                //}

                //if (siteUser.ageForSearch == "All")
                //{
                //    id = user.ageForSearchid;
                //    siteUser.ageForSearch = db.AgeForSearch.FirstOrDefault(x => x.id == id).rangeOfAge;
                //}

                //if (siteUser.cityForSearch == "All")
                //{
                //    id = user.cityForSearchid;
                //    siteUser.cityForSearch = db.Cities.FirstOrDefault(x => x.id == id).cityName;
                //}



                int AdminId = db.Roles.FirstOrDefault(x => x.roleName == "Admin").id;
                int ModerId = db.Roles.FirstOrDefault(x => x.roleName == "Moder").id;

                if ((user.roleid == AdminId) ||                                                                                               //Запрещаем не админам реактировать админа
                    ((siteUser.roleid == AdminId || siteUser.roleid == ModerId) && (user.roleid != AdminId && siteUser.roleid != ModerId)) || //Только админ может дать юзеру дали роль модера или админа
                    ((siteUser.roleid != AdminId && siteUser.roleid != ModerId) && (user.roleid == AdminId && siteUser.roleid == ModerId)))   //Только админ может понизить модера или админа в роли(до юзера или забанить)
                {
                    CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();
                    if (!CheckAccess.IsAccess(cookie, siteUser.id, "Admin"))
                    {
                        return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
                    }
                }
                else
                {
                    CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();
                    if (!CheckAccess.IsAccess(cookie, siteUser.id, "User"))
                    {
                        return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
                    }
                }
            }

            SiteUser editedUser = new SiteUser(siteUser);

            db.Entry(editedUser).State = EntityState.Modified;//в данном случае EntityState.Modified рвет веб сокет(onlineChecker) при редактировании

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SiteUserExists(siteUser.id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            ClientUser clientUser = new ClientUser(editedUser);

            //return Ok(SortByFilter(new Filter(siteUser),1));
            return(CreatedAtRoute("DefaultApi", new { id = clientUser.id }, clientUser));
        }
        public IHttpActionResult PostGallery(List <Gallery> gallery)
        {
            if (gallery.Count == 0)
            {
                return(NotFound());
            }

            CookieHeaderValue cookie = Request.Headers.GetCookies("UserSession").FirstOrDefault();

            if (!CheckAccess.IsAccess(cookie, gallery[0].siteUserid, "User"))
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            int    siteUserid = gallery[0].siteUserid;//gallery[0].siteUserid -все siteUserid в массиве одинаковы, т к это галлерея 1 пользователся
            string path       = HttpContext.Current.Server.MapPath("~")
                                + "UserFiles\\"
                                + db.SiteUsers.FirstOrDefault(x => x.id == siteUserid).id + "\\Gallery\\";


            List <Gallery> usersGalleryFromDB = db.Galleries.Where(x => x.siteUserid == siteUserid).ToList();


            if (gallery[0].content == null)//значит, что всё было удалено и стоит очистить бд
            {
                for (int i = 0; i < usersGalleryFromDB.Count; i++)
                {
                    db.Galleries.Remove(usersGalleryFromDB[i]);
                    File.Delete(usersGalleryFromDB[i].content);
                }
                db.SaveChanges();
                return(Ok(gallery));
            }


            for (int i = 0; i < usersGalleryFromDB.Count; i++)
            {
                //Поиск вхождения старых данных в новых(если в новых данныъ нет старых, значит они удаляются из базы)
                if (gallery.Find(x => x.content.Contains(usersGalleryFromDB[i].content)) == null)
                {
                    db.Galleries.Remove(usersGalleryFromDB[i]);
                    File.Delete(usersGalleryFromDB[i].content);
                }
            }

            for (int i = 0; i < gallery.Count; i++)
            {
                string content = gallery[i].content;

                if (db.Galleries.Where(x => x.content == content).ToList().Count == 0)
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var base64 = (gallery[i].content).Substring((gallery[i].content).IndexOf(',') + 1);

                    string fileName = String.Format(@"{0}.png", System.Guid.NewGuid());


                    var bytes = Convert.FromBase64String(base64);
                    using (var imageFile = new FileStream(path + fileName, FileMode.Create))
                    {
                        imageFile.Write(bytes, 0, bytes.Length);
                        imageFile.Flush();
                    }
                    gallery[i].content = path + fileName;
                    db.Galleries.Add(gallery[i]);
                }
            }
            db.SaveChanges();

            return(Ok(gallery));
        }