public void WeemoApi_RestSharpWeemoClient_GetAuthTokenAsync_should_return_AuthResponse_with_token()
        {
            // given
            var baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var pathToPrivateCA = Path.Combine(baseDir, "Certs", "weemo-ca.pem").ToString();
            var pathToClientCert = Path.Combine(baseDir, "Certs", "client.p12").ToString();

            var config = new WeemoConfig(new CertLoader())
                {
                    AuthUrl = "https://oauths.weemo.com/auth/",
                    ClientId = "CLIENT_ID_GOES_HERE",
                    ClientSecret = "CLIENT_SECRET_GOES_HERE",
                    ClientRootCertAuthorityIsInstalledOnServer = false
                }
                .SetClientRootCertAuthorityFromPath(pathToPrivateCA)
                .SetClientCertFromPath(pathToClientCert, "CERT_SECRET_GOES_HERE");

            var validator = new CertificateValidator(config);
            var client = new RestSharpWeemoClient(config, validator);
            var request = new AuthRequest
            {
                Uid = "UNIQUE_USER_ID_GOES_HERE",
                Domain = "your-domain.com",
                LicenseType = WeemoLicenseTypes.premium
            };

            // when
            var token = client.GetAuthTokenAsync(request).Result;

            // then
            Assert.IsNotNull(token);
            Assert.IsNotNull(token.Token);
            Assert.IsFalse(token.Token.Contains("error"));
            Assert.IsFalse(String.IsNullOrWhiteSpace(token.Token));
        }
Example #2
0
 public LoginCompletedEventArgs Login(string username, string password)
 {
     if (isLoggedIn)
         return new LoginCompletedEventArgs("Already logged in");
     uint pID = IntGen.GetNewGUID();
     AuthRequest authRequest = new AuthRequest();
     authRequest.Username = username;
     authRequest.Password = password;
     GASClient.GAS.SendPacket(authRequest.Write(), pID);
     GASClient.GAS.Recieve(pID);
     if (!GASClient.GAS.RecievedPacketsContains(pID))
         return new LoginCompletedEventArgs("Server timed out");
     IPacket ipacket = BasePacket.Read(GASClient.GAS.RecievedPacketsGet(pID));
     if (ipacket.GetPacketType() != PacketTypeEnum.LoginResponse)
         return new LoginCompletedEventArgs("Incorrect server response");
     AuthResponse authResponse = (AuthResponse)ipacket;
     Log.Debug(authResponse.ResponseType.ToString());
     if (authResponse.ResponseType == LoginResponseTypeEnum.LoginValidated)
     {
         this.isLoggedIn = true;
         this.FluxID = authResponse.FluxID;
         return new LoginCompletedEventArgs(true);
     }
     if (authResponse.ResponseType == LoginResponseTypeEnum.LoginInvalid)
         return new LoginCompletedEventArgs("Your login doesn't seem to be valid.");
     if (authResponse.ResponseType == LoginResponseTypeEnum.ServerNA)
         return new LoginCompletedEventArgs("The server is set to maintence mode.");
     if (authResponse.ResponseType == LoginResponseTypeEnum.UserBanned)
         return new LoginCompletedEventArgs("You are banned.");
     return new LoginCompletedEventArgs("Unknown Error"); //Why is this even called, there is no other possible enum option
 }
Example #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        AccountSettings accountSettings = new AccountSettings();

        OneLogin.Saml.AuthRequest req = new AuthRequest(new AppSettings(), accountSettings);
        
        Response.Redirect(accountSettings.idp_sso_target_url + "?SAMLRequest=" + Server.UrlEncode(req.GetRequest(AuthRequest.AuthRequestFormat.Base64)));
    }
 private async Task<IRestResponse> GetAuthTokenIRestResponseAsync(AuthRequest request) 
 {
     // create web request
     var endPointWithClientInfo = BuildFqdnEndpointWithClientInfo(config.QueryString);
     var restRequest = BuildWeemoPostRequest(endPointWithClientInfo, request);
     var client = new RestClient();
     client.ClientCertificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
     client.ClientCertificates.Add(config.ClientCert);
     return await client.ExecutePostTaskAsync(restRequest);
 }
        /// <summary>
        /// Make the RestRequest object and set appropriate headers and params
        /// </summary>
        /// <param name="url">the url to be used for Authentication</param>
        /// <returns>A RestRequest object</returns>
        private RestRequest BuildWeemoPostRequest(string url, AuthRequest body)
        {
            var request = new RestRequest(url, Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("uid", body.EncodedUid);
            request.AddParameter("identifier_client", body.EncodedDomain);
            request.AddParameter("id_profile", body.EncodedLicenseType);
            ServicePointManager.ServerCertificateValidationCallback = certValidator.ValidateRemoteCertificate;

            return request;
        }
Example #6
0
 public async Task<dynamic> Post(AuthRequest req)
 {
     // Obviously, at this point you need to validate the username and password against whatever system you wish.
     var signin = await _signInManager.PasswordSignInAsync(req.username, req.password, false, false);
     if (signin.Succeeded)
     {
         DateTime? expires = DateTime.UtcNow.AddDays(1);
         var token = await GetToken(req.username, expires);
         return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
     }
     return new { authenticated = false };
 }
Example #7
0
 public ResponseMessageWrap<AuthResponse> Auth(AuthRequest reqMsg)
 {
     String Token = service.Auth(reqMsg.AppId, reqMsg.AppSecret);
     var resp = new ResponseMessageWrap<AuthResponse>
     {
         Body = new AuthResponse
         {
             Token = Token
         }
     };
     return resp;
 }
Example #8
0
        public virtual ActionResult Authenticate(string openid_identifier, string returnUrl)
        {
            var response = RelyService.GetResponse();
            if (response != null) return new EmptyResult();

            var authRequest = new AuthRequest {
                ProviderUrl = openid_identifier,
                RedirectUrl = returnUrl,
                RequestUri = Request.Url
            };

            var request = RelyService.CreateRequest(authRequest);
            return request.RedirectingResponse.AsActionResult();
        }
Example #9
0
        public override void OnOpen(USocket us)
        {
            Console.WriteLine ("连接建立");
            AuthRequest request = new AuthRequest();
            request.loginid = "lkjlkj;sdf你好";
            request.serverid = 1;
            MemoryStream  stream = new MemoryStream();
            ProtoBuf.Serializer.Serialize<AuthRequest>(stream, request);

            Frame f = new Frame(512);
            f.PutShort(6);
            f.PutBytes(stream.ToArray());
            f.End();
            us.Send (f);
        }
        /// <summary>
        /// Get the authorization token from Weemo
        /// </summary>
        /// <param name="callerUid">The uid of the person making the call</param>
        /// <param name="tenantDomain">The domain of the tenant</param>
        /// <param name="licenseType">The license type for the token (i.e. standard or premium)</param>
        /// <returns>An AuthResponse with an authorization token</returns>
        public AuthResponse GetAuthToken(AuthRequest request)
        {
            // create web request
            var endPointWithClientInfo = BuildFqdnEndpointWithClientInfo(config.QueryString);
            var webRequest = BuildWeemoPostRequest(endPointWithClientInfo);

            // make web request
            using (var webResponse = ExecuteRequest(webRequest, request.QueryString))
            {
                // read web response stream
                var resultString = ReadStringFromResponseStream(webResponse);

                // parse and return the result
                return JsonConvert.DeserializeObject<AuthResponse>(resultString);
            }
        }
Example #11
0
 public object Get(AuthRequest request)
 {
     try
     {
         return
             new HttpResult(new AuthResponse
             {
                 RedirectUri = request.RedirectUri,
                 ClientId = request.ClientId,
                 State = request.State
             });
     }
     catch
     {
         return new HttpError(InternalServerError, "Internal Server Error");
     }
 }
Example #12
0
 public static void Main(string[] args)
 {
     AuthRequest ar = new AuthRequest();
     string json = JsonMapper.ToJson(ar);
     Console.WriteLine(ar.GetType().Name+":"+json);
     Console.Read();
     /**
     SocketListner listner = new TestListner ();
     USocket us = new USocket ();
     us.setLister (listner);
     //Protocal p = new Varint32HeaderProtocol ();
     Protocal p = new LVProtocal();
     us.setProtocal (p);
     us.Connect ("localhost", 4887);
     Console.Read();
      */
 }
Example #13
0
    static async Task GetToken(HttpClient client)
    {
      // get token for authentication
      var auth = new AuthRequest() { username = "******", password = "******" };
      var authresponse = await client.PostAsync("api/Token",
        new StringContent(JsonConvert.SerializeObject(auth, Formatting.Indented), Encoding.UTF8, "application/json"));
      if (authresponse.IsSuccessStatusCode)
      {
        //var awe = await authresponse.Content.ReadAsStringAsync();
        //AuthResponse authRes = JsonConvert.DeserializeObject<AuthResponse>(awe);
        var authRes = await authresponse.Content.ReadAsAsync<AuthResponse>();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authRes.token);
        _logger.LogInformation("token.authenticated = " + authRes.authenticated);
      }
      else
      {
        _logger.LogError("Can't get token");
      }

    }
Example #14
0
        public async Task<AuthResult> Login(AuthRequest request)
        {
            AuthResult r = new AuthResult();
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                LoginForm l = new LoginForm(request.Name, request.LoginUrl, request.ClientId, request.Scopes, request.RedirectUri,request.ScopesCommaSeparated);
                l.Owner = _owner;
                bool? res = l.ShowDialog();
                if (res.HasValue && res.Value)
                {
                    r.Code = l.Code;
                    r.Scopes = l.Scopes;
                    r.HasError = false;
                }
                else
                {
                    r.HasError = true;
                    r.ErrorString = "Unable to login";
                }

            });
            return r;
        }
Example #15
0
 public void Login(AuthRequest request)
 {
     this.AsyncProcessMessage(request);
 }
Example #16
0
        private int Validate_SiteInfo(out string errorMessage)
        {
            try
            {
                var isHq         = TranslateUtils.ToBool(RblIsRoot.SelectedValue); // 是否主站
                var parentSiteId = 0;
                var siteDir      = string.Empty;

                if (isHq == false)
                {
                    if (DirectoryUtils.IsSystemDirectory(TbSiteDir.Text))
                    {
                        errorMessage = "文件夹名称不能为系统文件夹名称!";
                        return(0);
                    }

                    parentSiteId = TranslateUtils.ToInt(DdlParentId.SelectedValue);
                    siteDir      = TbSiteDir.Text;

                    var list = DataProvider.SiteDao.GetLowerSiteDirList(parentSiteId);
                    if (list.IndexOf(siteDir.ToLower()) != -1)
                    {
                        errorMessage = "已存在相同的发布路径!";
                        return(0);
                    }

                    if (!DirectoryUtils.IsDirectoryNameCompliant(siteDir))
                    {
                        errorMessage = "文件夹名称不符合系统要求!";
                        return(0);
                    }
                }

                var nodeInfo = new ChannelInfo();

                nodeInfo.ChannelName          = nodeInfo.IndexName = "首页";
                nodeInfo.ParentId             = 0;
                nodeInfo.ContentModelPluginId = string.Empty;

                var psInfo = new SiteInfo
                {
                    SiteName  = PageUtils.FilterXss(TbSiteName.Text),
                    SiteDir   = siteDir,
                    TableName = DdlTableName.SelectedValue,
                    ParentId  = parentSiteId,
                    IsRoot    = isHq
                };

                psInfo.Additional.IsCheckContentLevel = TranslateUtils.ToBool(RblIsCheckContentUseLevel.SelectedValue);

                if (psInfo.Additional.IsCheckContentLevel)
                {
                    psInfo.Additional.CheckContentLevel = TranslateUtils.ToInt(DdlCheckContentLevel.SelectedValue);
                }
                psInfo.Additional.Charset = DdlCharset.SelectedValue;

                var theSiteId = DataProvider.ChannelDao.InsertSiteInfo(nodeInfo, psInfo, AuthRequest.AdminName);

                if (AuthRequest.AdminPermissions.IsSystemAdministrator && !AuthRequest.AdminPermissions.IsConsoleAdministrator)
                {
                    var siteIdList = AuthRequest.AdminPermissions.SiteIdList ?? new List <int>();
                    siteIdList.Add(theSiteId);
                    DataProvider.AdministratorDao.UpdateSiteIdCollection(AuthRequest.AdminName, TranslateUtils.ObjectCollectionToString(siteIdList));
                }

                AuthRequest.AddAdminLog("创建新站点", $"站点名称:{PageUtils.FilterXss(TbSiteName.Text)}");

                errorMessage = string.Empty;
                return(theSiteId);
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
                return(0);
            }
        }
 protected virtual string DetectGrantType(AuthRequest model)
 {
     if (!string.IsNullOrEmpty(model.username) || !string.IsNullOrEmpty(model.password))
     {
         return "password";
     }
     if (!string.IsNullOrEmpty(model.code))
     {
         return "authorization_code";
     }
     if (!string.IsNullOrEmpty(model.refresh_token))
     {
         return "refresh_token";
     }
     return null;
 }
Example #18
0
 public override AsyncUnaryCall <AuthReply> AuthenticationAsync(AuthRequest request, Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default)
 {
     return(base.AuthenticationAsync(request, headers, deadline, cancellationToken));
 }
Example #19
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }
            if (IsPostBack)
            {
                return;
            }

            VerifySystemPermissions(ConfigManager.SettingsPermissions.Chart);

            LtlPageTitle1.Text = $"管理员登录最近{_count}{EStatictisXTypeUtils.GetText(EStatictisXTypeUtils.GetEnumType(AuthRequest.GetQueryString("XType")))}分配图表(按日期统计)";
            LtlPageTitle2.Text = $"管理员登录最近{_count}{EStatictisXTypeUtils.GetText(EStatictisXTypeUtils.GetEnumType(AuthRequest.GetQueryString("XType")))}分配图表(按管理员统计)";

            EStatictisXTypeUtils.AddListItems(DdlXType);

            _xType = EStatictisXTypeUtils.GetEnumType(AuthRequest.GetQueryString("XType"));

            if (Equals(_xType, EStatictisXType.Day))
            {
                _count = 30;
            }
            else if (Equals(_xType, EStatictisXType.Month))
            {
                _count = 12;
            }
            else if (Equals(_xType, EStatictisXType.Year))
            {
                _count = 10;
            }


            TbDateFrom.Text        = AuthRequest.GetQueryString("DateFrom");
            TbDateTo.Text          = AuthRequest.GetQueryString("DateTo");
            DdlXType.SelectedValue = EStatictisXTypeUtils.GetValue(_xType);

            //管理员登录量统计,按照日期
            var trackingDayDictionary = DataProvider.LogDao.GetAdminLoginDictionaryByDate(TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateFrom")), TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateTo"), DateTime.Now), EStatictisXTypeUtils.GetValue(_xType), LogInfo.AdminLogin);

            //管理员登录量统计,按照用户名
            var adminNumDictionaryName = DataProvider.LogDao.GetAdminLoginDictionaryByName(TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateFrom")), TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateTo"), DateTime.Now), LogInfo.AdminLogin);

            var now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            for (var i = 0; i < _count; i++)
            {
                var datetime = now.AddDays(-i);
                if (Equals(_xType, EStatictisXType.Day))
                {
                    now      = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    datetime = now.AddDays(-i);
                }
                else if (Equals(_xType, EStatictisXType.Month))
                {
                    now      = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
                    datetime = now.AddMonths(-i);
                }
                else if (Equals(_xType, EStatictisXType.Year))
                {
                    now      = new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0);
                    datetime = now.AddYears(-i);
                }

                var accessNum = 0;
                if (trackingDayDictionary.ContainsKey(datetime))
                {
                    accessNum = trackingDayDictionary[datetime];
                }
                _adminNumDictionaryDay.Add(_count - i, accessNum);
                if (accessNum > _maxAdminNum)
                {
                    _maxAdminNum = accessNum;
                }
            }

            for (var i = 1; i <= _count; i++)
            {
                StrArray1 += $@"
xArray.push('{GetGraphicX(i)}');
yArray.push('{GetGraphicY(i)}');
";
            }

            foreach (var key in adminNumDictionaryName.Keys)
            {
                StrArray2 += $@"
xArray.push('{key}');
yArray.push('{GetGraphicYUser(adminNumDictionaryName, key)}');
";
            }
        }
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsPostBack || !Page.IsValid)
            {
                return;
            }

            var relatedFileName = TbRelatedFileName.Text;

            if (!StringUtils.EndsWithIgnoreCase(relatedFileName, _ext))
            {
                relatedFileName += _ext;
            }

            if (_fileName != null)
            {
                var isChanged = false;
                if (!StringUtils.EqualsIgnoreCase(_fileName, relatedFileName))//文件名改变
                {
                    var fileNames = DirectoryUtils.GetFileNames(_directoryPath);
                    foreach (var theFileName in fileNames)
                    {
                        if (StringUtils.EqualsIgnoreCase(theFileName, relatedFileName))
                        {
                            FailMessage($"{_name}修改失败,文件已存在!");
                            return;
                        }
                    }

                    isChanged = true;
                }

                var previousFileName = string.Empty;
                if (isChanged)
                {
                    previousFileName = _fileName;
                }

                var charset = ECharsetUtils.GetEnumType(DdlCharset.SelectedValue);
                FileUtils.WriteText(PathUtils.Combine(_directoryPath, relatedFileName), charset, TbContent.Text);
                if (!string.IsNullOrEmpty(previousFileName))
                {
                    FileUtils.DeleteFileIfExists(PathUtils.Combine(_directoryPath, previousFileName));
                }
                AuthRequest.AddSiteLog(SiteId, $"修改{_name}", $"{_name}:{relatedFileName}");
                SuccessMessage($"{_name}修改成功!");
                AddWaitAndRedirectScript(PageTemplateAssets.GetRedirectUrl(SiteId, _type));
            }
            else
            {
                var fileNames = DirectoryUtils.GetFileNames(_directoryPath);
                foreach (var theFileName in fileNames)
                {
                    if (StringUtils.EqualsIgnoreCase(theFileName, relatedFileName))
                    {
                        FailMessage($"{_name}添加失败,文件已存在!");
                        return;
                    }
                }

                var charset = ECharsetUtils.GetEnumType(DdlCharset.SelectedValue);
                FileUtils.WriteText(PathUtils.Combine(_directoryPath, relatedFileName), charset, TbContent.Text);
                AuthRequest.AddSiteLog(SiteId, $"添加{_name}", $"{_name}:{relatedFileName}");
                SuccessMessage($"{_name}添加成功!");
                AddWaitAndRedirectScript(PageTemplateAssets.GetRedirectUrl(SiteId, _type));
            }
        }
Example #21
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");
            _channelId = AuthRequest.IsQueryExists("channelId") ? AuthRequest.GetQueryInt("channelId") : SiteId;

            _isCheckOnly   = AuthRequest.GetQueryBool("isCheckOnly");
            _isTrashOnly   = AuthRequest.GetQueryBool("isTrashOnly");
            _isWritingOnly = AuthRequest.GetQueryBool("isWritingOnly");
            _isAdminOnly   = AuthRequest.GetQueryBool("isAdminOnly");

            _channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);
            var tableName = ChannelManager.GetTableName(SiteInfo, _channelInfo);

            _relatedIdentities   = RelatedIdentities.GetChannelRelatedIdentities(SiteId, _channelId);
            _styleInfoList       = TableStyleManager.GetTableStyleInfoList(tableName, _relatedIdentities);
            _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(ChannelManager.GetContentAttributesOfDisplay(SiteId, _channelId));
            _allStyleInfoList    = ContentUtility.GetAllTableStyleInfoList(_styleInfoList);
            _pluginMenus         = PluginContentManager.GetContentMenus(_channelInfo);
            _pluginColumns       = PluginContentManager.GetContentColumns(_channelInfo);
            _isEdit = TextUtility.IsEdit(SiteInfo, _channelId, AuthRequest.AdminPermissions);

            var state      = AuthRequest.IsQueryExists("state") ? AuthRequest.GetQueryInt("state") : CheckManager.LevelInt.All;
            var searchType = AuthRequest.IsQueryExists("searchType") ? AuthRequest.GetQueryString("searchType") : ContentAttribute.Title;
            var dateFrom   = AuthRequest.IsQueryExists("dateFrom") ? AuthRequest.GetQueryString("dateFrom") : string.Empty;
            var dateTo     = AuthRequest.IsQueryExists("dateTo") ? AuthRequest.GetQueryString("dateTo") : string.Empty;
            var keyword    = AuthRequest.IsQueryExists("keyword") ? AuthRequest.GetQueryString("keyword") : string.Empty;

            var checkedLevel = 5;
            var isChecked    = true;

            foreach (var owningChannelId in AuthRequest.AdminPermissions.OwningChannelIdList)
            {
                int checkedLevelByChannelId;
                var isCheckedByChannelId = CheckManager.GetUserCheckLevel(AuthRequest.AdminPermissions, SiteInfo, owningChannelId, out checkedLevelByChannelId);
                if (checkedLevel > checkedLevelByChannelId)
                {
                    checkedLevel = checkedLevelByChannelId;
                }
                if (!isCheckedByChannelId)
                {
                    isChecked = false;
                }
            }

            RptContents.ItemDataBound += RptContents_ItemDataBound;

            var allLowerAttributeNameList = TableMetadataManager.GetAllLowerAttributeNameListExcludeText(tableName);
            var whereString = DataProvider.ContentDao.GetPagerWhereSqlString(SiteInfo, _channelInfo,
                                                                             searchType, keyword,
                                                                             dateFrom, dateTo, state, _isCheckOnly, false, _isTrashOnly, _isWritingOnly, _isAdminOnly,
                                                                             AuthRequest.AdminPermissions,
                                                                             allLowerAttributeNameList);

            PgContents.Param = new PagerParam
            {
                ControlToPaginate = RptContents,
                TableName         = tableName,
                PageSize          = SiteInfo.Additional.PageSize,
                Page              = AuthRequest.GetQueryInt(Pager.QueryNamePage, 1),
                OrderSqlString    = ETaxisTypeUtils.GetContentOrderByString(ETaxisType.OrderByIdDesc),
                ReturnColumnNames = TranslateUtils.ObjectCollectionToString(allLowerAttributeNameList),
                WhereSqlString    = whereString,
                TotalCount        = DataProvider.DatabaseDao.GetPageTotalCount(tableName, whereString)
            };

            if (IsPostBack)
            {
                return;
            }

            if (_isTrashOnly)
            {
                if (AuthRequest.IsQueryExists("IsDeleteAll"))
                {
                    DataProvider.ContentDao.DeleteContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "清空回收站");
                    SuccessMessage("成功清空回收站!");
                }
                else if (AuthRequest.IsQueryExists("IsRestore"))
                {
                    var idsDictionary = ContentUtility.GetIDsDictionary(Request.QueryString);
                    foreach (var channelId in idsDictionary.Keys)
                    {
                        var contentIdArrayList = idsDictionary[channelId];
                        DataProvider.ContentDao.TrashContents(SiteId, ChannelManager.GetTableName(SiteInfo, channelId), contentIdArrayList);
                    }
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原内容");
                    SuccessMessage("成功还原内容!");
                }
                else if (AuthRequest.IsQueryExists("IsRestoreAll"))
                {
                    DataProvider.ContentDao.RestoreContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原所有内容");
                    SuccessMessage("成功还原所有内容!");
                }
            }

            ChannelManager.AddListItems(DdlChannelId.Items, SiteInfo, true, true, AuthRequest.AdminPermissions);

            CheckManager.LoadContentLevelToList(DdlState, SiteInfo, _isCheckOnly, isChecked, checkedLevel);
            ControlUtils.SelectSingleItem(DdlState, state.ToString());

            foreach (var styleInfo in _allStyleInfoList)
            {
                if (styleInfo.InputType == InputType.TextEditor)
                {
                    continue;
                }

                var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                DdlSearchType.Items.Add(listitem);
            }

            //ETriStateUtils.AddListItems(DdlState, "全部", "已审核", "待审核");

            if (SiteId != _channelId)
            {
                ControlUtils.SelectSingleItem(DdlChannelId, _channelId.ToString());
            }
            //ControlUtils.SelectSingleItem(DdlState, AuthRequest.GetQueryString("State"));
            ControlUtils.SelectSingleItem(DdlSearchType, searchType);
            TbKeyword.Text  = keyword;
            TbDateFrom.Text = dateFrom;
            TbDateTo.Text   = dateTo;

            PgContents.DataBind();

            LtlColumnsHead.Text += TextUtility.GetColumnsHeadHtml(_styleInfoList, _pluginColumns, _attributesOfDisplay);


            BtnSelect.Attributes.Add("onclick", ModalSelectColumns.GetOpenWindowString(SiteId, _channelId));

            if (_isTrashOnly)
            {
                LtlColumnsHead.Text  += @"<th class=""text-center text-nowrap"" width=""150"">删除时间</th>";
                BtnAddToGroup.Visible = BtnTranslate.Visible = BtnCheck.Visible = false;
                PhTrash.Visible       = true;
                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible    = false;
                    BtnDeleteAll.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, true, PageUrl));
                    BtnDeleteAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsDeleteAll", "True"), "确实要清空回收站吗?"));
                }
                BtnRestore.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValue(PageUtils.AddQueryString(PageUrl, "IsRestore", "True"), "IDsCollection", "IDsCollection", "请选择需要还原的内容!"));
                BtnRestoreAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsRestoreAll", "True"), "确实要还原所有内容吗?"));
            }
            else
            {
                LtlColumnsHead.Text += @"<th class=""text-center text-nowrap"" width=""100"">操作</th>";

                BtnAddToGroup.Attributes.Add("onclick", ModalAddToGroup.GetOpenWindowStringToContentForMultiChannels(SiteId));

                if (HasChannelPermissions(SiteId, ConfigManager.ChannelPermissions.ContentCheck))
                {
                    BtnCheck.Attributes.Add("onclick", ModalContentCheck.GetOpenWindowStringForMultiChannels(SiteId, PageUrl));
                    if (_isCheckOnly)
                    {
                        BtnCheck.CssClass = "btn m-r-5 btn-success";
                    }
                }
                else
                {
                    PhCheck.Visible = false;
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentTranslate))
                {
                    BtnTranslate.Visible = false;
                }
                else
                {
                    BtnTranslate.Attributes.Add("onclick", PageContentTranslate.GetRedirectClickStringForMultiChannels(SiteId, PageUrl));
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, false, PageUrl));
                }
            }
        }
Example #22
0
        public async Task <InvokeResult <AuthResponse> > CreateUserAsync(RegisterUser newUser, bool sendAuthEmail = true, bool autoLogin = true)
        {
            if (String.IsNullOrEmpty(newUser.Email))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingEmail.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingEmail.ToErrorMessage()));
            }

            var user = await _appUserRepo.FindByEmailAsync(newUser.Email);

            if (user != null)
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegErrorUserExists.Message);
                if (sendAuthEmail)
                {
                    return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegErrorUserExists.ToErrorMessage()));
                }
                else
                {
                    return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegisterUserExists_3rdParty.ToErrorMessage()));
                }
            }

            /* Need to check all these, if any fail, we want to aboart, we need to refactor this into the UserAdmin module :( */
            if (String.IsNullOrEmpty(newUser.AppId))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingAppId.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingAppId.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.ClientType))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingClientType.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingClientType.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.DeviceId))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingDeviceId.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingDeviceId.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.FirstName))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingFirstLastName.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingFirstLastName.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.LastName))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingLastName.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingLastName.ToErrorMessage()));
            }


            if (String.IsNullOrEmpty(newUser.Password))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingPassword.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingPassword.ToErrorMessage()));
            }

            var emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

            if (!emailRegEx.Match(newUser.Email).Success)
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegInvalidEmailAddress.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegInvalidEmailAddress.ToErrorMessage()));
            }

            var appUser = new AppUser(newUser.Email, $"{newUser.FirstName} {newUser.LastName}")
            {
                FirstName = newUser.FirstName,
                LastName  = newUser.LastName,
            };

            var identityResult = await _userManager.CreateAsync(appUser, newUser.Password);

            if (identityResult.Successful)
            {
                await LogEntityActionAsync(appUser.Id, typeof(AppUser).Name, "New User Registered", null, appUser.ToEntityHeader());

                if (autoLogin)
                {
                    await _signInManager.SignInAsync(appUser);
                }

                if (newUser.ClientType != "WEBAPP")
                {
                    var authRequest = new AuthRequest()
                    {
                        AppId         = newUser.AppId,
                        DeviceId      = newUser.DeviceId,
                        AppInstanceId = newUser.AppInstanceId,
                        ClientType    = newUser.ClientType,
                        GrantType     = "password",
                        Email         = newUser.Email,
                        UserName      = newUser.Email,
                        Password      = newUser.Password,
                    };

                    var tokenResponse = await _authTokenManager.AccessTokenGrantAsync(authRequest);

                    if (tokenResponse.Successful)
                    {
                        await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader());

                        return(InvokeResult <AuthResponse> .Create(tokenResponse.Result));
                    }
                    else
                    {
                        var failedValidationResult = new InvokeResult <AuthResponse>();
                        failedValidationResult.Concat(tokenResponse);
                        return(failedValidationResult);
                    }
                }
                else
                {
                    if (sendAuthEmail)
                    {
                        await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader());
                    }

                    /* If we are logging in as web app, none of this applies */
                    return(InvokeResult <AuthResponse> .Create(new AuthResponse()
                    {
                        AccessToken = "N/A",
                        AccessTokenExpiresUTC = "N/A",
                        RefreshToken = "N/A",
                        AppInstanceId = "N/A",
                        RefreshTokenExpiresUTC = "N/A",
                        IsLockedOut = false,
                        User = appUser.ToEntityHeader(),
                        Roles = new List <EntityHeader>()
                    }));
                }
            }
            else
            {
                return(InvokeResult <AuthResponse> .FromInvokeResult(identityResult));
            }
        }
Example #23
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId", "channelId");
            var channelId = AuthRequest.GetQueryInt("channelId");

            _relatedIdentities   = RelatedIdentities.GetChannelRelatedIdentities(SiteId, channelId);
            _channelInfo         = ChannelManager.GetChannelInfo(SiteId, channelId);
            _tableName           = ChannelManager.GetTableName(SiteInfo, _channelInfo);
            _styleInfoList       = TableStyleManager.GetTableStyleInfoList(_tableName, _relatedIdentities);
            _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(ChannelManager.GetContentAttributesOfDisplay(SiteId, channelId));
            _allStyleInfoList    = ContentUtility.GetAllTableStyleInfoList(_styleInfoList);

            _pluginMenus   = PluginContentManager.GetContentMenus(_channelInfo);
            _pluginColumns = PluginContentManager.GetContentColumns(_channelInfo);
            _isEdit        = TextUtility.IsEdit(SiteInfo, channelId, AuthRequest.AdminPermissions);

            if (_channelInfo.Additional.IsPreviewContentsExists)
            {
                new Action(() =>
                {
                    DataProvider.ContentDao.DeletePreviewContents(SiteId, _tableName, _channelInfo);
                }).BeginInvoke(null, null);
            }

            if (!HasChannelPermissions(channelId, ConfigManager.ChannelPermissions.ContentView, ConfigManager.ChannelPermissions.ContentAdd, ConfigManager.ChannelPermissions.ContentEdit, ConfigManager.ChannelPermissions.ContentDelete, ConfigManager.ChannelPermissions.ContentTranslate))
            {
                if (!AuthRequest.IsAdminLoggin)
                {
                    PageUtils.RedirectToLoginPage();
                    return;
                }
                PageUtils.RedirectToErrorPage("您无此栏目的操作权限!");
                return;
            }

            RptContents.ItemDataBound += RptContents_ItemDataBound;

            var allLowerAttributeNameList = TableMetadataManager.GetAllLowerAttributeNameListExcludeText(_tableName);
            var pagerParam = new PagerParam
            {
                ControlToPaginate = RptContents,
                TableName         = _tableName,
                PageSize          = SiteInfo.Additional.PageSize,
                Page              = AuthRequest.GetQueryInt(Pager.QueryNamePage, 1),
                OrderSqlString    = DataProvider.ContentDao.GetPagerOrderSqlString(_channelInfo),
                ReturnColumnNames = TranslateUtils.ObjectCollectionToString(allLowerAttributeNameList)
            };

            var administratorName = AuthRequest.AdminPermissions.IsViewContentOnlySelf(SiteId, channelId) ? AuthRequest.AdminName : string.Empty;

            if (AuthRequest.IsQueryExists("searchType"))
            {
                pagerParam.WhereSqlString = DataProvider.ContentDao.GetPagerWhereSqlString(SiteInfo, _channelInfo, AuthRequest.GetQueryString("searchType"), AuthRequest.GetQueryString("keyword"),
                                                                                           AuthRequest.GetQueryString("dateFrom"), string.Empty, CheckManager.LevelInt.All, false, true, false, false, false, AuthRequest.AdminPermissions, allLowerAttributeNameList);
                pagerParam.TotalCount =
                    DataProvider.DatabaseDao.GetPageTotalCount(_tableName, pagerParam.WhereSqlString);
            }
            else
            {
                pagerParam.WhereSqlString = DataProvider.ContentDao.GetPagerWhereSqlString(channelId, ETriState.All, administratorName);
                pagerParam.TotalCount     = _channelInfo.ContentNum;
            }

            PgContents.Param = pagerParam;

            if (IsPostBack)
            {
                return;
            }

            PgContents.DataBind();

            var btnHtmls         = WebUtils.GetContentCommands(AuthRequest.AdminPermissions, SiteInfo, _channelInfo, PageUrl);
            var btnDropDownsHtml =
                WebUtils.GetContentMoreCommands(AuthRequest.AdminPermissions, SiteInfo, _channelInfo, PageUrl);

            LtlButtonsHead.Text = GetButtonsHtml(true, btnHtmls, btnDropDownsHtml);
            if (pagerParam.TotalCount > 10)
            {
                LtlButtonsFoot.Text = GetButtonsHtml(false, btnHtmls, btnDropDownsHtml);
            }

            foreach (var styleInfo in _allStyleInfoList)
            {
                if (styleInfo.InputType == InputType.TextEditor)
                {
                    continue;
                }

                var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                DdlSearchType.Items.Add(listitem);
            }

            if (AuthRequest.IsQueryExists("searchType"))
            {
                TbDateFrom.Text = AuthRequest.GetQueryString("dateFrom");
                ControlUtils.SelectSingleItem(DdlSearchType, AuthRequest.GetQueryString("searchType"));
                TbKeyword.Text = AuthRequest.GetQueryString("keyword");
                if (!string.IsNullOrEmpty(AuthRequest.GetQueryString("searchType")) || !string.IsNullOrEmpty(TbDateFrom.Text) ||
                    !string.IsNullOrEmpty(TbKeyword.Text))
                {
                    LtlButtonsHead.Text += @"
<script>
$(document).ready(function() {
	$('#contentSearch').show();
});
</script>
";
                }
            }
            else
            {
                ControlUtils.SelectSingleItem(DdlSearchType, ContentAttribute.Title);
            }

            LtlColumnsHead.Text = TextUtility.GetColumnsHeadHtml(_styleInfoList, _pluginColumns, _attributesOfDisplay);
        }
Example #24
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            if (AuthRequest.IsQueryExists("Delete"))
            {
                var list = TranslateUtils.StringCollectionToIntList(AuthRequest.GetQueryString("IDCollection"));
                try
                {
                    DataProvider.ErrorLogDao.Delete(list);
                    SuccessDeleteMessage();
                }
                catch (Exception ex)
                {
                    FailDeleteMessage(ex);
                }
            }
            else if (AuthRequest.IsQueryExists("DeleteAll"))
            {
                try
                {
                    DataProvider.ErrorLogDao.DeleteAll();
                    SuccessDeleteMessage();
                }
                catch (Exception ex)
                {
                    FailDeleteMessage(ex);
                }
            }
            else if (AuthRequest.IsQueryExists("Setting"))
            {
                ConfigManager.SystemConfigInfo.IsLogError = !ConfigManager.SystemConfigInfo.IsLogError;
                DataProvider.ConfigDao.Update(ConfigManager.Instance);
                SuccessMessage($"成功{(ConfigManager.SystemConfigInfo.IsLogError ? "启用" : "禁用")}日志记录");
            }

            SpContents.ControlToPaginate = RptContents;
            SpContents.ItemsPerPage      = Constants.PageSize;

            SpContents.SelectCommand = DataProvider.ErrorLogDao.GetSelectCommend(AuthRequest.GetQueryString("category"), AuthRequest.GetQueryString("pluginId"), AuthRequest.GetQueryString("keyword"),
                                                                                 AuthRequest.GetQueryString("dateFrom"), AuthRequest.GetQueryString("dateTo"));

            SpContents.SortField       = nameof(ErrorLogInfo.Id);
            SpContents.SortMode        = SortMode.DESC;
            RptContents.ItemDataBound += RptContents_ItemDataBound;

            if (IsPostBack)
            {
                return;
            }

            DdlCategory.Items.Add(new ListItem("全部", string.Empty));
            foreach (var category in LogUtils.AllCategoryList.Value)
            {
                DdlCategory.Items.Add(new ListItem(category.Value, category.Key));
            }

            DdlPluginId.Items.Add(new ListItem("全部", string.Empty));
            foreach (var pluginInfo in PluginManager.AllPluginInfoList)
            {
                DdlPluginId.Items.Add(new ListItem(pluginInfo.Id, pluginInfo.Id));
            }

            VerifySystemPermissions(ConfigManager.SettingsPermissions.Log);

            if (AuthRequest.IsQueryExists("keyword"))
            {
                ControlUtils.SelectSingleItem(DdlCategory, AuthRequest.GetQueryString("category"));
                ControlUtils.SelectSingleItem(DdlPluginId, AuthRequest.GetQueryString("pluginId"));
                TbKeyword.Text  = AuthRequest.GetQueryString("keyword");
                TbDateFrom.Text = AuthRequest.GetQueryString("dateFrom");
                TbDateTo.Text   = AuthRequest.GetQueryString("dateTo");
            }

            BtnDelete.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValueAndAlert(PageUtils.GetSettingsUrl(nameof(PageLogError), new NameValueCollection
            {
                { "Delete", "True" }
            }), "IDCollection", "IDCollection", "请选择需要删除的日志!", "此操作将删除所选日志,确认吗?"));

            BtnDeleteAll.Attributes.Add("onclick",
                                        AlertUtils.ConfirmRedirect("删除所有日志", "此操作将删除所有日志信息,确定吗?", "删除全部",
                                                                   PageUtils.GetSettingsUrl(nameof(PageLogError), new NameValueCollection
            {
                { "DeleteAll", "True" }
            })));

            if (ConfigManager.SystemConfigInfo.IsLogError)
            {
                BtnSetting.Text = "禁用系统错误日志";
                BtnSetting.Attributes.Add("onclick",
                                          AlertUtils.ConfirmRedirect("禁用系统错误日志", "此操作将禁用系统错误日志记录功能,确定吗?", "禁 用",
                                                                     PageUtils.GetSettingsUrl(nameof(PageLogError), new NameValueCollection
                {
                    { "Setting", "True" }
                })));
            }
            else
            {
                LtlState.Text   = @"<div class=""alert alert-danger m-t-10"">系统错误日志当前处于禁用状态,系统将不会记录系统错误日志!</div>";
                BtnSetting.Text = "启用系统错误日志";
                BtnSetting.Attributes.Add("onclick",
                                          AlertUtils.ConfirmRedirect("启用系统错误日志", "此操作将启用系统错误日志记录功能,确定吗?", "启 用",
                                                                     PageUtils.GetSettingsUrl(nameof(PageLogError), new NameValueCollection
                {
                    { "Setting", "True" }
                })));
            }

            SpContents.DataBind();
        }
Example #25
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");

            if (AuthRequest.IsQueryExists("channelId") && (AuthRequest.IsQueryExists("Subtract") || AuthRequest.IsQueryExists("Add")))
            {
                var channelId = AuthRequest.GetQueryInt("channelId");
                if (SiteId != channelId)
                {
                    var isSubtract = AuthRequest.IsQueryExists("Subtract");
                    DataProvider.ChannelDao.UpdateTaxis(SiteId, channelId, isSubtract);

                    AuthRequest.AddSiteLog(SiteId, channelId, 0, "栏目排序" + (isSubtract ? "上升" : "下降"),
                                           $"栏目:{ChannelManager.GetChannelName(SiteId, channelId)}");

                    PageUtils.Redirect(GetRedirectUrl(SiteId, channelId));
                    return;
                }
            }

            if (IsPostBack)
            {
                return;
            }

            ClientScriptRegisterClientScriptBlock("NodeTreeScript", ChannelLoading.GetScript(SiteInfo, string.Empty, ELoadingType.Channel, null));

            if (AuthRequest.IsQueryExists("CurrentChannelId"))
            {
                _currentChannelId = AuthRequest.GetQueryInt("CurrentChannelId");
                var onLoadScript = ChannelLoading.GetScriptOnLoad(SiteId, _currentChannelId);
                if (!string.IsNullOrEmpty(onLoadScript))
                {
                    ClientScriptRegisterClientScriptBlock("NodeTreeScriptOnLoad", onLoadScript);
                }
            }

            LtlButtonsHead.Text = LtlButtonsFoot.Text = GetButtonsHtml();

            var channelIdList = ChannelManager.GetChannelIdList(ChannelManager.GetChannelInfo(SiteId, SiteId), EScopeType.SelfAndChildren, string.Empty, string.Empty, string.Empty);

            RptContents.DataSource     = channelIdList;
            RptContents.ItemDataBound += RptContents_ItemDataBound;
            RptContents.DataBind();
        }
Example #26
0
        public async Task MakeSessionAsync(string acessToken, string refreshToken = null)
        {
            var rsa = new RsaService();
            var aes = new AesCrypt();

            var rsaPair = rsa.GenerateKeys();

            var strongKeyRequest = new
            {
                publicKey = rsaPair.publicKey
            };

            var authRequest = new AuthRequest(acessToken);

            string strongKeyJsonRequest    = JsonConvert.SerializeObject(strongKeyRequest);
            var    strongKeyRequestMessage = authRequest.BuildRequestMessage(ConfigurationManager.AppSettings.Get("devUrl") + Urls.GetStrongKeyUrl, HttpMethod.Post, strongKeyJsonRequest);

            var strongKeyResponseMessage = await authRequest.httpClient.SendAsync(strongKeyRequestMessage);

            if (strongKeyResponseMessage.StatusCode == HttpStatusCode.NotFound)
            {
                var firstSessionRequestModel = new CreateMessangerSessionRequest()
                {
                    PublicKey = rsaPair.publicKey
                };

                string jsonRequest = JsonConvert.SerializeObject(firstSessionRequestModel);

                var firstSessionResponse = await authRequest.GetStringFromHttpResultAsync(ConfigurationManager.AppSettings.Get("devUrl") + Urls.CreateFirstSessionUrl, HttpMethod.Post, jsonRequest);

                var response = JsonConvert.DeserializeObject <CreateFirstMessangerSessionResponse>(firstSessionResponse);

                string decryptedAesKey = rsa.Decrypt(rsaPair.privateKey, response.CryptedAes);

                byte[] decryptedAesKeyBuffer = decryptedAesKey.FromUrlSafeBase64();

                await userProvider.CreateStrongKeyAsync(UserId, decryptedAesKeyBuffer);

                string newToken = await tokenService.MakeAuthTokenAsync(UserId, true);

                authRequest = new AuthRequest(newToken);

                rsaPair = rsa.GenerateKeys();

                string cryptedPublicKey    = aes.Crypt(decryptedAesKeyBuffer.ToUrlSafeBase64(), rsaPair.publicKey);
                var    sessionRequestModel = new CreateMessangerSessionRequest()
                {
                    PublicKey = cryptedPublicKey
                };

                jsonRequest = JsonConvert.SerializeObject(sessionRequestModel);

                var httpRequest     = authRequest.BuildRequestMessage(ConfigurationManager.AppSettings.Get("devUrl") + Urls.CreateSessionUrl, HttpMethod.Post, jsonRequest);
                var sessionResponse = await authRequest.httpClient.SendAsync(httpRequest);

                sessionResponse.EnsureSuccessStatusCode();

                var    session = JsonConvert.DeserializeObject <CreateMessangerSessionResponse>(await sessionResponse.Content.ReadAsStringAsync());
                string decryptedServerPublicKey = aes.Decrypt(decryptedAesKey, session.ServerPublicKey);
                string decryptedSessionId       = aes.Decrypt(decryptedAesKey, session.SessionId);

                await userProvider.CreateSessionAsync(new Session()
                {
                    ClientPrivateKey = rsaPair.privateKey,
                    ServerPublicKey  = decryptedServerPublicKey,
                    ClientPublicKey  = rsaPair.publicKey,
                    UserId           = UserId,
                    SessionId        = decryptedSessionId
                });
            }
            else if (!string.IsNullOrEmpty(refreshToken) && strongKeyResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                var strongKeyResponse = JsonConvert.DeserializeObject <GetStrongKeyResponse>(
                    await strongKeyResponseMessage.Content.ReadAsStringAsync()
                    );

                var decryptedStrongKey = rsa.Decrypt(rsaPair.privateKey, strongKeyResponse.StrongKey);
                await userProvider.CreateStrongKeyAsync(UserId, decryptedStrongKey.FromUrlSafeBase64());

                rsaPair = rsa.GenerateKeys();
                var cryptedPublicKey = aes.Crypt(decryptedStrongKey, rsaPair.publicKey);

                var sessionRequest = new CreateMessangerSessionRequest()
                {
                    PublicKey = cryptedPublicKey
                };

                string jsonSessionRequest = JsonConvert.SerializeObject(sessionRequest);
                var    sessionResponse    = await authRequest.MakeRequestAsync <CreateMessangerSessionResponse>(ConfigurationManager.AppSettings.Get("devUrl") + Urls.CreateSessionUrl, HttpMethod.Post, jsonSessionRequest);

                string decryptedPublicKey = aes.Decrypt(decryptedStrongKey, sessionResponse.ServerPublicKey);
                string decryptedSessionId = aes.Decrypt(decryptedStrongKey, sessionResponse.SessionId);

                await userProvider.CreateSessionAsync(new Session()
                {
                    ClientPrivateKey = rsaPair.privateKey,
                    ClientPublicKey  = rsaPair.publicKey,
                    ServerPublicKey  = decryptedPublicKey,
                    UserId           = UserId,
                    SessionId        = decryptedSessionId
                });
            }
        }
Example #27
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId", "channelId");

            var channelId = AuthRequest.GetQueryInt("channelId");
            var contentId = AuthRequest.GetQueryInt("id");

            ReturnUrl = StringUtils.ValueFromUrl(AuthRequest.GetQueryString("returnUrl"));
            if (string.IsNullOrEmpty(ReturnUrl))
            {
                ReturnUrl = CmsPages.GetContentsUrl(SiteId, channelId);
            }

            _channelInfo = ChannelManager.GetChannelInfo(SiteId, channelId);
            _tableName   = ChannelManager.GetTableName(SiteInfo, _channelInfo);
            ContentInfo contentInfo = null;

            _styleInfoList = TableStyleManager.GetContentStyleInfoList(SiteInfo, _channelInfo);

            if (!IsPermissions(contentId))
            {
                return;
            }

            if (contentId > 0)
            {
                contentInfo = ContentManager.GetContentInfo(SiteInfo, _channelInfo, contentId);
            }

            var titleFormat = IsPostBack ? Request.Form[ContentAttribute.GetFormatStringAttributeName(ContentAttribute.Title)] : contentInfo?.GetString(ContentAttribute.GetFormatStringAttributeName(ContentAttribute.Title));

            LtlTitleHtml.Text = ContentUtility.GetTitleHtml(titleFormat);

            AcAttributes.SiteInfo      = SiteInfo;
            AcAttributes.ChannelId     = _channelInfo.Id;
            AcAttributes.ContentId     = contentId;
            AcAttributes.StyleInfoList = _styleInfoList;

            if (!IsPostBack)
            {
                var pageTitle = contentId == 0 ? "添加内容" : "编辑内容";

                LtlPageTitle.Text = pageTitle;

                if (HasChannelPermissions(_channelInfo.Id, ConfigManager.ChannelPermissions.ContentTranslate))
                {
                    PhTranslate.Visible = true;
                    BtnTranslate.Attributes.Add("onclick", ModalChannelMultipleSelect.GetOpenWindowString(SiteId, true));

                    ETranslateContentTypeUtils.AddListItems(DdlTranslateType, true);
                    ControlUtils.SelectSingleItem(DdlTranslateType, ETranslateContentTypeUtils.GetValue(ETranslateContentType.Copy));
                }
                else
                {
                    PhTranslate.Visible = false;
                }

                CblContentAttributes.Items.Add(new ListItem("置顶", ContentAttribute.IsTop));
                CblContentAttributes.Items.Add(new ListItem("推荐", ContentAttribute.IsRecommend));
                CblContentAttributes.Items.Add(new ListItem("热点", ContentAttribute.IsHot));
                CblContentAttributes.Items.Add(new ListItem("醒目", ContentAttribute.IsColor));
                TbAddDate.DateTime = DateTime.Now;
                TbAddDate.Now      = true;

                var contentGroupNameList = ContentGroupManager.GetGroupNameList(SiteId);
                foreach (var groupName in contentGroupNameList)
                {
                    var item = new ListItem(groupName, groupName);
                    CblContentGroups.Items.Add(item);
                }

                BtnContentGroupAdd.Attributes.Add("onclick", ModalContentGroupAdd.GetOpenWindowString(SiteId));

                LtlTags.Text = ContentUtility.GetTagsHtml(AjaxCmsService.GetTagsUrl(SiteId));

                if (HasChannelPermissions(_channelInfo.Id, ConfigManager.ChannelPermissions.ContentCheck))
                {
                    PhStatus.Visible = true;
                    int checkedLevel;
                    var isChecked = CheckManager.GetUserCheckLevel(AuthRequest.AdminPermissionsImpl, SiteInfo, _channelInfo.Id, out checkedLevel);
                    if (AuthRequest.IsQueryExists("contentLevel"))
                    {
                        checkedLevel = TranslateUtils.ToIntWithNagetive(AuthRequest.GetQueryString("contentLevel"));
                        if (checkedLevel != CheckManager.LevelInt.NotChange)
                        {
                            isChecked = checkedLevel >= SiteInfo.Additional.CheckContentLevel;
                        }
                    }

                    CheckManager.LoadContentLevelToEdit(DdlContentLevel, SiteInfo, contentInfo, isChecked, checkedLevel);
                }
                else
                {
                    PhStatus.Visible = false;
                }

                BtnSubmit.Attributes.Add("onclick", InputParserUtils.GetValidateSubmitOnClickScript("myForm", true, "autoCheckKeywords()"));
                //自动检测敏感词
                ClientScriptRegisterStartupScript("autoCheckKeywords", WebUtils.GetAutoCheckKeywordsScript(SiteInfo));

                if (contentId == 0)
                {
                    var attributes = TableStyleManager.GetDefaultAttributes(_styleInfoList);

                    if (AuthRequest.IsQueryExists("isUploadWord"))
                    {
                        var isFirstLineTitle  = AuthRequest.GetQueryBool("isFirstLineTitle");
                        var isFirstLineRemove = AuthRequest.GetQueryBool("isFirstLineRemove");
                        var isClearFormat     = AuthRequest.GetQueryBool("isClearFormat");
                        var isFirstLineIndent = AuthRequest.GetQueryBool("isFirstLineIndent");
                        var isClearFontSize   = AuthRequest.GetQueryBool("isClearFontSize");
                        var isClearFontFamily = AuthRequest.GetQueryBool("isClearFontFamily");
                        var isClearImages     = AuthRequest.GetQueryBool("isClearImages");
                        var contentLevel      = AuthRequest.GetQueryInt("contentLevel");
                        var fileName          = AuthRequest.GetQueryString("fileName");

                        var formCollection = WordUtils.GetWordNameValueCollection(SiteId, isFirstLineTitle, isFirstLineRemove, isClearFormat, isFirstLineIndent, isClearFontSize, isClearFontFamily, isClearImages, fileName);
                        attributes.Load(formCollection);

                        TbTitle.Text = formCollection[ContentAttribute.Title];
                    }

                    AcAttributes.Attributes = attributes;
                }
                else if (contentInfo != null)
                {
                    TbTitle.Text = contentInfo.Title;

                    TbTags.Text = contentInfo.Tags;

                    var list = new List <string>();
                    if (contentInfo.IsTop)
                    {
                        list.Add(ContentAttribute.IsTop);
                    }
                    if (contentInfo.IsRecommend)
                    {
                        list.Add(ContentAttribute.IsRecommend);
                    }
                    if (contentInfo.IsHot)
                    {
                        list.Add(ContentAttribute.IsHot);
                    }
                    if (contentInfo.IsColor)
                    {
                        list.Add(ContentAttribute.IsColor);
                    }
                    ControlUtils.SelectMultiItems(CblContentAttributes, list);
                    TbLinkUrl.Text = contentInfo.LinkUrl;
                    if (contentInfo.AddDate.HasValue)
                    {
                        TbAddDate.DateTime = contentInfo.AddDate.Value;
                    }

                    ControlUtils.SelectMultiItems(CblContentGroups, TranslateUtils.StringCollectionToStringList(contentInfo.GroupNameCollection));

                    AcAttributes.Attributes = contentInfo;
                }
            }
            else
            {
                AcAttributes.Attributes = new AttributesImpl(Request.Form);
            }
            //DataBind();
        }
Example #28
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsPostBack || !Page.IsValid)
            {
                return;
            }

            var contentId   = AuthRequest.GetQueryInt("id");
            var redirectUrl = string.Empty;

            if (contentId == 0)
            {
                try
                {
                    var dict = BackgroundInputTypeParser.SaveAttributes(SiteInfo, _styleInfoList, Request.Form, ContentAttribute.AllAttributes.Value);

                    var contentInfo = new ContentInfo(dict)
                    {
                        ChannelId           = _channelInfo.Id,
                        SiteId              = SiteId,
                        AddUserName         = AuthRequest.AdminName,
                        LastEditDate        = DateTime.Now,
                        GroupNameCollection = ControlUtils.SelectedItemsValueToStringCollection(CblContentGroups.Items),
                        Title = TbTitle.Text
                    };

                    var formatString    = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatStrong"]);
                    var formatEm        = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatEM"]);
                    var formatU         = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatU"]);
                    var formatColor     = Request.Form[ContentAttribute.Title + "_formatColor"];
                    var theFormatString = ContentUtility.GetTitleFormatString(formatString, formatEm, formatU, formatColor);
                    contentInfo.Set(ContentAttribute.GetFormatStringAttributeName(ContentAttribute.Title), theFormatString);

                    contentInfo.LastEditUserName = contentInfo.AddUserName;

                    foreach (ListItem listItem in CblContentAttributes.Items)
                    {
                        var value         = listItem.Selected.ToString();
                        var attributeName = listItem.Value;
                        contentInfo.Set(attributeName, value);
                    }
                    contentInfo.LinkUrl = TbLinkUrl.Text;
                    contentInfo.AddDate = TbAddDate.DateTime;

                    contentInfo.CheckedLevel = TranslateUtils.ToIntWithNagetive(DdlContentLevel.SelectedValue);
                    contentInfo.IsChecked    = contentInfo.CheckedLevel >= SiteInfo.Additional.CheckContentLevel;
                    contentInfo.Tags         = TranslateUtils.ObjectCollectionToString(TagUtils.ParseTagsString(TbTags.Text), " ");

                    foreach (var service in PluginManager.Services)
                    {
                        try
                        {
                            service.OnContentFormSubmit(new ContentFormSubmitEventArgs(SiteId, _channelInfo.Id,
                                                                                       contentInfo.Id, TranslateUtils.ToDictionary(Request.Form), contentInfo));
                        }
                        catch (Exception ex)
                        {
                            LogUtils.AddErrorLog(service.PluginId, ex, nameof(IService.ContentFormSubmit));
                        }
                    }


                    //判断是不是有审核权限
                    int checkedLevelOfUser;
                    var isCheckedOfUser = CheckManager.GetUserCheckLevel(AuthRequest.AdminPermissionsImpl, SiteInfo, contentInfo.ChannelId, out checkedLevelOfUser);
                    if (CheckManager.IsCheckable(contentInfo.IsChecked, contentInfo.CheckedLevel, isCheckedOfUser, checkedLevelOfUser))
                    {
                        if (contentInfo.IsChecked)
                        {
                            contentInfo.CheckedLevel = 0;
                        }

                        contentInfo.Set(ContentAttribute.CheckUserName, AuthRequest.AdminName);
                        contentInfo.Set(ContentAttribute.CheckDate, DateUtils.GetDateAndTimeString(DateTime.Now));
                        contentInfo.Set(ContentAttribute.CheckReasons, string.Empty);
                    }

                    contentInfo.Id = DataProvider.ContentDao.Insert(_tableName, SiteInfo, _channelInfo, contentInfo);

                    TagUtils.UpdateTags(string.Empty, TbTags.Text, SiteId, contentInfo.Id);

                    CreateManager.CreateContent(SiteId, _channelInfo.Id, contentInfo.Id);
                    CreateManager.TriggerContentChangedEvent(SiteId, _channelInfo.Id);

                    AuthRequest.AddSiteLog(SiteId, _channelInfo.Id, contentInfo.Id, "添加内容",
                                           $"栏目:{ChannelManager.GetChannelNameNavigation(SiteId, contentInfo.ChannelId)},内容标题:{contentInfo.Title}");

                    ContentUtility.Translate(SiteInfo, _channelInfo.Id, contentInfo.Id, Request.Form["translateCollection"], ETranslateContentTypeUtils.GetEnumType(DdlTranslateType.SelectedValue), AuthRequest.AdminName);

                    redirectUrl = PageContentAddAfter.GetRedirectUrl(SiteId, _channelInfo.Id, contentInfo.Id,
                                                                     ReturnUrl);
                }
                catch (Exception ex)
                {
                    LogUtils.AddErrorLog(ex);
                    FailMessage($"内容添加失败:{ex.Message}");
                }
            }
            else
            {
                var contentInfo = ContentManager.GetContentInfo(SiteInfo, _channelInfo, contentId);
                try
                {
                    contentInfo.LastEditUserName = AuthRequest.AdminName;
                    contentInfo.LastEditDate     = DateTime.Now;

                    var dict = BackgroundInputTypeParser.SaveAttributes(SiteInfo, _styleInfoList, Request.Form, ContentAttribute.AllAttributes.Value);
                    contentInfo.Load(dict);

                    contentInfo.GroupNameCollection = ControlUtils.SelectedItemsValueToStringCollection(CblContentGroups.Items);

                    contentInfo.Title = TbTitle.Text;
                    var formatString    = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatStrong"]);
                    var formatEm        = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatEM"]);
                    var formatU         = TranslateUtils.ToBool(Request.Form[ContentAttribute.Title + "_formatU"]);
                    var formatColor     = Request.Form[ContentAttribute.Title + "_formatColor"];
                    var theFormatString = ContentUtility.GetTitleFormatString(formatString, formatEm, formatU, formatColor);
                    contentInfo.Set(ContentAttribute.GetFormatStringAttributeName(ContentAttribute.Title), theFormatString);
                    foreach (ListItem listItem in CblContentAttributes.Items)
                    {
                        var value         = listItem.Selected.ToString();
                        var attributeName = listItem.Value;
                        contentInfo.Set(attributeName, value);
                    }
                    contentInfo.LinkUrl = TbLinkUrl.Text;
                    contentInfo.AddDate = TbAddDate.DateTime;

                    var checkedLevel = TranslateUtils.ToIntWithNagetive(DdlContentLevel.SelectedValue);
                    if (checkedLevel != CheckManager.LevelInt.NotChange)
                    {
                        contentInfo.IsChecked    = checkedLevel >= SiteInfo.Additional.CheckContentLevel;
                        contentInfo.CheckedLevel = checkedLevel;
                    }

                    TagUtils.UpdateTags(contentInfo.Tags, TbTags.Text, SiteId, contentId);
                    contentInfo.Tags = TranslateUtils.ObjectCollectionToString(TagUtils.ParseTagsString(TbTags.Text), " ");

                    foreach (var service in PluginManager.Services)
                    {
                        try
                        {
                            service.OnContentFormSubmit(new ContentFormSubmitEventArgs(SiteId, _channelInfo.Id,
                                                                                       contentInfo.Id, TranslateUtils.ToDictionary(Request.Form), contentInfo));
                        }
                        catch (Exception ex)
                        {
                            LogUtils.AddErrorLog(service.PluginId, ex, nameof(IService.ContentFormSubmit));
                        }
                    }

                    DataProvider.ContentDao.Update(SiteInfo, _channelInfo, contentInfo);

                    ContentUtility.Translate(SiteInfo, _channelInfo.Id, contentInfo.Id, Request.Form["translateCollection"], ETranslateContentTypeUtils.GetEnumType(DdlTranslateType.SelectedValue), AuthRequest.AdminName);

                    CreateManager.CreateContent(SiteId, _channelInfo.Id, contentId);
                    CreateManager.TriggerContentChangedEvent(SiteId, _channelInfo.Id);

                    AuthRequest.AddSiteLog(SiteId, _channelInfo.Id, contentId, "修改内容",
                                           $"栏目:{ChannelManager.GetChannelNameNavigation(SiteId, contentInfo.ChannelId)},内容标题:{contentInfo.Title}");

                    redirectUrl = ReturnUrl;

                    //更新引用该内容的信息
                    //如果不是异步自动保存,那么需要将引用此内容的content修改
                    //var sourceContentIdList = new List<int>
                    //{
                    //    contentInfo.Id
                    //};
                    //var tableList = DataProvider.TableDao.GetTableCollectionInfoListCreatedInDb();
                    //foreach (var table in tableList)
                    //{
                    //    var targetContentIdList = DataProvider.ContentDao.GetReferenceIdList(table.TableName, sourceContentIdList);
                    //    foreach (var targetContentId in targetContentIdList)
                    //    {
                    //        var targetContentInfo = DataProvider.ContentDao.GetContentInfo(table.TableName, targetContentId);
                    //        if (targetContentInfo == null || targetContentInfo.GetString(ContentAttribute.TranslateContentType) != ETranslateContentType.ReferenceContent.ToString()) continue;

                    //        contentInfo.Id = targetContentId;
                    //        contentInfo.SiteId = targetContentInfo.SiteId;
                    //        contentInfo.ChannelId = targetContentInfo.ChannelId;
                    //        contentInfo.SourceId = targetContentInfo.SourceId;
                    //        contentInfo.ReferenceId = targetContentInfo.ReferenceId;
                    //        contentInfo.Taxis = targetContentInfo.Taxis;
                    //        contentInfo.Set(ContentAttribute.TranslateContentType, targetContentInfo.GetString(ContentAttribute.TranslateContentType));
                    //        DataProvider.ContentDao.Update(table.TableName, contentInfo);

                    //        //资源:图片,文件,视频
                    //        var targetSiteInfo = SiteManager.GetSiteInfo(targetContentInfo.SiteId);
                    //        var bgContentInfo = contentInfo as BackgroundContentInfo;
                    //        var bgTargetContentInfo = targetContentInfo as BackgroundContentInfo;
                    //        if (bgTargetContentInfo != null && bgContentInfo != null)
                    //        {
                    //            if (bgContentInfo.ImageUrl != bgTargetContentInfo.ImageUrl)
                    //            {
                    //                //修改图片
                    //                var sourceImageUrl = PathUtility.MapPath(SiteInfo, bgContentInfo.ImageUrl);
                    //                CopyReferenceFiles(targetSiteInfo, sourceImageUrl);
                    //            }
                    //            else if (bgContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.ImageUrl)) != bgTargetContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.ImageUrl)))
                    //            {
                    //                var sourceImageUrls = TranslateUtils.StringCollectionToStringList(bgContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.ImageUrl)));

                    //                foreach (string imageUrl in sourceImageUrls)
                    //                {
                    //                    var sourceImageUrl = PathUtility.MapPath(SiteInfo, imageUrl);
                    //                    CopyReferenceFiles(targetSiteInfo, sourceImageUrl);
                    //                }
                    //            }
                    //            if (bgContentInfo.FileUrl != bgTargetContentInfo.FileUrl)
                    //            {
                    //                //修改附件
                    //                var sourceFileUrl = PathUtility.MapPath(SiteInfo, bgContentInfo.FileUrl);
                    //                CopyReferenceFiles(targetSiteInfo, sourceFileUrl);

                    //            }
                    //            else if (bgContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.FileUrl)) != bgTargetContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.FileUrl)))
                    //            {
                    //                var sourceFileUrls = TranslateUtils.StringCollectionToStringList(bgContentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.FileUrl)));

                    //                foreach (var fileUrl in sourceFileUrls)
                    //                {
                    //                    var sourceFileUrl = PathUtility.MapPath(SiteInfo, fileUrl);
                    //                    CopyReferenceFiles(targetSiteInfo, sourceFileUrl);
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    LogUtils.AddErrorLog(ex);
                    FailMessage($"内容修改失败:{ex.Message}");
                    return;
                }
            }

            PageUtils.Redirect(redirectUrl);
        }
Example #29
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            if (IsPostBack)
            {
                return;
            }

            VerifyAdministratorPermissions(ConfigManager.SettingsPermissions.SiteAdd);

            DataProvider.TableDao.CreateAllTableCollectionInfoIfNotExists();

            var hqSiteId = DataProvider.SiteDao.GetIdByIsRoot();

            if (hqSiteId == 0)
            {
                ControlUtils.SelectSingleItem(RblIsRoot, true.ToString());
                PhIsNotRoot.Visible = false;
            }
            else
            {
                RblIsRoot.Enabled = false;
            }

            DdlParentId.Items.Add(new ListItem("<无上级站点>", "0"));
            var siteIdArrayList       = SiteManager.GetSiteIdList();
            var mySystemInfoArrayList = new ArrayList();
            var parentWithChildren    = new Hashtable();

            foreach (var siteId in siteIdArrayList)
            {
                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo.IsRoot == false)
                {
                    if (siteInfo.ParentId == 0)
                    {
                        mySystemInfoArrayList.Add(siteInfo);
                    }
                    else
                    {
                        var children = new ArrayList();
                        if (parentWithChildren.Contains(siteInfo.ParentId))
                        {
                            children = (ArrayList)parentWithChildren[siteInfo.ParentId];
                        }
                        children.Add(siteInfo);
                        parentWithChildren[siteInfo.ParentId] = children;
                    }
                }
            }
            foreach (SiteInfo siteInfo in mySystemInfoArrayList)
            {
                AddSite(DdlParentId, siteInfo, parentWithChildren, 0);
            }
            ControlUtils.SelectSingleItem(DdlParentId, "0");

            ECharsetUtils.AddListItems(DdlCharset);
            ControlUtils.SelectSingleItem(DdlCharset, ECharsetUtils.GetValue(ECharset.utf_8));

            var tableList = DataProvider.TableDao.GetTableCollectionInfoListCreatedInDb();

            foreach (var tableInfo in tableList)
            {
                if (tableInfo.DisplayName.StartsWith("插件内容表:"))
                {
                    continue;
                }

                var li = new ListItem($"{tableInfo.DisplayName}({tableInfo.TableName})", tableInfo.TableName);
                DdlTableName.Items.Add(li);
            }

            RblIsCheckContentUseLevel.Items.Add(new ListItem("默认审核机制", false.ToString()));
            RblIsCheckContentUseLevel.Items.Add(new ListItem("多级审核机制", true.ToString()));
            ControlUtils.SelectSingleItem(RblIsCheckContentUseLevel, false.ToString());

            if (SiteTemplateManager.Instance.IsSiteTemplateExists)
            {
                RblSource.Items.Add(new ListItem("创建空站点(不使用站点模板)", ETriStateUtils.GetValue(ETriState.True)));
                RblSource.Items.Add(new ListItem("使用本地站点模板创建站点", ETriStateUtils.GetValue(ETriState.False)));
                RblSource.Items.Add(new ListItem("使用在线站点模板创建站点", ETriStateUtils.GetValue(ETriState.All)));
            }
            else
            {
                RblSource.Items.Add(new ListItem("创建空站点(不使用站点模板)", ETriStateUtils.GetValue(ETriState.True)));
                RblSource.Items.Add(new ListItem("使用在线站点模板创建站点", ETriStateUtils.GetValue(ETriState.All)));
            }
            ControlUtils.SelectSingleItem(RblSource, ETriStateUtils.GetValue(ETriState.True));

            var siteTemplateDir    = AuthRequest.GetQueryString("siteTemplateDir");
            var onlineTemplateName = AuthRequest.GetQueryString("onlineTemplateName");

            if (!string.IsNullOrEmpty(siteTemplateDir))
            {
                HihSiteTemplateDir.Value = siteTemplateDir;
                ControlUtils.SelectSingleItem(RblSource, ETriStateUtils.GetValue(ETriState.False));
                BtnNext_Click(null, EventArgs.Empty);
            }
            else if (!string.IsNullOrEmpty(onlineTemplateName))
            {
                HihOnlineTemplateName.Value = onlineTemplateName;
                ControlUtils.SelectSingleItem(RblSource, ETriStateUtils.GetValue(ETriState.All));
                BtnNext_Click(null, EventArgs.Empty);
            }
        }
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId", "channelId", "ReturnUrl");

            _channelId = AuthRequest.GetQueryInt("channelId");
            ReturnUrl  = StringUtils.ValueFromUrl(AuthRequest.GetQueryString("ReturnUrl"));

            if (AuthRequest.GetQueryString("CanNotEdit") == null && AuthRequest.GetQueryString("UncheckedChannel") == null)
            {
                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ChannelEdit))
                {
                    PageUtils.RedirectToErrorPage("您没有修改栏目的权限!");
                    return;
                }
            }
            if (AuthRequest.IsQueryExists("CanNotEdit"))
            {
                BtnSubmit.Visible = false;
            }

            var channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);

            if (channelInfo == null)
            {
                return;
            }

            CacAttributes.SiteInfo  = SiteInfo;
            CacAttributes.ChannelId = _channelId;

            if (!IsPostBack)
            {
                DdlContentModelPluginId.Items.Add(new ListItem("<默认>", string.Empty));
                var contentTables = PluginContentManager.GetContentModelPlugins();
                foreach (var contentTable in contentTables)
                {
                    DdlContentModelPluginId.Items.Add(new ListItem(contentTable.Title, contentTable.Id));
                }
                ControlUtils.SelectSingleItem(DdlContentModelPluginId, channelInfo.ContentModelPluginId);

                var plugins = PluginContentManager.GetAllContentRelatedPlugins(false);
                if (plugins.Count > 0)
                {
                    var relatedPluginIds =
                        TranslateUtils.StringCollectionToStringList(channelInfo.ContentRelatedPluginIds);
                    foreach (var pluginMetadata in plugins)
                    {
                        CblContentRelatedPluginIds.Items.Add(new ListItem(pluginMetadata.Title, pluginMetadata.Id)
                        {
                            Selected = relatedPluginIds.Contains(pluginMetadata.Id)
                        });
                    }
                }
                else
                {
                    PhContentRelatedPluginIds.Visible = false;
                }

                CacAttributes.Attributes = channelInfo.Additional;

                TbImageUrl.Attributes.Add("onchange", GetShowImageScript("preview_NavigationPicPath", SiteInfo.Additional.WebUrl));

                var showPopWinString = ModalFilePathRule.GetOpenWindowString(SiteId, _channelId, true, TbChannelFilePathRule.ClientID);
                BtnCreateChannelRule.Attributes.Add("onclick", showPopWinString);

                showPopWinString = ModalFilePathRule.GetOpenWindowString(SiteId, _channelId, false, TbContentFilePathRule.ClientID);
                BtnCreateContentRule.Attributes.Add("onclick", showPopWinString);

                showPopWinString = ModalSelectImage.GetOpenWindowString(SiteInfo, TbImageUrl.ClientID);
                BtnSelectImage.Attributes.Add("onclick", showPopWinString);

                showPopWinString = ModalUploadImage.GetOpenWindowString(SiteId, TbImageUrl.ClientID);
                BtnUploadImage.Attributes.Add("onclick", showPopWinString);

                ELinkTypeUtils.AddListItems(DdlLinkType);
                ETaxisTypeUtils.AddListItemsForChannelEdit(DdlTaxisType);

                ControlUtils.AddListControlItems(CblNodeGroupNameCollection, ChannelGroupManager.GetGroupNameList(SiteId));
                //CblNodeGroupNameCollection.DataSource = DataProvider.ChannelGroupDao.GetDataSource(SiteId);

                DdlChannelTemplateId.DataSource = DataProvider.TemplateDao.GetDataSourceByType(SiteId, TemplateType.ChannelTemplate);

                DdlContentTemplateId.DataSource = DataProvider.TemplateDao.GetDataSourceByType(SiteId, TemplateType.ContentTemplate);

                DataBind();

                DdlChannelTemplateId.Items.Insert(0, new ListItem("<未设置>", "0"));
                ControlUtils.SelectSingleItem(DdlChannelTemplateId, channelInfo.ChannelTemplateId.ToString());

                DdlContentTemplateId.Items.Insert(0, new ListItem("<未设置>", "0"));
                ControlUtils.SelectSingleItem(DdlContentTemplateId, channelInfo.ContentTemplateId.ToString());

                TbNodeName.Text      = channelInfo.ChannelName;
                TbNodeIndexName.Text = channelInfo.IndexName;
                TbLinkUrl.Text       = channelInfo.LinkUrl;

                foreach (ListItem item in CblNodeGroupNameCollection.Items)
                {
                    item.Selected = StringUtils.In(channelInfo.GroupNameCollection, item.Value);
                }
                TbFilePath.Text            = channelInfo.FilePath;
                TbChannelFilePathRule.Text = channelInfo.ChannelFilePathRule;
                TbContentFilePathRule.Text = channelInfo.ContentFilePathRule;

                ControlUtils.SelectSingleItem(DdlLinkType, channelInfo.LinkType);
                ControlUtils.SelectSingleItem(DdlTaxisType, channelInfo.Additional.DefaultTaxisType);
                ControlUtils.SelectSingleItem(RblIsChannelAddable, channelInfo.Additional.IsChannelAddable.ToString());
                ControlUtils.SelectSingleItem(RblIsContentAddable, channelInfo.Additional.IsContentAddable.ToString());

                TbImageUrl.Text = channelInfo.ImageUrl;

                TbContent.SetParameters(SiteInfo, ChannelAttribute.Content, channelInfo.Content);

                TbKeywords.Text    = channelInfo.Keywords;
                TbDescription.Text = channelInfo.Description;

                //this.Content.SiteId = base.SiteId;
                //this.Content.Text = StringUtility.TextEditorContentDecode(channelInfo.Content, ConfigUtils.Instance.ApplicationPath, base.SiteInfo.SiteUrl);
            }
            else
            {
                CacAttributes.Attributes = new AttributesImpl(Request.Form);
            }
        }
Example #31
0
 /// <summary>
 /// Attempts to setup a token from the specified authorization code.
 /// </summary>
 /// <param name="code">The HF API code used to generate a token.</param>
 /// <param name="token">The acquired token.</param>
 public bool TryGetAuthToken(string code, out AuthToken token)
 {
     token = AuthRequest.GetToken(Client, ClientId, ClientSecret, code);
     return(token.IsSuccess);
 }
Example #32
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            var isChanged = false;

            if (!string.IsNullOrEmpty(_tagName))
            {
                try
                {
                    if (!string.Equals(_tagName, TbTags.Text))
                    {
                        var tagCollection = TagUtils.ParseTagsString(TbTags.Text);
                        var contentIdList = DataProvider.TagDao.GetContentIdListByTag(_tagName, SiteId);
                        if (contentIdList.Count > 0)
                        {
                            foreach (var contentId in contentIdList)
                            {
                                if (!tagCollection.Contains(_tagName))//删除
                                {
                                    var tagInfo = DataProvider.TagDao.GetTagInfo(SiteId, _tagName);
                                    if (tagInfo != null)
                                    {
                                        var idArrayList = TranslateUtils.StringCollectionToIntList(tagInfo.ContentIdCollection);
                                        idArrayList.Remove(contentId);
                                        tagInfo.ContentIdCollection = TranslateUtils.ObjectCollectionToString(idArrayList);
                                        tagInfo.UseNum = idArrayList.Count;
                                        DataProvider.TagDao.Update(tagInfo);
                                    }
                                }

                                TagUtils.UpdateTags(string.Empty, TbTags.Text, SiteId, contentId);

                                var tuple = DataProvider.ContentDao.GetValue(SiteInfo.TableName, contentId, ContentAttribute.Tags);

                                if (tuple != null)
                                {
                                    var contentTagList = TranslateUtils.StringCollectionToStringList(tuple.Item2);
                                    contentTagList.Remove(_tagName);
                                    foreach (var theTag in tagCollection)
                                    {
                                        if (!contentTagList.Contains(theTag))
                                        {
                                            contentTagList.Add(theTag);
                                        }
                                    }
                                    DataProvider.ContentDao.Update(SiteInfo.TableName, tuple.Item1, contentId, ContentAttribute.Tags, TranslateUtils.ObjectCollectionToString(contentTagList));
                                }
                            }
                        }
                        else
                        {
                            DataProvider.TagDao.DeleteTag(_tagName, SiteId);
                        }
                    }

                    AuthRequest.AddSiteLog(SiteId, "修改内容标签", $"内容标签:{TbTags.Text}");

                    isChanged = true;
                }
                catch (Exception ex)
                {
                    FailMessage(ex, "标签修改失败!");
                }
            }
            else
            {
                try
                {
                    TagUtils.UpdateTags(string.Empty, TbTags.Text, SiteId, 0);
                    AuthRequest.AddSiteLog(SiteId, "添加内容标签", $"内容标签:{TbTags.Text}");
                    isChanged = true;
                }
                catch (Exception ex)
                {
                    FailMessage(ex, "标签添加失败!");
                }
            }

            if (isChanged)
            {
                LayerUtils.Close(Page);
            }
        }
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            _exportType = AuthRequest.GetQueryString("ExportType");

            if (!IsPostBack)
            {
                var isExport = true;
                var fileName = string.Empty;
                try
                {
                    if (_exportType == ExportTypeRelatedField)
                    {
                        var relatedFieldId = AuthRequest.GetQueryInt("RelatedFieldID");
                        fileName = ExportRelatedField(relatedFieldId);
                    }
                    else if (_exportType == ExportTypeContentZip)
                    {
                        var channelId           = AuthRequest.GetQueryInt("channelId");
                        var contentIdCollection = TranslateUtils.StringCollectionToIntList(AuthRequest.GetQueryString("contentIdCollection"));
                        var isPeriods           = AuthRequest.GetQueryBool("isPeriods");
                        var startDate           = AuthRequest.GetQueryString("startDate");
                        var endDate             = AuthRequest.GetQueryString("endDate");
                        var checkedState        = ETriStateUtils.GetEnumType(AuthRequest.GetQueryString("checkedState"));
                        isExport = ExportContentZip(channelId, contentIdCollection, isPeriods, startDate, endDate, checkedState, out fileName);
                    }
                    else if (_exportType == ExportTypeContentAccess)
                    {
                        var channelId           = AuthRequest.GetQueryInt("channelId");
                        var contentIdCollection = TranslateUtils.StringCollectionToIntList(AuthRequest.GetQueryString("contentIdCollection"));
                        var displayAttributes   = TranslateUtils.StringCollectionToStringList(AuthRequest.GetQueryString("DisplayAttributes"));
                        var isPeriods           = AuthRequest.GetQueryBool("isPeriods");
                        var startDate           = AuthRequest.GetQueryString("startDate");
                        var endDate             = AuthRequest.GetQueryString("endDate");
                        var checkedState        = ETriStateUtils.GetEnumType(AuthRequest.GetQueryString("checkedState"));
                        isExport = ExportContentAccess(channelId, contentIdCollection, displayAttributes, isPeriods, startDate, endDate, checkedState, out fileName);
                    }
                    else if (_exportType == ExportTypeContentExcel)
                    {
                        var channelId           = AuthRequest.GetQueryInt("channelId");
                        var contentIdCollection = TranslateUtils.StringCollectionToIntList(AuthRequest.GetQueryString("contentIdCollection"));
                        var displayAttributes   = TranslateUtils.StringCollectionToStringList(AuthRequest.GetQueryString("DisplayAttributes"));
                        var isPeriods           = AuthRequest.GetQueryBool("isPeriods");
                        var startDate           = AuthRequest.GetQueryString("startDate");
                        var endDate             = AuthRequest.GetQueryString("endDate");
                        var checkedState        = ETriStateUtils.GetEnumType(AuthRequest.GetQueryString("checkedState"));
                        ExportContentExcel(channelId, contentIdCollection, displayAttributes, isPeriods, startDate, endDate, checkedState, out fileName);
                    }
                    else if (_exportType == ExportTypeChannel)
                    {
                        var channelIdList = TranslateUtils.StringCollectionToIntList(AuthRequest.GetQueryString("ChannelIDCollection"));
                        fileName = ExportChannel(channelIdList);
                    }
                    else if (_exportType == ExportTypeSingleTableStyle)
                    {
                        var tableName       = AuthRequest.GetQueryString("TableName");
                        var relatedIdentity = AuthRequest.GetQueryInt("RelatedIdentity");
                        fileName = ExportSingleTableStyle(tableName, relatedIdentity);
                    }

                    if (isExport)
                    {
                        var link     = new HyperLink();
                        var filePath = PathUtils.GetTemporaryFilesPath(fileName);
                        link.NavigateUrl = ApiRouteActionsDownload.GetUrl(ApiManager.InnerApiUrl, filePath);
                        link.Text        = "下载";
                        var successMessage = "成功导出文件!&nbsp;&nbsp;" + ControlUtils.GetControlRenderHtml(link);
                        SuccessMessage(successMessage);
                    }
                    else
                    {
                        FailMessage("导出失败,所选条件没有匹配内容,请重新选择条件导出内容");
                    }
                }
                catch (Exception ex)
                {
                    var failedMessage = "文件导出失败!<br/><br/>原因为:" + ex.Message;
                    FailMessage(ex, failedMessage);
                }
            }
        }
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId", "type");
            _type = AuthRequest.GetQueryString("type");
            if (_type == PageTemplateAssets.TypeInclude)
            {
                _name      = PageTemplateAssets.NameInclude;
                _ext       = PageTemplateAssets.ExtInclude;
                _assetsDir = SiteInfo.Additional.TemplatesAssetsIncludeDir.Trim('/');
                PhCodeMirrorInclude.Visible = true;
            }
            else if (_type == PageTemplateAssets.TypeJs)
            {
                _name                  = PageTemplateAssets.NameJs;
                _ext                   = PageTemplateAssets.ExtJs;
                _assetsDir             = SiteInfo.Additional.TemplatesAssetsJsDir.Trim('/');
                PhCodeMirrorJs.Visible = true;
            }
            else if (_type == PageTemplateAssets.TypeCss)
            {
                _name      = PageTemplateAssets.NameCss;
                _ext       = PageTemplateAssets.ExtCss;
                _assetsDir = SiteInfo.Additional.TemplatesAssetsCssDir.Trim('/');
                PhCodeMirrorCss.Visible = true;
            }

            if (string.IsNullOrEmpty(_assetsDir))
            {
                return;
            }

            _directoryPath = PathUtility.MapPath(SiteInfo, "@/" + _assetsDir);

            if (AuthRequest.IsQueryExists("fileName"))
            {
                _fileName = AuthRequest.GetQueryString("fileName");
                _fileName = PathUtils.RemoveParentPath(_fileName);
            }

            if (IsPostBack)
            {
                return;
            }

            VerifySitePermissions(ConfigManager.WebSitePermissions.Template);

            LtlPageTitle.Text = string.IsNullOrEmpty(_fileName) ? $"添加{_name}" : $"编辑{_name}";

            var isCodeMirror = SiteInfo.Additional.ConfigTemplateIsCodeMirror;

            BtnEditorType.Text   = isCodeMirror ? "采用纯文本编辑模式" : "采用代码编辑模式";
            PhCodeMirror.Visible = isCodeMirror;

            ECharsetUtils.AddListItems(DdlCharset);

            if (_fileName != null)
            {
                if (!StringUtils.EqualsIgnoreCase(PathUtils.GetExtension(_fileName), _ext))
                {
                    PageUtils.RedirectToErrorPage("对不起,此文件格式无法编辑!");
                }
                else
                {
                    TbRelatedFileName.Text = _fileName;
                    var fileCharset = FileUtils.GetFileCharset(PathUtils.Combine(_directoryPath, _fileName));
                    ControlUtils.SelectSingleItemIgnoreCase(DdlCharset, ECharsetUtils.GetValue(fileCharset));
                    TbContent.Text = FileUtils.ReadText(PathUtils.Combine(_directoryPath, _fileName), fileCharset);
                }
            }
            else
            {
                ControlUtils.SelectSingleItemIgnoreCase(DdlCharset, SiteInfo.Additional.Charset);
            }
        }
Example #35
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            var pageNum                = AuthRequest.GetQueryInt("pageNum") == 0 ? 30 : AuthRequest.GetQueryInt("pageNum");
            var keyword                = AuthRequest.GetQueryString("keyword");
            var roleName               = AuthRequest.GetQueryString("roleName");
            var lastActivityDate       = AuthRequest.GetQueryInt("lastActivityDate");
            var isConsoleAdministrator = AuthRequest.AdminPermissionsImpl.IsConsoleAdministrator;
            var adminName              = AuthRequest.AdminName;
            var order        = AuthRequest.IsQueryExists("order") ? AuthRequest.GetQueryString("order") : nameof(AdministratorInfo.UserName);
            var departmentId = AuthRequest.GetQueryInt("departmentId");
            var areaId       = AuthRequest.GetQueryInt("areaId");

            if (AuthRequest.IsQueryExists("Delete"))
            {
                var userNameCollection = AuthRequest.GetQueryString("UserNameCollection");
                try
                {
                    var userNameArrayList = TranslateUtils.StringCollectionToStringList(userNameCollection);
                    foreach (var userName in userNameArrayList)
                    {
                        var adminInfo = AdminManager.GetAdminInfoByUserName(userName);
                        DataProvider.AdministratorDao.Delete(adminInfo);
                    }

                    AuthRequest.AddAdminLog("删除管理员", $"管理员:{userNameCollection}");

                    SuccessDeleteMessage();
                }
                catch (Exception ex)
                {
                    FailDeleteMessage(ex);
                }
            }
            else if (AuthRequest.IsQueryExists("Lock"))
            {
                var userNameCollection = AuthRequest.GetQueryString("UserNameCollection");
                try
                {
                    var userNameList = TranslateUtils.StringCollectionToStringList(userNameCollection);
                    DataProvider.AdministratorDao.Lock(userNameList);

                    AuthRequest.AddAdminLog("锁定管理员", $"管理员:{userNameCollection}");

                    SuccessMessage("成功锁定所选管理员!");
                }
                catch (Exception ex)
                {
                    FailMessage(ex, "锁定所选管理员失败!");
                }
            }
            else if (AuthRequest.IsQueryExists("UnLock"))
            {
                var userNameCollection = AuthRequest.GetQueryString("UserNameCollection");
                try
                {
                    var userNameList = TranslateUtils.StringCollectionToStringList(userNameCollection);
                    DataProvider.AdministratorDao.UnLock(userNameList);

                    AuthRequest.AddAdminLog("解除锁定管理员", $"管理员:{userNameCollection}");

                    SuccessMessage("成功解除锁定所选管理员!");
                }
                catch (Exception ex)
                {
                    FailMessage(ex, "解除锁定所选管理员失败!");
                }
            }

            PgContents.Param = new PagerParam
            {
                ControlToPaginate = RptContents,
                TableName         = DataProvider.AdministratorDao.TableName,
                PageSize          = pageNum,
                Page              = AuthRequest.GetQueryInt(Pager.QueryNamePage, 1),
                OrderSqlString    = DataProvider.AdministratorDao.GetOrderSqlString(order),
                ReturnColumnNames = SqlUtils.Asterisk,
                WhereSqlString    = DataProvider.AdministratorDao.GetWhereSqlString(isConsoleAdministrator, adminName, keyword, roleName, lastActivityDate, departmentId, areaId)
            };

            PgContents.Param.TotalCount =
                DataProvider.DatabaseDao.GetPageTotalCount(DataProvider.AdministratorDao.TableName, PgContents.Param.WhereSqlString);

            RptContents.ItemDataBound += RptContents_ItemDataBound;

            _lockType = EUserLockTypeUtils.GetEnumType(ConfigManager.SystemConfigInfo.AdminLockLoginType);

            if (IsPostBack)
            {
                return;
            }

            VerifySystemPermissions(ConfigManager.SettingsPermissions.Admin);

            var theListItem = new ListItem("全部", string.Empty)
            {
                Selected = true
            };

            DdlRoleName.Items.Add(theListItem);

            var allRoles = AuthRequest.AdminPermissionsImpl.IsConsoleAdministrator ? DataProvider.RoleDao.GetRoleNameList() : DataProvider.RoleDao.GetRoleNameListByCreatorUserName(AuthRequest.AdminName);

            var allPredefinedRoles = EPredefinedRoleUtils.GetAllPredefinedRoleName();

            foreach (var theRoleName in allRoles)
            {
                if (allPredefinedRoles.Contains(theRoleName))
                {
                    var listitem = new ListItem(EPredefinedRoleUtils.GetText(EPredefinedRoleUtils.GetEnumType(theRoleName)), theRoleName);
                    DdlRoleName.Items.Add(listitem);
                }
                else
                {
                    var listitem = new ListItem(theRoleName, theRoleName);
                    DdlRoleName.Items.Add(listitem);
                }
            }

            DdlDepartmentId.Items.Add(new ListItem("<所有部门>", "0"));
            var departmentIdList = DepartmentManager.GetDepartmentIdList();

            foreach (var theDepartmentId in departmentIdList)
            {
                var departmentInfo = DepartmentManager.GetDepartmentInfo(theDepartmentId);
                DdlDepartmentId.Items.Add(new ListItem(GetTreeItem(departmentInfo.DepartmentName, departmentInfo.ParentsCount, departmentInfo.IsLastNode, _parentsCountDictOfDepartment), theDepartmentId.ToString()));
            }
            ControlUtils.SelectSingleItem(DdlDepartmentId, departmentId.ToString());

            DdlAreaId.Items.Add(new ListItem("<全部区域>", "0"));
            var areaIdList = AreaManager.GetAreaIdList();

            foreach (var theAreaId in areaIdList)
            {
                var areaInfo = AreaManager.GetAreaInfo(theAreaId);
                DdlAreaId.Items.Add(new ListItem(GetTreeItem(areaInfo.AreaName, areaInfo.ParentsCount, areaInfo.IsLastNode, _parentsCountDictOfArea), theAreaId.ToString()));
            }
            ControlUtils.SelectSingleItem(DdlAreaId, areaId.ToString());

            ControlUtils.SelectSingleItem(DdlRoleName, roleName);
            ControlUtils.SelectSingleItem(DdlPageNum, pageNum.ToString());
            TbKeyword.Text = keyword;
            ControlUtils.SelectSingleItem(DdlDepartmentId, departmentId.ToString());
            ControlUtils.SelectSingleItem(DdlAreaId, areaId.ToString());
            ControlUtils.SelectSingleItem(DdlLastActivityDate, lastActivityDate.ToString());
            ControlUtils.SelectSingleItem(DdlOrder, order);

            PgContents.DataBind();

            var urlAdministrator = GetRedirectUrl();

            BtnLock.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValueAndAlert(urlAdministrator + "?Lock=True", "UserNameCollection", "UserNameCollection", "请选择需要锁定的管理员!", "此操作将锁定所选管理员,确认吗?"));

            BtnUnLock.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValueAndAlert(urlAdministrator + "?UnLock=True", "UserNameCollection", "UserNameCollection", "请选择需要解除锁定的管理员!", "此操作将解除锁定所选管理员,确认吗?"));

            BtnDelete.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValueAndAlert(urlAdministrator + "?Delete=True", "UserNameCollection", "UserNameCollection", "请选择需要删除的管理员!", "此操作将删除所选管理员,确认吗?"));
        }
        public async Task<AuthResponse> GetAuthTokenAsync(AuthRequest request)
        {
            var _response = await GetAuthTokenIRestResponseAsync(request);

            return JsonConvert.DeserializeObject<AuthResponse>(_response.Content);
        }
 protected void lnkInitiateSSO_Click(object sender, EventArgs e)
 {
     AccountSettings accountSettings = new AccountSettings();
     AuthRequest req = new AuthRequest(new AppSettings(), accountSettings);
     Response.Redirect(accountSettings.idp_sso_target_url + "?SAMLRequest=" + Server.UrlEncode(req.GetRequest(AuthRequest.AuthRequestFormat.Base64)));
 }
Example #38
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            if (string.IsNullOrEmpty(AuthRequest.GetQueryString("startDate")))
            {
                _begin = DateTime.Now.AddMonths(-1);
                _end   = DateTime.Now;
            }
            else
            {
                _begin = TranslateUtils.ToDateTime(AuthRequest.GetQueryString("startDate"));
                _end   = TranslateUtils.ToDateTime(AuthRequest.GetQueryString("endDate"));
            }

            if (IsPostBack)
            {
                return;
            }

            VerifySystemPermissions(ConfigManager.SettingsPermissions.Chart);

            DdlSiteId.Items.Add(new ListItem("<<全部站点>>", "0"));
            var siteIdList = SiteManager.GetSiteIdListOrderByLevel();

            foreach (var siteId in siteIdList)
            {
                var siteInfo = SiteManager.GetSiteInfo(siteId);
                DdlSiteId.Items.Add(new ListItem(siteInfo.SiteName, siteId.ToString()));
            }

            TbStartDate.Text = DateUtils.GetDateAndTimeString(_begin);
            TbEndDate.Text   = DateUtils.GetDateAndTimeString(_end);

            BindGrid();

            foreach (var key in _siteIdList)
            {
                var yValueNew    = GetYHashtable(key, YTypeNew);
                var yValueUpdate = GetYHashtable(key, YTypeUpdate);

                if (yValueNew != "0")
                {
                    StrArray += $@"
xArrayNew.push('{GetXHashtable(key)}');
yArrayNew.push('{yValueNew}');";
                }
                if (yValueUpdate != "0")
                {
                    StrArray += $@"
xArrayUpdate.push('{GetXHashtable(key)}');
yArrayUpdate.push('{yValueUpdate}');";
                }
            }

            LtlVerticalNew.Text      = GetVertical(YTypeNew);
            LtlVerticalUpdate.Text   = GetVertical(YTypeUpdate);
            LtlVerticalTotalNum.Text = GetVerticalTotalNum();
        }
Example #39
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");
            _channelId = AuthRequest.GetQueryInt("channelId");
            if (_channelId == 0)
            {
                _channelId = SiteId;
            }
            var channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);
            var tableName   = ChannelManager.GetTableName(SiteInfo, channelInfo);

            _relatedIdentities  = RelatedIdentities.GetChannelRelatedIdentities(SiteId, _channelId);
            _tableStyleInfoList = TableStyleManager.GetTableStyleInfoList(tableName, _relatedIdentities);

            SpContents.ControlToPaginate = RptContents;
            if (string.IsNullOrEmpty(AuthRequest.GetQueryString("channelId")))
            {
                SpContents.ItemsPerPage  = TranslateUtils.ToInt(DdlPageNum.SelectedValue) == 0 ? SiteInfo.Additional.PageSize : TranslateUtils.ToInt(DdlPageNum.SelectedValue);
                SpContents.SelectCommand = DataProvider.ContentDao.GetSqlString(tableName, SiteId, _channelId, AuthRequest.AdminPermissions.IsSystemAdministrator, AuthRequest.AdminPermissions.OwningChannelIdList, DdlSearchType.SelectedValue, TbKeyword.Text, TbDateFrom.Text, TbDateTo.Text, true, ETriState.All, false, true);
            }
            else
            {
                SpContents.ItemsPerPage  = AuthRequest.GetQueryInt("PageNum") == 0 ? SiteInfo.Additional.PageSize : AuthRequest.GetQueryInt("PageNum");
                SpContents.SelectCommand = DataProvider.ContentDao.GetSqlString(tableName, SiteId, _channelId, AuthRequest.AdminPermissions.IsSystemAdministrator, AuthRequest.AdminPermissions.OwningChannelIdList, AuthRequest.GetQueryString("SearchType"), AuthRequest.GetQueryString("Keyword"), AuthRequest.GetQueryString("DateFrom"), AuthRequest.GetQueryString("DateTo"), true, ETriState.All, false, true);
            }
            SpContents.OrderByString   = ETaxisTypeUtils.GetContentOrderByString(ETaxisType.OrderByIdDesc);
            RptContents.ItemDataBound += RptContents_ItemDataBound;

            if (!IsPostBack)
            {
                VerifySitePermissions(ConfigManager.WebSitePermissions.Content);

                if (AuthRequest.IsQueryExists("IsDeleteAll"))
                {
                    DataProvider.ContentDao.DeleteContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "清空回收站");
                    SuccessMessage("成功清空回收站!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                if (AuthRequest.IsQueryExists("IsRestore"))
                {
                    var idsDictionary = ContentUtility.GetIDsDictionary(Request.QueryString);
                    foreach (var channelId in idsDictionary.Keys)
                    {
                        var contentIdArrayList = idsDictionary[channelId];
                        DataProvider.ContentDao.TrashContents(SiteId, ChannelManager.GetTableName(SiteInfo, channelId), contentIdArrayList);
                    }
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原内容");
                    SuccessMessage("成功还原内容!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                if (AuthRequest.IsQueryExists("IsRestoreAll"))
                {
                    DataProvider.ContentDao.RestoreContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原所有内容");
                    SuccessMessage("成功还原所有内容!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                ChannelManager.AddListItems(DdlChannelId.Items, SiteInfo, true, false, AuthRequest.AdminPermissions);

                if (_tableStyleInfoList != null)
                {
                    foreach (var styleInfo in _tableStyleInfoList)
                    {
                        var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                        DdlSearchType.Items.Add(listitem);
                    }
                }
                //添加隐藏属性
                DdlSearchType.Items.Add(new ListItem("内容ID", ContentAttribute.Id));
                DdlSearchType.Items.Add(new ListItem("添加者", ContentAttribute.AddUserName));
                DdlSearchType.Items.Add(new ListItem("最后修改者", ContentAttribute.LastEditUserName));

                if (AuthRequest.IsQueryExists("channelId"))
                {
                    if (SiteId != _channelId)
                    {
                        ControlUtils.SelectSingleItem(DdlChannelId, _channelId.ToString());
                    }
                    ControlUtils.SelectSingleItem(DdlPageNum, AuthRequest.GetQueryString("PageNum"));
                    ControlUtils.SelectSingleItem(DdlSearchType, AuthRequest.GetQueryString("SearchType"));
                    TbKeyword.Text  = AuthRequest.GetQueryString("Keyword");
                    TbDateFrom.Text = AuthRequest.GetQueryString("DateFrom");
                    TbDateTo.Text   = AuthRequest.GetQueryString("DateTo");
                }

                SpContents.DataBind();
            }

            if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
            {
                BtnDelete.Visible    = false;
                BtnDeleteAll.Visible = false;
            }
            else
            {
                BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, true, PageUrl));
                BtnDeleteAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsDeleteAll", "True"), "确实要清空回收站吗?"));
            }
            BtnRestore.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValue(PageUtils.AddQueryString(PageUrl, "IsRestore", "True"), "IDsCollection", "IDsCollection", "请选择需要还原的内容!"));
            BtnRestoreAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsRestoreAll", "True"), "确实要还原所有内容吗?"));
        }
        protected virtual dynamic Auth(RestClient restClient, AuthRequest model, string clientId, bool detectGrantType)
        {
            var request = new RestRequest("auth", Method.POST);
            if (string.IsNullOrEmpty(model.client_id))
            {
                model.client_id = clientId;
            }
            if (string.IsNullOrEmpty(model.grant_type) && detectGrantType)
            {
                model.grant_type = DetectGrantType(model);
            }
            request.AddJsonBody(model);

            return Proxy(restClient, request);
        }
Example #41
0
        public void ResetToken()
        {
            using (HttpClient client = new HttpClient())
            {
                AuthRequest reqMsg = new AuthRequest
                {
                    AppId = AppId,
                    AppSecret = AppSecret
                };
                //Install-Package Microsoft.AspNet.WebApi.Client
                HttpResponseMessage resp = client.PostAsJsonAsync<AuthRequest>(ServiceAuth, reqMsg).Result;
                var respModel = JsonConvert.DeserializeObject<ResponseMessageWrap<AuthResponse>>(resp.Content.ReadAsStringAsync().Result);

                if (!respModel.IsSuccess)
                {
                    throw new Exception(respModel.ErrorCode);
                }
                ApiToken = respModel.Body.Token;

            }
        }
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }
            if (IsPostBack)
            {
                return;
            }

            VerifySystemPermissions(ConfigManager.AppPermissions.SettingsAnalysisUser);
            LtlPageTitle.Text = $"用户增加最近{_count}{EStatictisXTypeUtils.GetText(EStatictisXTypeUtils.GetEnumType(AuthRequest.GetQueryString("XType")))}分配图表";

            EStatictisXTypeUtils.AddListItems(DdlXType);

            _xType = EStatictisXTypeUtils.GetEnumType(AuthRequest.GetQueryString("XType"));

            if (Equals(_xType, EStatictisXType.Day))
            {
                _count = 30;
            }
            else if (Equals(_xType, EStatictisXType.Month))
            {
                _count = 12;
            }
            else if (Equals(_xType, EStatictisXType.Year))
            {
                _count = 10;
            }

            TbDateFrom.Text        = AuthRequest.GetQueryString("DateFrom");
            TbDateTo.Text          = AuthRequest.GetQueryString("DateTo");
            DdlXType.SelectedValue = EStatictisXTypeUtils.GetValue(_xType);

            //用户添加量统计
            var trackingDayDict = DataProvider.UserDao.GetTrackingDictionary(TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateFrom")), TranslateUtils.ToDateTime(AuthRequest.GetQueryString("DateTo"), DateTime.Now), EStatictisXTypeUtils.GetValue(_xType));

            var now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            for (var i = 0; i < _count; i++)
            {
                var datetime = now.AddDays(-i);
                if (Equals(_xType, EStatictisXType.Day))
                {
                    now      = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    datetime = now.AddDays(-i);
                }
                else if (Equals(_xType, EStatictisXType.Month))
                {
                    now      = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
                    datetime = now.AddMonths(-i);
                }
                else if (Equals(_xType, EStatictisXType.Year))
                {
                    now      = new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0);
                    datetime = now.AddYears(-i);
                }

                var accessNum = 0;
                if (trackingDayDict.ContainsKey(datetime))
                {
                    accessNum = trackingDayDict[datetime];
                }
                _userNumHashtable.Add(_count - i, accessNum);
                if (accessNum > _maxUserNum)
                {
                    _maxUserNum = accessNum;
                }
            }

            for (var i = 1; i <= _count; i++)
            {
                StrArray += $@"
xArray.push('{GetGraphicX(i)}');
yArray.push('{GetGraphicY(i)}');
";
            }
        }
Example #43
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            bool isChanged;

            try
            {
                if (_isContent)
                {
                    var groupNameList = new List <string>();
                    foreach (ListItem item in CblGroupNameCollection.Items)
                    {
                        if (item.Selected)
                        {
                            groupNameList.Add(item.Value);
                        }
                    }

                    foreach (var channelId in _idsDictionary.Keys)
                    {
                        var tableName          = ChannelManager.GetTableName(SiteInfo, channelId);
                        var contentIdArrayList = _idsDictionary[channelId];
                        if (contentIdArrayList != null)
                        {
                            foreach (var contentId in contentIdArrayList)
                            {
                                DataProvider.ContentDao.AddContentGroupList(tableName, contentId, groupNameList);
                            }
                        }
                    }

                    AuthRequest.AddSiteLog(SiteId, "添加内容到内容组", $"内容组:{TranslateUtils.ObjectCollectionToString(groupNameList)}");

                    isChanged = true;
                }
                else
                {
                    var groupNameList = new List <string>();
                    foreach (ListItem item in CblGroupNameCollection.Items)
                    {
                        if (item.Selected)
                        {
                            groupNameList.Add(item.Value);
                        }
                    }

                    foreach (int channelId in _channelIdArrayList)
                    {
                        DataProvider.ChannelDao.AddGroupNameList(SiteId, channelId, groupNameList);
                    }

                    AuthRequest.AddSiteLog(SiteId, "添加栏目到栏目组", $"栏目组:{TranslateUtils.ObjectCollectionToString(groupNameList)}");

                    isChanged = true;
                }
            }
            catch (Exception ex)
            {
                FailMessage(ex, ex.Message);
                isChanged = false;
            }

            if (isChanged)
            {
                LayerUtils.Close(Page);
            }
        }
Example #44
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");
            ReturnUrl = StringUtils.ValueFromUrl(AuthRequest.GetQueryString("ReturnUrl"));

            if (!HasChannelPermissions(SiteId, ConfigManager.ChannelPermissions.ContentDelete))
            {
                RblIsDeleteAfterTranslate.Visible = false;
            }

            if (IsPostBack)
            {
                return;
            }

            PhReturn.Visible = !string.IsNullOrEmpty(ReturnUrl);
            ETranslateTypeUtils.AddListItems(DdlTranslateType);
            ControlUtils.SelectSingleItem(DdlTranslateType,
                                          AuthRequest.IsQueryExists("ChannelIDCollection")
                    ? ETranslateTypeUtils.GetValue(ETranslateType.All)
                    : ETranslateTypeUtils.GetValue(ETranslateType.Content));

            var siteIdList = AuthRequest.AdminPermissions.SiteIdList;

            foreach (var psId in siteIdList)
            {
                var psInfo   = SiteManager.GetSiteInfo(psId);
                var listitem = new ListItem(psInfo.SiteName, psId.ToString());
                if (psId == SiteId)
                {
                    listitem.Selected = true;
                }
                DdlSiteId.Items.Add(listitem);
            }

            var channelIdStrList = new List <string>();

            if (AuthRequest.IsQueryExists("ChannelIDCollection"))
            {
                channelIdStrList = TranslateUtils.StringCollectionToStringList(AuthRequest.GetQueryString("ChannelIDCollection"));
            }

            var channelIdList = ChannelManager.GetChannelIdList(SiteId);
            var nodeCount     = channelIdList.Count;

            _isLastNodeArray = new bool[nodeCount];
            foreach (var theChannelId in channelIdList)
            {
                var enabled = IsOwningChannelId(theChannelId);
                if (!enabled)
                {
                    if (!IsDescendantOwningChannelId(theChannelId))
                    {
                        continue;
                    }
                }
                var nodeInfo = ChannelManager.GetChannelInfo(SiteId, theChannelId);

                var value = enabled ? nodeInfo.Id.ToString() : string.Empty;
                value = nodeInfo.Additional.IsContentAddable ? value : string.Empty;

                var text     = GetTitle(nodeInfo);
                var listItem = new ListItem(text, value);
                if (channelIdStrList.Contains(value))
                {
                    listItem.Selected = true;
                }
                LbChannelIdFrom.Items.Add(listItem);
                listItem = new ListItem(text, value);
                DdlChannelIdTo.Items.Add(listItem);
            }
        }
Example #45
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            _type = Request.QueryString["type"];

            if (IsPostBack)
            {
                return;
            }

            if (StringUtils.EqualsIgnoreCase(_type, TypePreviewImage))
            {
                var siteId          = AuthRequest.GetQueryInt("siteID");
                var siteInfo        = SiteManager.GetSiteInfo(siteId);
                var textBoxClientId = AuthRequest.GetQueryString("textBoxClientID");
                LtlHtml.Text = $@"
<span id=""previewImage""></span>
<script>
var rootUrl = '{PageUtils.GetRootUrl(string.Empty)}';
var siteUrl = '{PageUtils.ParseNavigationUrl($"~/{siteInfo.SiteDir}")}';
var imageUrl = window.parent.document.getElementById('{textBoxClientId}').value;
if(imageUrl && imageUrl.search(/\.bmp|\.jpg|\.jpeg|\.gif|\.png|\.webp$/i) != -1){{
	if (imageUrl.charAt(0) == '~'){{
		imageUrl = imageUrl.replace('~', rootUrl);
	}}else if (imageUrl.charAt(0) == '@'){{
		imageUrl = imageUrl.replace('@', siteUrl);
	}}
	if(imageUrl.substr(0,2)=='//'){{
		imageUrl = imageUrl.replace('//', '/');
	}}
    $('#previewImage').html('<img src=""' + imageUrl + '"" class=""img-polaroid"" />');
}}
</script>
";
            }
            else if (StringUtils.EqualsIgnoreCase(_type, TypePreviewVideo))
            {
                var siteId          = AuthRequest.GetQueryInt("siteID");
                var siteInfo        = SiteManager.GetSiteInfo(siteId);
                var textBoxClientId = AuthRequest.GetQueryString("textBoxClientID");

                LtlHtml.Text = $@"
<span id=""previewVideo""></span>
<script>
var rootUrl = '{PageUtils.GetRootUrl(string.Empty)}';
var siteUrl = '{PageUtils.ParseNavigationUrl($"~/{siteInfo.SiteDir}")}';
var videoUrl = window.parent.document.getElementById('{textBoxClientId}').value;
if (videoUrl.charAt(0) == '~'){{
	videoUrl = videoUrl.replace('~', rootUrl);
}}else if (videoUrl.charAt(0) == '@'){{
	videoUrl = videoUrl.replace('@', siteUrl);
}}
if(videoUrl.substr(0,2)=='//'){{
	videoUrl = videoUrl.replace('//', '/');
}}
if (videoUrl){{
    $('#previewVideo').html('<embed src=""../assets/player.swf"" allowfullscreen=""true"" flashvars=""controlbar=over&autostart=true&file='+videoUrl+'"" width=""{450}"" height=""{350}""/>');
}}
</script>
";
            }
            else if (StringUtils.EqualsIgnoreCase(_type, TypePreviewVideoByUrl))
            {
                var siteId   = AuthRequest.GetQueryInt("siteID");
                var siteInfo = SiteManager.GetSiteInfo(siteId);
                var videoUrl = AuthRequest.GetQueryString("videoUrl");

                LtlHtml.Text = $@"
<embed src=""../assets/player.swf"" allowfullscreen=""true"" flashvars=""controlbar=over&autostart=true&file={PageUtility
                    .ParseNavigationUrl(siteInfo, videoUrl, true)}"" width=""{450}"" height=""{350}""/>
";
            }
            else
            {
                LtlHtml.Text = TranslateUtils.DecryptStringBySecretKey(Request.QueryString["html"]);
            }
        }
Example #46
0
        private async Task <AuthResponse <DeviceDisplayClaims> > DoDeviceAuth(string token)
        {
            var id     = Guid.NewGuid().ToString();
            var serial = Guid.NewGuid().ToString();
            //UUID uuid = new UUID(Guid.NewGuid().ToByteArray());

            //	var key = EcDsa.ExportParameters(false);
            var authRequest = new AuthRequest
            {
                RelyingParty = "http://auth.xboxlive.com",
                TokenType    = "JWT",
                Properties   = new Dictionary <string, object>()
                {
                    //	{"RpsTicket", token},
                    //	{"SiteName", "user.auth.xboxlive.com"},
                    { "DeviceType", "Nintendo" },
                    { "Id", id },
                    { "SerialNumber", serial },
                    { "Version", "0.0.0.0" },
                    { "AuthMethod", "ProofOfPossession" },
                    {
                        "ProofKey", new Dictionary <string, string>()
                        {
                            { "crv", "P-256" },
                            { "alg", "ES256" },
                            { "use", "sig" },
                            { "kty", "EC" },
                            { "x", UrlSafe(X) },
                            { "y", UrlSafe(Y) }
                        }
                    }
                }
            };

            AuthResponse <DeviceDisplayClaims> deviceAuthResponse;
            //using (var client = new HttpClient())
            var client = GetClient();

            using (var r = new HttpRequestMessage(HttpMethod.Post,
                                                  DeviceAuth))
            {
                r.Headers.Clear();

                r.Headers.Add("x-xbl-contract-version", "1");

                //var json = JsonConvert.SerializeObject(authRequest);
                //Console.WriteLine($"Device Request: " + json);
                r.Content = SetHttpContent(authRequest, out var jsonData);

                Sign(r, jsonData);

                using (var response = await client
                                      .SendAsync(r, HttpCompletionOption.ResponseContentRead)
                                      .ConfigureAwait(false))
                {
                    var resp = await response.Content.ReadAsStringAsync();

                    response.EnsureSuccessStatusCode();

                    deviceAuthResponse =
                        JsonConvert.DeserializeObject <AuthResponse <DeviceDisplayClaims> >(
                            resp);

                    Console.WriteLine();
                }
            }

            return(deviceAuthResponse);
        }
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsPostBack || !Page.IsValid)
            {
                return;
            }

            ChannelInfo channelInfo;

            try
            {
                var channelName             = TbNodeName.Text;
                var indexName               = TbNodeIndexName.Text;
                var filePath                = TbFilePath.Text;
                var channelFilePathRule     = TbChannelFilePathRule.Text;
                var contentFilePathRule     = TbContentFilePathRule.Text;
                var contentModelPluginId    = DdlContentModelPluginId.SelectedValue;
                var contentRelatedPluginIds = ControlUtils.GetSelectedListControlValueCollection(CblContentRelatedPluginIds);
                var groupNameCollection     = TranslateUtils.ObjectCollectionToString(ControlUtils.GetSelectedListControlValueStringList(CblNodeGroupNameCollection));
                var imageUrl                = TbImageUrl.Text;
                var content           = ContentUtility.TextEditorContentEncode(SiteInfo, Request.Form[ChannelAttribute.Content]);
                var keywords          = TbKeywords.Text;
                var description       = TbDescription.Text;
                var isChannelAddable  = TranslateUtils.ToBool(RblIsChannelAddable.SelectedValue);
                var isContentAddable  = TranslateUtils.ToBool(RblIsContentAddable.SelectedValue);
                var linkUrl           = TbLinkUrl.Text;
                var linkType          = DdlLinkType.SelectedValue;
                var defaultTaxisType  = ETaxisTypeUtils.GetValue(ETaxisTypeUtils.GetEnumType(DdlTaxisType.SelectedValue));
                var channelTemplateId = DdlChannelTemplateId.Items.Count > 0 ? TranslateUtils.ToInt(DdlChannelTemplateId.SelectedValue) : 0;
                var contentTemplateId = DdlContentTemplateId.Items.Count > 0 ? TranslateUtils.ToInt(DdlContentTemplateId.SelectedValue) : 0;

                channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);
                if (!channelInfo.IndexName.Equals(indexName) && !string.IsNullOrEmpty(indexName))
                {
                    var indexNameList = DataProvider.ChannelDao.GetIndexNameList(SiteId);
                    if (indexNameList.IndexOf(indexName) != -1)
                    {
                        FailMessage("栏目属性修改失败,栏目索引已存在!");
                        return;
                    }
                }

                if (channelInfo.ContentModelPluginId != contentModelPluginId)
                {
                    channelInfo.ContentModelPluginId = contentModelPluginId;
                }
                channelInfo.ContentRelatedPluginIds = contentRelatedPluginIds;

                filePath = filePath.Trim();
                if (!channelInfo.FilePath.Equals(filePath) && !string.IsNullOrEmpty(filePath))
                {
                    if (!DirectoryUtils.IsDirectoryNameCompliant(filePath))
                    {
                        FailMessage("栏目页面路径不符合系统要求!");
                        return;
                    }

                    if (PathUtils.IsDirectoryPath(filePath))
                    {
                        filePath = PageUtils.Combine(filePath, "index.html");
                    }

                    var filePathList = DataProvider.ChannelDao.GetAllFilePathBySiteId(SiteId);
                    if (filePathList.IndexOf(filePath) != -1)
                    {
                        FailMessage("栏目修改失败,栏目页面路径已存在!");
                        return;
                    }
                }

                if (!string.IsNullOrEmpty(channelFilePathRule))
                {
                    var filePathRule = channelFilePathRule.Replace("|", string.Empty);
                    if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                    {
                        FailMessage("栏目页面命名规则不符合系统要求!");
                        return;
                    }
                    if (PathUtils.IsDirectoryPath(filePathRule))
                    {
                        FailMessage("栏目页面命名规则必须包含生成文件的后缀!");
                        return;
                    }
                }

                if (!string.IsNullOrEmpty(contentFilePathRule))
                {
                    var filePathRule = contentFilePathRule.Replace("|", string.Empty);
                    if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                    {
                        FailMessage("内容页面命名规则不符合系统要求!");
                        return;
                    }
                    if (PathUtils.IsDirectoryPath(filePathRule))
                    {
                        FailMessage("内容页面命名规则必须包含生成文件的后缀!");
                        return;
                    }
                }

                var styleInfoList      = TableStyleManager.GetChannelStyleInfoList(channelInfo);
                var extendedAttributes = BackgroundInputTypeParser.SaveAttributes(SiteInfo, styleInfoList, Request.Form, null);
                channelInfo.Additional.Load(extendedAttributes);

                channelInfo.ChannelName         = channelName;
                channelInfo.IndexName           = indexName;
                channelInfo.FilePath            = filePath;
                channelInfo.ChannelFilePathRule = channelFilePathRule;
                channelInfo.ContentFilePathRule = contentFilePathRule;

                channelInfo.GroupNameCollection = groupNameCollection;
                channelInfo.ImageUrl            = imageUrl;
                channelInfo.Content             = content;

                channelInfo.Keywords    = keywords;
                channelInfo.Description = description;

                channelInfo.Additional.IsChannelAddable = isChannelAddable;
                channelInfo.Additional.IsContentAddable = isContentAddable;

                channelInfo.LinkUrl  = linkUrl;
                channelInfo.LinkType = linkType;
                channelInfo.Additional.DefaultTaxisType = defaultTaxisType;
                channelInfo.ChannelTemplateId           = channelTemplateId;
                channelInfo.ContentTemplateId           = contentTemplateId;

                DataProvider.ChannelDao.Update(channelInfo);
            }
            catch (Exception ex)
            {
                FailMessage(ex, $"栏目修改失败:{ex.Message}");
                LogUtils.AddErrorLog(ex);
                return;
            }

            CreateManager.CreateChannel(SiteId, channelInfo.Id);

            AuthRequest.AddSiteLog(SiteId, "修改栏目", $"栏目:{TbNodeName.Text}");

            SuccessMessage("栏目修改成功!");
            PageUtils.Redirect(ReturnUrl);
        }
 private string RedirectUrl()
 {
     return ModalFileView.GetRedirectUrl(SiteId, AuthRequest.GetQueryString("rootPath"),
         AuthRequest.GetQueryString("FileName"), TbFileName.Text, AuthRequest.GetQueryString("HiddenClientID"));
 }
Example #49
0
        private int Validate_SiteInfo(out string errorMessage)
        {
            try
            {
                var isRoot       = TranslateUtils.ToBool(RblIsRoot.SelectedValue); // 是否主站
                var parentSiteId = 0;
                var siteDir      = string.Empty;

                if (isRoot == false)
                {
                    if (DirectoryUtils.IsSystemDirectory(TbSiteDir.Text))
                    {
                        errorMessage = "文件夹名称不能为系统文件夹名称!";
                        return(0);
                    }

                    parentSiteId = TranslateUtils.ToInt(DdlParentId.SelectedValue);
                    siteDir      = TbSiteDir.Text;

                    var list = DataProvider.SiteDao.GetLowerSiteDirList(parentSiteId);
                    if (list.IndexOf(siteDir.ToLower()) != -1)
                    {
                        errorMessage = "已存在相同的发布路径!";
                        return(0);
                    }

                    if (!DirectoryUtils.IsDirectoryNameCompliant(siteDir))
                    {
                        errorMessage = "文件夹名称不符合系统要求!";
                        return(0);
                    }
                }

                var nodeInfo = new ChannelInfo();

                nodeInfo.ChannelName          = nodeInfo.IndexName = "首页";
                nodeInfo.ParentId             = 0;
                nodeInfo.ContentModelPluginId = string.Empty;

                var tableName = string.Empty;
                var tableRule = ETableRuleUtils.GetEnumType(RblTableRule.SelectedValue);
                if (tableRule == ETableRule.Choose)
                {
                    tableName = DdlTableChoose.SelectedValue;
                }
                else if (tableRule == ETableRule.HandWrite)
                {
                    tableName = TbTableHandWrite.Text;
                    if (!DataProvider.DatabaseDao.IsTableExists(tableName))
                    {
                        DataProvider.ContentDao.CreateContentTable(tableName, DataProvider.ContentDao.TableColumnsDefault);
                    }
                    else
                    {
                        DataProvider.DatabaseDao.AlterSystemTable(tableName, DataProvider.ContentDao.TableColumnsDefault);
                    }
                }

                var siteInfo = new SiteInfo
                {
                    SiteName  = AttackUtils.FilterXss(TbSiteName.Text),
                    SiteDir   = siteDir,
                    TableName = tableName,
                    ParentId  = parentSiteId,
                    IsRoot    = isRoot
                };

                siteInfo.Additional.IsCheckContentLevel = TranslateUtils.ToBool(RblIsCheckContentUseLevel.SelectedValue);

                if (siteInfo.Additional.IsCheckContentLevel)
                {
                    siteInfo.Additional.CheckContentLevel = TranslateUtils.ToInt(DdlCheckContentLevel.SelectedValue);
                }
                siteInfo.Additional.Charset = DdlCharset.SelectedValue;

                var siteId = DataProvider.ChannelDao.InsertSiteInfo(nodeInfo, siteInfo, AuthRequest.AdminName);

                if (string.IsNullOrEmpty(tableName))
                {
                    tableName = ContentDao.GetContentTableName(siteId);
                    DataProvider.ContentDao.CreateContentTable(tableName, DataProvider.ContentDao.TableColumnsDefault);
                    DataProvider.SiteDao.UpdateTableName(siteId, tableName);
                }

                if (AuthRequest.AdminPermissionsImpl.IsSystemAdministrator && !AuthRequest.AdminPermissionsImpl.IsConsoleAdministrator)
                {
                    var siteIdList = AuthRequest.AdminPermissionsImpl.GetSiteIdList() ?? new List <int>();
                    siteIdList.Add(siteId);
                    var adminInfo = AdminManager.GetAdminInfoByUserId(AuthRequest.AdminId);
                    DataProvider.AdministratorDao.UpdateSiteIdCollection(adminInfo, TranslateUtils.ObjectCollectionToString(siteIdList));
                }

                AuthRequest.AddAdminLog("创建新站点", $"站点名称:{AttackUtils.FilterXss(TbSiteName.Text)}");

                errorMessage = string.Empty;
                return(siteId);
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
                return(0);
            }
        }