Exemplo n.º 1
0
        private async Task SeedGlobalAdministrator(
            ICredentialRoleStore credentialRoleStore,
            ICredentialStore credentialStore)
        {
            bool isExistingAnyAdminCredentials =
                await credentialStore.IsExistingByCredentialRoleCode(SentinelCredentialRoleCodes.GlobalAdmin);

            if (!isExistingAnyAdminCredentials)
            {
                string adminCredentialId = SentinelCredentialIds.Admin;

                CredentialRole adminRole =
                    await credentialRoleStore.Get(SentinelCredentialRoleCodes.GlobalAdmin);

                Credential admin = new Credential();
                admin.BirthDate    = new DateTime(2000, 1, 1);
                admin.CreationDate = DateTime.UtcNow;
                admin.DisplayName  = adminCredentialId;
                admin.CredentialId = adminCredentialId;
                admin.Email        = adminCredentialId + "@admin.com";
                admin.PasswordSalt = HashingUtil.GenerateSalt();
                admin.PasswordHash = HashingUtil.GenerateHash(adminCredentialId, admin.PasswordSalt);
                admin.Roles        = new List <CredentialRole> {
                    adminRole
                };

                await credentialStore.Create(admin);
            }
        }
Exemplo n.º 2
0
 public CredentialBuilder(string credentialId)
 {
     _credential              = new Credential();
     _credential.BirthDate    = new DateTime(1990, 6, 1);
     _credential.CreationDate = DateTime.UtcNow;
     _credential.CredentialId = credentialId;
     _credential.DisplayName  = credentialId;
     _credential.Email        = credentialId + "@mail.com";
     _credential.PasswordSalt = HashingUtil.GenerateSalt();
     _credential.PasswordHash = HashingUtil.GenerateHash("12345678", _credential.PasswordSalt);
 }
Exemplo n.º 3
0
        public List <Credential> GetTestCredentials()
        {
            var testRoles = GetTestRoles();

            var credentials = new List <Credential>();

            string newId = "";

            Credential cred1 = new Credential();

            cred1.CredentialId = "agnael";
            cred1.DisplayName  = "Agnael";
            cred1.CreationDate = new DateTime(2015, 5, 4);
            cred1.Email        = "*****@*****.**";
            cred1.PasswordSalt = "ABCDEFGHIJKLMNOP";
            cred1.PasswordHash = HashingUtil.GenerateHash("12345678", cred1.PasswordSalt);
            cred1.BirthDate    = new DateTime(1994, 10, 26);

            // TODO: CAMBIE EL SISTEMA DE ROLES PARA QUE HAYA POR CREDENCIAL Y POR USUARIO DE CADA API, ASIQUE TODO ESTO YA NO TIENE SENTIDO Y HAY QUE CAMBIARLo

            //cred1.Roles = new List<Role>
            //{
            //    testRoles[0],
            //    testRoles[1],
            //    testRoles[2],
            //    testRoles[3]
            //};

            Credential cred2 = new Credential();

            cred2.CredentialId = "simbad";
            cred2.DisplayName  = "Simbad";
            cred2.CreationDate = new DateTime(2015, 5, 4);
            cred2.Email        = "*****@*****.**";
            cred2.PasswordSalt = "ABCDEFGHIJKLMNOP";
            cred2.PasswordHash = HashingUtil.GenerateHash("12345678", cred1.PasswordSalt);
            cred2.BirthDate    = new DateTime(1998, 6, 2);
            //cred2.Roles = new List<Role>
            //{
            //    testRoles[1],
            //    testRoles[3]
            //};

            credentials.Add(cred1);
            credentials.Add(cred2);

            return(credentials);
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Create(CredentialCreateForm form)
        {
            var validationResult =
                new CredentialCreateFormValidator(
                    CredentialStore,
                    DisplayNameRule)
                .Validate(form);

            validationResult.AddToModelState(this.ModelState, null);

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

            Credential credential = new Credential();

            credential.BirthDate    = form.Birthdate;
            credential.CreationDate = DateTime.UtcNow;
            credential.DisplayName  = form.Username;
            credential.CredentialId = form.Username.ToLower();
            credential.Email        = form.Email;
            credential.PasswordSalt = HashingUtil.GenerateSalt();
            credential.PasswordHash = HashingUtil.GenerateHash(form.Password, credential.PasswordSalt);

            CredentialRole defaultRole = await CredentialRoleStore.Get(SentinelCredentialRoleCodes.RegularUser);

            credential.Roles.Add(defaultRole);

            await this.CredentialStore.Create(credential);

            string url  = Url.Action(nameof(GetByCredentialId), new { credential.CredentialId });
            var    view = await this.GetByCredentialId(credential.CredentialId);

            return(Created(url, view));
        }
Exemplo n.º 5
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));
        }
Exemplo n.º 6
0
 public CredentialBuilder WithPassword(string unhashedPassword)
 {
     _credential.PasswordSalt = HashingUtil.GenerateSalt();
     _credential.PasswordHash = HashingUtil.GenerateHash(unhashedPassword, _credential.PasswordSalt);
     return(this);
 }