public async Task <ActionResult> ManualJoin(string code)
        {
            var user       = db.Users.Find(User.Identity.GetUserId());
            var realGuid   = Guid.Parse(code);
            var invitation = db.Invitations.FirstOrDefault(i => i.RecipientEmail == user.Email && i.Code == realGuid);

            if (invitation == null)
            {
                return(View("NotFoundError"));
            }
            var expirationDate = invitation.Created.AddDays(invitation.TTL);

            if (invitation.IsValid && DateTime.Now < expirationDate)
            {
                InvitationHelper.MarkAsInvalid(invitation.Id);
                user.HouseholdId = invitation.HouseholdId;
                roleHelper.UpdateUserRole(user.Id, "Member");

                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Dashboard", "Home"));
            }

            return(View("AcceptError", invitation));
        }
        public async Task <ActionResult> ChangeHeadAsync(string newHoH, bool leave)
        {
            if (string.IsNullOrEmpty(newHoH) || newHoH == User.Identity.GetUserId())
            {
                return(RedirectToAction("Dashboard", "Home"));
            }

            var user = db.Users.Find(User.Identity.GetUserId());

            roleHelper.UpdateUserRole(newHoH, "Head");
            if (leave)
            {
                user.HouseholdId = null;

                foreach (var account in user.Accounts)
                {
                    account.HouseholdId = null;
                }
                db.SaveChanges();
                roleHelper.UpdateUserRole(user.Id, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);
            }
            else
            {
                roleHelper.UpdateUserRole(user.Id, "Member");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);
            }
            return(RedirectToAction("Dashboard", "Home"));
        }
Beispiel #3
0
        // GET: Matches/Finish/5
        public ActionResult Finish(int id)
        {
            if (!AuthorizeExtensions.CurrentUserIsAdmin())
            {
                return(View());
            }

            var match = webClient.ExecuteGet <MatchDto>(new Models.ApiRequest()
            {
                EndPoint = $"matches/{id}"
            });

            if (match == null)
            {
                return(View());
            }

            ViewBag.Title = "Finish " + match.Boxer1?.Name + " vs " + match.Boxer2?.Name;

            var model = new MatchesListItem()
            {
                Id       = match.Id,
                Boxer1Id = match.Boxer1Id,
                Boxer1   = new BoxersListItem(match.Boxer1.Name),
                Boxer2Id = match.Boxer2Id,
                Boxer2   = new BoxersListItem(match.Boxer2.Name),
                WinnerId = match.WinnerId
            };

            return(View(model));
        }
        //[Authorize(Roles = "New User")]
        public async Task <ActionResult> BuildHouse(BuildHouseWizardVM model, bool isPersonalAccount = false)
        {
            if (ModelState.IsValid)
            {
                // success path
                db.Households.Add(model.Household);
                db.SaveChanges();

                var user = db.Users.Find(User.Identity.GetUserId());
                user.HouseholdId = model.Household.Id;
                rolesHelper.UpdateUserRole(user.Id, "Head");
                db.SaveChanges();

                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                // add bank account info
                var bankAccount = new BankAccount
                                  (
                    model.StartingBalance,
                    model.BankAccount.WarningBalance,
                    model.BankAccount.AccountName
                                  );

                bankAccount.HouseholdId = (int)user.HouseholdId;
                bankAccount.AccountType = model.BankAccount.AccountType;

                if (isPersonalAccount)
                {
                    bankAccount.OwnerId = user.Id;
                }
                else
                {
                    bankAccount.OwnerId = null;
                }

                db.BankAccounts.Add(bankAccount);

                // add budget info
                var budget = new Budget();
                budget.HouseholdId = (int)model.Household.Id;
                budget.BudgetName  = model.Budget.BudgetName;
                db.Budgets.Add(budget);
                db.SaveChanges();

                // add budget item info
                var budgetItem = new BudgetItem();
                budgetItem.BudgetId     = budget.Id;
                budgetItem.TargetAmount = model.BudgetItem.TargetAmount;
                budgetItem.ItemName     = model.BudgetItem.ItemName;
                db.BudgetItems.Add(budgetItem);
                db.SaveChanges();

                // now that the household has been established, refresh their login and send them to the dashboard.

                return(RedirectToAction("Dashboard", "Home"));
            }

            // error
            return(View(model));
        }
 public ActionResult Login(string returnUrl)
 {
     if (User.Identity.IsAuthenticated)
     {
         AuthorizeExtensions.AutoLogOut(HttpContext);
     }
     ViewBag.ReturnUrl = returnUrl;
     return(View());
 }
Beispiel #6
0
        public async Task <ActionResult> LeaveAsync()
        {
            var userId = User.Identity.GetUserId();
            var user   = db.Users.Find(userId);
            var role   = roleHelper.ListUserRoles(userId).FirstOrDefault();

            switch (role)
            {
            case "Head":
                var memberCount = db.Users.Where(u => u.HouseholdId == user.HouseholdId).Count() - 1;
                if (memberCount >= 1)
                {
                    TempData["Message"] = $"You are unable to leave the Household! There are still <b>{memberCount}</b> other members in the Household. You must select one of them to assume your role!";
                    return(RedirectToAction("ExitDenied"));
                }
                user.Household.IsDeleted = true;
                user.HouseholdId         = null;
                //This is a soft delete, the record stays in the DB but you can limit access on the front end
                //This is a hard delete, the record is removed from the DB and anything with the Household's ForeignKey will be cascade deleted
                //var household = db.Households.Find(user.HouseholdId);
                //db.Households.Remove(household);

                //Remove the HouseholdID from all BankAccounts associated with this user
                foreach (var account in user.Accounts)
                {
                    account.HouseholdId = null;
                }

                db.SaveChanges();

                roleHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Index", "Home"));

            case "Member":
                user.HouseholdId = null;
                //Remove the HouseholdID from all BankAccounts associated with this user
                foreach (var account in user.Accounts)
                {
                    account.HouseholdId = null;
                }
                db.SaveChanges();

                roleHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Index", "Home"));

            default:
                return(RedirectToAction("Index", "Home"));
            }
        }
        public async Task <ActionResult> UpdateProfile(UpdateProfileVM model)
        {
            var user = db.Users.Find(model.Id);

            user.FirstName = model.FirstName;
            user.LastName  = model.LastName;
            db.SaveChanges();

            await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

            return(RedirectToAction("UpdateProfile"));
        }
        public async Task <ActionResult> LeaveAsync()
        {
            var userId = User.Identity.GetUserId();
            var user   = db.Users.Find(userId);
            var role   = roleHelper.ListUserRoles(userId).FirstOrDefault();

            switch (role)
            {
            case "Head":
                var memberCount = db.Users.Where(u => u.HouseholdId == user.HouseholdId).Count() - 1;
                if (memberCount >= 1)
                {
                    TempData["Message"] = $"You are unable to leave the Household! There are still <b{memberCount}</b> other members in the household, you must select one of them to assume your role!";
                    return(RedirectToAction("ExitDenied"));
                }
                var household = db.Households.Find(user.HouseholdId);
                user.HouseholdId = null;
                db.Households.Remove(household);
                foreach (var account in user.Accounts)
                {
                    account.HouseholdId = null;
                }

                db.SaveChanges();

                roleHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Dashboard", "Home"));

            case "Member":
                user.HouseholdId = null;
                foreach (var account in user.Accounts)
                {
                    account.HouseholdId = null;
                }
                db.SaveChanges();

                roleHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(View("Dashboard", "Home"));

            default:
                return(RedirectToAction("Dashboard", "Home"));
            }
        }
        public async Task <ActionResult> ChangeHeadAsync(string newHoH, bool leave)
        {
            if (string.IsNullOrEmpty(newHoH) || newHoH == User.Identity.GetUserId())
            {
                return(RedirectToAction("Dashboard", "Home"));
            }

            var user       = db.Users.Find(User.Identity.GetUserId());
            var newHoHuser = db.Users.Find(newHoH);

            if (user.HouseholdId != newHoHuser.HouseholdId)
            {
                user.HouseholdId = newHoHuser.HouseholdId;
            }

            rolesHelper.UpdateUserRole(newHoH, "Head");

            if (leave)
            {
                user.HouseholdId = null;

                // Drew had this code because he wants the accounts to stay with the user, not be "household" acocunts
                // but I want the accounts to belong to the household (like for joint accounts).
                // so I will have to do something different here.
                // I'll need to think through it.
                //
                // remove the HouseholdId from all BankAccounts associated with this user.
                //foreach(var account in user.Accounts)
                //{
                //    account.HouseholdId = null;
                //}

                db.SaveChanges();

                rolesHelper.UpdateUserRole(user.Id, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);
            }
            else
            {
                rolesHelper.UpdateUserRole(user.Id, "Member");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);
            }

            return(RedirectToAction("Dashboard", "Home"));
        }
Beispiel #10
0
        private HttpClient GetHttpClient(string authToken = null)
        {
            HttpClientHandler handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }

            HttpClient client = new HttpClient(handler);

            client.BaseAddress = new Uri(configurationService.GetValue("ApiBaseUrl"));

            client.Timeout = TimeSpan.FromSeconds(20);

            if (!AuthorizeExtensions.AuthTokenAvailable() &&
                !AuthorizeExtensions.AdminTokenAvailable() &&
                authToken == null)
            {
                throw new UnauthorizedAccessException();
            }

            if (AuthorizeExtensions.AdminTokenAvailable())
            {
                var adminToken = AuthorizeExtensions.GetAdminToken();
                client.DefaultRequestHeaders.Add(Constants.Headers.AdminTokenHeader, adminToken);
            }
            if (authToken == null && AuthorizeExtensions.AuthTokenAvailable())
            {
                authToken = AuthorizeExtensions.GetAuthToken();
            }

            if (authToken != null)
            {
                client.DefaultRequestHeaders.Add(Constants.Headers.AuthTokenHeader, authToken);
            }

            if (handler.SupportsAutomaticDecompression)
            {
                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
            }

            return(client);
        }
Beispiel #11
0
        //[Authorize(Roles = "Head")]
        public async Task <ActionResult> Create([Bind(Include = "Id,HouseholdName,Greeting")] Household household)
        {
            if (ModelState.IsValid)
            {
                household.Created = DateTime.Now;
                db.Households.Add(household);
                db.SaveChanges();

                var user = db.Users.Find(User.Identity.GetUserId());
                user.HouseholdId = household.Id;
                roleHelper.UpdateUserRole(user.Id, "Head");
                db.SaveChanges();

                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("ConfigureHouse"));
            }

            return(View(household));
        }
Beispiel #12
0
        // GET: Matches
        public ActionResult Index([FromUri] int skip = 0, [FromUri] int take = 10, [FromUri] string search = null, [FromUri] bool?pastUnfinished = null)
        {
            if (pastUnfinished.HasValue && pastUnfinished.Value && !AuthorizeExtensions.CurrentUserIsAdmin())
            {
                throw new UnauthorizedAccessException();
            }

            MatchesListViewModel model = new MatchesListViewModel();

            var searchQueryParam = string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                searchQueryParam         = $"&search={search}";
                ViewData["SearchString"] = search;
            }

            var pastUnfinishedQueryParam = string.Empty;

            if (pastUnfinished.HasValue)
            {
                pastUnfinishedQueryParam   = $"&pastUnfinished={pastUnfinished.Value}";
                ViewData["PastUnfinished"] = pastUnfinished.Value;
            }

            model.Items = webClient.ExecuteGet <IEnumerable <MatchDto> >(new Models.ApiRequest()
            {
                EndPoint = $"matches?skip={skip}&take={take}{searchQueryParam}{pastUnfinishedQueryParam}"
            })
                          ?.Select(q => new MatchesListItem()
            {
                Id          = q.Id,
                Boxer1Id    = q.Boxer1Id,
                Boxer2Id    = q.Boxer2Id,
                Boxer1      = new BoxersListItem(q.Boxer1.Name),
                Boxer2      = new BoxersListItem(q.Boxer2.Name),
                Address     = q.Address,
                Time        = q.Time,
                Description = q.Description,
                WinnerId    = q.WinnerId
            })?.ToList();

            var currentUser   = AuthorizeExtensions.GetCurrentUser();
            var currentUserId = currentUser != null ? currentUser.Id : 0;

            var predictions = webClient.ExecuteGet <IEnumerable <PredictionDto> >(new Models.ApiRequest()
            {
                EndPoint = "predictions"
            })
                              ?.Select(q => new PredictionsListItem()
            {
                Id = q.Id,
                PredictedBoxerId = q.PredictedBoxerId,
                MatchId          = q.MatchId,
                UserId           = q.UserId
            })?.Where(p => p.UserId == currentUserId)?.ToList();

            ViewData["Predictions"] = predictions;
            ViewData["Page"]        = (skip / take) + 1;
            ViewData["PageSize"]    = take;
            return(View(model));
        }
Beispiel #13
0
        public async Task <ActionResult> LeaveAsync()
        {
            var userId = User.Identity.GetUserId();
            var user   = db.Users.Find(userId);
            var role   = rolesHelper.ListUserRoles(userId).FirstOrDefault();

            switch (role)
            {
            case "Head":
                // -1 because I don't count the user doing this
                var memberCount = db.Users.Where(u => u.HouseholdId == user.HouseholdId).Count() - 1;
                if (memberCount >= 1)
                {
                    // if I get here, I am not the last person in the household.

                    var members = db.Users.Where(u => u.HouseholdId == user.HouseholdId).ToList();
                    ViewBag.NewHoH = new SelectList(members, "Id", "FullName");
                    return(View("ExitDenied"));
                }

                // this user is the last person in the household, so it's safe to "soft" delete the household.
                // this is a "soft" delete.  record stays in the database, but you can limit access on the front end
                user.Household.IsDeleted = true;

                // uncomment the next two lines for a hard delete, the record is removed from the database and anything with the
                // household foreign key will be cascade deleted
                //var household = db.Households.Find(user.HouseholdId);
                //db.Households.Remove(household);

                user.HouseholdId = null;

                // Drew had this code because he wants the accounts to stay with the user, not be "household" acocunts
                // but I want the accounts to belong to the household (like for joint accounts).
                // so I will have to do something different here.
                // I'll need to think through it.
                //
                // remove the HouseholdId from all BankAccounts associated with this user.
                //foreach(var account in user.Accounts)
                //{
                //    account.HouseholdId = null;
                //}

                db.SaveChanges();

                rolesHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Dashboard", "Home"));

            case "Member":
                user.HouseholdId = null;

                db.SaveChanges();

                rolesHelper.UpdateUserRole(userId, "New User");
                await AuthorizeExtensions.RefreshAuthentication(HttpContext, user);

                return(RedirectToAction("Dashboard", "Home"));

            default:
                return(RedirectToAction("Dashboard", "Home"));
            }
        }
        // GET: Predictions/Predict?parentId=5
        public ActionResult Predict(int parentId)
        {
            PredictionsDetailsViewModel model = new PredictionsDetailsViewModel();

            model.MatchId = parentId;

            ViewBag.Title = "Predict";

            var match = webClient.ExecuteGet <MatchDto>(new Models.ApiRequest()
            {
                EndPoint = $"matches/{parentId}"
            });

            if (match == null)
            {
                return(View());
            }

            var currentUser = AuthorizeExtensions.GetCurrentUser();

            if (currentUser == null)
            {
                throw new UnauthorizedAccessException();
            }

            model.UserId = currentUser.Id;

            var prediction = webClient.ExecuteGet <IEnumerable <PredictionDto> >(new Models.ApiRequest()
            {
                EndPoint = "predictions"
            })
                             ?.Select(q => new PredictionsListItem()
            {
                Id = q.Id, UserId = q.UserId, MatchId = q.MatchId, PredictedBoxerId = q.PredictedBoxerId
            })?.
                             FirstOrDefault(p => p.MatchId == match.Id && p.UserId == currentUser.Id);

            if (prediction != null)
            {
                model.Id = prediction.Id;
                model.PredictedBoxerId = prediction.PredictedBoxerId;
            }

            var boxers = webClient.ExecuteGet <IEnumerable <BoxerDto> >(new Models.ApiRequest()
            {
                EndPoint = "boxers"
            })
                         ?.Select(q => new BoxersListItem()
            {
                Id = q.Id, Name = q.Name
            })?.Where(b => b.Id == match.Boxer1Id || b.Id == match.Boxer2Id)?.ToList();

            if (boxers != null && boxers.Count == 2)
            {
                if (model.PredictedBoxerId != 0)
                {
                    ViewData["PredictedBoxer"] = boxers.FirstOrDefault(b => b.Id == model.PredictedBoxerId);
                    var boxersList = new List <BoxersListItem>();
                    if (model.PredictedBoxerId == match.Boxer1Id)
                    {
                        boxersList.Add(null);
                    }
                    boxersList.Add(boxers.FirstOrDefault(b => b.Id != model.PredictedBoxerId));
                    if (model.PredictedBoxerId == match.Boxer2Id)
                    {
                        boxersList.Add(null);
                    }
                    ViewData["Boxers"] = boxersList;
                }
                else
                {
                    ViewData["Boxers"] = boxers;
                }
            }

            return(View(model));
        }
        public ActionResult Predict(PredictionsDetailsViewModel model)
        {
            try
            {
                var currentUser = AuthorizeExtensions.GetCurrentUser();
                var match       = webClient.ExecuteGet <MatchDto>(new Models.ApiRequest()
                {
                    EndPoint = $"matches/{model.MatchId}"
                });
                if (currentUser == null || match == null)
                {
                    return(View());
                }

                if (Request.Form[match.Boxer1Id.ToString()] != null)
                {
                    model.PredictedBoxerId = match.Boxer1Id;
                }
                else if (Request.Form[match.Boxer2Id.ToString()] != null)
                {
                    model.PredictedBoxerId = match.Boxer2Id;
                }
                else
                {
                    return(View());
                }

                var prediction = webClient.ExecuteGet <IEnumerable <PredictionDto> >(new Models.ApiRequest()
                {
                    EndPoint = "predictions"
                })?.
                                 FirstOrDefault(p => p.MatchId == model.MatchId && p.UserId == currentUser.Id);

                if (prediction != null)
                {
                    webClient.ExecutePut <object>(new Models.ApiRequest()
                    {
                        EndPoint = string.Format("predictions/{0}", prediction.Id),
                        Request  = new PredictionDto()
                        {
                            UserId           = model.UserId,
                            MatchId          = model.MatchId,
                            PredictedBoxerId = model.PredictedBoxerId
                        }
                    });
                }
                else
                {
                    webClient.ExecutePost <object>(new Models.ApiRequest()
                    {
                        EndPoint = string.Format("predictions"),
                        Request  = new PredictionDto()
                        {
                            UserId           = model.UserId,
                            MatchId          = model.MatchId,
                            PredictedBoxerId = model.PredictedBoxerId
                        }
                    });
                }

                return(RedirectToAction("Index", controllerName: "Matches"));
            }
            catch
            {
                return(View());
            }
        }