Ejemplo n.º 1
0
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    try
                    {
                        //let us take out the username now                
                        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                        int v = 0;
                        String userRole = "";
                        using (UsersContext entities = new UsersContext())
                        {
                            RegisteredUser user = entities.RegisteredUsers.SingleOrDefault(u => u.UserName == username);
                            Applicant applicant = entities.Applicants.SingleOrDefault(u => u.RegisteredUserRefId == user.RegisteredUserID);
                            if (applicant != null)
                            {
                                userRole = "Applicant;User";
                            }
                            SystemAdmin admin = entities.SystemAdmins.SingleOrDefault(u => u.RegisteredUserRefId == user.RegisteredUserID);
                            if (admin != null)
                            {
                                userRole = "Admin;User";
                            }
                            GeneralUser generalUser=entities.GeneralUsers.SingleOrDefault(u => u.RegisteredUserRefId == user.RegisteredUserID);
                            if (generalUser != null)
                            {
                                userRole = "GeneralUser;User";
                            }
                            else if (user != null && applicant==null&&admin==null&&generalUser==null)
                            {
                                userRole = "User";
                            }

                        }

                        //let us extract the roles from our own custom cookie


                        //Let us set the Pricipal with our user specific details
                        System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                          new System.Security.Principal.GenericIdentity(username, "Forms"), userRole.Split(';'));
                    }
                    catch (Exception)
                    {
                        //somehting went wrong
                    }
                }
            }
        } 
        public ActionResult Login(RegisteredUser model, string returnUrl)
        {


            using (UsersContext entities = new UsersContext())
            {
                string username = model.UserName;
                string password = model.Password;
                Debug.AutoFlush = true;

                // Now if our password was enctypted or hashed we would have done the
                // same operation on the user entered password here, But for now
                // since the password is in plain text lets just authenticate directly
                var currentUser = entities.RegisteredUsers.SingleOrDefault(user => user.UserName == username);
                bool userValid=false; 
                if (currentUser != null) { 
                    userValid = currentUser.UserName.Equals(username) && currentUser.Password.Equals(password);
                }
                // User found in the database
                if (userValid)
                {

                    FormsAuthentication.SetAuthCookie(username, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {

                        return Redirect(returnUrl);
                    }
                    else
                    {
                        UsersContext db = new UsersContext();
                        RegisteredUser registeredUser = new UsersContext().RegisteredUsers.SingleOrDefault(user => user.UserName == username);
                        registeredUser.IsActivated = "Yes";
                        db.Entry(registeredUser).State = EntityState.Modified;
                        db.SaveChanges();
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "আপনার নাম অথবা পাসওয়ার্ডটি ভুল হয়েছে.");
                }
            }


            // If we got this far, something failed, redisplay form
            return View(model);

        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

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

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

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

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

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

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

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