public object Vote(VoteModel model) { Choice choice = db.Choices.Include("Poll").Include("VotedBy").FirstOrDefault(c => c.Id == model.ChoiceId); User user = db.Users.FirstOrDefault(u => u.Id == model.UserId); if (choice == null || user == null) { return(new { Success = false, Message = "Invalid User and/or Choice." }); } PaulPrincipal paul = User as PaulPrincipal; if (paul != null && user.Id != paul.Id) { return(new { Success = false, Message = "You can only vote as the currently logged in user." }); } // Toggle off if (choice.VotedBy.Count(u => u.Id == model.UserId) > 0) { User userToRemove = choice.VotedBy.FirstOrDefault(u => u.Id == model.UserId); choice.VotedBy.Remove(userToRemove); db.Entry(choice).State = EntityState.Modified; db.SaveChanges(); return(new { Success = true, Choice = choice, Action = "Removed" }); } // Check if max Poll poll = choice.Poll; int userVoteCount = 0; foreach (Choice pollChoice in poll.Choices) { userVoteCount += pollChoice.VotedBy.Count(u => u.Id == model.UserId); if (userVoteCount >= poll.MaxVotes) { return (new { Success = false, Message = "You are only allowed to vote " + poll.MaxVotes + " times in this poll." }); } } choice.VotedBy.Add(user); db.Entry(choice).State = EntityState.Modified; db.SaveChanges(); return(new { Success = true, Choice = choice, Action = "Added" }); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); PaulPrincipalSerializableModel model = serializer.Deserialize <PaulPrincipalSerializableModel>(authTicket.UserData); PaulPrincipal principal = new PaulPrincipal(model.Username); principal.Id = model.Id; principal.Username = model.Username; principal.DisplayName = model.DisplayName; principal.Name = model.Name; principal.FBId = model.FBId; HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } }