예제 #1
0
        public void CanPostString()
        {
            _eventQueue.DeleteQueue();
            RemoveAllEvents();

            try {
                _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(IdentityUtils.CreateUserIdentity(TestConstants.UserEmail, TestConstants.UserId, new[] { TestConstants.OrganizationId }, new[] { AuthorizationRoles.Client }, TestConstants.ProjectId)), false, false);

                var statsCounter = IoC.GetInstance <IAppStatsClient>() as InMemoryAppStatsClient;
                Assert.NotNull(statsCounter);

                Assert.True(statsCounter.WaitForCounter(StatNames.PostsQueued, work: () => {
                    var actionResult = _eventController.Post(Encoding.UTF8.GetBytes("simple string"));
                    Assert.IsType <StatusCodeResult>(actionResult);
                }));

                Assert.Equal(1, _eventQueue.GetQueueCount());

                var processEventsJob = IoC.GetInstance <EventPostsJob>();
                processEventsJob.Run();

                Assert.Equal(0, _eventQueue.GetQueueCount());
                Assert.Equal(1, EventCount());
            } finally {
                RemoveAllEvents();
            }
        }
예제 #2
0
        public void WillReturnCorrectIdentityFormat()
        {
            var name = "Matthew Manela";
            var role = "Engineering Manager";

            var display = IdentityUtils.FormatIdentityName(name, role);

            Assert.AreEqual("Matthew Manela (Engineering Manager)", display);
        }
예제 #3
0
        public void WillNotShowRoleIfNull()
        {
            var    name = "Matthew Manela";
            string role = null;
//omjin
            var display = IdentityUtils.FormatIdentityName(name, role);

            Assert.AreEqual("Matthew Manela", display);
        }
예제 #4
0
        public async Task <IHttpActionResult> Post(RegistrationDTO item)
        {
            var userId = string.Empty;

            if (!ModelState.IsValid)
            {
                LogManager.WriteLog("error", userId, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}", JsonConvert.SerializeObject(item), JsonConvert.SerializeObject(ModelState))).Forget();
                return(BadRequest(ModelState));
            }
            var error = string.Empty;

            if (string.IsNullOrEmpty(item.Mobile) && string.IsNullOrEmpty(item.Email))
            {
                error = "Mobile or email are required";
                DataClassesManager.ControllerLog("error", userId, this.Request.RequestUri.PathAndQuery, error);
                return(BadRequest(error));
            }

            long?preUserId = 0;
            var  password  = AuthorizationUtils.HashPassword(item.Password);

            var validation = DataClassesManager.Register(item.Username.ToLower(), password.Hash, password.Salt, item.CountryId, IdentityUtils.GetIdentitiesXML(item.Mobile, item.Email), out preUserId, out error);

            if (!string.IsNullOrEmpty(error))
            {
                LogManager.WriteLog("error", userId, this.Request.RequestUri.PathAndQuery, error).Forget();
                return(BadRequest(error));
            }

            foreach (var v in validation)
            {
                IdentityUtils.ValidateIdentity(v);
            }

            LogManager.WriteLog("info", userId, this.Request.RequestUri.PathAndQuery, string.Format("{0}:{1}:{2}", preUserId, JsonConvert.SerializeObject(item), JsonConvert.SerializeObject(validation))).Forget();

            return(Ok(new
            {
                RefId = preUserId,
                Identity = from x in validation
                           where x.Immediate
                           select new IdentityDTO
                {
                    TypeId = x.TypeId,
                    Value = x.Identity,
                    Token = x.Token
                }
            }
                      ));
        }
예제 #5
0
        public async Task <IHttpActionResult> ValidateMobile(string id, string mobile)
        {
            DataClassesManager.ControllerLog("info", "", this.Request.RequestUri.PathAndQuery, string.Empty);
            var error = string.Empty;

            var regExp = DataClassesManager.GetRegExpByCountry(id);
            var result = IdentityUtils.ExactMatch(mobile, regExp);

            if (result)
            {
                return(Ok());
            }
            return(BadRequest());
        }
예제 #6
0
        public void CanPostSingleEvent()
        {
            RemoveAllEvents();

            try {
                _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(IdentityUtils.CreateUserIdentity(TestConstants.UserEmail, TestConstants.UserId, new[] { TestConstants.OrganizationId }, new[] { AuthorizationRoles.Client }, TestConstants.ProjectId)), true, false);
                var actionResult = _eventController.Post(Encoding.UTF8.GetBytes("simple string").Compress()).Result;
                Assert.IsType <StatusCodeResult>(actionResult);
                Assert.Equal(1, _eventQueue.Count);

                var processEventsJob = IoC.GetInstance <ProcessEventPostsJob>();
                processEventsJob.Run(1);

                Assert.Equal(0, _eventQueue.Count);
                Assert.Equal(1, EventCount());
            } finally {
                RemoveAllEvents();
            }
        }
예제 #7
0
        public async Task <KeyValuePair <string, int> > GetPersonInfo()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
            WyfDbContext      dbContext     = new WyfDbContext();

            var roles = IdentityUtils.GetRolesFromIdentity(RequestContext.Principal.Identity);

            var identityUserId = RequestContext.Principal.Identity.GetUserId();
            KeyValuePair <string, int> pair = new KeyValuePair <string, int>();
            var employerRoleName            = "Employer";
            var employeeRoleName            = "Employee";

            if (roles.Contains(employerRoleName) && !roles.Contains(employeeRoleName))
            {
                Employer employer = await this._context.Employers.FirstOrDefaultAsync(e => e.UserId == identityUserId);

                pair = new KeyValuePair <string, int>(employerRoleName, employer.Id);
            }
            else if (roles.Contains(employeeRoleName) && !roles.Contains(employerRoleName))
            {
                try
                {
                    Employee employee =
                        await this._context.Employees.FirstOrDefaultAsync(e => e.UserId == identityUserId);

                    pair = new KeyValuePair <string, int>(employeeRoleName, employee.Id);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent("There are Person with the current user identity found in the database."),
                    ReasonPhrase = "Missing Resource Exception"
                });
            }

            return(pair);
        }
예제 #8
0
        // Token: 0x060003FE RID: 1022 RVA: 0x00017434 File Offset: 0x00015634
        public static byte[] CreateSerializedSecurityAccessToken(this IRequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }
            SerializedSecurityAccessToken serializedSecurityAccessToken = new SerializedSecurityAccessToken();

            try
            {
                using (ClientSecurityContext clientSecurityContext = IdentityUtils.ClientSecurityContextFromIdentity(requestContext.GetCallerIdentity(), true))
                {
                    clientSecurityContext.SetSecurityAccessToken(serializedSecurityAccessToken);
                }
            }
            catch (AuthzException ex)
            {
                throw new HttpException(401, ex.Message);
            }
            return(serializedSecurityAccessToken.GetSecurityContextBytes());
        }
예제 #9
0
        // Token: 0x060003FD RID: 1021 RVA: 0x000173B4 File Offset: 0x000155B4
        public static SerializedClientSecurityContext GetSerializedClientSecurityContext(this IRequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }
            SerializedClientSecurityContext result = null;

            try
            {
                IIdentity callerIdentity = requestContext.GetCallerIdentity();
                using (ClientSecurityContext clientSecurityContext = IdentityUtils.ClientSecurityContextFromIdentity(callerIdentity, true))
                {
                    result = SerializedClientSecurityContext.CreateFromClientSecurityContext(clientSecurityContext, IIdentityExtensions.GetSafeName(callerIdentity, true), callerIdentity.AuthenticationType);
                }
            }
            catch (AuthzException ex)
            {
                throw new HttpException(401, ex.Message);
            }
            return(result);
        }
예제 #10
0
        public void CanPostManyEvents()
        {
            _eventQueue.DeleteQueue();
            RemoveAllEvents();

            const int batchSize  = 250;
            const int batchCount = 10;

            try {
                var countdown         = new CountDownLatch(10);
                var messageSubscriber = IoC.GetInstance <IMessageSubscriber>();
                messageSubscriber.Subscribe <EntityChanged>(ch => {
                    if (ch.ChangeType != ChangeType.Added || ch.Type != typeof(PersistentEvent).Name)
                    {
                        return;
                    }

                    if (countdown.Remaining <= 0)
                    {
                        throw new ApplicationException("Too many change notifications.");
                    }

                    countdown.Signal();
                });

                Parallel.For(0, batchCount, i => {
                    _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(IdentityUtils.CreateUserIdentity(TestConstants.UserEmail, TestConstants.UserId, new[] { TestConstants.OrganizationId }, new[] { AuthorizationRoles.Client }, TestConstants.ProjectId)), true, false);
                    var events           = new RandomEventGenerator().Generate(batchSize);
                    var compressedEvents = Encoding.UTF8.GetBytes(new DefaultJsonSerializer().Serialize(events)).Compress();
                    var actionResult     = _eventController.Post(compressedEvents, version: 2, userAgent: "exceptionless/2.0.0.0");
                    Assert.IsType <StatusCodeResult>(actionResult);
                });

                Assert.Equal(batchCount, _eventQueue.GetQueueCount());

                var sw = new Stopwatch();
                var processEventsJob = IoC.GetInstance <EventPostsJob>();
                sw.Start();
                processEventsJob.RunUntilEmpty();
                sw.Stop();
                Trace.WriteLine(sw.Elapsed);

                Assert.Equal(0, _eventQueue.GetQueueCount());
                Assert.Equal(batchSize * batchCount, EventCount());

                bool success = countdown.Wait(5000);
                Assert.True(success);
            } finally {
                _eventQueue.DeleteQueue();
            }
        }
예제 #11
0
        /// <summary>
        /// Execute create or update of specified entity
        /// </summary>
        /// <typeparam name="TEntity">Type of entity</typeparam>
        /// <param name="entity">Entity to save</param>
        /// <param name="dataSession">Data session</param>
        /// <param name="saveMethod">Save method</param>
        public static void Save <TEntity>(TEntity entity, IDataSession dataSession, Action <IDataSession> saveMethod)
            where TEntity : class, IEntity
        {
            //Se non è passato un dato valido, emetto eccezione
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (dataSession == null)
            {
                throw new ArgumentNullException(nameof(dataSession));
            }
            if (saveMethod == null)
            {
                throw new ArgumentNullException(nameof(saveMethod));
            }

            //Eseguo la validazione dell'entità da salvare
            IList <ValidationResult> validationResults = Validate(entity, dataSession);

            //Emetto eccezione nel caso in cui non sia possibile eseguire una validazione corretta
            if (validationResults.Count > 0)
            {
                throw new InvalidOperationException(string.Format("The entity '{0}' identified by value '{1}' " +
                                                                  "cannot be validated and changes won't be commited on database. Please invoke 'Validate' method before " +
                                                                  "submit changes on data domain. Invalid data : '{2}'", entity.GetType().FullName,
                                                                  entity.GetId(), validationResults.ToValidationSummary()));
            }

            //Se l'entità è "Rich", applico le informazioni di sistema
            if (entity is IRichEntity)
            {
                //Eseguo la conversione
                IRichEntity richEntity = (IRichEntity)entity;

                //Recupero il principal corrente. Se non è valido o anonimo
                //imposto stringa vuota, altrimenti il nome di autenticazione
                IPrincipal currentPrincipal = IdentityUtils.ResolvePrincipal();
                string     principalName    = currentPrincipal == null
                    ? null
                    : currentPrincipal.Identity.IsAuthenticated
                        ? currentPrincipal.Identity.Name
                        : null;

                //Se l'entità non è mai stata salvata sulla base dati,
                //devo impostare le informazioni di sistema
                if (richEntity.GetId() == null)
                {
                    //Imposto la data corrente per l'inserimento
                    richEntity.CreationTime = DateTime.UtcNow;

                    //Se non ho già un utente, imposto il principal
                    if (string.IsNullOrEmpty(richEntity.CreatedBy))
                    {
                        richEntity.CreatedBy = principalName;
                    }
                }

                //In tutti i casi imposto la data di aggiornamento
                richEntity.LastUpdateTime = DateTime.UtcNow;

                //Se non ho già un utente, imposto il principal
                if (string.IsNullOrEmpty(richEntity.LastUpdateBy))
                {
                    richEntity.LastUpdateBy = principalName;
                }
            }

            //Mando in esecuzione il metodo di salvataggio
            saveMethod(dataSession);
        }