Example #1
0
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
            var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            try
            {
                if (!rm.RoleExists("admin"))
                {
                    rm.Create(new IdentityRole("admin"));
                    var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var user = new ApplicationUser() { UserName = "adminn" };
                    um.Create(user, "asdfgh");
                    UserLoginInfo info = new UserLoginInfo("Google",
                            "https://www.google.com/accounts/o8/id?id=AItOawka6ZSrKNn7UY3ZUcjFRZMSLhMqQNKArWQ");
                    um.AddToRole(user.Id, "admin");
                    um.AddLogin(user.Id, info);

                }
            }
            catch (TimeoutException)
            {
                //CreateAdmin();

            }
        }
        protected void Page_Load()
        {
            // Process the result from an auth provider in the request
            ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect("~/Account/Login");
            }
            if (!IsPostBack)
            {
                var manager = new UserManager();
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    Response.Redirect("~/Account/Login");
                }
                var user = manager.Find(loginInfo.Login);
                if (user != null)
                {
                    //MyUser user1 = MyUser.getUser(user.UserName, "");
                    //if(Session["UserId"]!=null && Convert.ToInt32(Session["UserId"].ToString())!=user1.userId)
                    //    Session.Add("UserId", user1.userId);
                    IdentityHelper.SignIn(manager, user, isPersistent: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else if (User.Identity.IsAuthenticated)
                {
                    // Apply Xsrf check when linking
                    var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
                    if (verifiedloginInfo == null)
                    {
                        Response.Redirect("~/Account/Login");
                    }

                    var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
                    if (result.Succeeded)
                    {
                        MyUser user1 = MyUser.getUser(user.UserName, "");
                        if (Session["UserId"] != null && Convert.ToInt32(Session["UserId"].ToString()) != user1.userId)
                            Session.Add("UserId", user1.userId);
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    }
                    else
                    {
                        AddErrors(result);
                        return;
                    }
                }
                else
                {
                    userName.Text = loginInfo.DefaultUserName;
                }
            }
        }
        protected void Page_Load()
        {
            // 要求の認証プロバイダーからの結果を処理します
            ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect("~/Account/Login");
            }
            if (!IsPostBack)
            {
                var manager = new UserManager();
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    Response.Redirect("~/Account/Login");
                }
                var user = manager.Find(loginInfo.Login);
                if (user != null)
                {
                    IdentityHelper.SignIn(manager, user, isPersistent: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else if (User.Identity.IsAuthenticated)
                {
                    // Apply Xsrf check when linking
                    var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
                    if (verifiedloginInfo == null)
                    {
                        Response.Redirect("~/Account/Login");
                    }

                    var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
                    if (result.Succeeded)
                    {
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    }
                    else
                    {
                        AddErrors(result);
                        return;
                    }
                }
                else
                {
                    userName.Text = loginInfo.DefaultUserName;
                }
            }
        }
    protected void Page_Load()
    {
        // Procesar el resultado de un proveedor de autenticación en la solicitud
        ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
        if (String.IsNullOrEmpty(ProviderName))
        {
            Response.Redirect("~/Account/Login");
        }
        if (!IsPostBack)
        {
            var manager = new UserManager();
            var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
            if (loginInfo == null)
            {
                Response.Redirect("~/Account/Login");
            }
            var user = manager.Find(loginInfo.Login);
            if (user != null)
            {
                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else if (User.Identity.IsAuthenticated)
            {
                // Aplicar comprobación de Xsrf durante la vinculación
                var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
                if (verifiedloginInfo == null)
                {
                    Response.Redirect("~/Account/Login");
                }

                var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
                if (result.Succeeded)
                {
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else
                {
                    AddErrors(result);
                    return;
                }
            }
            else
            {
                userName.Text = loginInfo.DefaultUserName;
            }
        }
    }
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             MyUser myuser = new MyUser(userName.Text, "", nameUser.Text, contactNo.Text, (UserType)Enum.Parse(typeof(UserType), userType.SelectedItem.Value));
             int returncode = myuser.addUser();
             //MyUser user1 = MyUser.getUser(userName.Text, "");
             //if (Session["UserId"] != null && Convert.ToInt32(Session["UserId"].ToString()) != user1.userId)
             //    Session.Add("UserId", user1.userId);
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
    private void CreateAndLoginUser()
    {
        if (!IsValid)
        {
            return;
        }
        var manager = new UserManager();
        var user = new ApplicationUser() { UserName = userName.Text };
        IdentityResult result = manager.Create(user);
        if (result.Succeeded)
        {
            var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
            if (loginInfo == null)
            {
                Response.Redirect("~/Account/Login");
                return;
            }
            result = manager.AddLogin(user.Id, loginInfo.Login);
            if (result.Succeeded)
            {
                try
                {
                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                    conn.Open();
                    string insertQuery = "insert into [ACCOUNT] ([name],[balance],[Account_Number]) values (@name1,@balance1,@account1)";
                    SqlCommand com = new SqlCommand(insertQuery, conn);
                    com.Parameters.AddWithValue("@name1", user);
                    com.Parameters.AddWithValue("@balance1", "100000000");
                    com.Parameters.AddWithValue("@account1", "1");
                    com.ExecuteNonQuery();
                    conn.Close();
                }

                catch (Exception ex)
                {
                    Response.Write("Error:" + ex.ToString());
                }
                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                return;
            }
        }
        AddErrors(result);
    }
        public async Task Can_create_user_and_log_in()
        {
            const string username = "DavidBoike";
            const string userId = "user_id_1";
            string password = Guid.NewGuid().ToString("n");
            const string googleLogin = "http://www.google.com/fake/user/identifier";
            const string yahooLogin = "http://www.yahoo.com/fake/user/identifier";

            var user = new SimpleAppUser { Id = userId, UserName = username };

            using (var docStore = NewDocStore())
            {
                using (var session = docStore.OpenAsyncSession())
                {
                    using (var mgr = new UserManager<SimpleAppUser>(new UserStore<SimpleAppUser>(session)))
                    {
                        IdentityResult result = mgr.Create(user, password);

                        Assert.True(result.Succeeded);
                        Assert.NotNull(user.Id);

                        var res1 = mgr.AddLogin(user.Id, new UserLoginInfo("Google", googleLogin));
                        var res2 = mgr.AddLogin(user.Id, new UserLoginInfo("Yahoo", yahooLogin));

                        Assert.True(res1.Succeeded);
                        Assert.True(res2.Succeeded);
                    }
                    await session.SaveChangesAsync();
                }

                using (var session = docStore.OpenSession())
                {
                    var loaded = session.Load<SimpleAppUser>(user.Id);
                    Assert.NotNull(loaded);
                    Assert.NotSame(loaded, user);
                    Assert.Equal(loaded.Id, user.Id);
                    Assert.Equal(loaded.UserName, user.UserName);
                    Assert.NotNull(loaded.PasswordHash);

                    Assert.Equal(loaded.Logins.Count, 2);
                    Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Google" && x.ProviderKey == googleLogin));
                    Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Yahoo" && x.ProviderKey == yahooLogin));

                    var loadedLogins = session.Advanced.LoadStartingWith<IdentityUserLogin>("IdentityUserLogins/");
                    Assert.Equal(loadedLogins.Length, 2);

                    foreach (var login in loaded.Logins)
                    {
                        var loginDoc = session.Load<IdentityUserLogin>(Util.GetLoginId(login));
                        Assert.Equal(login.LoginProvider, loginDoc.Provider);
                        Assert.Equal(login.ProviderKey, loginDoc.ProviderKey);
                        Assert.Equal(user.Id, loginDoc.UserId);
                    }
                }

                using (var session = docStore.OpenAsyncSession())
                {
                    using (var mgr = new UserManager<SimpleAppUser>(new UserStore<SimpleAppUser>(session)))
                    {
                        var userByName = mgr.Find(username, password);
                        var userByGoogle = mgr.Find(new UserLoginInfo("Google", googleLogin));
                        var userByYahoo = mgr.Find(new UserLoginInfo("Yahoo", yahooLogin));

                        Assert.NotNull(userByName);
                        Assert.NotNull(userByGoogle);
                        Assert.NotNull(userByYahoo);

                        Assert.Equal(userByName.Id, userId);
                        Assert.Equal(userByName.UserName, username);

                        // The Session cache should return the very same objects
                        Assert.Same(userByName, userByGoogle);
                        Assert.Same(userByName, userByYahoo);
                    }
                    await session.SaveChangesAsync();
                }
            }
        }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var currentApplicationId = new ApplicationDbContext().Applications.SingleOrDefault(x => x.ApplicationName == "/").ApplicationId;

            var manager = new UserManager();
            var user = new User() { UserName = Username.Text, ApplicationId = currentApplicationId, LoweredUserName = Username.Text.ToLower() };

            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    Response.Redirect("~/IdentityAccount/Login.aspx");
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    IdentityHelper.SignIn(manager, user, isPersistent: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
 public void CreateWithoutCommitingNHibernateTransactionShouldNotInsertRows()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session));
     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session));
     using (var ts = _session.BeginTransaction())
     {
         userManager.Create(new ApplicationUser() { UserName = "test", Email = "[email protected]", EmailConfirmed = true }, "Welcome1");
         var x = userManager.FindByEmail("[email protected]");
         roleManager.Create(new IdentityRole("Admin"));
         userManager.AddClaim(x.Id, new Claim("role", "admin"));
         userManager.AddClaim(x.Id, new Claim("role", "user"));
         userManager.AddToRole(x.Id, "Admin");
         userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234"));
     }
     var x2 = userManager.FindByEmail("[email protected]");
     Assert.IsNull(x2);
 }
 public void CreateWithoutCommitingTransactionScopeShouldNotInsertRows()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session));
     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session));
     using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew))
     {
         // session is not opened inside the scope so we need to enlist it manually
         ((System.Data.Common.DbConnection)_session.Connection).EnlistTransaction(System.Transactions.Transaction.Current);
         userManager.Create(new ApplicationUser() { UserName = "test", Email = "[email protected]", EmailConfirmed = true }, "Welcome1");
         var x = userManager.FindByEmail("[email protected]");
         roleManager.Create(new IdentityRole("Admin"));
         userManager.AddClaim(x.Id, new Claim("role", "admin"));
         userManager.AddClaim(x.Id, new Claim("role", "user"));
         userManager.AddToRole(x.Id, "Admin");
         userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234"));
     }
     var x2 = userManager.FindByEmail("[email protected]");
     Assert.IsNull(x2);
 }
 public void FindByEmailAggregated()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session));
     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session));
     userManager.Create(new ApplicationUser() { UserName = "test", Email = "[email protected]", EmailConfirmed = true }, "Welcome");
     var x = userManager.FindByEmail("[email protected]");
     roleManager.CreateAsync(new IdentityRole("Admin"));
     userManager.AddClaim(x.Id, new Claim("role", "admin"));
     userManager.AddClaim(x.Id, new Claim("role", "user"));
     userManager.AddToRole(x.Id, "Admin");
     userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234"));
     this._session.Clear();
     x = userManager.FindByEmail("[email protected]");
     Assert.IsNotNull(x);
     Assert.AreEqual(2, x.Claims.Count);
     Assert.AreEqual(1, x.Roles.Count);
     Assert.AreEqual(1, x.Logins.Count);
 }