protected void Application_Start()
        {
            //Set the data base initializer for the site. This will drop and re-create the database if any model changes are made.
            Database.SetInitializer(new UserRolesContextInitializer());

            //Force the context to initialize on app start... comment this line out after the site starts up for the first time!
            using (var context = new UserRolesContext())
            {
                context.Database.Initialize(true);
            }

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
        public ActionResult UpdateUserInfo(ManageNonPasswordModel model)
        {
            bool userExists = false;
            if (ModelState.IsValid)
            {
                using (var context = new UserRolesContext())
                {
                    var updateMe = context.UserProfiles.FirstOrDefault(x => x.UserId == model.UserId);
                    if (updateMe != null)
                    {
                        updateMe.FirstName = model.FirstName;
                        updateMe.LastName = model.LastName;
                        updateMe.PhoneNumber = model.PhoneNumber;
                        context.SaveChanges();
                        userExists = true;
                    }
                }
                if (userExists)
                    return RedirectToAction("Manage", new { Message = ManageMessageId.UdpateUserInfoSuccess });
            }

            return RedirectToAction("Manage", new { Message = ManageMessageId.UpdateUserInfoFailed });
        }
        //
        // GET: /Account/Manage
        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : message == ManageMessageId.UdpateUserInfoSuccess ? "User info updated successfully."
                : message == ManageMessageId.UpdateUserInfoFailed ? "There was an error while trying to update user info"
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));

            var userId = WebSecurity.GetUserId(User.Identity.Name);
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(userId);
            var model = new LocalPasswordModel();

            //Populate the user info stuff
            if (hasLocalAccount)
            {
                using (var context = new UserRolesContext())
                {
                    var user = context.UserProfiles.FirstOrDefault(x => x.UserId == userId);
                    model.UserInfo = new ManageNonPasswordModel
                        {
                            UserId = user.UserId,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            PhoneNumber = user.PhoneNumber
                        };
                }
            }

            ViewBag.ReturnUrl = Url.Action("Manage");
            return View(model);
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

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

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new UserRolesContext())
                {
                    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);
        }
        /// <summary>
        /// Get a collection of permissions for each controller on the site that inherit from base controller.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<CustomPermissionViewModel> GetAllControllerPermissions()
        {
            _urlLookupList.Clear();
            var permissions = new List<CustomPermissionViewModel>();
            var assembly = Assembly.GetCallingAssembly();
            Type baseType = typeof(BaseController);
            var controllers = assembly.GetTypes().Where(x => baseType.IsAssignableFrom(x) && x.Name != "BaseController");

            foreach (var crtl in controllers)
            {
                var methods = crtl.GetMethods().Where(x => x.ReturnType == typeof(ActionResult));
                var controllerName = crtl.Name.Replace("Controller", "");
                foreach (var method in methods)
                {
                    //Ignore if the method has an anonymous attribute
                    var anonymous =
                        method.CustomAttributes.FirstOrDefault(attr => attr.AttributeType.Name == "AllowAnonymousAttribute");
                    if (anonymous != null)
                    {
                        //Add an anonymous user to the controller and method
                        var permission = new CustomPermissionViewModel
                        {
                            ControllerName = controllerName,
                            ActionName = method.Name,
                            UserNames = new List<string>(new[] { Constants.ANONYMOUS_USER }),
                            Roles = new List<string>()
                        };
                        permissions.Add(permission);

                        //Keep a list of all the available URLs
                        _urlLookupList.Add(new UrlLookupHelper
                        {
                            ActionName = permission.ActionName,
                            ControllerName = permission.ControllerName,
                            Url = permission.Url
                        });
                        continue;
                    }

                    var permissionExists =
                        permissions.FirstOrDefault(
                            x => x.ActionName == method.Name && x.ControllerName == controllerName);

                    //Only add the new permission if there is not already a permission for the current controller / action
                    if (permissionExists == null)
                    {
                        var permission = new CustomPermissionViewModel
                        {
                            ControllerName = controllerName,
                            ActionName = method.Name,
                            UserNames = new List<string>(),
                            Roles = new List<string>()
                        };

                        using (var context = new UserRolesContext())
                        {
                            var row = context.Permissions.FirstOrDefault(x => x.Action == permission.ActionName
                                                                              && x.Controller == permission.ControllerName);
                            if (row != null)
                            {
                                permission.UserNames = (row.UserNames != null) ? row.UserNames.Split(new[] { ',' }).ToList() : new List<string>();
                                permission.Roles = (row.RoleNames != null) ? row.RoleNames.Split(new[] { ',' }).ToList() : new List<string>();
                                permission.CustomPermissionId = row.CustomPermissionId;
                            }
                        }

                        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                        permission.Url = urlHelper.Action(permission.ActionName, permission.ControllerName);

                        permissions.Add(permission);

                        //Keep a list of all the available URLs
                        _urlLookupList.Add(new UrlLookupHelper
                            {
                                ActionName = permission.ActionName,
                                ControllerName = permission.ControllerName,
                                Url = permission.Url
                            });
                    }
                }
            }

            return permissions;
        }
        /// <summary>
        /// Update the permissions in the database 
        /// </summary>
        /// <param name="permission">A CustomPermissionViewModel</param>
        public static void UpdateSecurityPermission(CustomPermissionViewModel permission)
        {
            using (var context = new UserRolesContext())
            {
                //Get the appropriate action and controller for the updated URL...
                var lookup = _urlLookupList.FirstOrDefault(x => x.Url == permission.Url);

                var roleList = "";
                var userList = "";
                if (permission.Roles != null) permission.Roles.ForEach(role => roleList += (roleList == "") ? role : "," + role);
                if (permission.UserNames != null) permission.UserNames.ForEach(userName => userList += (userList == "") ? userName : "******" + userName);

                var updateMe =
                    context.Permissions.FirstOrDefault(x => x.CustomPermissionId == permission.CustomPermissionId);

                if (updateMe != null)
                {
                    updateMe.Controller = lookup.ControllerName;
                    updateMe.Action = lookup.ActionName;
                    updateMe.RoleNames = roleList;
                    updateMe.UserNames = userList;
                }else
                {
                    var addMe = new CustomPermission();
                    addMe.Action = lookup.ActionName;
                    addMe.Controller = lookup.ControllerName;
                    addMe.RoleNames = roleList;
                    addMe.UserNames = userList;
                    context.Permissions.Add(addMe);
                }

                context.SaveChanges();
            }
        }