Example #1
0
        private void GetRolesForUserCore(IIdentity identity)
        {
            // (new PermissionSet(PermissionState.Unrestricted)).Assert(); //

            CookieContainer cookies = null;

            if (identity is ClientFormsIdentity)
            {
                cookies = ((ClientFormsIdentity)identity).AuthenticationCookies;
            }

            if (_UsingWFCService)
            {
                throw new NotImplementedException();

//                 CustomBinding binding = ProxyHelper.GetBinding();
//                 ChannelFactory<RolesService> channelFactory = new ChannelFactory<RolesService>(binding, new EndpointAddress(GetServiceUri())); //(@"http://localhost/AuthSvc/service.svc"));
//                 RolesService clientService = channelFactory.CreateChannel();
//                 using (new OperationContextScope((IContextChannel)clientService)) {
//                     ProxyHelper.AddCookiesToWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider);
//                     _Roles = clientService.GetRolesForCurrentUser();
//                     if (_Roles == null)
//                         _Roles = new string[0];
//                     ProxyHelper.GetCookiesFromWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider);
//                 }
            }
            else
            {
                object o = ProxyHelper.CreateWebRequestAndGetResponse(GetServiceUri() + "/GetRolesForCurrentUser",
                                                                      ref cookies,
                                                                      identity.Name,
                                                                      _ConnectionString,
                                                                      _ConnectionStringProvider,
                                                                      null,
                                                                      null,
                                                                      typeof(string []));
                if (o != null)
                {
                    _Roles = (string [])o;
                }
                else
                {
                    _Roles = new string[0];
                }
            }
            _CacheExpiryDate = DateTime.UtcNow.AddMinutes(_CacheTimeout);
        }
        public void Logout()
        {
            IPrincipal p = Thread.CurrentPrincipal;

            if (p == null || !(p.Identity is ClientFormsIdentity))
            {
                return;
            }
            lock (this) {
                if (!ConnectivityStatus.IsOffline)
                {
                    CookieContainer cookies = ((ClientFormsIdentity)p.Identity).AuthenticationCookies;

                    if (_UsingWFCService)
                    {
                        throw new NotImplementedException();

//                         CustomBinding binding = ProxyHelper.GetBinding();
//                         ChannelFactory<LoginService> channelFactory = new ChannelFactory<LoginService>(binding, new EndpointAddress(GetServiceUri()));
//                         LoginService clientService = channelFactory.CreateChannel();
//                         using (new OperationContextScope((IContextChannel)clientService)) {
//                             ProxyHelper.AddCookiesToWCF(cookies, GetServiceUri(), p.Identity.Name, _ConnectionString, _ConnectionStringProvider);
//                             clientService.Logout();
//                             ProxyHelper.GetCookiesFromWCF(cookies, GetServiceUri(), p.Identity.Name, _ConnectionString, _ConnectionStringProvider);
//                         }
                    }
                    else
                    {
                        ProxyHelper.CreateWebRequestAndGetResponse(GetServiceUri() + "/Logout",
                                                                   ref cookies,
                                                                   p.Identity.Name,
                                                                   _ConnectionString,
                                                                   _ConnectionStringProvider,
                                                                   null,
                                                                   null,
                                                                   null);
                    }
                }
                SqlHelper.DeleteAllCookies(p.Identity.Name, _ConnectionString, _ConnectionStringProvider);
                Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            }
            StoreLastUserNameInOffileStore(null);
            if (UserValidated != null)
            {
                UserValidated(this, new UserValidatedEventArgs(""));
            }
        }
        public event EventHandler <UserValidatedEventArgs> UserValidated; /*{
                                                                           * add { _UserValidated += value; }
                                                                           * remove { _UserValidated -= value; }
                                                                           * }
                                                                           * private event EventHandler<UserValidatedEventArgs> _UserValidated; */
        /////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////
        // Private methods
        private bool ValidateUserCore(string username, string password, int rememberMeInt, ref int promptCount, bool tryToUseLastLoggedInUser)
        {
            // (new PermissionSet(PermissionState.Unrestricted)).Assert(); //

            string          currentUser             = null;
            bool            validated               = false;
            string          lastLoggedInUser        = (tryToUseLastLoggedInUser ? GetLastUserNameFromOffileStore() : null);
            bool            usernameNotSupplied     = string.IsNullOrEmpty(username);
            CookieContainer cookies                 = null;
            bool            sameAsLastLoggedInUser  = false;
            bool            rememberMe              = (rememberMeInt == 1);
            bool            rememberMeExplicitlySet = (rememberMeInt != 2);

            if (Thread.CurrentPrincipal != null && Thread.CurrentPrincipal.Identity is ClientFormsIdentity)
            {
                currentUser = Thread.CurrentPrincipal.Identity.Name;
            }
            if (string.IsNullOrEmpty(lastLoggedInUser) && currentUser != null)
            {
                lastLoggedInUser = currentUser;
            }

            ///////////////////////////////////////////////////////////////
            // Step 1: If username not supplied, use the last remembered user
            if (usernameNotSupplied)
            {
                username = lastLoggedInUser;
            }

            if ((Thread.CurrentPrincipal is ClientRolePrincipal) && (Thread.CurrentPrincipal.Identity is ClientFormsIdentity) && Thread.CurrentPrincipal.Identity.Name == username)
            {
                cookies = ((ClientFormsIdentity)Thread.CurrentPrincipal.Identity).AuthenticationCookies;
            }

            ///////////////////////////////////////////////////////////////
            // Step 2: If username is same as the last remembered user,
            //         try authenticating by looking in the cookie store and calling the
            //          WebService if we are on-line
            if (!string.IsNullOrEmpty(lastLoggedInUser) && string.Compare(lastLoggedInUser, username, StringComparison.OrdinalIgnoreCase) == 0)
            {
                if (!ConnectivityStatus.IsOffline)
                {
                    validated = ValidateByCallingIsLoggedIn(lastLoggedInUser, ref cookies);
                }
                else
                {
                    validated = ProxyHelper.DoAnyCookiesExist(GetServiceUri(), lastLoggedInUser, _ConnectionString, _ConnectionStringProvider);
                }
                sameAsLastLoggedInUser = true;
            }


            if (!validated)
            {
                ///////////////////////////////////////////////////////////////
                // Step 3: If username is not supplied, then prompt for it
                if (usernameNotSupplied)
                {
                    promptCount++;
                    if (!GetCredsFromUI(ref username, ref password, ref rememberMe))
                    {
                        promptCount += 100; // don't prompt again
                        return(false);
                    }
                    rememberMeExplicitlySet = true;
                }

                if (!ConnectivityStatus.IsOffline)
                {
                    ///////////////////////////////////////////////////////////////
                    // Step 4: If app is online, connect to the server
                    if (!ValidateUserByCallingLogin(username, password, rememberMe, GetServiceUri(),
                                                    _UsingWFCService, ref cookies,
                                                    _ConnectionString, _ConnectionStringProvider))
                    {
                        return(false);
                    }
                    // Store hash of password
                    StoreHashedPasswordInDB(username, password);
                }
                else
                {
                    ///////////////////////////////////////////////////////////////
                    // Step 5: If app is offline, validate with offline store
                    if (!ValidateUserWithOfflineStore(username, password))
                    {
                        return(false);
                    }
                }
            }

            ///////////////////////////////////////////////////////////////
            // Step 6: Store last logged in user
            if (!sameAsLastLoggedInUser || rememberMeExplicitlySet)
            {
                StoreLastUserNameInOffileStore(rememberMe ? username : null);
            }

            ///////////////////////////////////////////////////////////////
            // Step 7: Save principal
            if (!(Thread.CurrentPrincipal is ClientRolePrincipal) || !(Thread.CurrentPrincipal.Identity is ClientFormsIdentity) || Thread.CurrentPrincipal.Identity.Name != username)
            {
                if (cookies == null)
                {
                    cookies = ProxyHelper.ConstructCookieContainer(GetServiceUri(), username, _ConnectionString, _ConnectionStringProvider);
                }
                Thread.CurrentPrincipal = new ClientRolePrincipal(new ClientFormsIdentity(username, password, this, "ClientForms", true, cookies));
            }
            if (currentUser != null && string.Compare(username, currentUser, StringComparison.OrdinalIgnoreCase) != 0)
            {
                SqlHelper.DeleteAllCookies(currentUser, _ConnectionString, _ConnectionStringProvider);
            }

            return(true);
        }
        private void GetPropertyValuesFromWebCore(bool bubbleExceptionFromSvc)
        {
            string []       propertyNames = new string[_Properties.Count];
            int             iter          = 0;
            CookieContainer cookies       = null;
            IIdentity       id            = Thread.CurrentPrincipal.Identity;

            foreach (SettingsProperty setting in _Properties)
            {
                propertyNames[iter++] = setting.Name;
            }

            if (id is ClientFormsIdentity)
            {
                cookies = ((ClientFormsIdentity)id).AuthenticationCookies;
            }

            if (_UsingWFCService)
            {
                throw new NotImplementedException();

//                 CustomBinding                    binding        = ProxyHelper.GetBinding();
//                 ChannelFactory<ProfileService>   channelFactory = new ChannelFactory<ProfileService>(binding, new EndpointAddress(GetServiceUri()));
//                 ProfileService                   clientService  = channelFactory.CreateChannel();
//                 Dictionary<string, object>       propertyValues = null;


//                 using (new OperationContextScope((IContextChannel)clientService)) {
//                     ProxyHelper.AddCookiesToWCF(cookies, GetServiceUri(), id.Name, GetConnectionString(), _ConnectionStringProvider);
//                     propertyValues = clientService.GetPropertiesForCurrentUser(propertyNames, id.IsAuthenticated && (id is ClientFormsIdentity));
//                     ProxyHelper.GetCookiesFromWCF(cookies, GetServiceUri(), id.Name, GetConnectionString(), _ConnectionStringProvider);
//                 }

//                 for(iter = 0; iter<propertyNames.Length; iter++) {
//                     string name = propertyNames[iter];
//                     if (!propertyValues.ContainsKey(name))
//                         continue;
//                     SettingsProperty setting = _Properties[name];
//                     if (setting == null)
//                         continue; // Bad -- why wasn't it found?
//                     bool mustAdd = false;
//                     SettingsPropertyValue value = _PropertyValues[setting.Name];
//                     if (value == null) {
//                         value = new SettingsPropertyValue(setting);
//                         mustAdd = true;
//                     }

//                     //if ((value.SerializedValue is string) && ((string)value.SerializedValue == "(null)")) {
//                     value.PropertyValue = propertyValues[name];
//                     value.Deserialized = true;
//                     //                 } else if (setting.SerializeAs == SettingsSerializeAs.Binary)
//                     //                     value.SerializedValue = Convert.FromBase64String(propertyValues[iter]);
//                     //                 else
//                     //                     value.SerializedValue = propertyValues[iter];
//                     //                 value.Deserialized = false;
//                     value.IsDirty = false;
//                     if (mustAdd)
//                         _PropertyValues.Add(value);
//                 }
            }
            else
            {
                string [] paramNames  = new string [] { "properties", "authenticatedUserOnly" };
                object [] paramValues = new object [] { propertyNames, id.IsAuthenticated&& (id is ClientFormsIdentity) };
                object    obj         = null;
                try {
                    obj = ProxyHelper.CreateWebRequestAndGetResponse(
                        GetServiceUri() + "/GetPropertiesForCurrentUser",
                        ref cookies,
                        id.Name,
                        _ConnectionString,
                        _ConnectionStringProvider,
                        paramNames,
                        paramValues,
                        typeof(Dictionary <string, object>));
                } catch {
                    if (bubbleExceptionFromSvc)
                    {
                        throw;
                    }
                }

                if (obj != null)
                {
                    Dictionary <string, object> ret = (Dictionary <string, object>)obj;

                    foreach (KeyValuePair <string, object> de in ret)
                    {
                        SettingsProperty setting = _Properties[(string)de.Key];
                        if (setting == null)
                        {
                            continue; // Bad -- why wasn't it found?
                        }
                        bool mustAdd = false;
                        SettingsPropertyValue value = _PropertyValues[setting.Name];
                        if (value == null)
                        {
                            value   = new SettingsPropertyValue(setting);
                            mustAdd = true;
                        }

                        if (de.Value != null && !setting.PropertyType.IsAssignableFrom(de.Value.GetType()))
                        {
                            object convertedValue = null;
                            if (!ObjectConverter.TryConvertObjectToType(de.Value,
                                                                        setting.PropertyType,
                                                                        new JavaScriptSerializer(),
                                                                        out convertedValue))
                            {
                                // Failure to convert!
                                continue;
                            }
                            value.PropertyValue = convertedValue;
                        }
                        else
                        {
                            value.PropertyValue = de.Value;
                        }

                        value.Deserialized = true;
                        value.IsDirty      = false;
                        if (mustAdd)
                        {
                            _PropertyValues.Add(value);
                        }
                    }
                }
            }
        }