Esempio n. 1
0
        public async Task Reload()
        {
            MicroLogger.LogDebug("Reloading data sets from Server");
            await TinyIoCContainer.Current.Resolve <OrderManager>().Load();

            await TinyIoCContainer.Current.Resolve <ProductManager>().Load();
        }
Esempio n. 2
0
        private Task <AuthState> PerformTokenRequest(TokenRequest request)
        {
            MicroLogger.LogDebug($"Request token {request.AuthorizationCode}");
            var tcs = new TaskCompletionSource <AuthState>();

            authService.PerformTokenRequest(request, ClientAuthentication,
                                            (TokenResponse tokenResponse, AuthorizationException authException) =>
            {
                if (tokenResponse != null)
                {
                    MicroLogger.LogDebug("Token request complete");
                    var authState = GetAuthState();
                    if (tokenResponse?.AccessTokenExpirationTime == null)
                    {
                        tokenResponse.AccessTokenExpirationTime = new Java.Lang.Long(
                            DateTimeOffset.Now
                            .AddMinutes(AuthConstants.ExpirationPeriodMinutes)
                            .ToUnixTimeMilliseconds()
                            );
                    }

                    authState.Update(tokenResponse, authException);
                    SetAuthState(authState);

                    tcs.SetResult(authState);
                }
                else
                {
                    throw authException;
                }
            });
            return(tcs.Task);
        }
Esempio n. 3
0
        public async Task SetValue(Uri requestUri, string version, string content, string mediaType)
        {
            var properties = GetProperties();

            if (properties.TryGetValue(requestUri.AbsolutePath, out var value))
            {
                if (value.RequiredVersion != value.ContentVersion)
                {
                    value.ContentVersion = version;
                    value.MediaType      = mediaType;

                    File.WriteAllText(GetFileName(value), content);
                }
                else
                {
                    MicroLogger.LogWarning("Cache same version error");
                }
            }
            else
            {
                value = new PropertiesObject
                {
                    UrlPath         = requestUri.AbsolutePath,
                    MediaType       = mediaType,
                    ContentVersion  = version,
                    RequiredVersion = version,
                    FileName        = Path.GetRandomFileName()
                };
                properties.Add(requestUri.AbsolutePath, value);

                File.WriteAllText(GetFileName(value), content);
            }

            await StoreProperties();
        }
Esempio n. 4
0
        private static async Task <TResult> AskRetryOnHttpStatusFail <TResult>(Func <Task <TResult> > requestFunction, int retryCounter)
            where TResult : new()
        {
            try
            {
                return(await requestFunction());
            }
            catch (HttpStatusCodeException ex)
            {
                MicroLogger.LogError(ex.Message);

                if (retryCounter < MaxRetries)
                {
                    await App.Current.MainPage.DisplayAlert(GeneralResources.ServerRequestFailedTitle, GeneralResources.ServerRequestFailedRetryMsg, GeneralResources.AlertRetry);

                    return(await AskRetryOnHttpStatusFail(requestFunction, retryCounter + 1));
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert(GeneralResources.ServerRequestFailedTitle, GeneralResources.ServerRequestFailedRetryMsg, GeneralResources.AlertExit);

                    DependencyService.Get <INativeAppService>().ExitApp();
                    return(new TResult());
                }
            }
        }
Esempio n. 5
0
        public async Task <(bool IsSucessful, string Error)> Login(Urls.OIDCUrls urls)
        {
            var configuration = new AuthorizationServiceConfiguration(
                ToUrl(urls.Authorization),
                ToUrl(urls.Token)
                );

            var authRequestBuilder = new AuthorizationRequest.Builder(
                configuration,
                AuthConstants.ClientId,
                ResponseTypeValues.Code,
                global::Android.Net.Uri.Parse(AuthConstants.RedirectUri)
                ).SetScope(AuthConstants.Scope);

            if (AuthConstants.Scope.Contains("offline_access"))
            {
                authRequestBuilder = authRequestBuilder.SetPrompt("consent");
            }
            var authRequest = authRequestBuilder.Build();

            MicroLogger.LogDebug("Making auth request to " + configuration.AuthorizationEndpoint);
#pragma warning disable IDE0059 // Unnecessary assignment of a value
            var intent = authService.GetAuthorizationRequestIntent(authRequest);
#pragma warning restore IDE0059 // Unnecessary assignment of a value

            taskCompletitionSource = new TaskCompletionSource <AuthState>();

            authService.PerformAuthorizationRequest(
                authRequest,
                AuthActivity.CreatePostAuthorizationIntent(
                    _context,
                    authRequest),
                authService.CreateCustomTabsIntentBuilder().Build()
                );

            var state = await taskCompletitionSource.Task;
            if (state.AuthorizationException != null)
            {
                return(false, state.AuthorizationException.ErrorDescription);
            }
            else
            {
                return(true, null);
            }
        }
Esempio n. 6
0
        internal void AuthActivityCreated(AuthorizationResponse resp, AuthorizationException ex)
        {
            var authState = GetAuthState();

            authState.Update(resp, ex);

            if (resp != null)
            {
                MicroLogger.LogDebug("Received AuthorizationResponse.");
                SetAuthState(authState);
                PerformTokenRequest(resp.CreateTokenExchangeRequest())
                .ContinueWith(t => taskCompletitionSource.SetResult(t.Result));
            }
            else
            {
                MicroLogger.LogError("Auth failed: " + ex);
                taskCompletitionSource.SetResult(authState);
            }
        }
Esempio n. 7
0
        public async Task Load()
        {
            MicroLogger.LogDebug("Loading Products");
            var items = await _restService.GetProducts();

            Products.Clear();
            var favorite = Preferences.Get(nameof(ProductViewModel.Favorite), 0, nameof(ProductManager));

            foreach (var item in items)
            {
                var model = new ProductViewModel(item);
                Products.Add(model);

                if (item.Id == favorite)
                {
                    model.Favorite = true;
                    _favorite      = model;
                }
            }
            MicroLogger.LogDebug("Loading Products Done");
        }
Esempio n. 8
0
        private async Task <AuthState> PerformRefresh(AuthState authState)
        {
            MicroLogger.LogDebug(nameof(PerformRefresh));

            var request = authState.TokenRefreshRequest();

            try
            {
                var tokenResponse = await AuthorizationService.PerformTokenRequestAsync(request);

                MicroLogger.LogDebug($"Received token response with accessToken: {tokenResponse.AccessToken}");

                authState.Update(tokenResponse, null);
            }
            catch (NSErrorException ex)
            {
                authState.Update(ex.Error);

                MicroLogger.LogError($"Token exchange error: {ex}");
            }
            return(authState);
        }
Esempio n. 9
0
        public async Task Load()
        {
            MicroLogger.LogDebug("Loading Account");
            var info = await _restService.GetAccountInfo();

            Info.Set(info);

            MicroLogger.LogDebug("Loading Purchases");
            var items = info.Orders;

            Items.Clear();

            foreach (var item in items)
            {
                Items.Add(GetViewModel(item));
            }
            MicroLogger.LogDebug("Loading Orders Done");

            if (await _cache.SetRequiredVersionToAll(info.DataVersion))
            {
                await TinyIoCContainer.Current.Resolve <ProductManager>().Load();
            }
        }
Esempio n. 10
0
        public async Task <(bool, string)> AuthWithAutoCodeExchange(Urls.OIDCUrls urls)
        {
            MicroLogger.LogDebug(nameof(AuthWithAutoCodeExchange));
            var redirectURI = new NSUrl(AuthConstants.RedirectUri);

            try
            {
                // discovers endpoints
                var configuration = new ServiceConfiguration(ToUrl(urls.Authorization), ToUrl(urls.Token));

                MicroLogger.LogDebug($"Got configuration: {configuration}");

                // builds authentication request
                var request = new AuthorizationRequest(configuration, AuthConstants.ClientId, AuthConstants.ClientSecret, AuthConstants.ScopesArray, redirectURI, ResponseType.Code, null);
                // performs authentication request
                var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
                MicroLogger.LogDebug($"Initiating authorization request with scope: {request.Scope}");

                var tcl = new TaskCompletionSource <(bool, string)>();

                appDelegate.CurrentAuthorizationFlow = AuthState
                                                       .PresentAuthorizationRequest(request, appDelegate.Window.RootViewController, (authState, error) =>
                {
                    MicroLogger.LogDebug(nameof(AuthState.PresentAuthorizationRequest) + "Done");
                    if (authState != null)
                    {
                        AuthService.SaveState(authState);
                        MicroLogger.LogDebug($"Got authorization tokens. Access token: {authState.LastTokenResponse.AccessToken}");
                        tcl.SetResult((true, null));
                    }
                    else
                    {
                        MicroLogger.LogError($"Authorization error: {error.LocalizedDescription}");
                        AuthService.ClearState();
                        tcl.SetResult((false, error.LocalizedDescription));
                    }
                });
Esempio n. 11
0
 public async Task <(bool IsSucessful, string Error)> Login(Api.Urls.OIDCUrls urls)
 {
     MicroLogger.LogDebug(nameof(Login));
     return(await AuthWithAutoCodeExchange(urls));
 }