Beispiel #1
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/user/index.aspx");

                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception d)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                //store user information into variables
                var userStore = new UserStore<IdentityUser>();
                var userManager = new UserManager<IdentityUser>(userStore);
                var user = userManager.Find(txtUsername.Text, txtPassword.Text);

                //if there is a current user
                if (user != null)
                {
                    //if the user is authenticated, redirect to products page
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    Response.Redirect("/admin/products.aspx", false);
                }
                else //if any fields are blank
                {
                    //show a message to the user
                    lblStatusMessage.Text = "Invalid username or password.";
                    lblStatusMessage.Visible = true;
                }
            }
            catch (Exception)
            {
                Response.Redirect("/Error.aspx");
            }
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
 public static void SignIn(UserManager manager, ApplicationUser user, bool isPersistent)
 {
     IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
     authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
     authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
 }
Beispiel #5
0
 public ClaimsIdentity GenerateUserIdentity(UserManager<User> manager)
 {
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
     var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
     // Add custom user claims here
     return userIdentity;
 }
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            //crete new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser()
            {
                UserName = UserNameTextBox.Text,
                PhoneNumber = PhoneNumberTextBox.Text,
                Email = EmailTextBox.Text
            };
            //create new user in the dbb and store the resukt
            IdentityResult result = userManager.Create(user, PasswordTextBox.Text);
            //check if succesfully registered
            if (result.Succeeded)
            {
                //authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //redirect to main menu
                Response.Redirect("~/Secured/TodoList.aspx");

            }
            else
            {
                //display error in the AlertFlash div
                StatusLabel.Text = result.Errors.FirstOrDefault();
                AlertFlash.Visible = true;
            }
        }
Beispiel #7
0
        protected void SignIn(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            IdentityUser user = userManager.Find(tbUsername.Text, tbPassword.Text);

            //if user info is found
            if (user != null)
            {
                //create cookie
                IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties {IsPersistent = false}, userIdentity);

                var returnUrl = Request.QueryString["returnUrl"];
                //if user came from different page, redirect to that one. Otherwise redirect to main page.
                Response.Redirect(returnUrl ?? "~/default.aspx");
            }
            //if not, show error message.
            else
            {
                lblConfirmationText.Text = "Invalid username or password.";
            }
        }
        /**
          Login - authenticate entered user credientials.
         **/
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                var userStore = new UserStore<IdentityUser>();
                var userManager = new UserManager<IdentityUser>(userStore);
                var user = userManager.Find(txtUsername.Text, txtPassword.Text);

                if (user != null)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    Response.Redirect("admin/bibleMenu.aspx");
                }
                else
                {
                    lblStatus.Text = "Invalid username or password.";
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/errors.aspx");
            }
        }
Beispiel #9
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //try
            //{
                var userStore = new UserStore<IdentityUser>();
                var userManager = new UserManager<IdentityUser>(userStore);
                var user = userManager.Find(txtUserName.Text, txtPassword.Text);

                if (user != null)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    Response.Redirect("~/admin/MainMenu.aspx");
                }
                else
                {
                    lblStatus.Text = "Invalid username or password.";

                }
            //}
            //catch (System.Exception)
            //{
            //    Response.Redirect("/MainMenu.aspx");
            //}
        }
Beispiel #10
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // Find the user
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // check if username and password combo exists
            if (user != null)
            {
                // authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // redirect to the Main Menu page
                Response.Redirect("~/game.aspx");
            }
            else
            {
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
        public ActionResult Register(User user)
        {
            string temp = user.Password;
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user2 = new IdentityUser() { UserName = user.Username };
            IdentityResult result = manager.Create(user2, user.Password);

            if (result.Succeeded)
            {
                TempData["message"] = "Identity user create worked";

                //var temp2 =  this.ControllerContext.HttpContext;
                var authenticationManager = HttpContext.GetOwinContext().Authentication;
                //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user2, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                //Response.Redirect("~/Login.aspx");
                //return View("Login");

                if (User.Identity.IsAuthenticated)
                {
                    TempData["message"] += "/n   User.Identity.IsAuthenticate working";
                }

                return View("Index");
            }
            else
            {
                TempData["message"] = "Failed: " + result.Errors.FirstOrDefault();
            }
            return View("Index");
        }
Beispiel #12
0
    protected void btnSignIn_OnClick(object sender, EventArgs e)
    {
        UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.
            ConnectionStrings["GarageDBConnectionString"].ConnectionString;

        UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

        //to retrieve a user from the database
        var user = manager.Find(txtUserName.Text, txtPassword.Text);

        if (user != null)
        {
            //Call OWIN functionality
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            //Sign in user
            authenticationManager.SignIn(new AuthenticationProperties
            {
                IsPersistent = false
            }, userIdentity);

            //Redirect user to homepage
            Response.Redirect("~/Index.aspx");
        }
        else
        {
            litStatus.Text = "Invalid username or password";
        }
    }
Beispiel #13
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["CANDZOILPDBConnectionString"].ConnectionString;

        UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

        var user = manager.Find(txtUserName.Text, txtPassword.Text);

        if (user != null) {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

            var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties{
                IsPersistent = false
            }, userIdentity);

            Response.Redirect("~/Index.aspx");
        }else{
            litStatus.Text = "Invalid username or password";
        }
    }
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // search for and create a new user object
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // if a match is found for the user
            if(user != null)
            {
                // authenticate and login our new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                // Sign the user
                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // Redirect to Main Menu
                Response.Redirect("~/Contoso/MainMenu.aspx");
            }
            else
            {
                // throw an error to the AlertFlash div
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
Beispiel #15
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            //database connection not-authicating
            //System.Data.Entity.Core.EntityCommandExecutionException
            //System.Data.SqlClient.SqlException
            try
            {
                var user = userManager.Find(txtUsername.Text, txtPassword.Text);

                if (user != null)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    Response.Redirect("/admin/main.aspx");
                }
                else
                {
                    lblStatus.Text = "Invalid username or password.";
                }
            }
            catch (System.Data.Entity.Core.EntityCommandExecutionException ECEE) {
                Server.Transfer("/ErrorPage.aspx", true);
            }
            catch (System.Data.SqlClient.SqlException SqlE) {
                Server.Transfer("/ErrorPage.aspx", true);
            }
        }
Beispiel #16
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            IdentityUser user = manager.Find(LoginUser.UserName, LoginUser.Password);

            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                if (Request.QueryString["ReturnUrl"] == null)
                    Response.Redirect("../Default.aspx");
                else
                    Response.Redirect(Request.QueryString["ReturnUrl"]);

            }
            else
            {
                LoginUser.FailureText = "Invalid User Name or Password";

            }
        }
Beispiel #17
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnectionEF
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser() { UserName = txtUName.Text };
            user.Email = txtEmail.Text;
            user.PhoneNumber = txtPhone.Text;
            IdentityResult result = manager.Create(user, txtPass.Text);

            if (result.Succeeded)
            {
                lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("/admin/main.aspx");

            }
            else
            {
                lblStatus.Text = result.Errors.FirstOrDefault();
            }
        }
Beispiel #18
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //declare the collection of users
            UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
            //declare the user manager
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
            //try to find the user
            IdentityUser user = manager.Find(txtEmpNum.Text, txtPassword.Text);
            if (user == null)
                lblStatus.Text = "Username or Password is incorrect";
            else
            {
                if (txtEmpNum.Text == "Administrator")
                {
                    IdentityResult userResult = manager.AddToRole(user.Id, "Admin");
                }
                //add user to role
                //authenticate user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(userIdentity);
                Response.Redirect("~/MainPage.aspx");

            }
        }
Beispiel #19
0
        protected void SignIn(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = userManager.Find(UserName.Text, Password.Text);
            try
            {
                if (user != null)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    StatusText.Text = "Invalid username or password.";
                    LoginStatus.Visible = true;
                }
            }
            catch (Exception)
            {
                Server.Transfer("/error.aspx");
            }
        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);
            //IdentityResult IdUserResult;

            var user = new IdentityUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

               // IdUserResult = manager.AddToRole(manager.FindByName(user.UserName).Id, "member");

                Session["uPass"] = Password.Text;
                Response.Redirect("~/WebForm2.aspx");
                // StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        public void SignIn(IAccount account, Boolean createPersistentCookie)
        {
            UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.context));
            ApplicationUser user = manager.FindByName(account.AccountName);

            this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            this.AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = createPersistentCookie }, identity);
        }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        // Default UserStore constructor uses the default connection string named: DefaultConnection
        var userStore = new UserStore<IdentityUser>();

        //Set ConnectionString to GarageConnectionString
        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["GarageConnectionString"].ConnectionString;
        var manager = new UserManager<IdentityUser>(userStore);

        //Create new user and try to store in DB.
        var user = new IdentityUser { UserName = txtUserName.Text };

        if (txtPassword.Text == txtConfirmPassword.Text)
        {
            try
            {
                IdentityResult result = manager.Create(user, txtPassword.Text);
                if (result.Succeeded)
                {
                    UserDetail userDetail = new UserDetail
                    {
                        Address = txtAddress.Text,
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        Guid = user.Id,
                        PostalCode = Convert.ToInt32(txtPostalCode.Text)
                    };

                    UserDetailModel model = new UserDetailModel();
                    model.InsertUserDetail(userDetail);

                    //Store user in DB
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    //If succeedeed, log in the new user and set a cookie and redirect to homepage
                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }
                else
                {
                    litStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                litStatusMessage.Text = ex.ToString();
            }
        }
        else
        {
            litStatusMessage.Text = "Passwords must match!";
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        UserStore <IdentityUser> userStore = new UserStore <IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["CANDZOILPDBConnectionString"].ConnectionString;

        UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);

        IdentityUser user = new IdentityUser();

        user.UserName = txtUserName.Text;

        if (txtPassword.Text.Equals(txtConfirmPassword.Text))
        {
            try {
                IdentityResult result = manager.Create(user, txtPassword.Text);
                if (result.Succeeded)
                {
                    UserInformation info = new UserInformation
                    {
                        Address    = txtAddress.Text,
                        FirstName  = txtFirstName.Text,
                        LastName   = txtLastName.Text,
                        PostalCode = Convert.ToInt32(txtPostalCode.Text),
                        GUID       = user.Id
                    };

                    UserInfoModel model = new UserInfoModel();
                    model.InsertUserInformation(info);

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }
                else
                {
                    litStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception er)
            {
                litStatusMessage.Text = er.ToString();
            }
        }
        else
        {
            litStatusMessage.Text = "Passwords must match!";
        }
    }
Beispiel #24
0
        public static void SignIn(UserManager manager, ApplicationUser user, bool isPersistent)
        {
            IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
Beispiel #25
0
        public IHttpActionResult RegisterUser(Account newAccount, string role)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("model is invalid"));
            }

            // register
            var userStore   = new UserStore <IdentityUser>(new DataDbContext());
            var userManager = new UserManager <IdentityUser>(userStore);
            var user        = new IdentityUser(newAccount.Email);

            // create the user
            userManager.Create(user, newAccount.Password);


            if (userManager.Users.Any(u => u.Email == newAccount.Email))
            {
                return(BadRequest("email is already taken"));
            }

            if (userManager.Users.Any(u => u.Email == newAccount.Email))
            {
                return(BadRequest("email is already taken"));
            }

            // assign role
            if (role.ToLower() == "user")
            {
                userManager.AddToRole(user.Id, "user");
            }
            else if (role.ToLower() == "agent")
            {
                userManager.AddToRole(user.Id, "agent");
            }
            else if (role.ToLower() == "admin")
            {
                userManager.AddToRole(user.Id, "admin");
            }
            else
            {
                return(BadRequest("no role assigned"));
            }

            var authManager    = Request.GetOwinContext().Authentication;
            var claimsIdentity = userManager.CreateIdentity(user, WebApiConfig.AuthenticationType);

            authManager.SignIn(new AuthenticationProperties {
                IsPersistent = true
            }, claimsIdentity);
            return(Ok("registered account and logged in"));
        }
Beispiel #26
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);

            // search for and create a new user object
            var user = userManager.Find(userNameTextBox.Text, passwordTextBox.Text);

            // if a match is found
            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                // sign in the user
                authenticationManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = false
                }, userIdentity);

                Session["userName"] = user.UserName;
                if (user.UserName == "admin")
                {
                    Session["admin"] = true;
                }
                Response.Redirect("Default.aspx");
            }
            else
            {
                // throw an error to alertFlash
                statusLabel.Text   = "Invalid User Name or Password";
                alertFlash.Visible = true;
            }



            ////connect to DB
            //using (comp2007db db = new comp2007db())
            //{
            //    User loginUser = (from user in db.Users where user.email == emailTextBox.Text && user.password == passwordTextBox.Text select user).FirstOrDefault();

            //    if (loginUser != null)
            //    {
            //        Session["userName"] = loginUser.FirstName;
            //        Response.Redirect("Default.aspx");
            //    }
            //    else
            //    {
            //        invalidLogin.Visible = true;
            //    }
            //}
        }
Beispiel #27
0
        public async Task <IHttpActionResult> Edit([FromBody] AccountEdit account)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Model state invalid"));
            }

            try
            {
                var userStore   = new UserStore <IdentityUser>(new AccountDbContext());
                var userManager = new UserManager <IdentityUser>(userStore);
                var user        = userManager.Users.First(x => x.UserName == account.Username);
                if (user == null)
                {
                    throw new ArgumentException("account");
                }

                if (!userManager.CheckPassword(user, account.Password))
                {
                    return(Unauthorized());
                }

                if (userManager.HasPassword(user.Id))
                {
                    userManager.RemovePassword(user.Id);
                }

                var hashedPw = userManager.PasswordHasher.HashPassword(account.newPassword);

                await userStore.SetPasswordHashAsync(user, hashedPw);

                await userManager.UpdateAsync(user);

                user.UserName = account.newUsername ?? account.Username;
                user.Email    = account.newEmail;
                userStore.Context.SaveChanges();

                // Refresh
                Request.GetOwinContext().Authentication.SignOut(WebApiConfig.AuthenticationType);
                var authManager    = Request.GetOwinContext().Authentication;
                var claimsIdentity = userManager.CreateIdentity(user, WebApiConfig.AuthenticationType);
                authManager.SignIn(new AuthenticationProperties {
                    IsPersistent = true
                }, claimsIdentity);

                return(Ok());
            }
            catch
            {
                return(BadRequest("Invalid user"));
            }
        }
Beispiel #28
0
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        var userStore = new UserStore <IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["GarageConnectionString"].ConnectionString;
        var manager = new UserManager <IdentityUser>(userStore);

        var user = new IdentityUser {
            UserName = txtUserName.Text
        };

        if (txtPassword.Text == txtConfirmPassword.Text)
        {
            try
            {
                IdentityResult result = manager.Create(user, txtPassword.Text);
                if (result.Succeeded)
                {
                    UserDetail userDetail = new UserDetail
                    {
                        Address    = txtAddress.Text,
                        FirstName  = txtFirstName.Text,
                        LastName   = txtLastName.Text,
                        Guid       = user.Id,
                        PostalCode = Convert.ToInt32(txtPostalCode.Text)
                    };

                    UserDetailModel model = new UserDetailModel();
                    model.InsertUserDetail(userDetail);

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity          = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }
                else
                {
                    litStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                litStatusMessage.Text = ex.ToString();
            }
        }
        else
        {
            litStatusMessage.Text = "Las Contraseñas deben coincidir!";
        }
    }
Beispiel #29
0
        protected void LogIn(object sender, EventArgs e)
        {
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);
            var user        = userManager.Find(UserName.Text, Password.Text);

            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = false
                }, userIdentity);

                // get user type, name and store them in HttpSession
                string usertype = "";
                try
                {
                    using (OdbcConnection connection = new OdbcConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
                    {
                        connection.Open();
                        string query = "SELECT type from user "
                                       + "WHERE username='******'";
                        using (OdbcCommand command = new OdbcCommand(query, connection))
                            using (OdbcDataReader dr = command.ExecuteReader())
                            {
                                while (dr.Read())
                                {
                                    usertype = dr[0].ToString();
                                }
                                dr.Close();
                            }
                        connection.Close();
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("An error occured: " + ex.Message);
                }
                Session["usertype"] = usertype;
                Session["username"] = UserName.Text;

                Response.Redirect("~/Default.aspx");
            }
            else
            {
                StatusText.Text     = "Invalid username or password.";
                LoginStatus.Visible = true;
            }
        }
Beispiel #30
0
        public void HandleCommand(UserManager <User> userManager, string message, Player player)
        {
            try
            {
                string commandText = message.Split(' ')[0];
                message     = message.Replace(commandText, "").Trim();
                commandText = commandText.Replace("/", "").Replace(".", "");

                if (_pluginCommands.Values.Where(t => t.Command.Equals(commandText)).Count().Equals(0))
                {
                    player.SendMessage("§dP§7R§8> §bCommand not found. Use /help for commands");
                    return;
                }
                string[] arguments = message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var handlerEntry in _pluginCommands)
                {
                    CommandAttribute commandAttribute = handlerEntry.Value;
                    if (!commandText.Equals(commandAttribute.Command, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    MethodInfo method = handlerEntry.Key;
                    if (method == null)
                    {
                        return;
                    }

                    var authorizationAttributes = method.GetCustomAttributes <AuthorizeAttribute>(true);
                    foreach (AuthorizeAttribute authorizationAttribute in authorizationAttributes)
                    {
                        User user         = userManager.FindByName(player.Username);
                        var  userIdentity = userManager.CreateIdentity(user, "none");
                        if (!authorizationAttribute.OnAuthorization(new GenericPrincipal(userIdentity, new string[0])))
                        {
                            player.SendMessage("§dP§7R§8> §cYou don't have permission");
                            return;
                        }
                    }

                    if (ExecuteCommand(method, player, arguments))
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex);
            }
        }
        public Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser, int> manager, string authenticationType, bool isThirdParty = false)
        {
            var userIdentity = manager.CreateIdentity(this, authenticationType);

            //var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);

            userIdentity.AddClaim(new Claim("UserId", this.Id.ToString()));
            //userIdentity.AddClaim(new Claim("FullName", this.FirstName + " " + this.LastName));
            //userIdentity.AddClaim(new Claim("CompanyId", this.CompanyId.ToString()));
            //userIdentity.AddClaim(new Claim("RoleId", roleId.ToString()));

            return(Task.FromResult(userIdentity));
        }
Beispiel #32
0
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = userManager.Find(model.Email, model.Password);

            if (user != null)
            {
                var identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                GetAuthenticationManager().SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            // user authN failed
            ModelState.AddModelError("", "Invalid email or password");
            return(View());
        }
 public ActionResult Login(Login model)
 {
     if (ModelState.IsValid)
     {
         var user = UserManager.Find(model.UserName, model.Password);
         if (user != null)
         {
             var authManager = HttpContext.GetOwinContext().Authentication;
             var identityClaims = UserManager.CreateIdentity(user, "ApplicationCookie");
             var authProperties = new AuthenticationProperties();
             authProperties.IsPersistent = model.RememberMe;
             authManager.SignIn(authProperties, identityClaims);
             return RedirectToAction("Profile", "User", user);
         }
         else
         {
             ModelState.AddModelError("userLoginError", "E-mail adresi ya da parola hatalı.");
         }
     }
 
     return View(model);
 }
 protected void btnIngresar_Click(object sender, EventArgs e)
 {
     var userStore = new UserStore<IdentityUser>();
     var userManager = new UserManager<IdentityUser>(userStore);
     var user = userManager.Find(txtNombreUsuario.Text, txtContrasenna.Text);
     if (user != null)
     {
         var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
         var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
         authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
         Response.Redirect("~/wfrmInicio.aspx");
     }
 }
Beispiel #35
0
        protected void SignUp_Click(object sender, EventArgs e)
        {
            try
            {
                UserStore <IdentityUser> userStore = new UserStore <IdentityUser>();

                userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager
                                                                         .ConnectionStrings["iCourtDatabaseConnection"].ConnectionString;

                UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);

                //Create new user and try to store in DB
                IdentityUser user = new IdentityUser();
                user.UserName = this.txtEmail.Text;

                if (this.txtPassword.Text == this.txtConfirmPassword.Text)
                {
                    try
                    {
                        //Create user object
                        IdentityResult result = manager.Create(user, this.txtPassword.Text);

                        if (result.Succeeded)
                        {
                            //Store user in DB
                            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

                            //Set to log in new user by Cookie.
                            var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                            //Log in the new user and redirect to homepage
                            authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                            this.Response.Redirect("~/default.aspx");
                        }
                        else
                        {
                            this.litRegisterError.Text = result.Errors.FirstOrDefault();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error message: " + ex);
            }
        }
Beispiel #36
0
        public ClaimsIdentity Authenticate(UserModelUoW userDto)
        {
            ClaimsIdentity claim = null;
            // находим пользователя
            ShopUser user = UserManager.Find(userDto.Email, userDto.Password);

            // авторизуем его и возвращаем объект ClaimsIdentity
            if (user != null)
            {
                claim = UserManager.CreateIdentity(user,
                                                   DefaultAuthenticationTypes.ApplicationCookie);
            }
            return(claim);
        }
Beispiel #37
0
        public ActionResult Login(string username, string password)
        {
            var user = UserManager.Find(username, password);

            //if (user != null)
            //{
            //    var authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
            //    var userIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            //    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
            //    //return Redirect("/Home");
            //}
            //else
            //{
            //    Debug.WriteLine("@@@");

            //    Debug.WriteLine(JsonConvert.SerializeObject(HttpNotFound()));
            //}

            //var role = db.Roles.Where(r => r.Name == "employee");
            if (user == null)
            {
                Debug.WriteLine("@@@");

                Debug.WriteLine(JsonConvert.SerializeObject(HttpNotFound()));
                return(HttpNotFound());
            }
            //else if (user != null && Roles.IsUserInRole(username, "admin"))
            //{
            //    bool result = User.IsInRole("admin");
            //    // success
            //    var ident = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            //    //use the instance that has been created.
            //    var authManager = HttpContext.GetOwinContext().Authentication;
            //    authManager.SignIn(
            //        new AuthenticationProperties { IsPersistent = false }, ident);
            //    return Redirect("/ManageUser");
            //}

            // success
            var ident = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            //use the instance that has been created.
            var authManager = HttpContext.GetOwinContext().Authentication;

            authManager.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            }, ident);

            return(Redirect("/PolicyClient"));
        }
Beispiel #38
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            UserStore <IdentityUser> userStore = new UserStore <IdentityUser>();

            userStore.Context.Database.Connection.ConnectionString =
                System.Configuration.ConfigurationManager.
                ConnectionStrings["F17_kswbhancoConnectionString"].ConnectionString;

            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);

            //create new user and try to store in db
            IdentityUser user = new IdentityUser();

            user.UserName = txtUsername.Text;

            if (txtPassword.Text == txtConfirmPassword.Text)
            {
                try
                {
                    //create user object
                    //db will be created/expanded automatically
                    IdentityResult result = manager.Create(user, txtPassword.Text);

                    if (result.Succeeded)
                    {
                        //store user in db
                        var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

                        //set to log in new user by cookie
                        var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                        //log in the new user and redirect to homepage
                        authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties(), userIdentity);
                        Response.Redirect("~/Pages/Index.aspx");
                    }
                    else
                    {
                        litStatus.Text = result.Errors.FirstOrDefault();
                    }
                }
                catch (Exception ex)
                {
                    litStatus.Text = ex.ToString();
                }
            }
            else
            {
                litStatus.Text = "Passwords must match.";
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            UserStore <IdentityUser> userStore = new UserStore <IdentityUser>();

            userStore.Context.Database.Connection.ConnectionString =
                System.Configuration.ConfigurationManager.
                ConnectionStrings["db_1525594_co5027_keerickConnectionString"].ConnectionString;

            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);

            //Create new user and try to store in DB.
            IdentityUser user = new IdentityUser();

            user.UserName = txtUserName.Text;

            if (txtPassword.Text == txtConfirmPassword.Text)
            {
                try
                {
                    //Create user object.
                    //Database will be created / expanded automatically.
                    IdentityResult result = manager.Create(user, txtPassword.Text);

                    if (result.Succeeded)
                    {
                        //Store user in DB
                        var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

                        //Set to log in new user by Cookie.
                        var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                        //Log in the new user and redirect to homepage
                        authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        litStatus.Text = result.Errors.FirstOrDefault();
                    }
                }
                catch (Exception ex)
                {
                    litStatus.Text = ex.ToString();
                }
            }
            else
            {
                litStatus.Text = "Passwords must match";
            }
        }
Beispiel #40
0
        public ClaimsIdentity GenerateUserIdentity(UserManager <UserAccount, long> manager)
        {
            var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);

            if (userIdentity != null)
            {
                userIdentity.AddClaims(new[] {
                    new Claim("Client_Id", Client_Id?.ToString() ?? ""),
                    new Claim("UserName", UserName),
                    new Claim("FullName", FullName),
                });
            }
            return(userIdentity);
        }
Beispiel #41
0
        /// <summary>
        /// Vendégadatok lekérdezése.
        /// </summary>
        /// <param name="userName">A felhasználónév.</param>

        /*
         * public Guest GetGuest(String userName)
         * {
         *  if (userName == null)
         *      return null;
         *
         *  // keresés a regisztrált felhasználók között
         *  IdentityGuest guest = _guestManager.FindByName(userName);
         *  if (guest != null)
         *  {
         *      return new Guest
         *      {
         *          Name = guest.Name,
         *          Email = guest.Email,
         *          Address = guest.Address,
         *          PhoneNumber = guest.PhoneNumber
         *      };
         *  }
         *
         *  // keresés a nem regisztrált felhasználók között
         *  return _entities.Guest.FirstOrDefault(c => c.UserName == userName);
         * }
         */

        /// <summary>
        /// Felhasználó bejelentkeztetése.
        /// </summary>
        /// <param name="user">A felhasználó nézetmodellje.</param>
        public Boolean Login(UserViewModel user)
        {
            if (user == null)
            {
                return(false);
            }

            // ellenőrizzük az annotációkat
            if (!Validator.TryValidateObject(user, new ValidationContext(user, null, null), null))
            {
                return(false);
            }

            // megkeressük a felhasználót
            IdentityTeacher identityTeacher = _teacherManager.Find(user.UserId, "password");

            if (identityTeacher == null) // ha nem sikerült, akkor nincs bejelentkeztetés
            {
                Teacher teacher = _entities.Teacher.Find(user.UserId);

                if (teacher == null)
                {
                    return(false);
                }

                IdentityResult result = _teacherManager.Create(new IdentityTeacher
                {
                    UserName = teacher.UserId,
                    UserId   = teacher.UserId,
                }, "password"); // felhasználó létrehozása

                identityTeacher = _teacherManager.Find(teacher.UserId, "password");
            }

            // ha valaki már bejelentkezett, kijelentkeztetjük
            HttpContext.Current.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            // bejelentkeztetjük az új felhasználót
            ClaimsIdentity claimsIdentity = _teacherManager.CreateIdentity(identityTeacher, DefaultAuthenticationTypes.ApplicationCookie);

            HttpContext.Current.GetOwinContext().Authentication.SignIn(new AuthenticationProperties {
                IsPersistent = false
            }, claimsIdentity);
            // perzisztens bejelentkezést állítunk be, amennyiben megjegyzést kért

            // módosítjuk a felhasználók számát
            // UserCount++;

            return(true);
        }
Beispiel #42
0
        public ActionResult Save(UserManagerViewModel newUserData)
        {
            if (!ModelState.IsValid)
            {
                return(View("UserManagerForm", newUserData));
            }


            var applicationUser = _userManager.FindById(newUserData.Id);

            if (applicationUser == null)
            {
                return(View("UserManagerForm", newUserData));
            }


            _userManager.RemoveFromRoles(applicationUser.Id, _userManager.GetRoles(applicationUser.Id).ToArray());

            if (newUserData.UserRoleIds != null)
            {
                var userRoleNames = newUserData.UserRoleIds
                                    .Select(r => _roleManager.FindById(r).Name)
                                    .ToArray();

                foreach (var roleName in userRoleNames)
                {
                    if (!_roleManager.RoleExists(roleName))
                    {
                        return(View("UserManagerForm", newUserData));
                    }
                }

                _userManager.AddToRoles(applicationUser.Id, userRoleNames);
            }

            _userManager.Update(applicationUser);


            var currentApplicationUser = _userManager.FindById(User.Identity.GetUserId());
            var authenticationManager  = System.Web.HttpContext.Current.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = _userManager.CreateIdentity(currentApplicationUser, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties {
                IsPersistent = false
            }, identity);

            return(RedirectToAction("Index"));
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["CANDZOILPDBConnectionString"].ConnectionString;
        
        UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

        IdentityUser user = new IdentityUser();
        user.UserName = txtUserName.Text;

        if (txtPassword.Text.Equals(txtConfirmPassword.Text))
        {
            try {
                IdentityResult result = manager.Create(user, txtPassword.Text);
                if (result.Succeeded)
                {
                    UserInformation info = new UserInformation
                    {

                        Address = txtAddress.Text,
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        PostalCode = Convert.ToInt32(txtPostalCode.Text),
                        GUID = user.Id
                    };

                    UserInfoModel model = new UserInfoModel();
                    model.InsertUserInformation(info);

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }else{
                    litStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception er)
            {
                litStatusMessage.Text = er.ToString();
            }
        }
        else {
            litStatusMessage.Text = "Passwords must match!";
        }
    }
Beispiel #44
0
        private void LogUserIn(UserManager <IdentityUser> usermanager, IdentityUser user)
        {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity          = usermanager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties()
            {
            }, userIdentity);

            if (Request.QueryString["ReturnUrl"] != null)
            {
                Response.Redirect(Request.QueryString["ReturnUrl"]);
            }
        }
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = userManager.Find(model.Email, model.Password);

            if (user != null)
            {
                var identity = userManager.CreateIdentity(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                GetAuthenticationManager().SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View());

            ////CHANGE WHEN YOU GO TO PRODUCTION!!!
            //if (model.Email == "*****@*****.**" && model.Password == "password")
            //{
            //    //once the user is authenticated, user info is passed to the cookie
            //    //using the ClaimsIdentity object
            //    var identity = new ClaimsIdentity(new[]
            //    {
            //        new Claim(ClaimTypes.Name, "Charles"),
            //        new Claim(ClaimTypes.Email, "*****@*****.**"),
            //        new Claim(ClaimTypes.Country, "USA"),
            //    },
            //        "ApplicationCookie");

            //    var ctx = Request.GetOwinContext();
            //    var authManager = ctx.Authentication;

            //    //set the auth cookie on the client
            //    authManager.SignIn(identity);

            //    //redirect the user to the url they were attempting
            //    //to access before they were forced to login
            //    return Redirect(GetRedirectUrl(model.ReturnUrl));
            //}

            //ModelState.AddModelError("", "Invalid email or password");
            //return View();
        }
Beispiel #46
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string ReturnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Получение сведений о пользователе от внешнего поставщика входа
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    var ident = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    await UserManager.AddClaimAsync(user.Id, new Claim("FullName", model.Name));

                    Data.Save_log.Log("Создан пользователь " + user.Id + " (" + model.Email + ") с помощью сервиса внешней авторизации в " + info.Login.LoginProvider + ".", "Login");
                    await UserManager.AddToRoleAsync(user.Id, "user");

                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        result = await UserManager.ConfirmEmailAsync(user.Id, code);

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        Data.Save_log.Log("Успешно связали пользователя " + user.Id + " с логином " + model.Email + " в " + info.Login.LoginProvider + ".", "Login");
                        return(RedirectToLocal(ReturnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = ReturnUrl;
            return(View(model));
        }
Beispiel #47
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            var userStore   = new UserStore <IdentityUser>();
            var userManager = new UserManager <IdentityUser>(userStore);
            var user        = userManager.Find(txtFname.Text, txtPwd.Text);

            if (CheckBox1.Checked)
            {
                Response.Cookies["UNAME"].Value = txtFname.Text;
                Response.Cookies["PWD"].Value   = txtPwd.Text;

                Response.Cookies["UNAME"].Expires = DateTime.Now.AddDays(15);
                Response.Cookies["PWD"].Expires   = DateTime.Now.AddDays(15);
            }
            else
            {
                Response.Cookies["UNAME"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["PWD"].Expires   = DateTime.Now.AddDays(-1);
            }

            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = false
                }, userIdentity);

                if (userManager.IsInRole(userManager.FindByName(userIdentity.GetUserName().ToString()).Id, "Admin"))
                {
                    Response.Redirect("~/AdminHome.aspx");
                    Response.Write(@"<script langauge='text/javascript'>alert('Welcome " + userIdentity.GetUserName().ToString() + "..');</script>");
                }
                else if (userManager.IsInRole(userManager.FindByName(userIdentity.GetUserName().ToString()).Id, "Customer"))
                {
                    Response.Redirect("~/UserHome.aspx");
                    Response.Write(@"<script langauge='text/javascript'>alert('Welcome " + userIdentity.GetUserName().ToString() + "..');</script>");
                }
            }
            else
            {
                Response.Write(@"<script langauge='text/javascript'>alert('Invalid email or password..');</script>");

                StatusText.Text     = "";
                LoginStatus.Visible = true;
            }
        }
Beispiel #48
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text == null)
            {
                lblErrorMsg.Text = "Username field required to register";
            }
            else if (txtEmail.Text == null)
            {
                lblErrorMsg.Text = "Email field required to register";
            }
            else if (txtPassword.Text == null)
            {
                lblErrorMsg.Text = "Password field required to register";
            }
            else if (txtConfirmPassword.Text == null)
            {
                lblErrorMsg.Text = "Confirm password field required to register";
            }
            else if (txtPassword.Text != txtConfirmPassword.Text)
            {
                lblErrorMsg.Text = "Passwords do not match";
            }
            else
            {
                var userStore = new UserStore <IdentityUser>();
                var manager   = new UserManager <IdentityUser>(userStore);
                var user      = new IdentityUser()
                {
                    UserName = txtUsername.Text,
                    Email    = txtEmail.Text
                };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity          = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties()
                    {
                    }, userIdentity);
                    Response.Redirect("~/Pages/Dashboard.aspx");
                }
                else
                {
                    lblErrorMsg.Text = result.Errors.FirstOrDefault();
                }
            }
        }
        public ActionResult Login(string username, string password)
        {
            var user = UserManager.Find(username, password);

            if (user != null)
            {
                var authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity          = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties()
                {
                }, userIdentity);
                return(Redirect("/Home"));
            }
            return(View("Login"));
        }
Beispiel #50
0
 private void LogUserIn(UserManager <IdentityUser> userManager, IdentityUser user)
 {
     try
     {
         var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
         var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
         authenticationManager.SignIn(new AuthenticationProperties()
         {
         }, userIdentity);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Beispiel #51
0
        private Operation <ClaimsIdentity> SignIn(User model, bool rememberMe)
        {
            return(Operation.Create(() =>
            {
                var identity = _user.CreateIdentity(model, DefaultAuthenticationTypes.ApplicationCookie);

                //Optional Add Additional Claims

                Authentication.SignIn(new AuthenticationProperties {
                    IsPersistent = rememberMe
                }, identity);

                return identity;
            }));
        }
Beispiel #52
0
 protected void CreateUser_Click(object sender, EventArgs e)
 {
     var userStore = new UserStore<IdentityUser>();
     var manager = new UserManager<IdentityUser>(userStore);
     var user = new IdentityUser() { UserName = UserName.Text };
     IdentityResult result = manager.Create(user, Password.Text);
     if (result.Succeeded) {
         var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
         var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
         authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
         Response.Redirect("~/Login.aspx");
     } else {
         StatusMessage.Text = result.Errors.FirstOrDefault();
     }
 }
        private void SignIn(IdentityUser user)
        {
            if (user != null)
            {
                var userStore   = new UserStore <IdentityUser>();
                var userManager = new UserManager <IdentityUser>(userStore);

                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = false
                }, userIdentity);
            }
        }
Beispiel #54
0
    protected void Register_Click(object sender, EventArgs e)
    {
        var userStore = new UserStore <IdentityUser>();

        userStore.Context.Database.Connection.ConnectionString = "data source=PC-ITSIX61;initial catalog=Garage;integrated security=True;";
        var manager = new UserManager <IdentityUser>(userStore);

        var user = new IdentityUser();

        user.UserName = UserNameTB.Text;

        if (PasswordTB.Text.Equals(ConfirmPasswordTB.Text))
        {
            try
            {
                var result = manager.Create(user, PasswordTB.Text);

                if (result.Succeeded)
                {
                    var userInfo = new UserInformation();
                    userInfo.FirstName  = FirstName.Text;
                    userInfo.LastName   = LastName.Text;
                    userInfo.Address    = Address.Text;
                    userInfo.GUID       = user.Id;
                    userInfo.PostalCode = Convert.ToInt32(PostalCode.Text);
                    var userModel = new UserInformationModel();
                    userModel.InsertUserInformation(userInfo);
                    var autenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity         = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    autenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }
                else
                {
                    Status.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                Status.Text = ex.ToString();
            }
        }
        else
        {
            Status.Text = "Password and Confirm password must match";
        }
    }
Beispiel #55
0
        private bool SalvarUsuario(Usuario usuario)
        {
            bool retorno = false;

            //Obter a UserStore, UserManager
            var usuarioStore       = new UserStore <IdentityUser>();
            var usuarioGerenciador =
                new UserManager <IdentityUser>(usuarioStore);

            //criar uma entidade
            var usuarioInfo =
                new IdentityUser()
            {
                UserName = usuario.UserName
            };

            // Gravar na base de dados o usuario
            IdentityResult resultado =
                usuarioGerenciador.Create(usuarioInfo, usuario.Password);

            if (resultado.Succeeded)
            {
                //Autentica e volta para a página inicial
                var gerenciadorDeAutenticacao = HttpContext.GetOwinContext().Authentication;

                var identidadeUsuario =
                    usuarioGerenciador.CreateIdentity(usuarioInfo,
                                                      DefaultAuthenticationTypes.ApplicationCookie);

                gerenciadorDeAutenticacao.SignIn(
                    new AuthenticationProperties()
                {
                }, identidadeUsuario);

                // retorna verdadeiro se o registro foi salvo com sucesso
                retorno = true;
            }
            else
            {
                // houve algum erro ao salvar o registro, então retorna false
                retorno = false;

                // adicionamos o erro na ViewBag para ser capturado em nossa pagina de login
                ViewBag.Erro = resultado.Errors;
            }

            return(retorno);
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                    //add user to users db
                    using (DefaultConnectionEF db = new DefaultConnectionEF())
                    {

                        blogUser u = new blogUser();
                        u.userID = user.Id;
                        u.fName = txtFName.Text;
                        u.lName = txtLName.Text;

                        db.blogUsers.Add(u);
                        db.SaveChanges();

                    }
                    //redirect to main menu
                    Response.Redirect("/admin/bibleMenu.aspx");
                }
                else
                {
                    //lblStatus.Text = result.Errors.FirstOrDefault();
                    //lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/errors.aspx");
            }
        }
Beispiel #57
0
        public void HandleCommand(UserManager<User> userManager, string message, Player player)
        {
            try
            {
                string commandText = message.Split(' ')[0];
                message = message.Replace(commandText, "").Trim();
                commandText = commandText.Replace("/", "").Replace(".", "");

                string[] arguments = message.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

                foreach (var handlerEntry in _pluginCommands)
                {
                    CommandAttribute commandAttribute = handlerEntry.Value;
                    if (!commandText.Equals(commandAttribute.Command, StringComparison.InvariantCultureIgnoreCase)) continue;

                    MethodInfo method = handlerEntry.Key;
                    if (method == null) return;

                    var authorizationAttributes = method.GetCustomAttributes<AuthorizeAttribute>(true);
                    foreach (AuthorizeAttribute authorizationAttribute in authorizationAttributes)
                    {
                        User user = userManager.FindByName(player.Username);
                        var userIdentity = userManager.CreateIdentity(user, "none");
                        if (!authorizationAttribute.OnAuthorization(new GenericPrincipal(userIdentity, new string[0])))
                        {
                            player.SendMessage("You are not permitted to use this command!");
                            return;
                        }
                    }

                    var e = new HandleCommandActionEventArgs { RoleRequired = commandAttribute.RoleRequired, player = player, command = commandAttribute.Command };
                    HandleCommandAction(this, e);
                    if (e.Cancel)
                    {
                        player.SendMessage("[Perm] §cУ вас нет прав!");
                        return;
                    }

                    if (ExecuteCommand(method, player, arguments)) return;
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex);
            }
        }
Beispiel #58
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);
            var user = new IdentityUser() { UserName = UserName.Text, Email = Email.Text };

            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //insert necessary info into the user info table
                //make a connection to the database
            string cs = "Data Source=pbc2o8qyql.database.windows.net;Initial Catalog=Hero;User ID=apple;Password=skull!1223";
            SqlConnection conn = new SqlConnection(cs);

              //insert into database for new user. [hash the password?]
                SqlCommand insert = new SqlCommand("insert into [UserInfo]([Username], [Hero Gender], [Level], [currExp]) values(@username,@herogender, @level, @currExp)", conn);
                insert.Parameters.AddWithValue("@username", UserName.Text);
                insert.Parameters.AddWithValue("@herogender", gender.SelectedValue);
                insert.Parameters.AddWithValue("@level", "1");
                insert.Parameters.AddWithValue("@currExp", "0");
                try
                {
                    conn.Open();
                    insert.ExecuteNonQuery();

                }
                catch (Exception ex)
                {
                    conn.Close();
                }

                Response.Redirect("~/Login.aspx");

            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        public HttpResponseMessage Post([FromBody]LoginPasswordUser user)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();

            //Set ConnectionString to GarageConnectionString
            userStore.Context.Database.Connection.ConnectionString =
                System.Configuration.ConfigurationManager.ConnectionStrings["GarageConnectionString"].ConnectionString;
            var manager = new UserManager<IdentityUser>(userStore);

            //Create new user and try to store in DB.
            var iUser = new IdentityUser { UserName = user.login };

            IdentityResult result = manager.Create(iUser, user.password);
            if (result.Succeeded)
            {
                UserDetail userDetail = new UserDetail
                {
                    Address = user.user.Address,
                    FirstName = user.user.FirstName,
                    LastName = user.user.LastName,
                    Guid = iUser.Id,
                    PostalCode = Convert.ToInt32(user.user.PostalCode)
                };

                UserDetailFacade facade = new UserDetailFacade(db);
                facade.Insert(userDetail);

                //Store identity-user in DB
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(iUser, DefaultAuthenticationTypes.ApplicationCookie);

                //If succeedeed, log in the new user and set the cookie
                authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "Bruger er registreret");
                return response;
            }
            else
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, result.Errors.ToString());
                return response;
            }
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                //create a new user using the selected fields
                var user = new IdentityUser() {
                    UserName = txtUsername.Text,
                    Email = txtEmail.Text,
                    //FirstName = txtFirstName.Text,
                    //LastName = txtLastName.Text,
                    //Address = txtAddress.Text,
                    //PostalCode = txtPostalCode.Text,
                    //Province = ddlProvince.SelectedValue
                };

                //create a user with the current details
                IdentityResult result = manager.Create(user, txtPassword.Text);

                //if creation was a success
                if (result.Succeeded)
                {
                    //lblStatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);

                    //sign the user in and redirect to products page
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/admin/products.aspx", false);
                }
                else
                {
                    //if failed, display an error message
                    lblStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/Error.aspx?Message=" + ex.Message);
            }
        }