示例#1
0
        public IActionResult SignIn()
        {
            try {
                if (HttpContext.Request.Cookies.TryGetValue("sessionId", out string sessionId))
                {
                    _session = _dataAccessor.GetSessionData(sessionId);
                    if (_session == null)
                    {
                        //remove the associated cookie
                        Response.Cookies.Delete("sessionId");
                        throw new InvalidCredentialsException();
                    }

                    UserPageModel secretMatch = buildUserPageModelFromDB(_session.User);
                    if (string.IsNullOrEmpty(secretMatch.TheirSecretMatch))
                    {
                        return(RedirectToAction("GetMatch"));
                    }
                    return(View("UserPage", secretMatch));
                }
                return(View("SignIn", new AuthenticatedUser()));
            }
            catch (InvalidCredentialsException) {
                return(View("InvalidCredentials"));
            }
            catch (UnregisteredUserException) {
                return(View("InvalidCredentials"));
            }
            catch (Exception) {
                return(View("Error"));
            }
        }
示例#2
0
        public IActionResult SignIn(AuthenticatedUser authUser)
        {
            try {
                //get a new session for this user
                _session = _dataAccessor.GetSession(authUser.Username, authUser.Password);
                if (_session == null)
                {
                    throw new InvalidCredentialsException();
                }

                //store the cookie
                Response.Cookies.Append("sessionId", _session.SessionId);

                UserPageModel secretMatch = buildUserPageModelFromDB(authUser.Username);
                if (string.IsNullOrEmpty(secretMatch.TheirSecretMatch))
                {
                    return(RedirectToAction("GetMatch"));
                }
                return(View("UserPage", secretMatch));
            }
            catch (InvalidCredentialsException) {
                return(View("InvalidCredentials"));
            }
            catch (UnregisteredUserException) {
                return(View("InvalidCredentials"));
            }
            catch (Exception) {
                return(View("Error"));
            }
        }
示例#3
0
        public IActionResult RerollResult(UserPageModel secretMatch)
        {
            //verify access
            if (!verifySessionCookie())
            {
                return(View("InvalidCredentials"));
            }
            bool.TryParse(_dataAccessor.GetSettingValue("AllowMatching"), out bool allowMatch);
            secretMatch.AllowMatching = allowMatch;
            if (string.IsNullOrEmpty(secretMatch?.Name) || !secretMatch.AllowMatching)
            {
                //How? Why? Just start over
                return(RedirectToAction("SignIn"));
            }

            if (!string.IsNullOrEmpty(secretMatch.TheirSecretMatch))
            {
                _dataAccessor.RemoveMatch(secretMatch.Name, secretMatch.TheirSecretMatch);
                _dataAccessor.CreateRestriction(secretMatch.Name, secretMatch.TheirSecretMatch, false, false);
            }

            UserPageModel match = new UserPageModel()
            {
                Name        = secretMatch.Name,
                AllowReroll = false
            };

            return(RedirectToAction("CreateMatch", match));
        }
示例#4
0
        public async Task <bool> UpdateUserAsync(UserPageModel user)
        {
            var dbUser = await _db.Users.FirstOrDefaultAsync(u => u.Id.Equals(user.Id)); if (dbUser == null)

            {
                return(false);
            }
            if (string.IsNullOrEmpty(user.Email))
            {
                return(false);
            }

            dbUser.Email = user.Email;

            var userRole = new IdentityUserRole <string>()
            {
                RoleId = "1", UserId = user.Id
            };

            var isAdmin = await _db.UserRoles.AnyAsync(ur => ur.Equals(userRole));

            if (isAdmin && !user.IsAdmin)
            {
                _db.UserRoles.Remove(userRole);
            }
            else if (!isAdmin && user.IsAdmin)
            {
                await _db.UserRoles.AddAsync(userRole);
            }

            var result = await _db.SaveChangesAsync(); return(result >= 0);
        }
示例#5
0
        public ActionResult List()
        {
            if ((Session["UserLogin"] == null) || (Session["UserLogin"] != null && Session["UserLogin"].ToString() == "admin"))
            {
                return(HttpNotFound());
            }

            string userLogin     = Session["UserLogin"].ToString();
            var    userPageModel = new UserPageModel(userLogin, GetUserFriends(userLogin));

            if (TempData["UserRemovedSuccessfully"] != null)
            {
                ViewBag.UserRemovedSuccessfully = true;
            }
            if (TempData["UserCanNotBeRemoved"] != null)
            {
                ViewBag.UserCanNotBeRemoved = true;
            }
            if (TempData["FriendAddedSuccessfully"] != null)
            {
                ViewBag.FriendAddedSuccessfully = true;
            }
            if (TempData["FriendAddingError"] != null)
            {
                ViewBag.FriendAddingError = true;
            }

            return(View(userPageModel));
        }
示例#6
0
        public async Task <UserPageModel> BuildUserPageModelAsync(Guid userId, IList <Guid> forumIds)
        {
            var result = new UserPageModel();

            var user = await _dbContext.Users
                       .FirstOrDefaultAsync(x =>
                                            x.Id == userId);

            if (user == null)
            {
                return(null);
            }

            result.User = new UserModel
            {
                Id           = user.Id,
                DisplayName  = user.DisplayName,
                TotalTopics  = user.TopicsCount,
                TotalReplies = user.RepliesCount,
                GravatarHash = _gravatarService.HashEmailForGravatar(user.Email),
                Status       = user.Status
            };

            result.Posts = await _searchModelBuilder.SearchPostModels(forumIds, new QueryOptions(), userId);

            return(result);
        }
示例#7
0
        public async Task <ActionResult> ViewUser(string userId = "user_id")
        {
            if (userId == "user_id")
            {
                userId = User.Identity.GetUserId();
            }
            AppUser user = await UserManager.FindByIdAsync(userId);

            if (user != null)
            {
                UserPageModel model = new UserPageModel();
                model.User             = user;
                model.ModeratedCinemas = from cinema in repository.GetCinemas()
                                         where (cinema.Moderator.Id == user.Id)
                                         select cinema;
                model.CurrentUserId = User.Identity.GetUserId();
                //model.IsAdministratorLogged = User.IsInRole("Administrator");
                model.IsAdministratorLogged = true;
                return(View("UserPage", model));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
示例#8
0
        public IActionResult GetMatch()
        {
            //verify access
            if (!verifySessionCookie())
            {
                return(View("InvalidCredentials"));
            }
            UserPageModel secretMatch = buildUserPageModelFromDB(_session.User);

            return(View("UserPage", secretMatch));
        }
示例#9
0
        public void OnGet()
        {
            //Assume Login with UserId
            int userId = _userDetails.Value.Id;


            UserVM = new UserPageModel()
            {
                UserId     = userId,
                Activities = _unitOfWork.UserActivities.GetAll(x => x.UserId == userId).ToList(),
                Quizzes    = _unitOfWork.Quiz.GetAll().ToList()
            };
        }
示例#10
0
        public async Task <string> GetProfileProducts()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return("bad");
            }
            List <UserInfo>    usersList  = new List <UserInfo>();
            List <Order>       ordersList = new List <Order>();
            UserInfo           user       = context.Users.SingleOrDefault(u => u.Username == User.Identity.Name);
            IQueryable <Order> orders     = from order in context.Orders
                                            where (order.UserInfo.Id == user.Id)
                                            select order;

            if (orders.Any())
            {
                ordersList = orders.ToList();
            }
            if (user == null)
            {
                user         = new UserInfo();
                user.isAdmin = false;
            }
            else
            {
                if (user.isAdmin)
                {
                    IQueryable <UserInfo> users = from contextUsers in context.Users
                                                  where (user.Username != contextUsers.Username && user.Id != contextUsers.Id)
                                                  select contextUsers;
                    usersList = users.ToList();
                }
            }
            await context.SaveChangesAsync();

            UserPageModel model = new UserPageModel()
            {
                User   = user,
                Users  = usersList,
                Orders = ordersList
            };

            var json = JsonConvert.SerializeObject(model, Formatting.Indented,
                                                   new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });

            return(json);
        }
示例#11
0
 public IActionResult UpdateInterests(UserPageModel match)
 {
     //verify access
     if (!verifySessionCookie())
     {
         return(View("InvalidCredentials"));
     }
     _dataAccessor.SetUserInterests(match.Name, match.Interests);
     if (!string.IsNullOrEmpty(match.TheirSecretMatch))
     {
         match = buildUserPageModelFromDB(match.Name);
         return(View("UserPage", match));
     }
     return(RedirectToAction("GetMatch"));
 }
示例#12
0
        public ActionResult UserPage()
        {
            UserPageModel currentUser = new UserPageModel
            {
                ID              = (int)Session["ID"],
                FirstName       = (string)Session["FirstName"],
                LastName        = (string)Session["LastName"],
                EmailAddress    = (string)Session["EmailAddress"],
                CellphoneNumber = (string)Session["CellphoneNumber"]
            };

            ViewBag.Message = "Login reusit.";

            return(View("UserPage", currentUser));
        }
示例#13
0
        public IActionResult OnGet(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            UserPageModel = _db.GetUser(id);


            if (UserPageModel == null)
            {
                return(NotFound());
            }

            return(Page());
        }
示例#14
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserName,PassWord,Gender,Age,Provinces,City,Image,Url")] UserPageModel usermodel)
        {
            if (id != usermodel.Id)
            {
                return(NotFound());
            }
            var user = await _context.Users.FindAsync(id);

            user.Id        = usermodel.Id;
            user.UserName  = usermodel.UserName;
            user.PassWord  = usermodel.PassWord;
            user.Gender    = usermodel.Gender;
            user.Age       = usermodel.Age;
            user.Provinces = usermodel.Provinces;
            user.City      = usermodel.City;
            string fileUrl = Guid.NewGuid().ToString() + ".png";

            usermodel.FileUrl = "../../Image/" + fileUrl;
            var path = Directory.GetCurrentDirectory();

            if (usermodel.Image != null)
            {
                using (FileStream fs = new FileStream(path + @"\wwwroot\Image\" + fileUrl, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    var memoryStream = new MemoryStream();

                    await usermodel.Image.CopyToAsync(memoryStream);


                    byte[] bytes = memoryStream.ToArray();
                    fs.Write(bytes, 0, bytes.Length);
                    user.Image = path + @"\wwwroot\Image\" + fileUrl;
                }
            }
            user.Url = usermodel.Url;
            if (!ModelState.IsValid)
            {
                _context.Update(user);
                await _context.SaveChangesAsync();

                return(View("Index"));
            }
            return(View(user));
        }
示例#15
0
        public void Reroll_Result_Redirects_To_Create_Match_With_Allow_Reroll_False()
        {
            var possibleNames = new List <Name> {
                new Name {
                    Id             = 1,
                    RegisteredName = "Test Person1",
                    HasRegistered  = true
                },
                new Name {
                    Id             = 2,
                    RegisteredName = "Test Person2",
                    HasRegistered  = true
                },
                new Name {
                    Id             = 3,
                    RegisteredName = "Test Person3",
                    HasRegistered  = true
                }
            };

            var secretMatch = new UserPageModel {
                AllowReroll      = true,
                Name             = "Test Person1",
                TheirSecretMatch = "Test Person2"
            };

            _dataAccessor.Setup(d => d.GetAllRegisteredNames()).Returns(possibleNames);
            _dataAccessor.Setup(d => d.CreateRestriction("Test Person1", "Test Person2", false, false)).Verifiable();
            _dataAccessor.Setup(d => d.RemoveMatch("Test Person1", "Test Person2")).Verifiable();


            var result = _controller.RerollResult(secretMatch);

            Assert.NotNull(result);
            var viewResult = result as RedirectToActionResult;

            Assert.NotNull(viewResult);
            Assert.IsFalse((bool)viewResult.RouteValues["AllowReroll"]);
            Assert.AreEqual("Test Person1", viewResult.RouteValues["Name"]);
            Assert.IsNull(viewResult.RouteValues["TheirSecretMatch"]); //Now we don't pass this, since it's set up as a restriction
            _dataAccessor.Verify(d => d.CreateRestriction("Test Person1", "Test Person2", false, false), Times.Once);
            _dataAccessor.Verify(d => d.RemoveMatch("Test Person1", "Test Person2"), Times.Once);
        }
示例#16
0
        public async Task <IActionResult> UserPage()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/Home/Login"));
            }
            List <UserInfo>    usersList  = new List <UserInfo>();
            List <Order>       ordersList = new List <Order>();
            UserInfo           user       = context.Users.SingleOrDefault(u => u.Username == User.Identity.Name);
            IQueryable <Order> orders     = from order in context.Orders
                                            where (order.UserInfo.Id == user.Id)
                                            select order;

            if (orders.Any())
            {
                ordersList = orders.ToList();
            }
            if (user == null)
            {
                user         = new UserInfo();
                user.isAdmin = false;
            }
            else
            {
                if (user.isAdmin)
                {
                    IQueryable <UserInfo> users = from contextUsers in context.Users
                                                  where (user.Username != contextUsers.Username && user.Id != contextUsers.Id)
                                                  select contextUsers;
                    usersList = users.ToList();
                }
            }
            await context.SaveChangesAsync();

            UserPageModel model = new UserPageModel()
            {
                User   = user,
                Users  = usersList,
                Orders = ordersList
            };

            return(View(model));
        }
示例#17
0
        public UserPageModel UserPage(string token, int lang, string id)
        {
            UserPageModel m = new UserPageModel();

            string userId = null;

            if (token != "" && token != null)
            {
                string machine = HttpContext.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
                userId = SessionCode.ValidateSessionCode(token, machine);
            }

            m.User     = ControllerBase.GetUser(id, id == userId, false);
            m.Targets  = ControllerBase.LatestTargetForUser(id, lang, 0, 5, DateTime.Now.AddDays(-5));
            m.Articles = ControllerBase.LatestArticlesForUser(id, lang, 0, 5);
            m.Videos   = ControllerBase.LatestVideosForUser(id, lang, 0, 5);

            return(m);
        }
示例#18
0
        private UserPageModel Parse(int id, HtmlDocument doc, UserProfileScrapingStatus userProfileStatus)
        {
            if (doc.DocumentNode.InnerHtml.Contains("An Error Has Occurred!"))
            {
                Log.Information("parsing - Profile doesn't exist");

                return(null);
            }
            if (doc.DocumentNode.InnerText.Contains("403"))
            {
                Log.Information("rate limited!!!! <- could be the root cause!");
                var context = new MariaContext();
                userProfileStatus.Status = ProfileStatus.Error;
                context.SetStatusForId(userProfileStatus);
                context.Dispose();
                throw new Exception("Error! getting 403 response. Quitting so we don't get locked out for longer!");
            }

            var item = new UserPageModel(id);

            item.Name = handleItem(doc.DocumentNode.SelectNodes(XpathSelectors.NameSelector));
            var baseCol = doc.DocumentNode.SelectSingleNode(XpathSelectors.baseSelector);

            if (baseCol == null)
            {
                throw new Exception("Error, should never be null!");
            }

            item.Merit          = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol,"Merit")}/td[2]"));
            item.Position       = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Position")}/td[2]"));
            item.Posts          = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Posts")}/td[2]"));
            item.Activity       = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Activity")}/td[2]"));
            item.DateRegistered = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Date Registered")}/td[2]"));
            item.LastActive     = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Last Active")}/td[2]"));
            item.Gender         = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Gender")}/td[2]"));
            item.Age            = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Age")}/td[2]"));
            item.Location       = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Location")}/td[2]"));
            item.LocalTime      = handleItem(baseCol.SelectNodes($"{DynamicXpath(baseCol, "Local Time")}/td[2]"));
            Log.Information("Finished successfully");

            return(item);
        }
示例#19
0
 public IActionResult UpdatePassword(UserPageModel pageModel)
 {
     if (!verifySessionCookie())
     {
         return(View("InvalidCredentials"));
     }
     //verify the passwords match, then verify the current password, then update
     if (!string.Equals(pageModel.PasswordReset.NewPassword, pageModel.PasswordReset.VerifyPassword, StringComparison.InvariantCulture))
     {
         return(View("PasswordsNotMatch"));
     }
     //verify user
     if (!_dataAccessor.VerifyCredentials(_session.User, pageModel.PasswordReset.CurrentPassword))
     {
         return(View("InvalidCredentials"));
     }
     //update password
     _dataAccessor.UpdateUserPassword(_session.User, pageModel.PasswordReset.NewPassword);
     return(RedirectToAction("GetMatch"));
 }
示例#20
0
        public void CreateMatch_Unrestricted_Creates_Match_And_Returns_GetMatch_View()
        {
            var possibleNames = new List <Name> {
                new Name {
                    Id             = 1,
                    RegisteredName = "Test Person1",
                    HasRegistered  = true
                },
                new Name {
                    Id             = 2,
                    RegisteredName = "Test Person2",
                    HasRegistered  = true
                }
            };

            var secretMatch = new UserPageModel {
                AllowReroll      = true,
                Name             = "Test Person1",
                TheirSecretMatch = null
            };

            _dataAccessor.Setup(d => d.GetMatchRestrictions("Test Person1")).Returns(new List <MatchRestriction>()).Verifiable();
            _dataAccessor.Setup(d => d.GetAllRegisteredNames()).Returns(possibleNames).Verifiable();
            _dataAccessor.Setup(d => d.CreateMatch("Test Person1", "Test Person2", true)).Verifiable();

            var result = _controller.CreateMatch(secretMatch);

            Assert.NotNull(result);
            var viewResult = result as ViewResult;

            Assert.NotNull(viewResult);
            Assert.AreEqual("GetMatch", viewResult.ViewName);
            var model = viewResult.Model as UserPageModel;

            Assert.NotNull(model);
            Assert.AreEqual("Test Person2", model.TheirSecretMatch);

            _dataAccessor.Verify(d => d.GetMatchRestrictions("Test Person1"), Times.Once); //This doesn't run, because the FindRandomMatch is what checks restrictions
            _dataAccessor.Verify(d => d.CreateMatch("Test Person1", "Test Person2", true), Times.Once);
            _dataAccessor.Verify(d => d.GetAllRegisteredNames(), Times.Once);
        }
示例#21
0
        public ActionResult OnGet()
        {
            UserPageModel CSharp = new UserPageModel {
                Name = "C#"
            };
            UserPageModel SQL = new UserPageModel {
                Name = "sql"
            };
            UserPageModel Javasript = new UserPageModel {
                Name = "java"
            };
            UserPageModel PHP = new UserPageModel {
                Name = "php"
            };

            models = new List <UserPageModel> {
                CSharp, SQL, Javasript, PHP
            };
            //return RedirectToPagePermanent("/*Pages/Message/Mine*/");
            return(Page());
        }
示例#22
0
        public IActionResult CreateMatch(UserPageModel secretMatch)
        {
            //verify access
            if (!verifySessionCookie())
            {
                return(View("InvalidCredentials"));
            }
            bool.TryParse(_dataAccessor.GetSettingValue("AllowMatching"), out bool allowMatch);
            secretMatch.AllowMatching = allowMatch;
            if (string.IsNullOrEmpty(secretMatch?.Name) || !secretMatch.AllowMatching)
            {
                //How? Why? Just start over
                return(RedirectToAction("SignIn"));
            }

            secretMatch.TheirSecretMatch = _createSecretMatch.FindRandomMatch(secretMatch.Name);
            _dataAccessor.CreateMatch(secretMatch.Name, secretMatch.TheirSecretMatch, secretMatch.AllowReroll);

            secretMatch = buildUserPageModelFromDB(secretMatch.Name);

            return(View("UserPage", secretMatch));
        }
示例#23
0
        public ActionResult LogIn(LogInModel model)
        {
            if (ModelState.IsValid)
            {
                List <EventOrganizerLibrary.Models.PersonModel> loginList = FindUser(model.EmailAddress, model.Password);

                if (loginList.Any())
                {
                    var userData = loginList.First();

                    currentUserID    = userData.ID;
                    currentUserEmail = userData.EmailAddress;
                    UserPageModel currentUser = new UserPageModel
                    {
                        ID              = userData.ID,
                        FirstName       = userData.FirstName,
                        LastName        = userData.LastName,
                        EmailAddress    = userData.EmailAddress,
                        CellphoneNumber = userData.CellphoneNumber
                    };

                    Session["ID"]              = userData.ID;
                    Session["FirstName"]       = userData.FirstName;
                    Session["LastName"]        = userData.LastName;
                    Session["EmailAddress"]    = userData.EmailAddress;
                    Session["CellphoneNumber"] = userData.CellphoneNumber;

                    return(RedirectToAction("UserPage"));
                }
                else
                {
                    return(RedirectToAction("LogIn"));
                }
            }

            return(View());
        }
示例#24
0
        // GET: Personal/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            UserPageModel usermodel = new UserPageModel();

            if (id == null)
            {
                return(NotFound());
            }

            var user = await _context.Users.FindAsync(id);

            usermodel.Id        = user.Id;
            usermodel.UserName  = user.UserName;
            usermodel.PassWord  = user.PassWord;
            usermodel.Gender    = user.Gender;
            usermodel.Age       = user.Age;
            usermodel.Provinces = user.Provinces;
            usermodel.City      = user.City;
            usermodel.FileUrl   = "../../Image/" + Path.GetFileName(user.Image);
            usermodel.Url       = user.Url;
            var dbProvince = await _context.Provinces.Where(m => m.id < 35).ToListAsync();

            var dbCity = await _context.Provinces.Where(m => m.parentid == usermodel.Provinces).ToListAsync();

            usermodel.ProvinceList = new List <SelectListItem>();
            foreach (var item in dbProvince)
            {
                if (usermodel.Provinces == item.id)
                {
                    usermodel.ProvinceList.Add(new SelectListItem()
                    {
                        Value = item.id.ToString(), Text = item.name, Selected = true
                    });
                }
                else
                {
                    usermodel.ProvinceList.Add(new SelectListItem()
                    {
                        Value = item.id.ToString(), Text = item.name
                    });
                }
            }
            usermodel.CityList = new List <SelectListItem>();
            foreach (var city in dbCity)
            {
                if (usermodel.City == city.id)
                {
                    usermodel.CityList.Add(new SelectListItem()
                    {
                        Value = city.id.ToString(), Text = city.name, Selected = true
                    });
                }
            }

            if (user == null)
            {
                return(NotFound());
            }

            return(View(usermodel));
        }
示例#25
0
        protected override async Task OnInitializedAsync()
        {
            var requestUri = Id == null ? "api/public/users" : $"api/public/users/{Id}";

            Model = await ApiService.GetFromJsonAsync <UserPageModel>(requestUri);
        }
        /// <summary>
        /// Get a list of expiring pages, collated by User
        /// </summary>
        /// <param name="noOfDaysFrom">
        /// How many days to look forward
        /// </param>
        /// <returns>
        /// List Users with expiring pages they are responsible for
        /// </returns>
        public IList <UserPagesModel> GetExpiringNodesByUser(int noOfDaysFrom)
        {
            // Get all content at the root
            var rootnodes = _contentService.GetRootContent();
            // Create a list to store expiring content
            List <IContent> expiringNodes = new List <IContent>();

            // for each content node at the root
            foreach (var node in rootnodes)
            {
                // if the node is expiring within the declared period, add it to the list
                if (node.ExpireDate > DateTime.Now && node.ExpireDate < DateTime.Now.AddDays(noOfDaysFrom))
                {
                    expiringNodes.Add(node);
                }
                // get the root nodes children that are expiring within the declared period.
                var descendants = node.Descendants().Where(nn => nn.ExpireDate > DateTime.Now && nn.ExpireDate < DateTime.Now.AddDays(noOfDaysFrom)).OrderBy(nn => nn.ExpireDate);
                foreach (var child in descendants)
                {
                    // add each one to the list
                    expiringNodes.Add(child);
                }
            }
            // once done, order by expire date.
            expiringNodes.OrderBy(nn => nn.ExpireDate);

            // For each page:
            IList <UserPagesModel> userPages = new List <UserPagesModel>();

            // Create a WebStaff record. Use -1 as an Id as there won't be a valid Umbraco user with that value.
            var webStaff     = new UserPagesModel();
            var webstaffUser = new UmbracoUserModel
            {
                UserId       = -1,
                UserName     = "******",
                FullName     = "Web Staff",
                EmailAddress = "*****@*****.**"
            };

            webStaff.User = webstaffUser;
            userPages.Add(webStaff);

            var helper = new UmbracoHelper(UmbracoContext.Current);

            foreach (var expiringNode in expiringNodes)
            {
                // this should not happen, but just in case...
                if (expiringNode.ExpireDate == null)
                {
                    continue;
                }

                var userPage = new UserPageModel
                {
                    PageId     = expiringNode.Id,
                    PageName   = expiringNode.Name,
                    PagePath   = expiringNode.Path,
                    PageUrl    = helper.NiceUrl(expiringNode.Id),
                    ExpiryDate = (DateTime)expiringNode.ExpireDate
                };

                // Get Web Authors with permission
                // if no permissions at all, then there will be only one element which will contain a "-"
                // If only the default permission then there will only be one element which will contain "F" (Browse Node)
                var perms =
                    _contentService.GetPermissionsForEntity(expiringNode)
                    .Where(
                        x =>
                        x.AssignedPermissions.Count() > 1 ||
                        (x.AssignedPermissions[0] != "-" && x.AssignedPermissions[0] != "F"));

                var nodeAuthors = perms as IList <EntityPermission> ?? perms.ToList();

                // if no Web Authors, add this page to the WebStaff list
                if (!nodeAuthors.Any())
                {
                    userPages.Where(p => p.User.UserId == -1).ForEach(u => u.Pages.Add(userPage));
                    continue;
                }

                // if all Authors of a page are disabled, add page to the webStaff list
                List <EntityPermission> disabledUsers = new List <EntityPermission>();
                foreach (var user in nodeAuthors)
                {
                    var tempUser = _userService.GetUserById(user.UserId);
                    if (!tempUser.IsApproved)
                    {
                        disabledUsers.Add(user);
                    }
                }
                if (disabledUsers.Count == nodeAuthors.Count)
                {
                    userPages.Where(p => p.User.UserId == -1).ForEach(u => u.Pages.Add(userPage));
                    continue;
                }

                // Add the current page to each user that has edit rights
                foreach (var author in nodeAuthors)
                {
                    var user = userPages.FirstOrDefault(f => f.User.UserId == author.UserId);

                    // Create a User record if one does not yet exist
                    if (user == null)
                    {
                        var pUser = _userService.GetUserById(author.UserId);

                        // Check that this author is not Disabled / Locked Out
                        // If they are, end this loop and move onto the next author
                        if (!pUser.IsApproved)
                        {
                            continue;
                        }

                        var p = new UmbracoUserModel
                        {
                            UserId       = author.UserId,
                            UserName     = pUser.Username,
                            FullName     = pUser.Name,
                            EmailAddress = pUser.Email
                        };

                        user = new UserPagesModel {
                            User = p
                        };
                        userPages.Add(user);
                    }

                    // Assign the current page (outer loop) to this author
                    userPages.Where(p => p.User.UserId == user.User.UserId).ForEach(u => u.Pages.Add(userPage));
                }
            }

            // Return a list of users to email, along with the page details
            return(userPages);
        }
示例#27
0
        public async Task <IActionResult> UserPage(int userID, string userIsAdmin, string buttonType)
        {
            List <UserInfo>    usersList  = new List <UserInfo>();
            List <Order>       ordersList = new List <Order>();
            UserInfo           user       = context.Users.SingleOrDefault(u => u.Username == User.Identity.Name);
            IQueryable <Order> orders     = from order in context.Orders
                                            where (order.UserInfo.Id == user.Id)
                                            select order;

            if (orders.Any())
            {
                ordersList = orders.ToList();
            }
            if (user == null)
            {
                user         = new UserInfo();
                user.isAdmin = false;
            }
            else
            {
                if (user.isAdmin)
                {
                    IQueryable <UserInfo> users = from contextUsers in context.Users
                                                  where (user.Username != contextUsers.Username && user.Id != contextUsers.Id)
                                                  select contextUsers;
                    usersList = users.ToList();
                }
            }

            if (buttonType == "Установить")
            {
                IQueryable <UserInfo> findUsers = from contextUsers in context.Users
                                                  where (userID == contextUsers.Id && userID != user.Id)
                                                  select contextUsers;
                var isAdmin = false;
                bool.TryParse(userIsAdmin, out isAdmin);
                if (findUsers.Any())
                {
                    try
                    {
                        foreach (var line in findUsers)
                        {
                            line.isAdmin = isAdmin;
                        }
                    }
                    catch (Exception e)
                    {
                        ViewBag.message = "<script>alert('Ошибка при изменении')</script>";
                        Console.WriteLine("Ошибка при изменении");
                        throw;
                    }
                }
            }
            if (buttonType.Contains("Убрать"))
            {
                var index     = buttonType.Split(" ").Last();
                var gameIndex = 0;
                if (int.TryParse(index, out gameIndex))
                {
                    IQueryable <Order> findOrders = from contextGame in context.Orders
                                                    where (gameIndex == contextGame.Id)
                                                    select contextGame;

                    if (findOrders.Any())
                    {
                        try
                        {
                            foreach (var line in findOrders)
                            {
                                context.Remove(line);
                            }
                        }
                        catch (Exception e)
                        {
                            ViewBag.message = "<script>alert('Ошибка при удалении')</script>";
                            Console.WriteLine("Ошибка при удалении");
                            throw;
                        }
                    }
                }
            }
            await context.SaveChangesAsync();

            IQueryable <Order> newOrders = from order in context.Orders
                                           where (order.UserInfo.Id == user.Id)
                                           select order;

            if (newOrders.Any())
            {
                ordersList = newOrders.ToList();
            }
            UserPageModel model = new UserPageModel()
            {
                User   = user,
                Users  = usersList,
                Orders = ordersList
            };

            return(View(model));
        }
        public IActionResult UserPage(int id)
        {
            UserPageModel userPageModel = new UserPageModel();

            bool myFriend = false;

            var friend = db.Friends.Where(c => c.USerOneId == Convert.ToInt32(User.Identity.Name) && c.USerTwoId == id).FirstOrDefault();

            if (friend != null)
            {
                userPageModel.myFriend = true;
            }
            else
            {
                userPageModel.myFriend = false;
            }

            User UserPage = db.Users.Where(c => c.UserId == id).FirstOrDefault();

            ViewData["user"] = UserPage;

            userPageModel.userPage = UserPage;

            List <MindModel> mindModel = new List <MindModel>();

            foreach (var myMind in db.Minds)
            {
                if (UserPage.UserId == myMind.UserId)
                {
                    MindModel m = new MindModel();
                    m.UserId     = myMind.UserId;
                    m.MindMess   = myMind.MindMess;
                    m.NumOfLikes = myMind.NumOfLikes;
                    m.DateOfMind = myMind.DateOfMind;
                    m.MindId     = myMind.MindId;
                    m.UserPic    = UserPage.ProfilePic;

                    m.Comments2 = new Dictionary <Comment, String>();

                    foreach (var comm in db.Comments)
                    {
                        if (comm.MindId == m.MindId)
                        {
                            User commenter = db.Users
                                             .Where(c => c.UserId == comm.UserId)
                                             .FirstOrDefault();

                            m.Comments2.Add(comm, commenter.ProfilePic);
                        }
                    }

                    var like = db.Likes.Where(c => c.MindId == myMind.MindId && /*UserPage.UserId*/ Convert.ToInt32(User.Identity.Name) == c.UserId).FirstOrDefault();
                    if (like != null)
                    {
                        m.liked = true;
                    }
                    else
                    {
                        m.liked = false;
                    }


                    mindModel.Add(m);
                }
            }

            userPageModel.userPageMinds = mindModel.ToList();

            return(View(userPageModel));
        }
示例#29
0
        // GET: User
        public ActionResult Index(int id = 0)
        {
            User user;

            if (id == 0)
            {
                user = currentUser;
            }
            else
            {
                user = userRepository.GetUserById(id);
            }

            List <string> friendIds;

            if (currentUser.FriendIds == null || currentUser.FriendIds == "")
            {
                friendIds = null;
            }
            else
            {
                friendIds = currentUser.FriendIds.Split(',').ToList();
            }

            List <int> friendRequestIds     = friendRepository.GetFriendRequestIds(currentUser.UserId);
            List <int> sentFriendRequestIds = friendRepository.GetSentFriendRequestIds(currentUser.UserId);


            string friendButtonText;
            string friendButtonClass = "UserButtonProfile";
            bool   requested         = false;

            if (friendIds != null && friendIds.Contains(user.UserId.ToString()))
            {
                friendButtonText = "Remove Friend";
            }
            else if (sentFriendRequestIds != null && sentFriendRequestIds.Contains(user.UserId))
            {
                friendButtonText  = "Cancel Request";
                friendButtonClass = "RemoveButtonProfile";
            }
            else if (friendRequestIds != null && friendRequestIds.Contains(user.UserId))
            {
                friendButtonText = "Accept";
                requested        = true;
            }
            else
            {
                friendButtonText  = "Add Friend";
                friendButtonClass = "AcceptButtonProfile";
            }

            UserPageModel userPage = new UserPageModel()
            {
                User              = user,
                Statuses          = statusRepository.UserStatuses(currentUser.UserId, user.UserId),
                Friends           = friendRepository.GetAllFriends(user.UserId),
                CurrentUserId     = currentUser.UserId,
                FriendIds         = friendIds,
                FriendButtonText  = friendButtonText,
                Requested         = requested,
                FriendButtonClass = friendButtonClass,
            };

            ViewBag.StatusClass = "ProfileStatus";
            return(View(userPage));
        }