Esempio n. 1
0
        private async Task <JObject> ConvertToJsonAsync(MasterDataKeyValue service, int newId)
        {
            var lastModifieUser =
                await _securityContext.Users.SingleOrDefaultAsync(us => us.Id == service.CreateUserId);

            return(JObject.FromObject(new
            {
                service.Id,
                service.Guid,
                NewGuid = SecureGuid.NewGuid().ToString("N"),
                NewId = newId,
                service.PathOrUrl,
                service.Key,
                service.Name,
                service.Code,
                service.Description,
                service.EditMode,
                service.SlidingExpirationTimeInMinutes,
                service.IsLeaf,
                service.ParentId,
                service.Order,
                service.ViewRoleId,
                service.ModifyRoleId,
                service.AccessRoleId,
                service.Version,
                service.EnableCache,
                service.Status,
                service.RowVersion,
                LastModifieUser = lastModifieUser.UserName,
                LastModifieLocalDateTime = service.ModifieLocalDateTime,
                JsCode = await GetResorcesAsync(service)
            }));
        }
        public async Task <JObject> GetWebPageContent(string url, int typeId)
        {
            var form = await _webPageBiz.GetWebPageForEditAsync(HttpUtility.UrlDecode(url.Replace(" ", "%")).Replace(Config.UrlDelimeter, Helper.RootUrl).Replace("#", ""), typeId);

            if (form != null)
            {
                return(form);
            }

            return(JObject.Parse(JsonConvert.SerializeObject(new WebPage()
            {
                Guid = SecureGuid.NewGuid().ToString("N")
            }, Formatting.None)));
        }
        public void EndLogRequest(IOwinRequest request, bool isSuccessed)
        {
            try
            {
                if (!Config.EnableActionLog || !EnableLog)
                {
                    return;
                }
                if (ServiceName == null)
                {
                    return;
                }
                double duration = 0;
                if (StartTime != null)
                {
                    duration = (DateTime.Now.TimeOfDay - TimeSpan.Parse(StartTime)).TotalMilliseconds;
                }



                AddedLogDictionary.TryAdd(SecureGuid.NewGuid().ToString(), new ActionLog()
                {
                    ServiceUrl = ServiceUrl ?? "?",
                    Ip         = request.RemoteIpAddress,
                    Url        = request.Path.Value,
                    Parameters = Helper.UrlDecode(request.Method.ToLower() == "get" ? ReadableStringCollectionToString(request.Query) : Body),
                    //ReadableStringCollectionToString(request.ReadFormAsync().Result)),
                    Type          = request.Method,
                    Coockies      = JsonConvert.SerializeObject(CookieManager.GetAll()),
                    Request       = Helper.UrlDecode(ReadableStringCollectionToString(request.Headers)),
                    DateTime      = DateTime.UtcNow,
                    IsDebugMode   = Settings.IsDebugMode,
                    IsMobileMode  = Settings.IsMobileMode,
                    LocalDateTime = LanguageManager.ToLocalDateTime(DateTime.UtcNow),
                    Name          = ServiceName ?? "?",
                    User          = CurrentUserManager.UserName,
                    ExecutionTimeInMilliseconds = duration,
                    IsSuccessed = isSuccessed,
                    UrlReferrer =
                        Helper.UrlDecode(
                            (UrlReferrer ?? request.Uri.AbsoluteUri ?? new Uri("http://unknown").AbsoluteUri).ToString())
                });
            }
            catch (Exception ex)
            {
                LogException(ex.ToString());
            }
        }
        public async Task <string> GetWcfGenreatedCode(JObject data)
        {
            var wcfGuid = SecureGuid.NewGuid().ToString("N");

            //save xml as file by guid name;
            await _dotNetBiz.WriteWcfWebServiceMetaDataAsync(data, wcfGuid);


            dynamic wcfData = data;

            return(_dotNetBiz.GetWcfWebServiceCode(HttpContext.Current.Request.Url.Scheme + "://"
                                                   + (HttpContext.Current.Request.Url.Authority +
                                                      "/develop/code/os/dotnet/WebService/GetWcfGenreatedCode/" +
                                                      wcfGuid).Replace("//", "/"),
                                                   (string)wcfData.Language));
        }
Esempio n. 5
0
        private async Task <JObject> ConvertToJsonAsync(MasterDataKeyValue masterData, int newId)
        {
            var lastModifieUser =
                await _securityContext.Users.SingleOrDefaultAsync(us => us.Id == masterData.CreateUserId);

            return(JObject.FromObject(new
            {
                masterData.Id,
                masterData.Guid,
                NewGuid = SecureGuid.NewGuid().ToString("N"),
                NewId = newId,
                masterData.PathOrUrl,
                masterData.SecondPathOrUrl,
                masterData.Name,
                masterData.Code,
                masterData.SecondCode,
                masterData.Key,
                masterData.Value,
                masterData.TypeId,
                masterData.ParentTypeId,
                masterData.Description,
                masterData.Data,
                masterData.EditMode,
                masterData.SlidingExpirationTimeInMinutes,
                masterData.IsLeaf,
                masterData.IsType,
                masterData.ParentId,
                masterData.Order,
                masterData.ForeignKey1,
                masterData.ForeignKey2,
                masterData.ForeignKey3,
                masterData.ViewRoleId,
                masterData.ModifyRoleId,
                masterData.AccessRoleId,
                masterData.Version,
                masterData.EnableCache,
                masterData.Status,
                LastModifieUser = lastModifieUser.UserName,
                LastModifieLocalDateTime = masterData.ModifieLocalDateTime,
                masterData.RowVersion
            }));
        }
        public void StartLogRequest(IOwinRequest request)
        {
            try
            {
                if (!Config.EnableActionLog || !EnableLog)
                {
                    return;
                }
                StartTime = DateTime.Now.TimeOfDay.ToString();
                if (request.Method.ToLower() == "post")
                {
                    Body = new StreamReader(request.Body).ReadToEnd();
                    byte[] requestData   = Encoding.UTF8.GetBytes(Body);
                    var    indexPassword = Body.IndexOf("password="******"&", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            Body = Body.Replace(
                                Body.Substring(indexPassword,
                                               Body.Substring(indexPassword).IndexOf("&", StringComparison.OrdinalIgnoreCase)), "");
                        }
                        else
                        {
                            Body = Body.Replace(
                                Body.Substring(indexPassword), "");
                        }
                    }


                    request.Body = new MemoryStream(requestData);
                }

                request.Headers.Add("asRequestId", new[] { SecureGuid.NewGuid().ToString() });
            }
            catch (Exception ex)
            {
                LogException(ex.ToString());
            }
        }
Esempio n. 7
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });


            //var userManager = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()), new DpapiDataProtectionProvider(), new EmailService(), new SmsService(), null);

            //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();


            using (var scope = context.OwinContext.GetAutofacLifetimeScope())
            {
                var claims          = new List <Claim>();
                var userManager     = scope.Resolve <ApplicationUserManager>();
                var securityContext = scope.Resolve <ISecurityContext>();
                var user            = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError(LanguageManager.ToAsErrorMessage(ExceptionKey.InvalidLogin));

                    return;
                }
                if (user.Status == 0)
                {
                    context.SetError(LanguageManager.ToAsErrorMessage(ExceptionKey.DisabledUser));
                    return;
                }

                // TODO: Ajax Login
                //var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                //var coockieIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);
                claims.Add(new Claim(ClaimTypes.Name, context.UserName));
                ////identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));



                //var userRoles = await userManager.GetRolesAsync(user.Id);
                //var userByRoles = await securityContext.Users.Where(us => us.Id == user.Id).Include(u => u.Roles).SingleOrDefaultAsync();
                //foreach (var role in userRoles)
                //{
                //    claims.Add(new Claim(ClaimTypes.Role, role));
                //}

                //foreach (var role in userByRoles.Roles)
                //{
                //    claims.Add(new Claim(ClaimTypes.SerialNumber, role.RoleId.ToString()));
                //    claims.Add(new Claim(ClaimTypes.Role, role.RoleId.ToString()));
                //}



                var usersGroups = await securityContext.ApplicationUserGroups.Where(ug => ug.UserId == user.Id).ToListAsync();

                claims.AddRange(usersGroups.Select(@group => new Claim(ClaimTypes.GroupSid, @group.GroupId.ToString())));

                AuthorizeManager.CacheUserRoles(usersGroups.Select(gr => gr.GroupId).ToList());



                claims.Add(new Claim(ClaimTypes.Email, user.Email));
                //identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
                //identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

                var identity = new ClaimsIdentity(claims, context.Options.AuthenticationType);


                //AuthenticationProperties properties = CreateProperties(context.UserName);
                //AuthenticationTicket ticket = new AuthenticationTicket(coockieIdentity, properties);
                //context.Validated(ticket);


                //var props = new AuthenticationProperties(new Dictionary<string, string>
                //{
                //    {
                //        "userName",context.UserName
                //    }
                //});



                //var ticket = new AuthenticationTicket(identity, props);
                //context.Validated(ticket);


                //var tiket = new AuthenticationTicket(identity, new AuthenticationProperties(
                //    new Dictionary<string, string>
                //    {
                //        {
                //            "debugId", debugId
                //        }
                //    }));
                //tiket.
                //context.Validated();


                _debugId = SecureGuid.NewGuid().ToString("N");
                if (Settings.IsDebugMode)
                {
                    var groupsRoles = AuthorizeManager.GetUserRoles(usersGroups.Select(gr => gr.GroupId).ToList());
                    if (
                        !groupsRoles.Exists(
                            gr => gr.RolesId.Contains((int)Roles.Debug) || gr.RolesId.Contains((int)Roles.Admin)))
                    {
                        context.SetError(LanguageManager.ToAsErrorMessage(code: ExceptionKey.InvalidDebugGrant));
                        return;
                    }
                    // SourceControl.DebugUsers = SourceControl.DebugUsers ?? new List<DebugUser>();


                    //var debugUsers = new List<DebugUser>();

                    //var debugUsersCache =
                    //    CacheManager.GetForCurrentUserByKey<List<DebugUser>>(
                    //        CacheManager.GetDebugUserKey(CacheKey.DebugUser.ToString(),
                    //            CurrentUserManager.Id, CurrentUserManager.Ip));

                    //if (debugUsersCache.IsCached)
                    //{
                    //    debugUsers = debugUsersCache.Value;
                    //}



                    ////var debugUser =
                    ////      SourceControl.DebugUsers.FirstOrDefault(du => du.Ip == CurrentUserManager.Ip && du.UserId == user.Id);

                    //var debugUser =
                    //    debugUsers.FirstOrDefault(du => du.Ip == CurrentUserManager.Ip && du.UserId == user.Id);

                    //if (debugUser != null)
                    //{
                    //    debugUser.Guid = _debugId;
                    //    debugUser.LoginDateTime = DateTime.UtcNow;
                    //}
                    //else
                    //{
                    //SourceControl.DebugUsers.Add(
                    //debugUsers.Add(
                    //    new DebugUser()
                    //    {
                    //        Ip = CurrentUserManager.Ip,
                    //        UserId = user.Id,
                    //        Guid = _debugId,
                    //        LoginDateTime = DateTime.UtcNow
                    //    });
                    //}

                    CacheManager.Store(
                        context.UserName + CacheManager.GetDebugUserKey(CacheKey.DebugUser.ToString(),
                                                                        user.Id, CurrentUserManager.Ip), new List <DebugUser>()
                    {
                        new DebugUser()
                        {
                            Ip            = CurrentUserManager.Ip,
                            UserId        = user.Id,
                            Guid          = _debugId,
                            LoginDateTime = DateTime.UtcNow
                        }
                    }, slidingExpiration: TimeSpan.FromMinutes(60));
                }

                var id = new ClaimsIdentity(claims,
                                            DefaultAuthenticationTypes.ApplicationCookie);

                context.Validated(id);
                context.Validated(identity);
                //var ctx = Request.GetOwinContext();
                var applicationSignInManager = scope.Resolve <ApplicationSignInManager>();
                applicationSignInManager.AuthenticationManager.SignIn(id, identity);
            }

            // var passwordHasher = new ApplicationPasswordHasher();

            // var dbContext = new Context();
            // var passwordHash = await dbContext.GetUsersHashePasswordAsync(context.UserName);
            // if (passwordHash == null)
            // {
            //     context.SetError(Resources.ErrorMessages.InvalidGrant, Resources.ErrorMessages.InvalidLogin);
            //     return;
            // }

            // if (passwordHasher.VerifyHashedPassword(passwordHash.ToString(), context.Password) == PasswordVerificationResult.Failed)
            //{
            //    context.SetError(Resources.ErrorMessages.InvalidGrant, Resources.ErrorMessages.InvalidLogin);
            //    return;
            //}



            //coockieIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            //context.Request.Context.Authentication.SignIn(properties, coockieIdentity);
        }
Esempio n. 8
0
        public async Task <MasterDataKeyValue> SaveBundleOrBundleSource(JObject data, bool isSource = false)
        {
            dynamic bundleOrSource = data;

            int    id            = bundleOrSource.Id;
            var    isNew         = id == 0;
            var    dependency    = new List <string>();
            string dependencyKey = "";

            id = id == 0 ? (await GetMaxId()) + 1 : id;
            var codeName = isSource ? SourceCode : BundleCode;

            if (isSource)
            {
                int bundleId = bundleOrSource.ParentId;
                var bundle   = await
                               ContentManagementContext.MasterDataKeyValues.AsNoTracking().FirstOrDefaultAsync(md => md.Id == bundleId);

                if (bundle == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                }


                var code = await
                           ContentManagementContext.MasterDataKeyValues.AsNoTracking().FirstOrDefaultAsync(
                    md => md.Id == bundle.ParentId);

                if (code == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                }

                if (code.EditMode)
                {
                    SourceControl.CheckCodeCheckOute(code);
                }

                string sourcePathOrUrl = bundleOrSource.PathOrUrl;

                if (bundle.Value == 1)
                {
                    if (
                        sourcePathOrUrl.ToLower()
                        .IndexOf(bundle.PathOrUrl.ToLower().Replace("~", code.PathOrUrl.ToLower()),
                                 StringComparison.Ordinal) != 0)
                    {
                        throw new KhodkarInvalidException(
                                  LanguageManager.ToAsErrorMessage(ExceptionKey.SourceOfOneByOneBundleNotValid));
                    }
                }
            }
            else
            {
                dependencyKey = bundleOrSource.DependencyKey;
                if (dependencyKey != null)
                {
                    JArray dependencyArray = bundleOrSource.Dependency;
                    if (dependencyArray != null)
                    {
                        dependency = dependencyArray.ToObject <List <string> >();
                    }
                }
            }
            int key = 0;

            try
            {
                key = bundleOrSource.Key;
            }
            catch (Exception)
            {
                // ignored
            }

            if (!isNew && !isSource)
            {
                var bundleEntity = await
                                   ContentManagementContext.MasterDataKeyValues.AsNoTracking().Where(md => md.Id == id)
                                   .FirstOrDefaultAsync();

                if (bundleEntity == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.BundleNotFound));
                }

                var code = await
                           ContentManagementContext.MasterDataKeyValues.AsNoTracking().FirstOrDefaultAsync(
                    md => md.Id == bundleEntity.ParentId);

                if (code == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.ParentRecordNotFound));
                }


                if (code.EditMode)
                {
                    SourceControl.CheckCodeCheckOute(code);
                }

                int value = 0;

                try
                {
                    value = bundleOrSource.Value;
                }
                catch (Exception)
                {
                    // ignored
                }
                //oneByOne Bundle
                if (value == 1 && ((bundleEntity.Value ?? 0) == 0))
                {
                    var sources = await
                                  ContentManagementContext.MasterDataKeyValues.AsNoTracking().Where(
                        md => md.ParentId == id && md.TypeId == (int)EntityIdentity.BundleSource)
                                  .ToListAsync();

                    if (sources.Any(source => source.PathOrUrl.ToLower()
                                    .IndexOf(bundleEntity.PathOrUrl.ToLower().Replace("~", code.PathOrUrl.ToLower()),
                                             StringComparison.Ordinal) != 0))
                    {
                        throw new KhodkarInvalidException(
                                  LanguageManager.ToAsErrorMessage(ExceptionKey.SourceOfOneByOneBundleNotValid));
                    }
                }
                if (bundleEntity.Code != codeName + id && dependencyKey != bundleEntity.Code)
                {
                    await SourceControl.AddOrUpdateDependencyEngineAsync(new BundleDependency()
                    {
                        DependencyKey = bundleEntity.Code,
                        Path          = bundleEntity.PathOrUrl,
                        Dependency    = await GetBundleDependencyForDependencyEngieen(bundleEntity.Id),
                        Version       = bundleEntity.Version,
                        IsPublish     = true,
                        IsDelete      = true
                    });
                }
            }
            return(await base.Save(JObject.Parse(JsonConvert.SerializeObject
                                                     (new
            {
                Id = id,
                Code = string.IsNullOrEmpty(dependencyKey) ? codeName + id : dependencyKey,
                SecondCode = string.Join(",", dependency.ToArray()),
                bundleOrSource.Description,
                bundleOrSource.Name,
                EditMode = false,
                EnableCache = false,
                Guid = SecureGuid.NewGuid().ToString("N"),
                IsLeaf = false,
                IsType = false,
                Language = Config.DefaultsLanguage,
                bundleOrSource.ModifyRoleId,
                bundleOrSource.ParentId,
                bundleOrSource.RowVersion,
                Key = key,
                bundleOrSource.Value,
                Status = 1,
                TypeId = isSource ? (int)EntityIdentity.BundleSource : (int)EntityIdentity.Bundle,
                IsPath = true,
                IsPathSecond = false,
                PathOrUrlProtocolId = (int)Protocol.PathProtocol,
                bundleOrSource.PathOrUrl,
                bundleOrSource.SecondPathOrUrl,
                bundleOrSource.ViewRoleId,
                bundleOrSource.AccessRoleId,
                bundleOrSource.IsNew
            }, Formatting.None,
                                                     new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            })), false));
        }
Esempio n. 9
0
        public async Task <File> Save(JObject data)
        {
            dynamic fileDto = data;

            string oldUrl = "";
            int?   fileId = fileDto.Id;
            var    file   = new File()
            {
                Id = fileId ?? 0
            };
            var currentFile = await _contentManagementContext.Files.AsNoTracking()
                              .SingleOrDefaultAsync(fl => fl.Id == file.Id);

            try
            {
                if (currentFile == null)
                {
                    throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.FileNotFound));
                }

                oldUrl          = currentFile.Url;
                file            = currentFile;
                file.RowVersion = fileDto.RowVersion;
                _contentManagementContext.Files.Attach(file);
            }
            catch (Exception)
            {
                _contentManagementContext.Files.Add(file);
            }

            try
            {
                file.Guid = fileDto.Guid;
            }
            catch (Exception)
            {
                file.Guid = SecureGuid.NewGuid();
            }

            string filePathUrl = fileDto.Url;

            if (filePathUrl.IndexOf(Helper.RootUrl, StringComparison.Ordinal) != 0)
            {
                filePathUrl = Helper.RootUrl + filePathUrl;
            }
            if (filePathUrl.LastIndexOf(Helper.RootUrl, StringComparison.Ordinal) == filePathUrl.Length - 1)
            {
                filePathUrl = filePathUrl.Substring(0, filePathUrl.Length - 1);
            }

            file.Name        = fileDto.Name;
            file.Description = fileDto.Description;
            file.TypeCode    = fileDto.TypeCode;


            var repeatedLink = await _contentManagementContext.FilePaths.Where(fp => fp.Url == filePathUrl).CountAsync();

            if ((repeatedLink > 0 && oldUrl == "") || (repeatedLink > 1 && oldUrl == ""))
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.RepeatedValue, filePathUrl));
            }

            file.ContentType = _fileSystemManager.GetExtension(filePathUrl);
            file.Url         = filePathUrl;
            file.Size        = _fileSystemManager.GetFileSize(filePathUrl);
            file.Language    = Config.DefaultsLanguage;
            file.Content     = _fileSystemManager.FileToByte(filePathUrl);

            //if(service.IsLeaf)
            if (currentFile != null)
            {
                file.ViewRoleId   = currentFile.ViewRoleId;
                file.ModifyRoleId = currentFile.ModifyRoleId;
                file.AccessRoleId = currentFile.AccessRoleId;
            }
            AuthorizeManager.SetAndCheckModifyAndAccessRole(file, fileDto);

            file.Status = fileDto.Status;


            await _contentManagementContext.SaveChangesAsync();

            return(file);
        }