예제 #1
0
        public void TestInitialize()
        {
            _mainViewModelMock     = new Mock <IShellViewModel>();
            _deployCommandMock     = new Mock <ICommand>();
            _newCommand            = new AuthorizeCommand <string>(new AuthorizationContext(), str => { }, str => true);
            _saveCommand           = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _openSearchCommand     = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _openSchedulerCommand  = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _openTasksCommand      = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _openSettingsCommand   = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _executeServiceCommand = new AuthorizeCommand(new AuthorizationContext(), obj => { }, obj => true);
            _startPageCommandMock  = new Mock <ICommand>();

            _mainViewModelMock.Setup(it => it.CheckForNewVersionAsync()).ReturnsAsync(true);
            _mainViewModelMock.SetupGet(it => it.NewServiceCommand).Returns(_newCommand);
            _mainViewModelMock.SetupGet(it => it.DeployCommand).Returns(_deployCommandMock.Object);
            _mainViewModelMock.SetupGet(it => it.SaveCommand).Returns(_saveCommand);
            _mainViewModelMock.SetupGet(it => it.SearchCommand).Returns(_openSearchCommand);
            _mainViewModelMock.SetupGet(it => it.SchedulerCommand).Returns(_openSchedulerCommand);
            _mainViewModelMock.SetupGet(it => it.TasksCommand).Returns(_openTasksCommand);
            _mainViewModelMock.SetupGet(it => it.SettingsCommand).Returns(_openSettingsCommand);
            _mainViewModelMock.SetupGet(it => it.DebugCommand).Returns(_executeServiceCommand);
            _mainViewModelMock.SetupGet(it => it.ShowStartPageCommand).Returns(_startPageCommandMock.Object);

            _target = new MenuViewModel(_mainViewModelMock.Object);

            _changedProperties = new List <string>();

            _target.PropertyChanged += _target_PropertyChanged;
        }
예제 #2
0
    void Start()
    {
        LoadViewController.ShowLoadIndicator();
        AuthorizeCommand authCmd = new AuthorizeCommand();

        authCmd.Callback = AfterAuthorize;
        authCmd.execute();
    }
예제 #3
0
 private void AssertAuthorize(AuthorizeCommand command, AuthorizeResponseDto result)
 {
     Assert.AreEqual(command.Email, result.Email);
     Assert.That(DateTimeService.NowUtc < result.ExpirationRefreshTokenUtc);
     Assert.That(DateTimeService.NowUtc < result.ExpirationTokenUtc);
     Assert.That(result.RefreshToken, IsNotNullOrEmpty);
     Assert.That(result.Token, IsNotNullOrEmpty);
     Assert.That(result.Roles, IsNotNullOrEmpty);
     Assert.AreEqual(DefaultUserId, result.UserId);
     Assert.That(result.Username, IsNotNullOrEmpty);
 }
예제 #4
0
        public void Handle_GivenInvalidType_ThrowsException()
        {
            var command = new AuthorizeCommand
            {
                Email    = DefaultUserEmail,
                Password = DefaultUserPassword,
                Type     = Guid.NewGuid().ToString()
            };

            var handler = GetNewHandler();

            Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() =>
                                                             await handler.Handle(command, CancellationToken.None));
        }
예제 #5
0
        public void Handle_GivenInvalidPassword_ThrowsException()
        {
            var command = new AuthorizeCommand
            {
                Email    = DefaultUserEmail,
                Password = Guid.NewGuid().ToString(),
                Type     = Token.TypePassword
            };

            var handler = GetNewHandler();

            Assert.ThrowsAsync <ValidationException>(async() =>
                                                     await handler.Handle(command, CancellationToken.None));
        }
예제 #6
0
        public void Authorize(IEnumerable <string> scopes, string rpcToken = null, string username = null)
        {
            DoStandardPrecheck(false);

            var cmd = new AuthorizeCommand()
            {
                ClientId = this.ClientId,
                Scopes   = scopes,
                RPCToken = rpcToken,
                UserName = username,
            };

            //Send the event
            connection.EnqueueCommand(cmd);
        }
예제 #7
0
        public async Task<IActionResult> Authorize([FromQuery]AuthorizationRequestModel model)
        {
            AuthorizationGrant grantType;
            if ("code".Equals(model.ResponseType, StringComparison.OrdinalIgnoreCase))
            {
                grantType = AuthorizationGrant.AuthorizationCode;
            }
            else if ("token".Equals(model.ResponseType, StringComparison.OrdinalIgnoreCase))
            {
                grantType = AuthorizationGrant.Implicit;
            }
            else
                return BadRequest();
            var command = new AuthorizeCommand
            {
                ClientId = model.ClientId,
                ScopeNames = model.Scope.Split(' '),
                GrantType = grantType
            };

            if (User.Identity.IsAuthenticated)
            {
                command.UserName = User.Identity.Name;
            }

            var result = await _sagaBus.InvokeAsync<AuthorizeCommand, OAuth20Result>(command);
            var context = _dataProtector.Protect(result.SagaId.ToString());
            switch (result.State)
            {
                case OAuth20State.RequireSignIn:
                    return View("SignIn", new OAuthSignInModel { ProtectedOAuthContext = context });

                case OAuth20State.RequirePermissionGrant:
                    return PermissionGrantView(result);

                case OAuth20State.AuthorizationCodeGenerated:
                    return AuthorizationCodeRedirect(result);

                case OAuth20State.Finished:
                    return ImplictRedirect(result);

                default:
                    return BadRequest();
            }
        }
예제 #8
0
        public async Task Handle_ShouldBeAuthorized()
        {
            var command = new AuthorizeCommand
            {
                Email    = DefaultUserEmail,
                Password = DefaultUserPassword,
                Type     = Token.TypePassword
            };

            var handler = GetNewHandler();

            var result = await handler.Handle(command, CancellationToken.None);

            AssertAuthorize(command, result);

            command.Type         = Token.TypeRefresh;
            command.RefreshToken = result.RefreshToken;

            result = await handler.Handle(command, CancellationToken.None);

            AssertAuthorize(command, result);
        }
예제 #9
0
        //this is copied from NexusModsLogin.xaml.cs cause I'm too lazy to make it shared code for what will likely never change
        private void AuthorizeWithNexus()
        {
            NamedBackgroundWorker nbw = new NamedBackgroundWorker(@"NexusAPICredentialsCheck");

            nbw.DoWork += async(a, b) =>
            {
                IsAuthorizing = true;
                VisibleIcon   = true;
                SpinIcon      = true;
                ActiveIcon    = FontAwesomeIcon.Spinner;
                AuthorizeCommand.RaiseCanExecuteChanged();
                CloseCommand.RaiseCanExecuteChanged();
                AuthorizeToNexusText = M3L.GetString(M3L.string_pleaseWait);

                var apiKeyReceived = await NexusModsUtilities.SetupNexusLogin(x => Debug.WriteLine(x));

                Application.Current.Dispatcher.Invoke(delegate { mainwindow.Activate(); });
                if (!string.IsNullOrWhiteSpace(apiKeyReceived))
                {
                    //Check api key
                    AuthorizeToNexusText = M3L.GetString(M3L.string_checkingKey);
                    try
                    {
                        var authInfo = NexusModsUtilities.AuthToNexusMods(apiKeyReceived).Result;
                        if (authInfo != null)
                        {
                            using FileStream fs = new FileStream(System.IO.Path.Combine(Utilities.GetNexusModsCache(), @"nexusmodsapikey"), FileMode.Create);
                            File.WriteAllBytes(System.IO.Path.Combine(Utilities.GetNexusModsCache(), @"entropy"), NexusModsUtilities.EncryptStringToStream(apiKeyReceived, fs));
                            fs.Close();
                            mainwindow.NexusUsername = authInfo.Name;
                            mainwindow.NexusUserID   = authInfo.UserID;
                            SetAuthorized(true);
                            mainwindow.RefreshNexusStatus();
                            AuthorizedToNexusUsername = authInfo.Name;
                            Analytics.TrackEvent(@"Authenticated to NexusMods");
                        }
                        else
                        {
                            Log.Error(@"Error authenticating to nexusmods, no userinfo was returned, possible network issue");
                            mainwindow.NexusUsername = null;
                            mainwindow.NexusUserID   = 0;
                            SetAuthorized(false);
                            mainwindow.RefreshNexusStatus();
                        }
                    }
                    catch (ApiException apiException)
                    {
                        Log.Error(@"Error authenticating to NexusMods: " + apiException.ToString());
                        Application.Current.Dispatcher.Invoke(delegate { M3L.ShowDialog(window, M3L.GetString(M3L.string_interp_nexusModsReturnedAnErrorX, apiException.ToString()), M3L.GetString(M3L.string_errorAuthenticatingToNexusMods), MessageBoxButton.OK, MessageBoxImage.Error); });
                    }
                    catch (Exception e)
                    {
                        Log.Error(@"Other error authenticating to NexusMods: " + e.Message);
                    }
                }
                else
                {
                    Log.Error(@"No API key - setting authorized to false for NM");
                    SetAuthorized(false);
                }

                IsAuthorizing = false;
            };
            nbw.RunWorkerCompleted += (a, b) =>
            {
                if (b.Error != null)
                {
                    Log.Error($@"Exception occurred in {nbw.Name} thread: {b.Error.Message}");
                }
                VisibleIcon = IsAuthorized;
                if (IsAuthorized)
                {
                    ActiveIcon = FontAwesomeIcon.CheckCircle;
                }
                SpinIcon = false;
                AuthorizeCommand.RaiseCanExecuteChanged();
                CloseCommand.RaiseCanExecuteChanged();
            };
            nbw.RunWorkerAsync();
        }
예제 #10
0
 public async Task <ActionResult <AuthorizeResponseDto> > Authorize(
     [FromBody] AuthorizeCommand command)
 {
     return(await Mediator.Send(command));
 }