Exemplo n.º 1
0
        protected void ChangePassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>();
                using (var _db = new Kronika106DBContext())
                {
                    string          userId = Context.User.Identity.Name;
                    ApplicationUser user   = _db.Users.First(u => u.UserName == userId);

                    IdentityResult result = manager.ChangePassword(user.Id, CurrentPassword.Text, NewPassword.Text);
                    if (result.Succeeded)
                    {
                        //var user = manager.FindById(User.Identity.GetUserId());
                        signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                        FormsAuthentication.SetAuthCookie(user.UserName, false);
                        Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
        }
Exemplo n.º 2
0
        public List <Kronika106.FileSystemModel.Year> LoadYears()
        {
            if (!IsPostBack)
            {
                List <Kronika106.FileSystemModel.Year> lstRoky = new List <FileSystemModel.Year>();
                var directiories = Directory.EnumerateDirectories(Server.MapPath(GlobalConstants.PthFileSystemRoot));
                using (var _db = new Kronika106DBContext())
                {
                    foreach (var dir in directiories)
                    {
                        Kronika106.FileSystemModel.Year yr = new FileSystemModel.Year();
                        yr.Rok = Path.GetFileName(dir);

                        yr.PocetKomentarov = _db.Forum.Count(c => c.EventId.StartsWith(yr.Rok));

                        string descPath = Path.Combine(dir, GlobalConstants.fnRokPopisShort);
                        if (File.Exists(descPath))
                        {
                            yr.Popis = File.ReadAllText(descPath);
                        }
                        yr.PathFotka = string.Format("{0}/{1}/{2}", GlobalConstants.PthFileSystemRoot, yr.Rok, GlobalConstants.fnRokFotka);
                        lstRoky.Add(yr);
                    }
                }
                return(lstRoky);
            }
            return(null);
        }
Exemplo n.º 3
0
 public bool IsDuplicateNick(string scoutNick, string userIDMail, out string error)
 {
     error = string.Empty;
     using (var _db = new Kronika106DBContext())
     {
         if (!string.IsNullOrEmpty(scoutNick))
         {
             var eUsr = _db.Users.FirstOrDefault(u => u.ScoutNickName.ToLower() == scoutNick.ToLower());
             if (eUsr != null)
             {
                 error = string.Format("Užívateľ so skautskou prezývkou: {0} je už registrovaný, zadajte inú prezývku napr: {0}zDetvy :-)", scoutNick);
                 //nerobit redirect zostavat na stránke
                 return(true);
             }
             eUsr = _db.Users.FirstOrDefault(u => u.Id == userIDMail);
             if (eUsr != null)
             {
                 error = string.Format("Užívateľ s mail adresou {0} je už registrovaný.", userIDMail);
                 //nerobit redirect zostavat na stránke
                 return(true);
             }
         }
     }
     return(false);
 }
Exemplo n.º 4
0
        /// <summary>
        /// aktualizuje komentar v databaze
        /// </summary>
        /// <param name="commentId">id aktualizovaneho komentara</param>
        /// <param name="updatedContent">novy obsah</param>
        public async void UpdateComment(string commentId, string updatedContent)
        {
            if (!Context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(updatedContent) || string.IsNullOrEmpty(commentId))
            {
                return;
            }
            using (var _db = new Kronika106DBContext())
            {
                EventComments curComment   = null;
                int           commentIdInt = -1;
                int.TryParse(commentId, out commentIdInt);
                if (commentIdInt <= 0)
                {
                    return;
                }
                curComment = _db.Forum.FirstOrDefault(c => c.ID == commentIdInt);
                if (curComment == null)
                {
                    return;
                }

                //ak ten co meni komentar nie je jeho majitel
                if (curComment.ApplicationUser.UserName != Context.User.Identity.Name)
                {
                    return;
                }
                curComment.Comment = updatedContent;
                await _db.SaveChangesAsync();
            }
            GetComments();
        }
Exemplo n.º 5
0
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim();

            txtSearch.Text = "";
            if (string.IsNullOrWhiteSpace(searchText))
            {
                return;
            }
            Session["lastSearch"] = searchText;
            txtSearch.Attributes.Add("placeholder", searchText);

            if (Properties.Settings.Default.EnableStatistic)
            {
                string userId = Context.User.Identity.Name;
                using (var _db = new Kronika106DBContext())
                {
                    ApplicationUser user = _db.Users.First(u => u.UserName == userId);
                    if (user != null)
                    {
                        _db.StatisticsSearch.Add(new StatisticsSearch()
                        {
                            ApplicationUser = user, CreatedUTC = DateTime.UtcNow, SearchPattern = searchText
                        });
                        _db.SaveChanges();
                    }
                }
            }


            //  lgSearch.SearchAll(searchText);
            Response.Redirect(Server.UrlPathEncode(string.Format("~/SearchResult.aspx?search={0}", searchText)));
        }
Exemplo n.º 6
0
 private bool HasPassword(ApplicationUserManager manager)
 {
     using (var _db = new Kronika106DBContext())
     {
         string          userId = Context.User.Identity.Name;
         ApplicationUser user   = _db.Users.First(u => u.UserName == userId);
         return(manager.HasPassword(user.Id));
     }
 }
Exemplo n.º 7
0
        private List <ForumControll.PageContent> SearchComments()
        {
            List <ForumControll.PageContent> dbResult      = null;
            List <ForumControll.PageContent> commentResult = new List <ForumControll.PageContent>();

            //hladanie v DB
            using (var _db = new Kronika106DBContext())
            {
                dbResult = (from EventComments events in _db.Forum
                            where dctSearchTerms.Keys.Any(x => events.Comment.Contains(x))
                            orderby events.CreatedUTC descending
                            select new ForumControll.PageContent {
                    ID = events.ID, NickName = events.ApplicationUser.NickName, ScoutNickName = events.ApplicationUser.ScoutNickName, EventId = events.EventId, Comment = events.Comment, CreatedUTC = events.CreatedUTC, ThumbPath = events.ThumbPath, IsEvent = events.IsEvent, IsPhoto = events.IsPhoto, IsVideo = events.IsVideo, RootID = events.RootID
                }).ToList();
            }
            foreach (ForumControll.PageContent res in dbResult)
            {
                string[] splittedRes = res.Comment.Split(splitters, StringSplitOptions.RemoveEmptyEntries);
                dctSearchTerms.ResetMatches();
                for (int i = 0; i < splittedRes.Length; i++)
                {
                    string curWordLower = splittedRes[i].ToLower();
                    foreach (string term in dctSearchTerms.Keys)
                    {
                        if (curWordLower.StartsWith(term))
                        {
                            dctSearchTerms[term] = true;
                            splittedRes[i]       = string.Format(matchHighliht, curWordLower);
                            if (Properties.Settings.Default.FullWordSearch)
                            {
                                //full match zlepsi rating
                                if (curWordLower.TrimEnd(trimChars).Equals(term))
                                {
                                    res.SearchRating++;
                                }
                            }
                            break;
                        }
                    }
                }
                if (dctSearchTerms.All(s => s.Value == true))
                {
                    res.Comment = string.Join(" ", splittedRes);
                    commentResult.Add(res);
                }
            }
            if (Properties.Settings.Default.FullWordSearch)
            {
                commentResult = commentResult.OrderByDescending(r => r.SearchRating).ToList();
            }

            return(commentResult);
        }
Exemplo n.º 8
0
        //prida komentár do databázy
        public async void AddComment(string commentContent, string thumbPath, string idRootEvetStr)
        {
            if (!Context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(commentContent))
            {
                return;
            }

            #region videoTime
            //TimeSpan? videoTime=null;
            //if (hiddenVideoPosition.Value != null)
            //{
            //    string seconds = hiddenVideoPosition.Value.Split('.')[0];
            //    if (!string.IsNullOrEmpty(seconds))
            //    {
            //        int sec = -1;
            //        if (int.TryParse(seconds, out sec))
            //        {
            //            videoTime = new TimeSpan(0, 0, sec);
            //        }
            //    }
            //}
            #endregion videoTime

            string trueQueryString = Server.UrlDecode(Request.QueryString["ID"]);
            using (var _db = new Kronika106DBContext())
            {
                int           idRootComment = -1;
                EventComments rootComment   = null;
                if (!string.IsNullOrEmpty(idRootEvetStr))
                {
                    int.TryParse(idRootEvetStr, out idRootComment);
                    if (idRootComment > 0)
                    {
                        rootComment     = _db.Forum.FirstOrDefault(c => c.ID == idRootComment);
                        trueQueryString = rootComment.EventId;
                    }
                }
                if (string.IsNullOrWhiteSpace(trueQueryString))
                {
                    return;
                }
                string          userId     = Context.User.Identity.Name;
                ApplicationUser user       = _db.Users.First(u => u.UserName == userId);
                EventComments   newComment = new EventComments()
                {
                    CreatedUTC = DateTime.UtcNow, EventId = trueQueryString, Comment = commentContent, ApplicationUser = user, ThumbPath = thumbPath, IsPhoto = forumType == ForumType.EventPhotoGallery, IsEvent = forumType == ForumType.Event, IsVideo = forumType == ForumType.EventVideoGallery, RootID = rootComment?.ID                                             /*, VideoPosition= videoTime*/
                };
                _db.Forum.Add(newComment);
                await _db.SaveChangesAsync();
            }
            GetComments();
        }
Exemplo n.º 9
0
        internal void AddUsersToAdminRole()
        {
            // Access the application context and create result variables.
            Models.Kronika106DBContext context = new Kronika106DBContext();
            IdentityResult             IdRoleResult;
            IdentityResult             IdUserResult;

            // Create a RoleStore object by using the ApplicationDbContext object.
            // The RoleStore is only allowed to contain IdentityRole objects.
            var roleStore = new RoleStore <IdentityRole>(context);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager <IdentityRole>(roleStore);

            // Then, you create the "canEdit" role if it doesn't already exist.
            if (!roleMgr.RoleExists(GlobalConstants.RoleAdmin))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole {
                    Name = GlobalConstants.RoleAdmin
                });
            }

            // Create a UserManager object based on the UserStore object and the ApplicationDbContext
            // object. Note that you can create new objects and use them as parameters in
            // a single line of code, rather than using multiple lines of code, as you did
            // for the RoleManager object.
            var userMgr = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            if (!string.IsNullOrEmpty(Properties.Settings.Default.AdminEmails))
            {
                string[] adminMails = Properties.Settings.Default.AdminEmails.Split(';');
                if (adminMails.Length > 0)
                {
                    for (int i = 0; i < adminMails.Length; i++)
                    {
                        var user = userMgr.FindByEmail(adminMails[i]);
                        if (user != null)
                        {
                            if (!userMgr.IsInRole(user.Id, GlobalConstants.RoleAdmin))
                            {
                                IdUserResult = userMgr.AddToRole(user.Id, GlobalConstants.RoleAdmin);
                            }
                        }
                    }
                    context.SaveChanges();
                }
            }
        }
Exemplo n.º 10
0
 protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
 {
     adminMenu.Visible = false;
     if (Properties.Settings.Default.EnableStatistic)
     {
         using (var _db = new Kronika106DBContext())
         {
             string          userId = Context.User.Identity.Name;
             ApplicationUser aUser  = _db.Users.FirstOrDefault(u => u.UserName == userId);
             if (aUser != null)
             {
                 aUser.LastLogOffUTC = DateTime.UtcNow;
                 _db.SaveChanges();
             }
         }
     }
     LogOutAll();
 }
Exemplo n.º 11
0
        public List <Kronika106.FileSystemModel.Akcia> AkcieGetForYear([QueryString("ID")] string yearId)
        {
            if (!IsPostBack)
            {
                List <Kronika106.FileSystemModel.Akcia> lstAkcie = new List <FileSystemModel.Akcia>();
                if (!string.IsNullOrEmpty(yearId))
                {
                    var directiories = Directory.EnumerateDirectories(Server.MapPath(yearPath));
                    using (var _db = new Kronika106DBContext())
                    {
                        foreach (var dir in directiories)
                        {
                            Kronika106.FileSystemModel.Akcia akcia = new FileSystemModel.Akcia();
                            akcia.Nazov = Path.GetFileName(dir);

                            string dbKey = $"{yearId}/{akcia.Nazov}";
                            akcia.PocetKomentarov = _db.Forum.Count(c => c.EventId.StartsWith(dbKey));


                            string descPath = Path.Combine(dir, GlobalConstants.fnAkciaPopisShort);
                            if (File.Exists(descPath))
                            {
                                akcia.Popis = File.ReadAllText(descPath);
                            }
                            else
                            {
                                akcia.Popis = string.Empty;
                            }
                            akcia.PathFotka = string.Format("{0}/{1}/{2}/{3}", GlobalConstants.PthFileSystemRoot, yearId, akcia.Nazov, GlobalConstants.fnAkciaFotka);
                            akcia.URL       = Page.Server.UrlEncode(string.Format("{0}/{1}", yearId, akcia.Nazov));
                            lstAkcie.Add(akcia);
                        }
                    }
                    return(lstAkcie);
                }
            }
            return(null);
        }
Exemplo n.º 12
0
 public async void DeleteComment(string commentId)
 {
     if (!Context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(commentId))
     {
         return;
     }
     using (var _db = new Kronika106DBContext())
     {
         EventComments curComment   = null;
         int           commentIdInt = -1;
         int.TryParse(commentId, out commentIdInt);
         if (commentIdInt <= 0)
         {
             return;
         }
         curComment = _db.Forum.FirstOrDefault(c => c.ID == commentIdInt);
         if (curComment == null)
         {
             return;
         }
         //ak ten co meni komentar nie je jeho majitel
         if (curComment.ApplicationUser.UserName != Context.User.Identity.Name)
         {
             return;
         }
         var lstChilds = _db.Forum.Where(c => c.RootID == commentIdInt);
         foreach (var child in lstChilds)
         {
             child.RootID          = curComment.RootID;
             child.ThumbPath       = curComment.ThumbPath;
             child.ApplicationUser = child.ApplicationUser;
         }
         _db.Forum.Remove(curComment);
         await _db.SaveChangesAsync();
     }
     GetComments();
 }
Exemplo n.º 13
0
        protected void SetPassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Create the local login info and link the local account to the user
                var             manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var             _db     = new Kronika106DBContext();
                string          userId  = Context.User.Identity.Name;
                ApplicationUser user    = _db.Users.First(u => u.UserName == userId);


                IdentityResult result = manager.AddPassword(user.Id, password.Text);
                if (result.Succeeded)
                {
                    user.EmailConfirmed = true;
                    _db.SaveChanges();
                    Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
                }
                else
                {
                    AddErrors(result);
                }
            }
        }
Exemplo n.º 14
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true

                //find user by eMail
                var user = manager.FindByEmail(Email.Text);

                if (user != null)
                {
                    if (!user.EmailConfirmed)
                    {
                        FailureText.Text      = "Neuspešný pokus o prihlásenie, najskôr musíte potvrdiť email.";
                        ErrorMessage.Visible  = true;
                        ResendConfirm.Visible = true;
                    }
                    else
                    {
                        var result = signinManager.PasswordSignIn(user.UserName, Password.Text, RememberMe.Checked, shouldLockout: false);

                        switch (result)
                        {
                        case SignInStatus.Success:
                            //FormsAuthentication.SetAuthCookie(user.UserName, RememberMe.Checked);
                            //Session[GlobalConstants.UserNick] = !string.IsNullOrEmpty(user.ScoutNickName) ? user.ScoutNickName : user.FirstName;

                            if (Properties.Settings.Default.EnableStatistic)
                            {
                                using (var _db = new Kronika106DBContext())
                                {
                                    ApplicationUser aUser = _db.Users.FirstOrDefault(u => u.UserName == user.UserName);
                                    if (aUser != null)
                                    {
                                        aUser.LastLogInUTC = DateTime.UtcNow;
                                        if (aUser.LoginCount.HasValue)
                                        {
                                            aUser.LoginCount++;
                                        }
                                        else
                                        {
                                            aUser.LoginCount = 1;
                                        }
                                        _db.SaveChanges();
                                    }
                                }
                            }

                            string returnUrl = Request.QueryString["ReturnUrl"];
                            if (string.IsNullOrEmpty(returnUrl))
                            {
                                returnUrl = (string)Session[GlobalConstants.RedirectURLKey];
                            }

                            IdentityHelper.RedirectToReturnUrl(returnUrl, Response);

                            break;

                        case SignInStatus.LockedOut:
                            Response.Redirect("/Account/Lockout");
                            break;

                        case SignInStatus.RequiresVerification:
                            Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                            Request.QueryString["ReturnUrl"],
                                                            RememberMe.Checked),
                                              true);
                            break;

                        case SignInStatus.Failure:
                        default:
                            FailureText.Text     = "Chybný pokus pre prihlásenie";
                            ErrorMessage.Visible = true;
                            break;
                        }
                    }
                }
                else
                {
                    FailureText.Text     = string.Format("Užívateľ neexistuje, prosím zeregistrujete sa");
                    ErrorMessage.Visible = true;
                }
            }
        }
Exemplo n.º 15
0
        //    public void ScrollTo(string controllCLientId)
        //    {

        //        this.RegisterClientScriptBlock("ScrollTo", string.Format(@"
        //	<script type='text/javascript'>

        //		$(document).ready(function() {{
        //			var element = document.getElementById('{0}');
        //			element.scrollIntoView();
        //			element.focus();
        //		}});

        //	</script>

        //", controllCLientId));
        //    }


        ////TimerRefreshForum.Interval = Properties.Settings.Default.ForumAutoRefrestInterval;
        ////TimerRefreshForum.Enabled = true;


        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string pageName = string.Empty;
                try
                {
                    //zruisenie cache
                    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                    Response.Cache.SetNoStore();

                    //kontrola ci bol poslany request param
                    Session[GlobalConstants.RedirectURLKey] = HttpContext.Current.Request.Url.PathAndQuery;
                    if (Request.QueryString.Count == 0 || string.IsNullOrEmpty(QueryStringHelper.GetIdFromRequest(Request)))
                    {
                        Response.Redirect(GlobalConstants.urlDefault, true);
                        return;
                    }

                    //kontrola ci je user prihlaseny
                    if (!Context.User.Identity.IsAuthenticated)
                    {
                        Response.Redirect(GlobalConstants.urlForbidden, true);
                        return;
                    }

                    //nacitanie filesystem query
                    string trueQuery = QueryStringHelper.GetIdFromRequest(Request);

                    //kontrola ci existuje filesystem struktura podla query
                    RelativePath   = string.Format("{0}/{1}", GlobalConstants.PthFileSystemRoot, trueQuery);
                    FileSystemPath = Server.MapPath(RelativePath);
                    if (!System.IO.Directory.Exists(FileSystemPath))
                    {
                        Response.Redirect(GlobalConstants.urlDefault, true);
                        return;
                    }
                    EventIdParams = trueQuery.Split(GlobalConstants.EventIdSeparator, StringSplitOptions.RemoveEmptyEntries);
                    //pre akcia, akcia popis
                    if (EventIdParams != null && EventIdParams.Length == NumberOfParams)
                    {
                        StrPageHeader = EventIdParams[1];
                        PageTitleBase = string.Format("{0} - {1}", EventIdParams[0], EventIdParams[1]);
                    }
                    else
                    {
                        Response.Redirect(GlobalConstants.urlDefault, true);
                        return;
                    }
                    Navigator.GenerateNavigation(Page.Master);

                    if (Properties.Settings.Default.EnableStatistic)
                    {
                        string userId = Context.User.Identity.Name;
                        using (var _db = new Kronika106DBContext())
                        {
                            ApplicationUser user = _db.Users.First(u => u.UserName == userId);
                            if (user != null)
                            {
                                _db.StatisticBrowse.Add(new StatisticBrowse()
                                {
                                    ApplicationUser = user, CreatedUTC = DateTime.UtcNow, Url = Server.UrlDecode(HttpContext.Current.Request.Url.PathAndQuery)
                                });
                                _db.SaveChanges();
                            }
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                }
            }
        }