public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                UsersContext db = new UsersContext();

                Usuario user = db.Usuarios.FirstOrDefault(x => x.UsuarioNome == filterContext.HttpContext.User.Identity.Name);
                if (user != null)
                {
                    user.Logado = DateTime.Now;
                    db.SaveChanges();
                }
            }
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    //WebSecurity.InitializeDatabaseConnection("AccountConnection", "User", "IdUser", "Username", autoCreateTables: true);

                    SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;
                    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");
                    }
                    if (!roles.RoleExists("User"))
                    {
                        roles.CreateRole("User");
                    }
                    if (membership.GetUser("admin1", false) == null)
                    {
                        WebSecurity.CreateUserAndAccount("admin1", "admin1", new
                        {
                            Username = "******",
                            Password = "******"
                        });
                        roles.AddUsersToRoles(new[] { "admin1" }, new[] { "Admin" });
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Crie o banco de dados de SimpleMembership sem o esquema de migração de Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("Chat", "Usuarios", "UsuarioId", "UsuarioNome", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("O banco de dados de ASP.NET Simple Membership não pôde ser inicializado. Para obter mais informações, consulte http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    //WebSecurity.InitializeDatabaseConnection("connString", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    WebSecurity.InitializeDatabaseConnection("connString", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
Exemple #5
0
        /*void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            int userId = (int)WebSecurity.CurrentUserId;
            using (var db = new UsersContext())
            {
                string s = db.getSessionId(userId);

                if ((filterContext.HttpContext.Session.SessionID != db.getSessionId(userId)) || db.getSessionId(userId) == null)
                {
                    WebSecurity.Logout();
                    filterContext.Result = new RedirectResult("/Home/Index");
                }
            }
        }*/
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //WebSecurity.InitializeDatabaseConnection("connString", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            bool isAuthorized = base.AuthorizeCore(httpContext);

            if (isAuthorized)
            {
                int userId = (int)WebSecurity.CurrentUserId;
                using (var db = new UsersContext())
                {
                    if ((httpContext.Session.SessionID != db.getSessionId(userId))
                        || db.getSessionId(userId) == null)
                    {
                        WebSecurity.Logout();
                        isAuthorized = false;
                        httpContext.Response.Redirect("/Home/Index");
                    }
                }
            }

            return isAuthorized;
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Inserir um novo usuário no banco de dados
                using (UsersContext db = new UsersContext())
                {
                    Usuario user = db.Usuarios.FirstOrDefault(u => u.UsuarioNome.ToLower() == model.UserName.ToLower());
                    // Verificar se o usuário já existe
                    if (user == null)
                    {
                        // Inserir o nome na tabela de perfil
                        db.Usuarios.Add(new Usuario { UsuarioNome = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "O nome de usuário já existe. Insira um nome de usuário diferente.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }