示例#1
0
        protected void AttemptAuth(object sender, EventArgs e)
        {
            _clientIdEntry.FetchValue();
            ClientId = _clientIdEntry.Value;
            _clientSecretEntry.FetchValue();
            ClientSecret = _clientSecretEntry.Value;
            _requestUriEntry.FetchValue();
            RequestUri = _requestUriEntry.Value;

            if ((string.IsNullOrEmpty(ClientId)) || (string.IsNullOrEmpty(ClientSecret)) || (string.IsNullOrEmpty(RequestUri)))
            {
                UIAlertView firstPageValidationAlert = new UIAlertView("Whoops!", "Please provide a Client Id, Client Secret and Request Uri.", null, "Okay");
                firstPageValidationAlert.Show();
            }
            else
            {
                //Elements for Second Page - authorization
                var secondPage = new UIViewController();
                secondPage.Title = "Authorize";
                var authorizeWebView = new UIWebView(secondPage.View.Frame);
                secondPage.View.AddSubview(authorizeWebView);
                viewController.VisibleViewController.NavigationController.PushViewController(secondPage, true);
                authorizeWebView.LoadFinished += delegate(object s, EventArgs ev) {
                    string       currentUrl     = authorizeWebView.Request.Url.AbsoluteString;
                    const string CodeIdentifier = "code=";
                    if (currentUrl.Contains(CodeIdentifier))
                    {
                        //We've received an authorization code - initialize the token manager to get a create a token
                        Code         = currentUrl.Substring(currentUrl.IndexOf(CodeIdentifier) + CodeIdentifier.Length);
                        TokenManager = new AccessTokenManager(ClientId, ClientSecret, RequestUri);
                        InvokeOnMainThread(() => {
                            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
                        });
                        TokenManager.InitAccessToken(Code);
                        var userRequest = new UsersEndpoint(TokenManager);
                        User = userRequest.GetUser();
                        var profileRequest = new ProfileEndpoint(TokenManager, User);
                        Profile = profileRequest.GetProfile();
                        InvokeOnMainThread(() => {
                            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
                        });
                        ShowUserAndProfile();
                    }
                };
                authorizeWebView.LoadRequest(new NSUrlRequest(new NSUrl(HealthGraphAuthorizeEndpoint + "?client_id=" + ClientId + "&redirect_uri=" + HttpUtility.UrlEncode(RequestUri) + "&response_type=code")));
            }
        }
        public IHttpActionResult ResetPassword(int id)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeUsers) ||
                              request.IsUserLoggin &&
                              request.UserId == id ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasSystemPermissions(ConfigManager.SettingsPermissions.User);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var userInfo = UserManager.GetUserInfoByUserId(id);
                if (userInfo == null)
                {
                    return(NotFound());
                }

                var password    = request.GetPostString("password");
                var newPassword = request.GetPostString("newPassword");

                if (!DataProvider.UserDao.CheckPassword(password, false, userInfo.Password, EPasswordFormatUtils.GetEnumType(userInfo.PasswordFormat), userInfo.PasswordSalt))
                {
                    return(BadRequest("原密码不正确,请重新输入"));
                }

                if (!DataProvider.UserDao.ChangePassword(userInfo.UserName, newPassword, out string errorMessage))
                {
                    return(BadRequest(errorMessage));
                }

                return(Ok(new
                {
                    Value = userInfo
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
        public IHttpActionResult Update(int id)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeUsers) ||
                              request.IsUserLoggin &&
                              request.UserId == id ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasSystemPermissions(ConfigManager.SettingsPermissions.User);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var body = request.GetPostObject <Dictionary <string, object> >();

                if (body == null)
                {
                    return(BadRequest("Could not read user from body"));
                }

                var userInfo = UserManager.GetUserInfoByUserId(id);
                if (userInfo == null)
                {
                    return(NotFound());
                }

                var retval = DataProvider.UserDao.Update(userInfo, body, out var errorMessage);
                if (retval == null)
                {
                    return(BadRequest(errorMessage));
                }

                return(Ok(new
                {
                    Value = retval
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#4
0
        public bool PerformCheckAndRefresh(out EPerformCheckAndRefreshSuccessStatus _SuccessStatus, out string _NewAccessTokenWithTokenType, out string _UserID, out string _EmailAddressWithoutPostfix)
        {
            _SuccessStatus = EPerformCheckAndRefreshSuccessStatus.None;

            _UserID = null;

            _NewAccessTokenWithTokenType = AccessToken_TokenTypeSpacePrepended;

            if (!ValidateAccessTokenSyntax(out _EmailAddressWithoutPostfix, out string _))
            {
                return(false);
            }

            var bCheckResult = CheckTokenExpiry(out _UserID, out bool _bExpired, out string _RefreshToken);

            if (!bCheckResult || _bExpired)
            {
                if (_UserID == null || _RefreshToken == null)
                {
                    return(false);
                }

                TryDeletingAuthMethodAndMemoryEntry(_UserID, _EmailAddressWithoutPostfix);

                if (!TryRefreshingAccessToken(out Controller_SSOAccessToken AccessTokenManager, out string NewRefreshToken, out int ExpiresInSeconds, _RefreshToken))
                {
                    return(false);
                }

                if (!AccessTokenManager.RegisterAuthMethodAndMemoryEntryAfterRefresh(_UserID, _EmailAddressWithoutPostfix, ExpiresInSeconds, NewRefreshToken))
                {
                    AccessTokenManager.TryDeletingAuthMethodAndMemoryEntry(_UserID, _EmailAddressWithoutPostfix); //Again, in case some are managed to be registered.
                    return(false);
                }

                _NewAccessTokenWithTokenType = AccessTokenManager.AccessToken_TokenTypeSpacePrepended;
                _SuccessStatus = EPerformCheckAndRefreshSuccessStatus.Refreshed;
            }
            else
            {
                _SuccessStatus = EPerformCheckAndRefreshSuccessStatus.AlreadyValid;
            }

            return(true);
        }
示例#5
0
        void WebBrowser1Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            string client_id      = "e54e428e76574fb1b5ae856f37befed2";
            string client_secret  = "d1d13b891ffa44c891ff41f74d0a6951";
            string CodeIdentifier = "code=";
            string Code           = "";

            txtUrl.Text = webBrowser1.Url.PathAndQuery;
            if (webBrowser1.Url.Query.Contains(CodeIdentifier))
            {
                Code = webBrowser1.Url.Query.Substring(webBrowser1.Url.Query.IndexOf(CodeIdentifier) + CodeIdentifier.Length);
                AccessTokenManager tm = new AccessTokenManager(client_id, client_secret, "https://www.facebook.com/connect/login_success.html");
                tm.InitAccessToken(Code);
                rk_auth_token     = tm.Token.AccessToken;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
示例#6
0
        public IHttpActionResult Delete(int siteId, int channelId)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeChannels) ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasChannelPermissions(siteId, channelId,
                                                                             ConfigManager.ChannelPermissions.ChannelDelete);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                var tableName = ChannelManager.GetTableName(siteInfo, channelId);
                DataProvider.ContentDao.UpdateTrashContentsByChannelId(siteId, channelId, tableName);
                DataProvider.ChannelDao.Delete(siteId, channelId);

                return(Ok(new
                {
                    Value = channelInfo.ToDictionary()
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#7
0
        static StallApplication()
        {
            var vendApp = new VendApplication(GreenspotConfiguration.AccessAccounts["vend"].Id,
                                              GreenspotConfiguration.AccessAccounts["vend"].Secret,
                                              GreenspotConfiguration.AccessAccounts["vend"].RedirectUri);

            var tokenManager = new AccessTokenManager(new VendAccessTokenStore(), vendApp);

            _instance = new StallApplication();
            _instance._vendApplication        = vendApp;
            _instance._vendAccessTokenManager = tokenManager;

            using (var db = new StallEntities())
            {
                _instance._areas = new Dictionary <string, Area>();
                foreach (var a in db.Areas.ToList())
                {
                    _instance._areas.Add(a.ID, a);
                }
            }
        }
示例#8
0
        public IHttpActionResult List(int siteId)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeChannels) ||
                              request.IsAdminLoggin;
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var root          = ChannelManager.GetChannelInfo(siteId, siteId);
                var channelIdList = ChannelManager.GetChannelIdList(root, EScopeType.Children);

                var dictInfoList = new List <Dictionary <string, object> >();
                foreach (var channelId in channelIdList)
                {
                    var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                    dictInfoList.Add(channelInfo.ToDictionary());
                }

                return(Ok(new
                {
                    Value = dictInfoList
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#9
0
        public async Task <ActionResult> Authenticate(string code, string state)
        {
            var baseTokenUrl    = ConfigurationManager.AppSettings["BaseTokenUrl"];
            var authenticateUrl = $"{baseTokenUrl}";
            var clientId        = ConfigurationManager.AppSettings["ClientId"];

            var payload = new Dictionary <string, string>()
            {
                { "client_id", clientId },
                { "client_secret", ConfigurationManager.AppSettings["ClientSecret"] },
                { "code", code },
                { "grant_type", ConfigurationManager.AppSettings["GrantType"] },
                { "redirect_uri", ConfigurationManager.AppSettings["RedirectUri"] },
                { "state", state }
            };
            var content = new FormUrlEncodedContent(payload);

            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("accept", "application/json");

            var response = await client.PostAsync(authenticateUrl, content);

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                var authenticationResponse = JsonConvert.DeserializeObject <AuthenticationResponse>(json);

                var accessTokenManager = new AccessTokenManager();
                accessTokenManager.saveAccessToken(authenticationResponse.access_token);

                var referringActionManager = new ReferringActionManager();
                var referringAction        = referringActionManager.getReferringAction();

                return(await Task.Run(() => Redirect(referringAction)));
            }

            return(await Task.Run(() => RedirectToAction("Index")));
        }
示例#10
0
        public void Update(AccessTokenInfo accessTokenInfo)
        {
            var sqlString = $@"UPDATE {TableName} SET
                {nameof(AccessTokenInfo.Title)} = @{nameof(AccessTokenInfo.Title)}, 
                {nameof(AccessTokenInfo.Scopes)} = @{nameof(AccessTokenInfo.Scopes)},
                {nameof(AccessTokenInfo.RateLimit)} = @{nameof(AccessTokenInfo.RateLimit)},
                {nameof(AccessTokenInfo.UpdatedDate)} = @{nameof(AccessTokenInfo.UpdatedDate)}
            WHERE {nameof(AccessTokenInfo.Id)} = @{nameof(AccessTokenInfo.Id)}";

            IDataParameter[] parameters =
            {
                GetParameter(nameof(accessTokenInfo.Title),       DataType.VarChar,            200, accessTokenInfo.Title),
                GetParameter(nameof(accessTokenInfo.Scopes),      DataType.VarChar,            200, accessTokenInfo.Scopes),
                GetParameter(nameof(accessTokenInfo.RateLimit),   DataType.VarChar,            200, accessTokenInfo.RateLimit),
                GetParameter(nameof(accessTokenInfo.UpdatedDate), DataType.DateTime, DateTime.Now),
                GetParameter(nameof(accessTokenInfo.Id),          DataType.Integer,  accessTokenInfo.Id)
            };

            ExecuteNonQuery(sqlString, parameters);

            AccessTokenManager.ClearCache();
        }
示例#11
0
        public string Regenerate(int id)
        {
            var token = TranslateUtils.EncryptStringBySecretKey(StringUtils.Guid());

            var sqlString = $@"UPDATE {TableName} SET
                {nameof(AccessTokenInfo.Token)} = @{nameof(AccessTokenInfo.Token)}, 
                {nameof(AccessTokenInfo.UpdatedDate)} = @{nameof(AccessTokenInfo.UpdatedDate)}
            WHERE {nameof(AccessTokenInfo.Id)} = @{nameof(AccessTokenInfo.Id)}";

            IDataParameter[] parameters =
            {
                GetParameter(nameof(AccessTokenInfo.Token),       DataType.VarChar,            200, token),
                GetParameter(nameof(AccessTokenInfo.UpdatedDate), DataType.DateTime, DateTime.Now),
                GetParameter(nameof(AccessTokenInfo.Id),          DataType.Integer,  id)
            };

            ExecuteNonQuery(sqlString, parameters);

            AccessTokenManager.ClearCache();

            return(token);
        }
示例#12
0
        private void AuthApi()
        {
            if (!string.IsNullOrEmpty(HttpRequest.Headers.Get(AuthKeyApiHeader)))
            {
                ApiToken = HttpRequest.Headers.Get(AuthKeyApiHeader);
            }
            else if (!string.IsNullOrEmpty(HttpRequest.QueryString[AuthKeyApiQuery]))
            {
                ApiToken = HttpRequest.QueryString[AuthKeyApiQuery];
            }
            else if (!string.IsNullOrEmpty(CookieUtils.GetCookie(AuthKeyApiCookie)))
            {
                ApiToken = CookieUtils.GetCookie(AuthKeyApiCookie);
            }

            if (!string.IsNullOrEmpty(ApiToken))
            {
                var tokenInfo = AccessTokenManager.GetAccessTokenInfo(ApiToken);
                SetAdmin(tokenInfo?.AdminName);
                IsApiAuthenticated = tokenInfo != null;
            }
        }
        public AppAccessTokenResult GetAppAccessToken(AppConfidential appConfidential)
        {
            if (CheckApplication.AppHasAccess(appConfidential.AppId, appConfidential.AppSecret))
            {
                WXCONFIG.WX_GLOBAL_APPID  = appConfidential.AppId;
                WXCONFIG.WX_GLOBAL_SECRET = appConfidential.AppSecret;
                var res = AccessTokenManager.GetAccessToken();

                AppAccessTokenResult ret = new AppAccessTokenResult();
                ret.Access_token = res.Token;
                ret.StartTime    = res.StartTime;
                ret.ExpireTime   = res.ExpireTime;
                return(ret);
            }
            else
            {
                return(new AppAccessTokenResult()
                {
                    Access_token = string.Empty
                });
            }
        }
示例#14
0
        public IHttpActionResult GetLogs(int id)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeUsers) ||
                              request.IsUserLoggin &&
                              request.UserId == id ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasSystemPermissions(ConfigManager.SettingsPermissions.User);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var userInfo = UserManager.GetUserInfoByUserId(id);
                if (userInfo == null)
                {
                    return(NotFound());
                }

                var top  = request.GetQueryInt("top", 20);
                var skip = request.GetQueryInt("skip");

                var logs = DataProvider.UserLogDao.ApiGetLogs(userInfo.UserName, skip, top);

                return(Ok(new PageResponse(logs, top, skip, request.HttpRequest.Url.AbsoluteUri)
                {
                    Count = DataProvider.UserDao.GetCount()
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#15
0
        public IHttpActionResult Update(int id, [FromBody] AdministratorInfoCreateUpdate adminInfo)
        {
            try
            {
                var request         = new AuthenticatedRequest();
                var isApiAuthorized = request.IsApiAuthenticated && AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeAdministrators);
                if (!isApiAuthorized)
                {
                    return(Unauthorized());
                }

                if (adminInfo == null)
                {
                    return(BadRequest("Could not read administrator from body"));
                }

                if (!DataProvider.AdministratorDao.ApiIsExists(id))
                {
                    return(NotFound());
                }

                var retval = DataProvider.AdministratorDao.ApiUpdate(id, adminInfo, out var errorMessage);
                if (retval == null)
                {
                    return(BadRequest(errorMessage));
                }

                return(Ok(new
                {
                    Value = retval
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#16
0
        public IHttpActionResult ResetPassword()
        {
            try
            {
                var request         = new AuthenticatedRequest();
                var isApiAuthorized = request.IsApiAuthenticated && AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeAdministrators);
                if (!isApiAuthorized)
                {
                    return(Unauthorized());
                }

                var account     = request.GetPostString("account");
                var password    = request.GetPostString("password");
                var newPassword = request.GetPostString("newPassword");

                if (!DataProvider.AdministratorDao.Validate(account, password, true, out var userName, out var errorMessage))
                {
                    return(BadRequest(errorMessage));
                }

                var adminInfo = AdminManager.GetAdminInfoByUserName(userName);

                if (!DataProvider.AdministratorDao.ChangePassword(adminInfo, newPassword, out errorMessage))
                {
                    return(BadRequest(errorMessage));
                }

                return(Ok(new
                {
                    Value = adminInfo
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#17
0
        public IHttpActionResult Get(int siteId, int channelId)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeChannels) ||
                              request.IsAdminLoggin;
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                channelInfo.Children = ChannelManager.GetChildren(siteId, channelId);

                return(Ok(new
                {
                    Value = channelInfo.ToDictionary()
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#18
0
 public WXMPClient(
     string appId,
     TicketClient ticketClient,
     BasisServiceClient basisServiceClient,
     CustomServiceClient customServiceClient,
     TemplateServiceClient templateServiceClient,
     MenuClient menuClient,
     UserManagerClient userManagerClient,
     AccountManagerClient accountManagerClient,
     MaterialClient materialClient,
     AccessTokenManager tokenManager)
 {
     AppId                 = appId;
     TicketClient          = ticketClient;
     BasisServiceClient    = basisServiceClient;
     CustomServiceClient   = customServiceClient;
     TemplateServiceClient = templateServiceClient;
     MenuClient            = menuClient;
     UserManagerClient     = userManagerClient;
     AccountManagerClient  = accountManagerClient;
     MaterialClient        = materialClient;
     TokenManager          = tokenManager;
 }
示例#19
0
        public void Insert(AccessTokenInfo accessTokenInfo)
        {
            var token = TranslateUtils.EncryptStringBySecretKey(StringUtils.Guid());

            var sqlString = $@"INSERT INTO {TableName}
           ({nameof(AccessTokenInfo.Title)}, 
            {nameof(AccessTokenInfo.Token)},
            {nameof(AccessTokenInfo.AdminName)},
            {nameof(AccessTokenInfo.Scopes)},
            {nameof(AccessTokenInfo.RateLimit)},
            {nameof(AccessTokenInfo.AddDate)},
            {nameof(AccessTokenInfo.UpdatedDate)})
     VALUES
           (@{nameof(AccessTokenInfo.Title)}, 
            @{nameof(AccessTokenInfo.Token)},
            @{nameof(AccessTokenInfo.AdminName)},
            @{nameof(AccessTokenInfo.Scopes)},
            @{nameof(AccessTokenInfo.RateLimit)},
            @{nameof(AccessTokenInfo.AddDate)},
            @{nameof(AccessTokenInfo.UpdatedDate)})";

            IDataParameter[] parameters =
            {
                GetParameter(nameof(accessTokenInfo.Title),       DataType.VarChar,                         200, accessTokenInfo.Title),
                GetParameter(nameof(accessTokenInfo.Token),       DataType.VarChar,                         200, token),
                GetParameter(nameof(accessTokenInfo.AdminName),   DataType.VarChar,                         200, accessTokenInfo.AdminName),
                GetParameter(nameof(accessTokenInfo.Scopes),      DataType.VarChar,                         200, accessTokenInfo.Scopes),
                GetParameter(nameof(accessTokenInfo.RateLimit),   DataType.Integer,  accessTokenInfo.RateLimit),
                GetParameter(nameof(accessTokenInfo.AddDate),     DataType.DateTime, DateTime.Now),
                GetParameter(nameof(accessTokenInfo.UpdatedDate), DataType.DateTime, DateTime.Now)
            };

            ExecuteNonQuery(sqlString, parameters);

            AccessTokenManager.ClearCache();
        }
示例#20
0
        public IHttpActionResult Delete(int id)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeUsers) ||
                              request.IsUserLoggin &&
                              request.UserId == id ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasSystemPermissions(ConfigManager.SettingsPermissions.User);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var userInfo = UserManager.GetUserInfoByUserId(id);
                if (userInfo == null)
                {
                    return(NotFound());
                }

                request.UserLogout();
                DataProvider.UserDao.Delete(userInfo);

                return(Ok(new
                {
                    Value = userInfo
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#21
0
        public async Task <ActionResult> VerifyHookDelayed()
        {
            var clientId = ConfigurationManager.AppSettings["ClientId"];

            var accessTokenManager = new AccessTokenManager();
            var accessToken        = accessTokenManager.getAccessToken();

            var baseApiUrl           = ConfigurationManager.AppSettings["BaseApiUrl"];
            var verifyHookDelayedUrl = $"{baseApiUrl}/hooks/{TempData["RestHookKey"].ToString()}/delayedVerify?access_token={accessToken}";

            var payload = new Dictionary <string, string>()
            {
                { "key", TempData["RestHookKey"].ToString() }
            };

            var httpContent       = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
            var hookSecretManager = new HookSecretManager();
            var hookSecret        = hookSecretManager.getHookSecret();

            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.DefaultRequestHeaders.Add("X-Hook-Secret", hookSecret);

            var content  = new FormUrlEncodedContent(payload);
            var response = await client.PostAsync(verifyHookDelayedUrl, httpContent);

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                var createHookResponse = JsonConvert.DeserializeObject <CreateHookResponse>(json);
            }

            return(await Task.Run(() => View("Index")));
        }
示例#22
0
        public IHttpActionResult Create(int siteId, int channelId)
        {
            try
            {
                var  request  = new RequestImpl();
                var  sourceId = request.GetPostInt(ContentAttribute.SourceId.ToCamelCase());
                bool isAuth;
                if (sourceId == SourceManager.User)
                {
                    isAuth = request.IsUserLoggin && request.UserPermissions.HasChannelPermissions(siteId, channelId, ConfigManager.ChannelPermissions.ContentAdd);
                }
                else
                {
                    isAuth = request.IsApiAuthenticated &&
                             AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeContents) ||
                             request.IsUserLoggin &&
                             request.UserPermissions.HasChannelPermissions(siteId, channelId,
                                                                           ConfigManager.ChannelPermissions.ContentAdd) ||
                             request.IsAdminLoggin &&
                             request.AdminPermissions.HasChannelPermissions(siteId, channelId,
                                                                            ConfigManager.ChannelPermissions.ContentAdd);
                }
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                if (!channelInfo.Additional.IsContentAddable)
                {
                    return(BadRequest("此栏目不能添加内容"));
                }

                var attributes = request.GetPostObject <Dictionary <string, object> >();
                if (attributes == null)
                {
                    return(BadRequest("无法从body中获取内容实体"));
                }
                var checkedLevel = request.GetPostInt("checkedLevel");

                var tableName = ChannelManager.GetTableName(siteInfo, channelInfo);
                var adminName = request.AdminName;

                var isChecked = checkedLevel >= siteInfo.Additional.CheckContentLevel;
                if (isChecked)
                {
                    if (sourceId == SourceManager.User || request.IsUserLoggin)
                    {
                        isChecked = request.UserPermissionsImpl.HasChannelPermissions(siteId, channelId,
                                                                                      ConfigManager.ChannelPermissions.ContentCheck);
                    }
                    else if (request.IsAdminLoggin)
                    {
                        isChecked = request.AdminPermissionsImpl.HasChannelPermissions(siteId, channelId,
                                                                                       ConfigManager.ChannelPermissions.ContentCheck);
                    }
                }

                var contentInfo = new ContentInfo(attributes)
                {
                    SiteId           = siteId,
                    ChannelId        = channelId,
                    AddUserName      = adminName,
                    LastEditDate     = DateTime.Now,
                    LastEditUserName = adminName,
                    AdminId          = request.AdminId,
                    UserId           = request.UserId,
                    SourceId         = sourceId,
                    IsChecked        = isChecked,
                    CheckedLevel     = checkedLevel
                };

                contentInfo.Id = DataProvider.ContentDao.Insert(tableName, siteInfo, channelInfo, contentInfo);

                foreach (var service in PluginManager.Services)
                {
                    try
                    {
                        service.OnContentFormSubmit(new ContentFormSubmitEventArgs(siteId, channelId, contentInfo.Id, new AttributesImpl(attributes), contentInfo));
                    }
                    catch (Exception ex)
                    {
                        LogUtils.AddErrorLog(service.PluginId, ex, nameof(IService.ContentFormSubmit));
                    }
                }

                if (contentInfo.IsChecked)
                {
                    CreateManager.CreateContent(siteId, channelId, contentInfo.Id);
                    CreateManager.TriggerContentChangedEvent(siteId, channelId);
                }

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

                return(Ok(new
                {
                    Value = contentInfo
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#23
0
        public IHttpActionResult Create(int siteId)
        {
            try
            {
                var request  = new AuthenticatedRequest();
                var parentId = request.GetPostInt(ChannelAttribute.ParentId, siteId);

                var isAuth = request.IsApiAuthenticated &&
                             AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeChannels) ||
                             request.IsAdminLoggin &&
                             request.AdminPermissions.HasChannelPermissions(siteId, parentId,
                                                                            ConfigManager.ChannelPermissions.ChannelAdd);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var contentModelPluginId    = request.GetPostString(ChannelAttribute.ContentModelPluginId);
                var contentRelatedPluginIds = request.GetPostString(ChannelAttribute.ContentRelatedPluginIds);

                var channelName         = request.GetPostString(ChannelAttribute.ChannelName);
                var indexName           = request.GetPostString(ChannelAttribute.IndexName);
                var filePath            = request.GetPostString(ChannelAttribute.FilePath);
                var channelFilePathRule = request.GetPostString(ChannelAttribute.ChannelFilePathRule);
                var contentFilePathRule = request.GetPostString(ChannelAttribute.ContentFilePathRule);
                var groupNameCollection = request.GetPostString(ChannelAttribute.GroupNameCollection);
                var imageUrl            = request.GetPostString(ChannelAttribute.ImageUrl);
                var content             = request.GetPostString(ChannelAttribute.Content);
                var keywords            = request.GetPostString(ChannelAttribute.Keywords);
                var description         = request.GetPostString(ChannelAttribute.Description);
                var linkUrl             = request.GetPostString(ChannelAttribute.LinkUrl);
                var linkType            = request.GetPostString(ChannelAttribute.LinkType);
                var channelTemplateId   = request.GetPostInt(ChannelAttribute.ChannelTemplateId);
                var contentTemplateId   = request.GetPostInt(ChannelAttribute.ContentTemplateId);

                var channelInfo = new ChannelInfo
                {
                    SiteId                  = siteId,
                    ParentId                = parentId,
                    ContentModelPluginId    = contentModelPluginId,
                    ContentRelatedPluginIds = contentRelatedPluginIds
                };

                if (!string.IsNullOrEmpty(indexName))
                {
                    var indexNameList = DataProvider.ChannelDao.GetIndexNameList(siteId);
                    if (indexNameList.IndexOf(indexName) != -1)
                    {
                        return(BadRequest("栏目添加失败,栏目索引已存在!"));
                    }
                }

                if (!string.IsNullOrEmpty(filePath))
                {
                    if (!DirectoryUtils.IsDirectoryNameCompliant(filePath))
                    {
                        return(BadRequest("栏目页面路径不符合系统要求!"));
                    }

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

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

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

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

                //var parentChannelInfo = ChannelManager.GetChannelInfo(siteId, parentId);
                //var styleInfoList = TableStyleManager.GetChannelStyleInfoList(parentChannelInfo);
                //var extendedAttributes = BackgroundInputTypeParser.SaveAttributes(siteInfo, styleInfoList, Request.Form, null);
                channelInfo.Additional.Load(request.GetPostObject <Dictionary <string, object> >());
                //foreach (string key in attributes)
                //{
                //    channelInfo.Additional.SetExtendedAttribute(key, attributes[key]);
                //}

                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.LinkUrl             = linkUrl;
                channelInfo.LinkType            = linkType;
                channelInfo.ChannelTemplateId   = channelTemplateId;
                channelInfo.ContentTemplateId   = contentTemplateId;

                channelInfo.AddDate = DateTime.Now;
                channelInfo.Id      = DataProvider.ChannelDao.Insert(channelInfo);
                //栏目选择投票样式后,内容

                CreateManager.CreateChannel(siteId, channelInfo.Id);

                request.AddSiteLog(siteId, "添加栏目", $"栏目:{channelName}");

                return(Ok(new
                {
                    Value = channelInfo.ToDictionary()
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#24
0
        public IHttpActionResult Update(int siteId, int channelId)
        {
            try
            {
                var request = new AuthenticatedRequest();
                var isAuth  = request.IsApiAuthenticated &&
                              AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeChannels) ||
                              request.IsAdminLoggin &&
                              request.AdminPermissions.HasChannelPermissions(siteId, channelId,
                                                                             ConfigManager.ChannelPermissions.ChannelEdit);
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                channelInfo.Additional.Load(request.GetPostObject <Dictionary <string, object> >());

                if (request.IsPostExists(ChannelAttribute.ChannelName))
                {
                    channelInfo.ChannelName = request.GetPostString(ChannelAttribute.ChannelName);
                }

                if (request.IsPostExists(ChannelAttribute.IndexName))
                {
                    var indexName = request.GetPostString(ChannelAttribute.IndexName);
                    if (!channelInfo.IndexName.Equals(indexName) && !string.IsNullOrEmpty(indexName))
                    {
                        var indexNameList = DataProvider.ChannelDao.GetIndexNameList(siteId);
                        if (indexNameList.IndexOf(indexName) != -1)
                        {
                            return(BadRequest("栏目属性修改失败,栏目索引已存在!"));
                        }
                    }
                    channelInfo.IndexName = indexName;
                }

                if (request.IsPostExists(ChannelAttribute.ContentModelPluginId))
                {
                    var contentModelPluginId = request.GetPostString(ChannelAttribute.ContentModelPluginId);
                    if (channelInfo.ContentModelPluginId != contentModelPluginId)
                    {
                        channelInfo.ContentModelPluginId = contentModelPluginId;
                    }
                }

                if (request.IsPostExists(ChannelAttribute.ContentRelatedPluginIds))
                {
                    channelInfo.ContentRelatedPluginIds = request.GetPostString(ChannelAttribute.ContentRelatedPluginIds);
                }

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

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

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

                if (request.IsPostExists(ChannelAttribute.ChannelFilePathRule))
                {
                    var channelFilePathRule = request.GetPostString(ChannelAttribute.ChannelFilePathRule);

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

                    channelInfo.ChannelFilePathRule = channelFilePathRule;
                }

                if (request.IsPostExists(ChannelAttribute.ContentFilePathRule))
                {
                    var contentFilePathRule = request.GetPostString(ChannelAttribute.ContentFilePathRule);

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

                    channelInfo.ContentFilePathRule = contentFilePathRule;
                }

                if (request.IsPostExists(ChannelAttribute.GroupNameCollection))
                {
                    channelInfo.GroupNameCollection = request.GetPostString(ChannelAttribute.GroupNameCollection);
                }

                if (request.IsPostExists(ChannelAttribute.ImageUrl))
                {
                    channelInfo.ImageUrl = request.GetPostString(ChannelAttribute.ImageUrl);
                }

                if (request.IsPostExists(ChannelAttribute.Content))
                {
                    channelInfo.Content = request.GetPostString(ChannelAttribute.Content);
                }

                if (request.IsPostExists(ChannelAttribute.Keywords))
                {
                    channelInfo.Keywords = request.GetPostString(ChannelAttribute.Keywords);
                }

                if (request.IsPostExists(ChannelAttribute.Description))
                {
                    channelInfo.Description = request.GetPostString(ChannelAttribute.Description);
                }

                if (request.IsPostExists(ChannelAttribute.LinkUrl))
                {
                    channelInfo.LinkUrl = request.GetPostString(ChannelAttribute.LinkUrl);
                }

                if (request.IsPostExists(ChannelAttribute.LinkType))
                {
                    channelInfo.LinkType = request.GetPostString(ChannelAttribute.LinkType);
                }

                if (request.IsPostExists(ChannelAttribute.ChannelTemplateId))
                {
                    channelInfo.ChannelTemplateId = request.GetPostInt(ChannelAttribute.ChannelTemplateId);
                }

                if (request.IsPostExists(ChannelAttribute.ContentTemplateId))
                {
                    channelInfo.ContentTemplateId = request.GetPostInt(ChannelAttribute.ContentTemplateId);
                }

                DataProvider.ChannelDao.Update(channelInfo);

                return(Ok(new
                {
                    Value = channelInfo.ToDictionary()
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#25
0
 public HomeController(ILogger <HomeController> logger, WindmillFarm.WindmillFarmClient client, AccessTokenManager tokenManager)
 {
     this.logger       = logger;
     this.client       = client;
     this.tokenManager = tokenManager;
 }
示例#26
0
        public StlRequest()
        {
            Request         = new RequestImpl();
            IsApiAuthorized = Request.IsApiAuthenticated && AccessTokenManager.IsScope(Request.ApiToken, AccessTokenManager.ScopeStl);

            if (!IsApiAuthorized)
            {
                return;
            }

            var siteId  = Request.GetQueryInt("siteId");
            var siteDir = Request.GetQueryString("siteDir");

            var channelId = Request.GetQueryInt("channelId");
            var contentId = Request.GetQueryInt("contentId");

            if (siteId > 0)
            {
                SiteInfo = SiteManager.GetSiteInfo(siteId);
            }
            else if (!string.IsNullOrEmpty(siteDir))
            {
                SiteInfo = SiteManager.GetSiteInfoByDirectory(siteDir);
            }
            else
            {
                SiteInfo = SiteManager.GetSiteInfoByIsRoot();
                if (SiteInfo == null)
                {
                    var siteInfoList = SiteManager.GetSiteInfoList();
                    if (siteInfoList != null && siteInfoList.Count > 0)
                    {
                        SiteInfo = siteInfoList[0];
                    }
                }
            }

            if (SiteInfo == null)
            {
                return;
            }

            if (channelId == 0)
            {
                channelId = SiteInfo.Id;
            }

            var templateInfo = new TemplateInfo(0, SiteInfo.Id, string.Empty, TemplateType.IndexPageTemplate, string.Empty, string.Empty, string.Empty, ECharset.utf_8, true);

            PageInfo = new PageInfo(channelId, contentId, SiteInfo, templateInfo, new Dictionary <string, object>())
            {
                UniqueId = 1000,
                UserInfo = Request.UserInfo
            };

            var attributes = TranslateUtils.NewIgnoreCaseNameValueCollection();

            foreach (var key in Request.QueryString.AllKeys)
            {
                attributes[key] = Request.QueryString[key];
            }

            ContextInfo = new ContextInfo(PageInfo)
            {
                IsStlEntity = true,
                Attributes  = attributes,
                InnerHtml   = string.Empty
            };
        }
示例#27
0
        public async Task Send(WnsNotification notification)
        {
            // Get or renew our access token
            var accessToken = await AccessTokenManager.GetAccessToken();

            //https://cloud.notify.windows.com/?token=.....
            //Authorization: Bearer {AccessToken}
            //

            // Not sure how to do this in httpclient
            var http = new HttpClient();

            http.DefaultRequestHeaders.ExpectContinue = false; //Disable expect-100 to improve latency

            http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-Type", string.Format("wns/{0}", notification.Type.ToString().ToLower()));

            if (!http.DefaultRequestHeaders.Contains("Authorization")) //prevent double values
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + accessToken);
            }

            if (notification.RequestForStatus.HasValue)
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-RequestForStatus", notification.RequestForStatus.Value.ToString().ToLower());
            }

            if (notification.TimeToLive.HasValue)
            {
                http.DefaultRequestHeaders.TryAddWithoutValidation("X-WNS-TTL", notification.TimeToLive.Value.ToString());  //Time to live in seconds
            }
            if (notification.Type == WnsNotificationType.Tile)
            {
                var winTileNot = notification as WnsTileNotification;

                if (winTileNot != null && winTileNot.CachePolicy.HasValue)
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WnsNotificationCachePolicyType.Cache ? "cache" : "no-cache");
                }

                if (winTileNot != null && !string.IsNullOrEmpty(winTileNot.NotificationTag))
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Tag", winTileNot.NotificationTag); // TILE only
                }
            }
            else if (notification.Type == WnsNotificationType.Badge)
            {
                var winTileBadge = notification as WnsBadgeNotification;

                if (winTileBadge != null && winTileBadge.CachePolicy.HasValue)
                {
                    http.DefaultRequestHeaders.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WnsNotificationCachePolicyType.Cache ? "cache" : "no-cache");
                }
            }

            HttpContent content = null;

            if (notification.Type == WnsNotificationType.Raw)
            {
                content = new StreamContent(new MemoryStream(((WnsRawNotification)notification).RawData));
            }
            else
            {
                content = new StringContent(
                    notification.Payload.ToString(), // Get XML payload
                    Encoding.UTF8,
                    "text/xml");
            }

            var result = await http.PostAsync(notification.ChannelUri, content);

            var status = ParseStatus(result, notification);

            //RESPONSE HEADERS
            // X-WNS-Debug-Trace   string
            // X-WNS-DeviceConnectionStatus  connected | disconnected | tempdisconnected   (if RequestForStatus was set to true)
            // X-WNS-Error-Description  string
            // X-WNS-Msg-ID   string  (max 16 char)
            // X-WNS-NotificationStatus   received | dropped | channelthrottled
            //

            // 200 OK
            // 400  One or more headers were specified incorrectly or conflict with another header.
            // 401  The cloud service did not present a valid authentication ticket. The OAuth ticket may be invalid.
            // 403  The cloud service is not authorized to send a notification to this URI even though they are authenticated.
            // 404  The channel URI is not valid or is not recognized by WNS. - Raise Expiry
            // 405  Invalid Method - never will get
            // 406  The cloud service exceeded its throttle limit.
            // 410  The channel expired. - Raise Expiry
            // 413  The notification payload exceeds the 5000 byte size limit.
            // 500  An internal failure caused notification delivery to fail.
            // 503  The server is currently unavailable.

            // OK, everything worked!
            if (status.HttpStatus == HttpStatusCode.OK &&
                status.NotificationStatus == WnsNotificationSendStatus.Received)
            {
                return;
            }

            //401
            if (status.HttpStatus == HttpStatusCode.Unauthorized)
            {
                AccessTokenManager.InvalidateAccessToken(accessToken);
                throw new RetryAfterException(notification, "Access token expired", DateTime.UtcNow.AddSeconds(5));
            }

            //404 or 410
            if (status.HttpStatus == HttpStatusCode.NotFound || status.HttpStatus == HttpStatusCode.Gone)
            {
                throw new DeviceSubscriptionExpiredException(notification)
                      {
                          OldSubscriptionId = notification.ChannelUri,
                          ExpiredAt         = DateTime.UtcNow
                      };
            }


            // Any other error
            throw new WnsNotificationException(status);
        }
示例#28
0
        private SquareClient(TimeSpan timeout, string squareVersion, string accessToken,
                             Environment environment, IDictionary <string, IAuthManager> authManagers,
                             IHttpClient httpClient, HttpCallBack httpCallBack,
                             IDictionary <string, List <string> > additionalHeaders,
                             IHttpClientConfiguration httpClientConfiguration)
        {
            Timeout                = timeout;
            SquareVersion          = squareVersion;
            AccessToken            = accessToken;
            Environment            = environment;
            this.httpCallBack      = httpCallBack;
            this.httpClient        = httpClient;
            this.authManagers      = new Dictionary <string, IAuthManager>(authManagers);
            accessTokenManager     = new AccessTokenManager(accessToken);
            this.additionalHeaders = additionalHeaders;                HttpClientConfiguration = httpClientConfiguration;

            mobileAuthorization = new Lazy <IMobileAuthorizationApi>(
                () => new MobileAuthorizationApi(this, this.httpClient, authManagers, this.httpCallBack));
            oAuth = new Lazy <IOAuthApi>(
                () => new OAuthApi(this, this.httpClient, authManagers, this.httpCallBack));
            v1Locations = new Lazy <IV1LocationsApi>(
                () => new V1LocationsApi(this, this.httpClient, authManagers, this.httpCallBack));
            v1Employees = new Lazy <IV1EmployeesApi>(
                () => new V1EmployeesApi(this, this.httpClient, authManagers, this.httpCallBack));
            v1Transactions = new Lazy <IV1TransactionsApi>(
                () => new V1TransactionsApi(this, this.httpClient, authManagers, this.httpCallBack));
            v1Items = new Lazy <IV1ItemsApi>(
                () => new V1ItemsApi(this, this.httpClient, authManagers, this.httpCallBack));
            applePay = new Lazy <IApplePayApi>(
                () => new ApplePayApi(this, this.httpClient, authManagers, this.httpCallBack));
            bankAccounts = new Lazy <IBankAccountsApi>(
                () => new BankAccountsApi(this, this.httpClient, authManagers, this.httpCallBack));
            cashDrawers = new Lazy <ICashDrawersApi>(
                () => new CashDrawersApi(this, this.httpClient, authManagers, this.httpCallBack));
            catalog = new Lazy <ICatalogApi>(
                () => new CatalogApi(this, this.httpClient, authManagers, this.httpCallBack));
            customers = new Lazy <ICustomersApi>(
                () => new CustomersApi(this, this.httpClient, authManagers, this.httpCallBack));
            customerGroups = new Lazy <ICustomerGroupsApi>(
                () => new CustomerGroupsApi(this, this.httpClient, authManagers, this.httpCallBack));
            customerSegments = new Lazy <ICustomerSegmentsApi>(
                () => new CustomerSegmentsApi(this, this.httpClient, authManagers, this.httpCallBack));
            devices = new Lazy <IDevicesApi>(
                () => new DevicesApi(this, this.httpClient, authManagers, this.httpCallBack));
            disputes = new Lazy <IDisputesApi>(
                () => new DisputesApi(this, this.httpClient, authManagers, this.httpCallBack));
            employees = new Lazy <IEmployeesApi>(
                () => new EmployeesApi(this, this.httpClient, authManagers, this.httpCallBack));
            inventory = new Lazy <IInventoryApi>(
                () => new InventoryApi(this, this.httpClient, authManagers, this.httpCallBack));
            invoices = new Lazy <IInvoicesApi>(
                () => new InvoicesApi(this, this.httpClient, authManagers, this.httpCallBack));
            labor = new Lazy <ILaborApi>(
                () => new LaborApi(this, this.httpClient, authManagers, this.httpCallBack));
            locations = new Lazy <ILocationsApi>(
                () => new LocationsApi(this, this.httpClient, authManagers, this.httpCallBack));
            checkout = new Lazy <ICheckoutApi>(
                () => new CheckoutApi(this, this.httpClient, authManagers, this.httpCallBack));
            transactions = new Lazy <ITransactionsApi>(
                () => new TransactionsApi(this, this.httpClient, authManagers, this.httpCallBack));
            loyalty = new Lazy <ILoyaltyApi>(
                () => new LoyaltyApi(this, this.httpClient, authManagers, this.httpCallBack));
            merchants = new Lazy <IMerchantsApi>(
                () => new MerchantsApi(this, this.httpClient, authManagers, this.httpCallBack));
            orders = new Lazy <IOrdersApi>(
                () => new OrdersApi(this, this.httpClient, authManagers, this.httpCallBack));
            payments = new Lazy <IPaymentsApi>(
                () => new PaymentsApi(this, this.httpClient, authManagers, this.httpCallBack));
            refunds = new Lazy <IRefundsApi>(
                () => new RefundsApi(this, this.httpClient, authManagers, this.httpCallBack));
            subscriptions = new Lazy <ISubscriptionsApi>(
                () => new SubscriptionsApi(this, this.httpClient, authManagers, this.httpCallBack));
            team = new Lazy <ITeamApi>(
                () => new TeamApi(this, this.httpClient, authManagers, this.httpCallBack));
            terminal = new Lazy <ITerminalApi>(
                () => new TerminalApi(this, this.httpClient, authManagers, this.httpCallBack));

            if (!authManagers.ContainsKey("default") ||
                ((AccessTokenManager)authManagers["default"]).AccessToken != accessToken)
            {
                authManagers["default"] = accessTokenManager;
            }
        }
示例#29
0
        public IHttpActionResult GetChannelContents(int siteId, int channelId)
        {
            try
            {
                var  request  = new RequestImpl();
                var  sourceId = request.GetPostInt(ContentAttribute.SourceId.ToCamelCase());
                bool isAuth;
                if (sourceId == SourceManager.User)
                {
                    isAuth = request.IsUserLoggin && request.UserPermissions.HasChannelPermissions(siteId, channelId, ConfigManager.ChannelPermissions.ContentView);
                }
                else
                {
                    isAuth = request.IsApiAuthenticated &&
                             AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeContents) ||
                             request.IsUserLoggin &&
                             request.UserPermissions.HasChannelPermissions(siteId, channelId,
                                                                           ConfigManager.ChannelPermissions.ContentView) ||
                             request.IsAdminLoggin &&
                             request.AdminPermissions.HasChannelPermissions(siteId, channelId,
                                                                            ConfigManager.ChannelPermissions.ContentView);
                }
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                if (!request.AdminPermissionsImpl.HasChannelPermissions(siteId, channelId,
                                                                        ConfigManager.ChannelPermissions.ContentView))
                {
                    return(Unauthorized());
                }

                var tableName = ChannelManager.GetTableName(siteInfo, channelInfo);

                var top     = request.GetQueryInt("top", 20);
                var skip    = request.GetQueryInt("skip");
                var like    = request.GetQueryString("like");
                var orderBy = request.GetQueryString("orderBy");

                int count;
                var contentIdList = DataProvider.ContentDao.ApiGetContentIdListByChannelId(tableName, siteId, channelId, top, skip, like, orderBy, request.QueryString, out count);
                var value         = new List <Dictionary <string, object> >();
                foreach (var contentId in contentIdList)
                {
                    var contentInfo = ContentManager.GetContentInfo(siteInfo, channelInfo, contentId);
                    if (contentInfo != null)
                    {
                        value.Add(contentInfo.ToDictionary());
                    }
                }

                return(Ok(new PageResponse(value, top, skip, request.HttpRequest.Url.AbsoluteUri)
                {
                    Count = count
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }
示例#30
0
        public IHttpActionResult Get(int siteId, int channelId, int id)
        {
            try
            {
                var  request  = new RequestImpl();
                var  sourceId = request.GetPostInt(ContentAttribute.SourceId.ToCamelCase());
                bool isAuth;
                if (sourceId == SourceManager.User)
                {
                    isAuth = request.IsUserLoggin && request.UserPermissions.HasChannelPermissions(siteId, channelId, ConfigManager.ChannelPermissions.ContentView);
                }
                else
                {
                    isAuth = request.IsApiAuthenticated &&
                             AccessTokenManager.IsScope(request.ApiToken, AccessTokenManager.ScopeContents) ||
                             request.IsUserLoggin &&
                             request.UserPermissions.HasChannelPermissions(siteId, channelId,
                                                                           ConfigManager.ChannelPermissions.ContentView) ||
                             request.IsAdminLoggin &&
                             request.AdminPermissions.HasChannelPermissions(siteId, channelId,
                                                                            ConfigManager.ChannelPermissions.ContentView);
                }
                if (!isAuth)
                {
                    return(Unauthorized());
                }

                var siteInfo = SiteManager.GetSiteInfo(siteId);
                if (siteInfo == null)
                {
                    return(BadRequest("无法确定内容对应的站点"));
                }

                var channelInfo = ChannelManager.GetChannelInfo(siteId, channelId);
                if (channelInfo == null)
                {
                    return(BadRequest("无法确定内容对应的栏目"));
                }

                if (!request.AdminPermissionsImpl.HasChannelPermissions(siteId, channelId,
                                                                        ConfigManager.ChannelPermissions.ContentView))
                {
                    return(Unauthorized());
                }

                var contentInfo = ContentManager.GetContentInfo(siteInfo, channelInfo, id);
                if (contentInfo == null)
                {
                    return(NotFound());
                }

                return(Ok(new
                {
                    Value = contentInfo
                }));
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(InternalServerError(ex));
            }
        }