Beispiel #1
0
        public void Refresh()
        {
            lock (_lockObject)
            {
                _cache.Clear();
                _cacheTypes.Clear();

                using (var context = LuckIndiaDBContext.GetContext())
                {
                    foreach (var modelClass in context.ModelClasses)
                    {
                        _cache.Add(modelClass.Title, modelClass.Id);
                    }
                }

                var types = Assembly.Load("LuckIndia.Models")//GetExecutingAssembly()
                            .GetTypes()
                            .Where(x => !x.IsAbstract && x.IsSubclassOf(typeof(Model))).ToList();

                foreach (var type in types)
                {
                    _cacheTypes.Add(type);
                }
            }
        }
Beispiel #2
0
 protected CrudHelper(T model, LuckIndiaDBContext context, bool shouldValidatePermissions = true)
 {
     this.Model   = model;
     this.Context = context;
     this.ShouldValidatePermissions = shouldValidatePermissions;
     this.ModelClassId = ModelClassCachingService.GetCurrent().GetModelClassId <T>();
 }
Beispiel #3
0
        SecurityContext IAuthProvider.Verify(string token)
        {
            // AuthorizedAccessToken authAcessToken = new AuthorizedAccessToken();
            SecurityContext securityContext = new SecurityContext();

            using (LuckIndiaDBContext context = new LuckIndiaDBContext())
            {
                var cacheModel = AccessTokenCachingService.GetCurrent().GetAccessTokenCacheModel(token);
                securityContext.AccessToken = cacheModel.AccessToken.Token;
                //securityContext.ApplicationInfo = new ApplicationInfo { Id = cacheModel.AccessToken.ApplicationId, Title = cacheModel.AccessToken.Application.Title };
                //CMD tokens wouldn't have expireation date.
                securityContext.EndDate   = DateTime.UtcNow;
                securityContext.StartDate = DateTime.UtcNow;

                securityContext.User = new User
                {
                    Email     = cacheModel.AccessToken.User.Email,
                    FirstName = cacheModel.AccessToken.User.FirstName,
                    Id        = cacheModel.AccessToken.User.Id,
                    LastName  = cacheModel.AccessToken.User.LastName,
                };

                //var roles = context.UserRoles.Where(z => z.UserId == securityContext.User.Id).Select(z => z.Role);//cacheModel.AccessToken.UserToken.User.UserRoles;
                //foreach (Models.Role userrole in roles)
                //{
                //    securityContext.User.Roles.Add(
                //        new ALPHAEON.API.Common.SecurityHelpers.Role { Id = userrole.Id, Title = userrole.Title }
                //        );
                //}
            }
            return(securityContext);
        }
Beispiel #4
0
        private void RefreshCacheForToken(string token)
        {
            using (var context = LuckIndiaDBContext.GetContext())
            {
                var accessToken = context.AccessTokens
                                  .Include(x => x.User)
                                  // .Include(x => x.Application)
                                  .FirstOrDefault(x => x.Token == token);

                if (accessToken == null ||
                    !ExpirableValidator.IsActive(accessToken.StartDate, accessToken.EndDate))
                {
                    throw new InvalidAccessTokenException();
                }

                var accessTokenCache = new AccessTokenCacheModel
                {
                    AccessToken   = accessToken,
                    ApplicationId = accessToken.ApplicationId,
                    UserId        = accessToken.UserId
                };

                _cache.TryAdd(token, accessTokenCache);
            }
        }
        /// <summary>
        /// Gets a single model.
        /// </summary>
        /// <param name="id">Id of the entity.</param>
        public virtual async Task <HttpResponseMessage> Get(int?id)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(await this.NotFound().ExecuteAsync(CancellationToken.None));
            }

            //var acceptTypes = this.GetAcceptContentTypes();

            TDTO dto;

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var model = context.GetSingle <TModel>(id.Value);

                //if (acceptTypes.Any() && !acceptTypes.Contains(MediaTypeValue.ANY) && !acceptTypes.Contains(MediaTypeValue.JSON))
                //{
                // return await this.PerformContentNegotiation(model, acceptTypes);
                //}

                //default functionality is to return the dto.
                dto = this.Factory.ToDTO(model);
            }

            return(await this.Ok(dto).ExecuteAsync(CancellationToken.None));
        }
Beispiel #6
0
        public IEnumerable <DeleteRule <T> > GetDeleteRules <T>(T model, LuckIndiaDBContext context) where T : Model
        {
            var type = typeof(T);

            if (_deleteCache.ContainsKey(type))
            {
                return(_deleteCache[type].Select(x => (DeleteRule <T>)Activator.CreateInstance(x, model, context)));
            }

            return(new List <DeleteRule <T> >());
        }
Beispiel #7
0
        public bool CanRead(int modelClassId, LuckIndiaDBContext context)
        {
            //if (!_readCache.ContainsKey(modelClassId))
            //{
            //    return false;
            //}

            //var userRoles = context.SecurityContext.User.Roles.Select(x => x.Id).ToList();
            //return _readCache[modelClassId].Intersect(userRoles).Any();
            return(true);
        }
        /// <summary>
        /// Deletes the given model.
        /// </summary>
        /// <param name="id">Id of the model.</param>
        public virtual IHttpActionResult Delete(int?id)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(this.NotFound());
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                context.Delete <TModel>(id.Value);
            }

            return(this.OkNoContent());
        }
        protected virtual IQueryable <TModel> GetCollection(ODataQueryOptions <TModel> queryOptions)
        {
            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var collection = context.GetCollection <TModel>();

                this.GetLogger().AppendLine("OData ApplyTo Started");

                var sw = Stopwatch.StartNew();

                collection = (IQueryable <TModel>)queryOptions.ApplyTo(collection, new ODataQuerySettings {
                    PageSize = WebApiConfig.PageSize
                });

                sw.Stop();
                this.GetLogger().AppendLine(string.Format("OData ApplyTo Done: {0} ms", sw.ElapsedMilliseconds));

                return(collection);
            }
        }
        /// <summary>
        /// Overriders must call this.Init() and run through permission checks and fire all the events.
        /// Do not call base. Typically only overridden to completely disable this method by using [NonAction] and then implementing your own Post()
        /// </summary>
        /// <param name="postedDto"></param>
        /// <returns></returns>
        public virtual IHttpActionResult Post(TDTO postedDto)
        {
            if (postedDto == null)
            {
                return(this.BadRequest("Invalid DTO."));
            }

            TModel model;

            try
            {
                model = this.Factory.FromDTO(postedDto);
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex.Message));
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                model = context.Create(model);
                return(this.Created(this.GetLocationUri(model), this.Factory.ToDTO(model)));
            }
        }
 public LuckUserUpdateRule(LuckUser user, IDictionary <string, object> oldValues, LuckIndiaDBContext context)
     : base(user, oldValues, context)
 {
 }
Beispiel #12
0
 protected CreateRule(T model, LuckIndiaDBContext context)
     : base(model, context)
 {
 }
Beispiel #13
0
 public CollectionHelper(LuckIndiaDBContext context) : base(null, context)
 {
 }
 public CreateHelper(T model, LuckIndiaDBContext context, bool shouldValidatePermissions = true) : base(model, context, shouldValidatePermissions)
 {
 }
Beispiel #15
0
 protected CrudHook(T model, LuckIndiaDBContext context)
 {
     this.Model   = model;
     this.Context = context;
 }
Beispiel #16
0
 public LuckUserCreateRule(LuckUser user, LuckIndiaDBContext context)
     : base(user, context)
 {
 }
 public UpdateHelper(T model, IDictionary <string, object> delta, LuckIndiaDBContext context, bool shouldValidatePermissions = true)
     : base(model, context, shouldValidatePermissions)
 {
     _delta = delta;
 }
Beispiel #18
0
        public IEnumerable <UpdateRule <T> > GetUpdateRules <T>(T model, IDictionary <string, object> oldValues, LuckIndiaDBContext context) where T : Model
        {
            var type = typeof(T);

            if (_updateCache.ContainsKey(type))
            {
                return(_updateCache[type].Select(x => (UpdateRule <T>)Activator.CreateInstance(x, model, oldValues, context)));
            }

            return(new List <UpdateRule <T> >());
        }
        /// <summary>
        /// Patches a model with the given changes.
        /// </summary>
        /// <param name="id">Id of the model.</param>
        /// <param name="json">Json object of the changes. Needs to be a single object with properties of base data types.</param>
        /// <returns></returns>
        public virtual IHttpActionResult Patch(int?id, JObject json)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(this.NotFound());
            }

            if (json == null)
            {
                return(this.BadRequest("Invalid JSON."));
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var userId = context.GetCurrentUser().Id;

                var dataInjectors = new List <IDataInjectable>
                {
                    new MyUserIdInjector(userId),
                    new UtcNowInjector()
                };

                var allProperties = typeof(TModel).GetProperties().Where(x => x.CanWrite).ToList();

                var validationErrors = new StringBuilder();

                var delta = new Dictionary <string, object>();

                var modelFound = context.Set <TModel>().FirstOrDefault(x => x.Id == id);
                if (modelFound == null)
                {
                    // CMDLogger.LogBusinessException("Model ID not found : " + id, json, string.Empty);
                }
                foreach (var o in json)
                {
                    var propInfo = allProperties.FirstOrDefault(x => String.Equals(x.Name, o.Key, StringComparison.CurrentCultureIgnoreCase));
                    if (null == propInfo)
                    {
                        continue;
                    }

                    var type = propInfo.PropertyType;

                    var injected = false;
                    foreach (var injectable in dataInjectors)
                    {
                        object tmp;

                        if (!injectable.TryParseObject(type, o.Value.ToString(), out tmp))
                        {
                            continue;
                        }

                        delta.Add(propInfo.Name, tmp);
                        injected = true;
                        break;
                    }

                    if (injected)
                    {
                        continue;
                    }

                    try
                    {
                        delta.Add(propInfo.Name, o.Value.ToObject(type));
                    }
                    catch
                    {
                        validationErrors.AppendFormat("Invalid data for: {0}", o.Key);
                        validationErrors.AppendLine();
                    }
                }

                if (json.Count != delta.Count)
                {
                    validationErrors.AppendLine("Invalid properties.");
                }

                if (validationErrors.Length > 0)
                {
                    return(this.BadRequest(validationErrors.ToString().Trim()));
                }
                var modelupdated = context.Update <TModel>(id.Value, delta);
                return(this.Ok(this.Factory.ToDTO(modelupdated)));
            }
        }
Beispiel #20
0
 public AccountCreateRule(Account user, LuckIndiaDBContext context)
     : base(user, context)
 {
 }
Beispiel #21
0
 public ReadHelper(int id, LuckIndiaDBContext context)
     : base(null, context)
 {
     _id = id;
 }
Beispiel #22
0
 protected ReadRule(T model, LuckIndiaDBContext context)
     : base(model, context)
 {
 }
 public QuestionCreateRule(Question question, LuckIndiaDBContext context)
     : base(question, context)
 {
 }
 protected UpdateRule(T model, IDictionary <string, object> oldValues, LuckIndiaDBContext context)
     : base(model, context)
 {
     this.OldValues = oldValues;
 }
Beispiel #25
0
 public LuckIndiaDBContext GetDatabaseContext()
 {
     return(LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()));
 }