Example #1
0
        public async Task <IActionResult> GetByFilter([FromQuery] CredentialFilter filter)
        {
            var validationResult = new CredentialFilterValidator().Validate(filter);

            validationResult.AddToModelState(this.ModelState, null);

            if (!validationResult.IsValid)
            {
                return(ValidationError());
            }

            var page = await CredentialStore.Get(filter);

            if (page.IsEmpty)
            {
                return(NotFound <Credential>(filter, page.Total));
            }

            var vmList = new List <CredentialVM>();

            foreach (Credential credential in page.Items)
            {
                var newVm = new CredentialVM(credential);
                vmList.Add(newVm);
            }

            return(Collection <Credential>(filter, page.Total, vmList));
        }
Example #2
0
        protected override Task <bool> RunInternalAsync(StringBuilder log, IList <string> additionalFiles)
        {
            log.AppendLine($"ICredentialStore instance is of type: {_credentialStore.GetType().Name}");

            // Create a service that is guaranteed to be unique
            string       service  = $"https://example.com/{Guid.NewGuid():N}";
            const string account  = "john.doe";
            const string password = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            try
            {
                log.Append("Writing test credential...");
                _credentialStore.AddOrUpdate(service, account, password);
                log.AppendLine(" OK");

                log.Append("Reading test credential...");
                ICredential outCredential = _credentialStore.Get(service, account);
                if (outCredential is null)
                {
                    log.AppendLine(" Failed");
                    log.AppendLine("Test credential object is null!");
                    return(Task.FromResult(false));
                }

                log.AppendLine(" OK");

                if (!StringComparer.Ordinal.Equals(account, outCredential.Account))
                {
                    log.Append("Test credential account did not match!");
                    log.AppendLine($"Expected: {account}");
                    log.AppendLine($"Actual: {outCredential.Account}");
                    return(Task.FromResult(false));
                }

                if (!StringComparer.Ordinal.Equals(password, outCredential.Password))
                {
                    log.Append("Test credential password did not match!");
                    log.AppendLine($"Expected: {password}");
                    log.AppendLine($"Actual: {outCredential.Password}");
                    return(Task.FromResult(false));
                }
            }
            finally
            {
                log.Append("Deleting test credential...");
                _credentialStore.Remove(service, account);
                log.AppendLine(" OK");
            }

            return(Task.FromResult(true));
        }
Example #3
0
        public void Setup()
        {
            mFactory = new Factory(new DefaultModuleConfiguration(), new ITModuleConfiguration());
              mObserver = (RecordingObserver)mFactory.Build<IMessageObserver>();
              mApp = mFactory.Build<IApp>();
              mFile = new DotNetFile();
              mRefreshToken = new RefreshTokenStore(mFile, "refreshToken.txt");
              mCredentials = new CredentialStore(mFile, "credentials.txt");

              var provider = new TestConfigurationProvider();
              provider.SetupCredentialsFile();
              provider.SetupRefreshTokenFile();
              provider.SetupDummyFile();

              mFileManager = new GDriveFileManager(mCredentials.Get(), mRefreshToken.Get());
              new Retry(30, 125)
            .WithWork(x => {
              mFileManager.CleanGDriveAcct();
              Assert.That(mFileManager.ListAllFilesOnRootById().ToArray(), Is.Empty);
            })
            .Start();

              mFolderManager = new FolderManager(mCredentials.Get(), mRefreshToken.Get());
        }
Example #4
0
 public ICredential Get(string service, string account)
 {
     EnsureBackingStore();
     return(_backingStore.Get(service, account));
 }
Example #5
0
 public ICredential Get(string key)
 {
     EnsureBackingStore();
     return(_backingStore.Get(key));
 }
Example #6
0
        public async Task <IActionResult> Login([FromBody] SessionCreateForm form)
        {
            // El form está comlpeto? --------------------
            if (form == null)
            {
                return(new BadRequestResult());
            }

            if (string.IsNullOrEmpty(form.UsernameOrEmail))
            {
                ModelState.AddModelError(nameof(form.UsernameOrEmail), "Required");
            }

            if (string.IsNullOrEmpty(form.Password))
            {
                ModelState.AddModelError(nameof(form.Password), "Required");
            }

            if (!ModelState.IsValid)
            {
                return(ValidationError());
            }

            // La IP tiene permiso de intentar login? --------------------
            var attemptRateResult = await LoginAttemptLimitingService.Check(RequestInfoService.RemoteIp, LoginAttemptStore);

            if (!attemptRateResult.IsApproved)
            {
                ModelState.AddModelError("", attemptRateResult.ErrorMessage);
                return(ValidationError());
            }

            LoginAttempt attempt = new LoginAttempt(this.RequestInfoService.RemoteIp, DateTime.UtcNow);

            // La credencial existe? --------------------
            string failedLoginMsg = "Invalid email and password combination.";

            Credential credential = null;
            bool       isEmail    = form.UsernameOrEmail.IsEmail();

            if (isEmail)
            {
                credential = await CredentialStore.GetByEmail(form.UsernameOrEmail);
            }
            else
            {
                credential = await CredentialStore.Get(form.UsernameOrEmail);
            }


            if (credential == null)
            {
                ModelState.AddModelError("", failedLoginMsg);
                await LoginAttemptStore.Create(attempt);

                return(ValidationError());
            }

            // La contraseña es correcta?
            string newCalculatedHash = HashingUtil.GenerateHash(form.Password, credential.PasswordSalt);

            if (newCalculatedHash != credential.PasswordHash)
            {
                ModelState.AddModelError("", failedLoginMsg);
                await LoginAttemptStore.Create(attempt);

                return(ValidationError());
            }

            // El usuario está penalizado?
            CredentialPenalty activePenalty = await CredentialPenaltyStore.Get(credential.CredentialId, DateTime.UtcNow);

            if (activePenalty != null)
            {
                string validationMsg = null;

                if (activePenalty.EndDate.HasValue)
                {
                    validationMsg = string.Format("User temporarily banned, until [{0}]. Reason: '{1}'", activePenalty.EndDate.Value.ToString(), activePenalty.Reason);
                }
                else
                {
                    validationMsg = string.Format("User permanently banned. Reason: '{0}'", activePenalty.Reason);
                }

                ModelState.AddModelError("", validationMsg);
                await LoginAttemptStore.Create(attempt);

                return(ValidationError());
            }

            var agent = RequestInfoService.UserAgent;

            // La credencial ya tiene una sesión activa?
            Session session =
                await this.SessionStore.Get(
                    credential.CredentialId,
                    agent.DeviceClass,
                    agent.DeviceName,
                    agent.AgentName,
                    agent.AgentVersion);

            if (session != null)
            {
                session.LastActiveDate = DateTime.UtcNow;

                if (session.AllowSelfRenewal)
                {
                    session.ExpirationDate = session.LastActiveDate.AddDays(1);
                }

                await SessionStore.Update(session);
            }
            else
            {
                // Crea la sesión
                session = new Session();
                session.CredentialId     = credential.CredentialId;
                session.LoginDate        = DateTime.UtcNow;
                session.ExpirationDate   = DateTime.UtcNow.AddDays(1);
                session.LastActiveDate   = session.LoginDate;
                session.AllowSelfRenewal = form.IsRememberLogin;
                session.Device           = new UserDevice(agent.DeviceClass, agent.DeviceName);
                session.Agent            = new UserAgent(agent.AgentName, agent.AgentVersion);

                await SessionStore.Create(session);
            }

            // Autentifica
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(form.ReturnUrl);

            await _events.RaiseAsync(new UserLoginSuccessEvent(credential.DisplayName, credential.CredentialId, credential.DisplayName, clientId : context?.ClientId));

            // only set explicit expiration here if user chooses "remember me".
            // otherwise we rely upon expiration configured in cookie middleware.
            AuthenticationProperties props = null;

            if (form.IsRememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromHours(8))
                };
            }
            ;

            // issue authentication cookie with subject ID and username
            var isuser = new IdentityServerUser(credential.CredentialId)
            {
                DisplayName = credential.DisplayName
            };

            await HttpContext.SignInAsync(isuser, props);

            // Devuelve el recurso Session
            return(Element <Session>(session));
        }