Ejemplo n.º 1
0
        private async Task HandleHttpResponse(HttpResponseMessage response)
        {
            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                if (_onOK != null)
                {
                    await _onOK(response);
                }
                break;

            case System.Net.HttpStatusCode.BadRequest:
                if (_onBadRequest != null)
                {
                    await _onBadRequest(response);
                }
                break;

            case System.Net.HttpStatusCode.Unauthorized:
            case System.Net.HttpStatusCode.Forbidden:
                uriHelper.NavigateTo("/login");
                break;

            case System.Net.HttpStatusCode.InternalServerError:
                JsInterop.Toastr("error", "A server error occured, sorry");
                break;
                //other case , we do nothing, I'll add this case as needed
            }
        }
Ejemplo n.º 2
0
        private async Task HandleResponse(HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                await _onOK(response);
            }
            else
            {
                switch (response.StatusCode)
                {
                case HttpStatusCode.Unauthorized:
                    _util.ShowLoginModal();
                    break;

                case HttpStatusCode.Forbidden:
                    _uriHelper.NavigateTo("/403");
                    break;

                case HttpStatusCode.InternalServerError:
                    _toastr.Error("An error happened at server. Please try again.");
                    break;

                case HttpStatusCode.NotFound:
                    _uriHelper.NavigateTo("/404");
                    break;
                }
            }
        }
Ejemplo n.º 3
0
        public async Task <T> GetJsonAuthorizedAsync <T>(string uri)
        {
            TryRetrieveToken();

            var response = await _httpClient.GetAsync("api/Gambler");

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                _uriHelper.NavigateTo($"/login?returnUrl={_uriHelper.GetAbsoluteUri()}");

                return(await Task.FromResult(default(T)));
            }

            return(await _httpClient.GetJsonAsync <T>(uri));
        }
Ejemplo n.º 4
0
 /// <see cref="Middleware.OnInternalMiddlewareChangeEnding"/>
 protected override void OnInternalMiddlewareChangeEnding()
 {
     if (Feature.State.Uri != UriHelper.GetAbsoluteUri())
     {
         UriHelper.NavigateTo(Feature.State.Uri);
     }
 }
Ejemplo n.º 5
0
        protected async override Task HandleAsync(AuthenticateAction action, IDispatcher dispatcher)
        {
            var currentUri = _uriHelper.GetAbsoluteUri();
            var host       = new Uri(currentUri).Host;
            var clientId   = new Guid("62c98281-193a-4884-a3a3-131eac593dff");

            if (host.Contains("jimhillr.dev"))
            {
                clientId = new Guid("1f14efd2-38c7-4dbd-a834-6b07233e1fb2");
            }
            var uriBuilder = new UriBuilder();

            uriBuilder.Scheme = "https";
            uriBuilder.Host   = "6umby.b2clogin.com";
            uriBuilder.Path   = "6umby.onmicrosoft.com/oauth2/v2.0/authorize";
            uriBuilder.Query  =
                "p=B2C_1_GumbySignUpSignIn" +
                "&client_id=" + clientId.ToString() +
                "&nonce=defaultNonce" +
                "&redirect_uri=" + currentUri +
                "&scope=openid" +
                "&response_type=id_token" +
                "&prompt=login";
            _uriHelper.NavigateTo(uriBuilder.ToString());
        }
Ejemplo n.º 6
0
        private void OnChange(EventArgs e)
        {
            var handler = Change;

            handler?.Invoke(this, e);

            var getLocation = _options.GetLocation;

            if (getLocation == null)
            {
                return;
            }
            var newLocation = getLocation(State);

            if (newLocation == _currentLocation || newLocation == null)
            {
                return;
            }

            lock (_syncRoot)
            {
                _currentLocation = newLocation;
            }

            _uriHelper.NavigateTo(newLocation);
        }
Ejemplo n.º 7
0
        private async Task <bool> ProblemWithQuery()
        {
            if (Http.DefaultRequestHeaders.Contains("Authorization"))
            {
                await serviceOfAuthorize.Logout();

                UriHelper.NavigateTo("/Login");
                return(false);
            }
            var result = await serviceOfAuthorize.Login();

            if (result == null)
            {
                UriHelper.NavigateTo("/Login");
            }
            return(true);
        }
Ejemplo n.º 8
0
        public async Task CreateOrder()
        {
            await _ordersService.CreateAsync();

            await Task.Delay(1000);

            _uriHelper.NavigateTo("/orders");
        }
        public void CheckPageAuth(List <string> requiredRoles = null)
        {
            Console.WriteLine("In Check Auth");
            Console.WriteLine($"_isLoggedIn = {_isLoggedIn}");
            if (!_isLoggedIn)
            {
                _uriHelper.NavigateTo("/signin");
            }

            if (requiredRoles != null)
            {
                bool result = _roles.Intersect(requiredRoles).Any();
                if (!result)
                {
                    _uriHelper.NavigateTo("/error403");
                }
            }
        }
Ejemplo n.º 10
0
 public Task EnsureAuthz(UserModel userState)
 {
     if (userState?.AccessToken != null && userState.Profile != null)
     {
         return(Task.CompletedTask);
     }
     _uriHelper.NavigateTo("/unauthorized");
     return(Task.CompletedTask);
 }
Ejemplo n.º 11
0
        public static async Task Login(Dispatcher <IAction> dispatch, HttpClient http, UserModel user, IUriHelper helper)
        {
            dispatch(new ClearUserAction());

            var createdUser = await http.PostJsonAsync <UserModel>("/api/accounts/login", user);

            dispatch(new UserLoggedInAction(createdUser));

            helper.NavigateTo("/");
        }
Ejemplo n.º 12
0
        public async Task Logout()
        {
            await _localStorage.RemoveItem("authToken");

            _httpClient.DefaultRequestHeaders.Clear();

            IsLoggedIn = false;

            _uriHelper.NavigateTo("/login");
        }
Ejemplo n.º 13
0
        public override Task <IAction[]> HandleAsync(Go action)
        {
            Uri fullUri = UriHelper.ToAbsoluteUri(action.NewUri);

            if (fullUri.ToString() != UriHelper.GetAbsoluteUri())
            {
                // Only navigate if we are not already at the URI specified
                UriHelper.NavigateTo(action.NewUri);
            }
            return(Task.FromResult(new IAction[0]));
        }
Ejemplo n.º 14
0
        public async Task GetAllThreadsForBoard(int boardId)
        {
            var result = await _client.GetJsonAsync <BoardDTO>(API + "boards/" + boardId + "/threads/");

            if (result == null)
            {
                _uriHelper.NavigateTo("/404");
                return;
            }

            if (Board != null && Board.thread != null && Board.id == result.id)
            {
                result.thread = Board.thread;
            }

            result.threads = result.threads.OrderByDescending(e => e.bumpDate);
            Board          = result;
            NotifyStateChanged();
            return;
        }
Ejemplo n.º 15
0
        public static async Task AddAnimal(
            Dispatcher <IAction> dispatch,
            HttpClient http,
            Animal animalToAdd,
            IUriHelper helper)
        {
            await http.PostJsonAsync("/api/animals", animalToAdd);

            helper.NavigateTo("/animals");
            dispatch(new LoadAnimalsAction());
        }
Ejemplo n.º 16
0
        public static async Task AddFood(
            Dispatcher <IAction> dispatch,
            HttpClient http,
            FoodItem foodItemToAdd,
            IUriHelper helper)
        {
            await http.PostJsonAsync("/api/food", foodItemToAdd);

            helper.NavigateTo("/food");
            dispatch(new LoadFoodsAction());
        }
Ejemplo n.º 17
0
        protected override Task HandleAsync(Go action, IDispatcher dispatcher)
        {
            Uri fullUri = UriHelper.ToAbsoluteUri(action.NewUri);

            if (fullUri.ToString() != UriHelper.GetAbsoluteUri())
            {
                // Only navigate if we are not already at the URI specified
                UriHelper.NavigateTo(action.NewUri);
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 18
0
        protected async override Task HandleAsync(LogoutAction action, IDispatcher dispatcher)
        {
            await localStorage.RemoveItem("branch.name");

            await localStorage.RemoveItem("user.name");

            await localStorage.RemoveItem("token");

            api.BranchId = Guid.Empty;

            uriHelper.NavigateTo("/login");
        }
Ejemplo n.º 19
0
 public HttpApiClientRequestBuilder OnOK(string successMessage, string navigateTo = null)
 {
     OnOK(async() =>
     {
         if (!string.IsNullOrEmpty(successMessage))
         {
             await JsInterop.Toastr("success", successMessage);
         }
         uriHelper.NavigateTo(navigateTo);
     });
     return(this);
 }
        /// <summary>
        /// Opens PlanningPoker page with specified team name and member name.
        /// </summary>
        /// <param name="uriHelper">Helper to navigate to URL.</param>
        /// <param name="team">Scrum team name to include in URL.</param>
        /// <param name="member">Member name to include in URL.</param>
        public static void OpenPlanningPokerPage(IUriHelper uriHelper, ScrumTeam team, string member)
        {
            if (uriHelper == null)
            {
                throw new ArgumentNullException(nameof(uriHelper));
            }

            var urlEncoder = UrlEncoder.Default;
            var uri        = $"PlanningPoker/{urlEncoder.Encode(team.Name)}/{urlEncoder.Encode(member)}";

            uriHelper.NavigateTo(uri);
        }
Ejemplo n.º 21
0
        public async Task <Dictionary <string, List <string> > > Login(LoginCommand loginCommand)
        {
            Dictionary <string, List <string> > _errors = null;
            await http.Create("/api/account/login")
            .OnBadRequest <Dictionary <string, List <string> > > (errors => _errors = errors)
            .OnOK(() => {
                uriHelper.NavigateTo("/");
            })
            .Post(loginCommand);

            return(_errors);
        }
        public Task NavigateToAsync(object viewModel)
        {
            calledNavigateTo = true;

            BackStack.Push(CurrentViewModel);
            ForwardStack.Clear();
            CurrentViewModel = viewModel;

            var path = GeneratePath(viewModel);

            uriHelper.NavigateTo(path);
            return(Task.CompletedTask);
        }
Ejemplo n.º 23
0
        public async Task <Dictionary <string, List <string> > > Login(LoginCommand loginCommand, ElementRef loginButton)
        {
            Dictionary <string, List <string> > _errors = null;
            await http.Create("/api/account/login", loginButton)
            .OnBadRequest <Dictionary <string, List <string> > >(errors => _errors = errors)
            .OnOK(() =>
            {
                OnLoginDone?.Invoke(this, null);
                uriHelper.NavigateTo("/");
            })
            .Post(loginCommand);

            return(_errors);
        }
 public HttpApiClientRequestBuilder OnOK(string successMessage, string navigateTo = null)
 {
     OnOK(() =>
     {
         if (!string.IsNullOrEmpty(successMessage))
         {
             _messageService.Info(successMessage);
         }
         if (!string.IsNullOrEmpty(navigateTo))
         {
             _uriHelper.NavigateTo(navigateTo);
         }
     });
     return(this);
 }
Ejemplo n.º 25
0
        public async Task Initialise()
        {
            int done = 10;

            while (done-- > 0)
            {
                if (ComponentContext.IsConnected)
                {
                    try
                    {
                        await LocalisationHelper.BuildLocalCulture();

                        await LocalisationHelper.BuildLocalTimeZone();

                        if (!HasApiKey)
                        {
                            SetApiKey(await LocalStorage.GetItemAsync <string>("GitterKey"));
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (done == 1)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }

                await Task.Delay(1000);
            }
            if (HasApiKey)
            {
                initialised = true;
            }
            else
            {
                var currentUri  = UriHelper.GetAbsoluteUri();
                var baseUri     = UriHelper.GetBaseUri();
                var currentPage = UriHelper.ToBaseRelativePath(baseUri, currentUri);
                if (!currentPage.Equals(LOGINPAGE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(currentPage))
                {
                    UriHelper.NavigateTo(LOGINPAGE);
                }
            }
        }
Ejemplo n.º 26
0
        private void SynchronizeUriLocationWithState(object sender, EventArgs e)
        {
            if (_getLocation != null && _uriHelper != null)
            {
                var newLocation = _getLocation(State);
                if (newLocation != null)
                {
                    if (newLocation != _currentLocation)
                    {
                        lock (_syncRoot)
                        {
                            _currentLocation = newLocation;
                        }

                        _uriHelper.NavigateTo(newLocation);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <inheritdoc cref="IUserApiClient.SigninAsync" />
        public async Task SigninAsync()
        {
            var pkce  = crypto.CreatePkceData();
            var disco = await cache.GetAsync();

            var url  = new RequestUrl(disco.AuthorizeEndpoint);
            var auth = url.CreateAuthorizeUrl(
                options.ClientId,
                OidcConstants.ResponseTypes.Code,
                GetScopes(options.Scopes),
                options.RedirectUri,
                state: pkce.CodeVerifier,
                responseMode: OidcConstants.ResponseModes.Query,
                codeChallenge: pkce.CodeChallenge,
                codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256,
                uiLocales: CultureInfo.CurrentUICulture.EnglishName
                );

            uri.NavigateTo(auth);
        }
Ejemplo n.º 28
0
        protected async override Task HandleAsync(LoginAction action, IDispatcher dispatcher)
        {
            var userInfo = await api.PostAsyncUnauthorized <UserInfo, LoginInfo>("api/users/login", action.LoginInfo);

            if (userInfo != null)
            {
                await localStorage.SetItem("branch.name", userInfo.BranchName);

                await localStorage.SetItem("user.name", userInfo.UserName);

                await localStorage.SetItem("token", userInfo.Token);

                api.BranchId = new JwToken(userInfo.Token).BranchId;
                dispatcher.Dispatch(new LoginSuccessAction(userInfo));
                uriHelper.NavigateTo("/");
            }
            else
            {
                dispatcher.Dispatch(new LoginFailedAction("email or password is incorrect"));
            }
        }
Ejemplo n.º 29
0
        protected async override Task HandleAsync(CheckLoginAction action, IDispatcher dispatcher)
        {
            var token = await localStorage.GetItem("token");

            if (token != null)
            {
                var jwt = new JwToken(token);
                api.BranchId = jwt.BranchId;
                var branch = await localStorage.GetItem("branch.name");

                var user = await localStorage.GetItem("user.name");

                var userInfo = new UserInfo {
                    Token = token, UserName = user, BranchName = branch
                };

                dispatcher.Dispatch(new LoginSuccessAction(userInfo));
            }
            else
            {
                uriHelper.NavigateTo("/login");
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Triggers the authentication mechanism specified in Startup.cs to sign the user into the login provider.
 /// </summary>
 public void SignIn()
 {
     _uriHelper.NavigateTo(_config.GenerateRedirectUrl());
 }