public String DeleteApp(UserProfileModel user, long appId)
        {
            var appToDel = db.CompetitionClimberTeams.Find(appId);

            if (appToDel == null)
            {
                return("Заявка не найдена");
            }
            if (!appToDel.AllowedEdit(user))
            {
                return("У вас нет прав для удаления данной заявки");
            }
            RemoveApp(appToDel);
            db.SaveChanges();
            return(String.Empty);
        }
예제 #2
0
 public override bool ResetPasswordWithToken(string token, string newPassword)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.Find(GetUserIdFromPasswordResetToken(token));
         if (usr == null)
         {
             return(false);
         }
         if (usr.PasswordTokenExpirationTime != null && usr.PasswordTokenExpirationTime.Value < DateTime.UtcNow)
         {
             return(false);
         }
         ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(usr.Name, newPassword, false);
         OnValidatingPassword(e);
         if (e.Cancel)
         {
             return(false);
         }
         usr.Token = null;
         usr.PasswordTokenExpirationTime = null;
         usr.SetPassword(newPassword);
         usr.Inactive = false;
         db.SaveChanges();
         return(true);
     }
 }
        public HttpResponseMessage PostClimber(APISignedRequest request)
        {
            CompetitionModel comp;
            var climber = GetRequestParameter <Comp_CompetitorRegistrationApiModel>(request, out comp);
            var res     = SaveOneClimber(climber, comp);

            db.SaveChanges();
            var response = Request.CreateResponse <Comp_CompetitorRegistrationApiModel>(HttpStatusCode.Created, res.ToApi(true));

            return(response);
        }
 public ActionResult Confirm(IEnumerable <AgeGroupModelWrapper> listModel)
 {
     if (Request.Form.AllKeys.Contains("Back"))
     {
         ViewBag.Scs = false;
         return(View("Index", listModel));
     }
     try
     {
         foreach (var m in listModel.Where(q => q.Confirmed))
         {
             if (m.IsNew)
             {
                 db.AgeGroups.Add(m.Value);
             }
             else if (m.ToDelete)
             {
                 var delModel = db.AgeGroups.Find(m.Value.Iid);
                 if (delModel != null && !delModel.IsReadOnly)
                 {
                     db.AgeGroups.Remove(delModel);
                 }
             }
             else
             {
                 var oldModel = db.AgeGroups.Find(m.Value.Iid);
                 if (oldModel != null)
                 {
                     oldModel.SecretaryName = m.Value.SecretaryName;
                     oldModel.FullName      = m.Value.FullName;
                     if (!oldModel.IsReadOnly)
                     {
                         oldModel.GenderProperty = m.Value.GenderProperty;
                         oldModel.MaxAge         = m.Value.MaxAge;
                         oldModel.MinAge         = m.Value.MinAge;
                     }
                 }
                 else
                 {
                     ModelState.AddModelError(String.Empty, String.Format("Группа {0} (compId={1}) не найдена", m.Value.FullName, m.Value.Iid));
                     return(View(listModel));
                 }
             }
         }
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         ModelState.AddModelError(String.Empty, ex);
         return(View(listModel));
     }
     return(RedirectToAction("Index", new { scs = true }));
 }
예제 #5
0
        public ActionResult Delete(CompetitionDeleteModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var comp = db.Competitions.Find(model.Iid);

            if (comp == null)
            {
                return(HttpNotFound());
            }
            if (!User.IsInRole(db, RoleEnum.Admin, comp.Region.IidParent))
            {
                return(RedirectToAction("Login", "Account", new { returnUrl = Url.Action("Delete", "Home", new { id = model.Iid }) }));
            }
            int year   = comp.Start.Year;
            var region = comp.Region.IidParent;

            db.Competitions.Remove(comp);
            db.SaveChanges();
            return(RedirectToAction("Index", new { comp_year = year, comp_region = region }));
        }
        public ActionResult Register(UserRegistrationModel model)
        {
            bool hasLocker = false;

            try
            {
                Monitor.Enter(locker, ref hasLocker);
                var regions = SetRegionsViewBag();
                if (regions.Count(r => r.Iid == (model.Region ?? 0)) < 1)
                {
                    ModelState.AddModelError(String.Empty, "У вас нет прав для создания пользователей от выбранного региона");
                }
                if (ModelState.IsValid && db.UserProfiles.Count(u => u.Name.Equals(model.UserName, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    ModelState.AddModelError(String.Empty, "Пользователь с таким именем существует");
                }
                if (ModelState.IsValid)
                {
                    var newUser = new UserProfileModel
                    {
                        Email    = model.Email,
                        Inactive = true,
                        RegionId = model.Region,
                        Name     = model.UserName,
                        Token    = GenerateToken()
                    };
                    newUser.SetPassword(String.Empty);

                    MailService.SendMessage(newUser.Email, "Активация пользователя",
                                            String.Format("На Ваше имя зарегистрирован пользователь.{0}" +
                                                          "Имя пользователя: {1}{0}" +
                                                          "Для активации учетной записи и создания пароля, пожалуйста, перейдите по ссылке {2}",
                                                          Environment.NewLine, newUser.Name,
                                                          Url.Action("Activate", "Account", new { id = newUser.Token }, "http")), false);
                    if (newUser.RegionId < 1)
                    {
                        newUser.RegionId = null;
                    }
                    db.UserProfiles.Add(newUser);
                    db.SaveChanges();
                    return(RedirectToAction("Index", new { id = newUser.RegionId == null ? null : newUser.Region.IidParent, creationResult = DbResult.Created }));
                }
                else
                {
                    return(View(model));
                }
            }
            finally
            {
                if (hasLocker)
                {
                    Monitor.Exit(locker);
                }
            }
        }
예제 #7
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            using (var db = new ClimbingContext())
            {
                var u = db.UserProfiles.Find(user.ProviderUserKey);
                if (u == null)
                {
                    return;
                }

                /*if (db.UserProfiles.Count(usr => usr.Iid != u.Iid && usr.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase)) > 0)
                 *  throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);*/
                u.Email    = user.Email;
                u.Inactive = user.IsLockedOut;
                db.SaveChanges();
            }
        }
예제 #8
0
 public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.SingleOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         if (usr == null)
         {
             return(null);
         }
         string token;
         do
         {
             token = GenerateToken();
         } while (db.UserProfiles.Count(u => u.Token.Equals(token, StringComparison.OrdinalIgnoreCase)) > 0);
         usr.Token = token;
         usr.PasswordTokenExpirationTime = DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow);
         db.SaveChanges();
         return(token);
     }
 }
예제 #9
0
 public override bool DeleteAccount(string userName)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.SingleOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         if (usr == null)
         {
             return(false);
         }
         if (usr.Roles.Count(r => r.RoleId == (int)RoleEnum.Admin) > 0 &&
             db.UserRoles.Count(ur => ur.UserId != usr.Iid && ur.RoleId == (int)RoleEnum.Admin) < 1)
         {
             //throw new ArgumentException(String.Format("Can\'t delete the last administrator {0}", userName));
             return(false);
         }
         db.UserProfiles.Remove(usr);
         db.SaveChanges();
         return(true);
     }
 }
예제 #10
0
        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary <string, object> values)
        {
            if (String.IsNullOrEmpty(password))
            {
                password = Membership.GeneratePassword(this.minRequiredPasswordLength + 10, this.minRequiredNonAlphanumericCharacters + 1);
            }
            else
            {
                ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(userName, password, true);
                OnValidatingPassword(e);
                if (e.Cancel)
                {
                    return(null);
                }
            }
            using (var db = new ClimbingContext())
            {
                var usr = db.UserProfiles.Create();
                usr.Name = userName;
                usr.SetPassword(password);
                usr.Inactive = true;

                if (requireConfirmation)
                {
                    string token;
                    do
                    {
                        token = GenerateToken();
                    } while (db.UserProfiles.Count(u => u.Token.Equals(token, StringComparison.OrdinalIgnoreCase)) > 0);
                    usr.Token = token;
                }
                else
                {
                    usr.Token = String.Empty;
                }
                db.UserProfiles.Add(usr);
                db.SaveChanges();
                return(usr.Token);
            }
        }
예제 #11
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (!ValidateUser(username, oldPassword))
            {
                return(false);
            }
            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, newPassword, false);

            OnValidatingPassword(e);
            if (e.Cancel)
            {
                return(false);
            }
            using (var db = new ClimbingContext())
            {
                var usr = db.UserProfiles.First(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase));

                usr.SetPassword(newPassword);
                db.SaveChanges();
                return(true);
            }
        }
예제 #12
0
 public override bool ConfirmAccount(string userName, string accountConfirmationToken)
 {
     using (var db = new ClimbingContext())
     {
         UserProfileModel usr;
         if (String.IsNullOrEmpty(userName))
         {
             usr = db.UserProfiles.Find(GetUserIdFromPasswordResetToken(accountConfirmationToken));
         }
         else
         {
             usr = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         }
         if (usr == null)
         {
             return(false);
         }
         usr.Inactive = false;
         usr.Token    = String.Empty;
         usr.PasswordTokenExpirationTime = null;
         db.SaveChanges();
         return(true);
     }
 }
예제 #13
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            bool createInactive = true;

            using (var db = new ClimbingContext())
            {
                if (db.UserProfiles.Count(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }
                if (String.IsNullOrEmpty(password))
                {
                    password = Membership.GeneratePassword(minRequiredPasswordLength + 10, minRequiredNonAlphanumericCharacters + 1);
                }
                else
                {
                    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
                    OnValidatingPassword(args);
                    if (args.Cancel)
                    {
                        status = MembershipCreateStatus.InvalidPassword;
                        return(null);
                    }
                }
                if (String.IsNullOrEmpty(email))
                {
                    status = MembershipCreateStatus.InvalidEmail;
                    return(null);
                }
                if (requiresUniqueEmail && db.UserProfiles.Count(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return(null);
                }
                try
                {
                    string token = null;
                    if (createInactive)
                    {
                        do
                        {
                            token = GenerateToken();
                        }while (db.UserProfiles.Count(p => p.Token.Equals(token, StringComparison.InvariantCultureIgnoreCase)) > 0);
                    }
                    var upm = db.UserProfiles.Create();
                    upm.Name = username;
                    upm.SetPassword(password);
                    upm.Email    = email;
                    upm.Inactive = createInactive;
                    upm.Token    = token;
                    upm.PasswordTokenExpirationTime = null;
                    db.UserProfiles.Add(upm);
                    db.SaveChanges();
                    status = MembershipCreateStatus.Success;
                    return(GetUser(username, false));
                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                    return(null);
                }
            }
        }
        public String[] SaveCompetition(CompetitionEditModel model, out long newIid)
        {
            newIid = model.Iid;

            List <String> errors = new List <string>();

            CompetitionModel comp;

            if (model.Iid > 0)
            {
                comp = db.Competitions.Find(model.Iid);
                foreach (var agr in model.ageGroups.Where(g => !g.Confirmed))
                {
                    var oldGRREg = comp.AgeGroups.FirstOrDefault(g => g.AgeGroupId == agr.GroupId);
                    if (oldGRREg == null)
                    {
                        continue;
                    }
                    if (oldGRREg.Competitiors.Count > 0)
                    {
                        errors.Add(String.Format("Нельзя удалить группу {0}. В ней есть заявленные участники", oldGRREg.AgeGroup.FullName));
                    }
                    else
                    {
                        db.CompetitionAgeGroups.Remove(oldGRREg);
                    }
                }
            }
            else
            {
                comp = new CompetitionModel
                {
                    AgeGroups  = new List <Comp_AgeGroupModel>(),
                    Parameters = new List <CompetitionParameterModel>()
                };
                if (comp.AgeGroups == null)
                {
                    comp.AgeGroups = new List <Comp_AgeGroupModel>();
                }
                db.Competitions.Add(comp);
            }
            var reg = db.Regions.Find(model.RegionId);

            if (reg == null)
            {
                errors.Add(String.Format("Регион с ID={0} не найден", model.RegionId));
            }

            comp.ApplicationsEnd     = model.ApplicationsEndDate.Value;
            comp.ApplicationsEditEnd = model.ApplicationsEditEndDate.Value;
            comp.AllowLateAppl       = model.AllowLateApps;
            comp.SignApplications    = model.RequireSignature;
            comp.AllowMultipleTeams  = model.AllowMultipleTeams;
            comp.Boulder             = model.Boulder;
            comp.End       = model.StopDate.Value;
            comp.Lead      = model.Lead;
            comp.Name      = model.FullName;
            comp.RegionId  = model.RegionId.Value;
            comp.ShortName = model.ShortName;
            comp.Speed     = model.Speed;
            comp.Start     = model.StartDate.Value;
            comp.Rank      = (reg.IidParent == null) ? CompetitionLevel.National : CompetitionLevel.Regional;

            foreach (var agr in model.ageGroups.Where(a => a.Confirmed))
            {
                if (comp.AgeGroups.FirstOrDefault(g => g.AgeGroupId == agr.GroupId) == null)
                {
                    comp.AgeGroups.Add(new Comp_AgeGroupModel()
                    {
                        AgeGroupId = agr.GroupId
                    });
                }
            }
            if (errors.Count > 0)
            {
                return(errors.ToArray());
            }
            try
            {
                db.SaveChanges();
                newIid = comp.Iid;
            }
            catch (Exception ex)
            {
                return(new String[] { String.Format("Ошибка сохранения:{0}{1}", Environment.NewLine, ex.ToString()) });
            }
            return(new String[0]);
        }
예제 #15
0
        public ErrorTuple[] SaveRegion(UserProfileModel user, RegionEditModel model)
        {
            List <ErrorTuple> res = new List <ErrorTuple>();

            if (!user.IsInRoleRegion(RoleEnum.Admin, model.IidParent))
            {
                res.Add(new ErrorTuple("IidParent", "У вас нет прав для создания команд в выбранном регионе"));
            }
            RegionModel saveModel;

            if ((model.Iid ?? 0) > 0)
            {
                saveModel = db.Regions.Find(model.Iid);
                if (saveModel == null)
                {
                    res.Add(new ErrorTuple(String.Empty, "Корректируемый регион был удален"));
                }
                else if (!user.IsInRoleRegion(RoleEnum.Admin, saveModel.IidParent))
                {
                    res.Add(new ErrorTuple(String.Empty, "У вас нет прав для корректировки выбранного региона"));
                }
                if (res.Count > 0)
                {
                    return(res.ToArray());
                }
            }
            else
            {
                if (res.Count > 0)
                {
                    return(res.ToArray());
                }
                saveModel = new RegionModel()
                {
                    UserRoles = new List <UserRoleModel>()
                };
                db.Regions.Add(saveModel);
            }
            saveModel.IidParent = model.IidParent;
            saveModel.Name      = model.Name;
            String prefixCode;

            if (model.IidParent == null)
            {
                prefixCode = String.Empty;
            }
            else
            {
                var preg = db.Regions.Find(model.IidParent);
                prefixCode = preg == null ? String.Empty : (preg.SymCode ?? String.Empty);
            }
            saveModel.SymCode = prefixCode + model.SymCode;
            if (model.Users == null)
            {
                saveModel.UserRoles.Clear();
            }
            else
            {
                var existingRoles = saveModel.UserRoles.ToList();
                var rolesToDel    = existingRoles.Where(r => r.CompID != null || r.RoleId < (int)RoleEnum.Admin).ToList();
                foreach (var r in rolesToDel)
                {
                    existingRoles.Remove(r);
                }
                rolesToDel.AddRange(existingRoles.Where(r => model.Users.Count(um => um.UserId == r.UserId && um.IsAdmin) < 1));
                foreach (var r in rolesToDel)
                {
                    existingRoles.Remove(r);
                }
                foreach (var um in model.Users.Where(um => um.IsAdmin && existingRoles.Count(r => r.UserId == um.UserId) < 1))
                {
                    saveModel.UserRoles.Add(new UserRoleModel {
                        UserId = um.UserId, CompID = null, RoleId = (int)RoleEnum.Admin
                    });
                }
                foreach (var r in rolesToDel)
                {
                    db.UserRoles.Remove(r);
                }
            }
            db.SaveChanges();
            model.Iid = saveModel.Iid;
            return(new ErrorTuple[0]);
        }