public void LogOut(AuthenticationData data) { if (data != null) { var result = (AuthenticationData)null; Authorized.TryRemove(data.Id, out result); } }
public HMACAuthenticator(AuthenticationData authenticationData) { string secretKey = _dao.GetSecretKey(authenticationData.SharedKey); if (secretKey == null) throw new SecurityException("Invalid shared key"); _hmac.Key = Encoding.UTF8.GetBytes(secretKey); }
public AuthenticationData Authenticate(string name, string hash) { var employee = Ninject.Get<GetEmployeesQuery>().Execute().FirstOrDefault(e => e.Name == name && e.Password == hash); if (employee != null) { var result = new AuthenticationData() { Id = Guid.NewGuid(), Employee = employee }; Authorized[result.Id] = result; return result; } return null; }
public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"); cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); IDataReader result = ExecuteReader(cmd, m_Connection); try { if (result.Read()) { ret.PrincipalID = principalID; if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } return ret; } else { return null; } } catch { } finally { //CloseCommand(cmd); } return null; }
public SuccessfulResponse AuthenticateMessage(AuthenticationData authenticationData) { if (isTimeoutVerificationEnabled) { var authenticationDataUtcTimeStamp = TimeZoneInfo.ConvertTimeToUtc(authenticationData.TimeStamp); if (authenticationDataUtcTimeStamp.CompareTo(DateTime.UtcNow.AddMilliseconds(-1 * maxtTimeout)) < 0) throw new TimeoutException("The message timed out."); } var timeStamp = authenticationData.TimeStamp.ToString("MM/dd/yyyy hh:mm:ss tt"); var concatenatedAuthenticationData = String.Format("{0}:{1}:{2}", timeStamp, authenticationData.URI.AbsolutePath, authenticationData.Payload); var calculatedHMACBytes = _hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(concatenatedAuthenticationData)); var calculatedHMACString = ByteArrayToString(calculatedHMACBytes); if (!calculatedHMACString.Equals(authenticationData.MessageAuthenticationCode)) throw new SecurityException("Could not verify the integrity of the message"); return new SuccessfulResponse(Encoding.UTF8.GetString(_hmac.Key), new object()); }
public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); MySqlCommand cmd = new MySqlCommand( "select * from `"+m_Realm+"` where UUID = ?principalID" ); cmd.Parameters.AddWithValue("?principalID", principalID.ToString()); IDataReader result = ExecuteReader(cmd); if (result.Read()) { ret.PrincipalID = principalID; if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } result.Close(); CloseReaderCommand(cmd); return ret; } result.Close(); CloseReaderCommand(cmd); return null; }
public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); string sql = string.Format("select * from '{0}' where UUID = @principalID", m_Realm); using (SqlConnection conn = new SqlConnection(m_ConnectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@principalID", principalID.ToString()); conn.Open(); using (SqlDataReader result = cmd.ExecuteReader()) { if (result.Read()) { ret.PrincipalID = principalID; if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } return ret; } } } return null; }
public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID", dbcon)) { cmd.Parameters.AddWithValue("?principalID", principalID.ToString()); IDataReader result = cmd.ExecuteReader(); if (result.Read()) { ret.PrincipalID = principalID; CheckColumnNames(result); foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } return ret; } else { return null; } } } }
protected void Page_Load(object sender, EventArgs e) { this._authenticationData = GetAuthenticationDataAndCulture(); this._year = DateTime.Today.Year; if ( !this._authenticationData.Authority.HasAccess(new Access( this._authenticationData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Read))) { throw new UnauthorizedAccessException(); } // TODO: Get and cache account tree and account balances Response.ContentType = "application/json"; _nearEdge = "left"; if (Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft) { _nearEdge = "right"; } string response = string.Empty; PopulateLookups(FinancialAccounts.ForOrganization(this._authenticationData.CurrentOrganization)); this._hashedAccounts = FinancialAccounts.GetHashedAccounts(this._authenticationData.CurrentOrganization); this._resultAccountId = this._authenticationData.CurrentOrganization.FinancialAccounts.CostsYearlyResult.Identity; response += GetAccountGroup(FinancialAccountType.Asset, Resources.Global.Financial_Asset) + ","; response += GetAccountGroup(FinancialAccountType.Debt, Resources.Global.Financial_Debt) + ","; response += GetAccountGroup(FinancialAccountType.Income, Resources.Global.Financial_Income) + ","; response += GetAccountGroup(FinancialAccountType.Cost, Resources.Global.Financial_Cost); Response.Output.WriteLine("[" + response + "]"); Response.End(); }
public static AjaxCallAutomationDataResult SetAccountAutomationProfile(int accountId, int profileId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (account.OrganizationId != authData.CurrentOrganization.Identity) { throw new UnauthorizedAccessException("A million nopes"); } if ( !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails, AccessType.Write))) { throw new UnauthorizedAccessException("No"); } account.AutomationProfileId = profileId; AjaxCallAutomationDataResult result = new AjaxCallAutomationDataResult(); result.Success = true; result.Data = GetAccountAutomationData(profileId); result.Data.NonPresentationCurrency = (result.Data.Profile.CurrencyId != authData.CurrentOrganization.Currency.Identity); if (result.Data.NonPresentationCurrency) { account.ForeignCurrency = Currency.FromCode(result.Data.AutomationCurrencyCode); } else { account.ForeignCurrency = null; } return(result); }
public virtual AuthInfo GetAuthInfo(UUID principalID) { AuthenticationData data = m_Database.Get(principalID); if (data == null) { return(null); } else { AuthInfo info = new AuthInfo() { PrincipalID = data.PrincipalID, AccountType = data.Data["accountType"] as string, PasswordHash = data.Data["passwordHash"] as string, PasswordSalt = data.Data["passwordSalt"] as string, WebLoginKey = data.Data["webLoginKey"] as string }; return(info); } }
public async void Invoke_ShouldInvokeNextIfKeysMatch() { // Arrange var context = new DefaultHttpContext(); var authData = new AuthenticationData() { AuthenticationKey = "key", BusinessId = "businessid", Version = 1, Endpoint = "endpoint", Verb = "GET", VersionText = "incorrectText" }; _authHelper.Setup(_ => _.ExtractAuthenticationDataFromContext(It.IsAny <HttpContext>())).Returns(authData); _configuration.Setup(_ => _["Authorization"]).Returns("key"); // Act await _middleware.Invoke(context); // Assert _requestDelegate.Verify(_ => _(It.IsAny <HttpContext>()), Times.Once); }
/// <summary> /// Customizes the raven database. /// </summary> /// <param name="documentStore">The document store.</param> private void CustomizeRavenDocumentStore(DocumentStore documentStore) { documentStore.Conventions.RegisterAsyncIdConvention <AuthenticationData>((databaseName, commands, entity) => { return(Task.FromResult(AuthenticationData.CreateId(entity.UserId))); }); documentStore.Conventions.RegisterAsyncIdConvention <AuthenticationToken>((databaseName, commands, entity) => { return(Task.FromResult(AuthenticationToken.CreateId(entity.Token))); }); documentStore.Conventions.RegisterAsyncIdConvention <MileageInternalSettings>((databaseName, commands, entity) => { return(Task.FromResult(MileageInternalSettings.CreateId())); }); documentStore.Conventions.RegisterAsyncIdConvention <MileageSettings>((databaseName, commands, entity) => { return(Task.FromResult(MileageSettings.CreateId())); }); documentStore.Conventions.RegisterAsyncIdConvention <StoredLayout>((databaseName, commands, entity) => { return(Task.FromResult(StoredLayout.CreateId(entity.UserId, entity.LayoutName))); }); }
public IActionResult SetConsent([FromBody] AuthenticationData consent, string bank) { try { if (string.IsNullOrEmpty(bank)) { bank = "bank1"; } var result = service.SetConsent(consent, bank.ToLower()); if (result == null) { throw new Exception("Ocorreu um erro ao gravar o consentimento"); } return(Ok(new { success = true, result })); } catch (Exception ex) { return(BadRequest(new { success = false, message = ex.Message })); } }
private async void SignInButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { if (!_isUserAuthenticated) { SignInButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed; SignInProgressRing.IsActive = true; _authenticationData = await _authenticationService.Authenticate(); SignInButton.Visibility = Windows.UI.Xaml.Visibility.Visible; SignInProgressRing.IsActive = false; if (_authenticationData != null) { MessageDialog dialog = new MessageDialog("Welcome!"); await dialog.ShowAsync(); SignInButton.Content = "SIGN OUT"; _isUserAuthenticated = true; CallApiButton.Visibility = Windows.UI.Xaml.Visibility.Visible; } } else { SignInButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed; SignInProgressRing.IsActive = true; await _authenticationService.SignOut(); SignInButton.Visibility = Windows.UI.Xaml.Visibility.Visible; SignInProgressRing.IsActive = false; SignInButton.Content = "SIGN IN"; _isUserAuthenticated = false; CallApiButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } }
public static bool AddTransactionRow(int txId, int accountId, string amountString) { AuthenticationData authData = GetAuthenticationDataAndCulture(); if ( !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write))) { return(false); // fail } FinancialTransaction transaction = FinancialTransaction.FromIdentity(txId); if (authData.CurrentOrganization.Parameters.FiscalBooksClosedUntilYear >= transaction.DateTime.Year) { return(false); // can't edit closed books } FinancialAccount account = FinancialAccount.FromIdentity(accountId); Double amountFloat = Double.Parse(amountString); Int64 amountCents = (Int64)(amountFloat * 100.0); if (account.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Account/Organization mismatch"); } if (amountCents == 0) { return(false); } transaction.AddRow(account, amountCents, authData.CurrentUser); return(true); }
public string Authenticate(UUID principalID, string password, int lifetime) { AuthenticationData data = m_Database.Get(principalID); string result = String.Empty; if (data != null && data.Data != null) { if (data.Data.ContainsKey("webLoginKey")) { m_log.DebugFormat("[AUTH SERVICE]: Attempting web key authentication for PrincipalID {0}", principalID); result = m_svcChecks["web_login_key"].Authenticate(principalID, password, lifetime); if (result == String.Empty) { m_log.DebugFormat("[AUTH SERVICE]: Web Login failed for PrincipalID {0}", principalID); } } if (result == string.Empty && data.Data.ContainsKey("passwordHash") && data.Data.ContainsKey("passwordSalt")) { m_log.DebugFormat("[AUTH SERVICE]: Attempting password authentication for PrincipalID {0}", principalID); result = m_svcChecks["password"].Authenticate(principalID, password, lifetime); if (result == String.Empty) { m_log.DebugFormat("[AUTH SERVICE]: Password login failed for PrincipalID {0}", principalID); } } if (result == string.Empty) { m_log.DebugFormat("[AUTH SERVICE]: Both password and webLoginKey-based authentication failed for PrincipalID {0}", principalID); } } else { m_log.DebugFormat("[AUTH SERVICE]: PrincipalID {0} or its data not found", principalID); } return(result); }
public static AjaxCallResult DenyItem(string recordId, string reason) { AuthenticationData authData = GetAuthenticationDataAndCulture(); IPayable payable = PayableFromRecordId(recordId); FinancialAccount budget = payable.Budget; if (budget.OrganizationId != authData.CurrentOrganization.Identity || (budget.OwnerPersonId != authData.CurrentUser.Identity && budget.OwnerPersonId != Person.NobodyId)) { throw new UnauthorizedAccessException(); } if (String.IsNullOrEmpty(reason.Trim())) { reason = Resources.Global.Global_NoReasonGiven; } payable.DenyApproval(authData.CurrentUser, reason); return(new AjaxCallResult { Success = true }); }
/// <summary> /// Creates a <see cref="RestClient"/> using a given <see cref="AuthenticationData"/> /// </summary> /// <param name="authenticationData">The data from which the instance will be created</param> public static RestClient CreateFrom(AuthenticationData authenticationData) { switch (authenticationData.Type) { case AuthenticationMethodProvider.AuthenticationType.SymmetricKey: { // Getting a specific module using REST with SAS token authentication string key = ConfigurationUtils.GetSymmetricKeyFromFile(authenticationData.FilePath); string sasToken = GenerateSaSToken(key, authenticationData.GatewayHostName, TimeSpan.FromMinutes(_sasTokenTtl)); var restClient = new RestClient(authenticationData.GatewayHostName, sasToken); return(restClient); } case AuthenticationMethodProvider.AuthenticationType.SelfSignedCertificate: { X509Certificate2 cert = CertificateLoader.Load(authenticationData.CertificateLocation.Value, authenticationData.FilePath); var restClient = new RestClient(authenticationData.GatewayHostName, cert); return(restClient); } default: throw new ArgumentOutOfRangeException(nameof(authenticationData.Type), authenticationData.Type, "Unsupported authentication type"); } }
public static void InitializeProcessing(string guid, string accountIdString) { // Start an async thread that does all the work, then return AuthenticationData authData = GetAuthenticationDataAndCulture(); int accountId = Int32.Parse(accountIdString); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (account.Organization.Identity != authData.CurrentOrganization.Identity || !authData.CurrentUser.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write))) { throw new UnauthorizedAccessException(); } Thread initThread = new Thread(ProcessUploadThread); ProcessThreadArguments args = new ProcessThreadArguments { Guid = guid, Organization = authData.CurrentOrganization, Account = account }; initThread.Start(args); }
static public AssignmentData GetAssignmentData(int assignmentId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); PositionAssignment assignment = PositionAssignment.FromIdentity(assignmentId); if (authData.Authority.CanAccess(assignment, AccessType.Read)) { return(new AssignmentData { Success = true, AssignedPersonCanonical = assignment.Person.Canonical, AssignedPersonId = assignment.PersonId, PositionAssignmentId = assignment.Identity, PositionId = assignment.PositionId, PositionLocalized = assignment.Position.Localized() }); } else { return(new AssignmentData { Success = false }); } }
public static UndoPayoutResult UndoPayout(int databaseId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); UndoPayoutResult result = new UndoPayoutResult(); Payout payout = Payout.FromIdentity(databaseId); if (!payout.Open) { // this payout has already been settled, or picked up for settling result.Success = false; result.DisplayMessage = String.Format(Resources.Pages.Financial.PayOutMoney_PayoutCannotUndo, databaseId); return(result); } payout.UndoPayout(); result.DisplayMessage = HttpUtility.UrlEncode(String.Format(Resources.Pages.Financial.PayOutMoney_PayoutUndone, databaseId)).Replace("+", "%20"); result.Success = true; return(result); }
public ActionResult Index(AuthenticationData data, string returnUrl) { if (ModelState.IsValid) { if (MyAuthService.SignIn(data.username, data.password, false)) { if (!String.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return(View(data)); }
public static InitialOrgData GetInitialData() { InitialOrgData result = new InitialOrgData(); AuthenticationData authData = GetAuthenticationDataAndCulture(); Organization org = authData.CurrentOrganization; if (org == null || authData.CurrentUser == null) { return(result); // just... don't } result.AccountBitcoinCold = (org.FinancialAccounts.AssetsBitcoinCold != null && org.FinancialAccounts.AssetsBitcoinCold.Active); result.AccountBitcoinHot = (org.FinancialAccounts.AssetsBitcoinHot != null && org.FinancialAccounts.AssetsBitcoinHot.Active); result.AccountPaypal = (org.FinancialAccounts.AssetsPaypal != null && org.FinancialAccounts.AssetsPaypal.Active); result.AccountsForex = (org.FinancialAccounts.IncomeCurrencyFluctuations != null && org.FinancialAccounts.IncomeCurrencyFluctuations.Active); result.AccountsVat = (org.FinancialAccounts.AssetsVatInbound != null && org.FinancialAccounts.AssetsVatInbound.Active); result.VatReportFrequency = org.VatReportFrequencyMonths; result.ParticipantFinancials = org.ParticipantFinancialsEnabled; result.PaypalAccountAddress = org.PaypalAccountMailAddress; result.GovernmentRegistrationId = org.GovernmentRegistrationId; result.TaxAuthority = org.TaxAuthority; result.TaxPaymentOcr = org.TaxPaymentOcr; result.OpenLedgersDomain = org.OpenLedgersDomain; result.VanityDomain = org.VanityDomain; // TODO: Add all the other fields return(result); }
public static int[] GetUninitializedBudgets() { AuthenticationData authData = GetAuthenticationDataAndCulture(); // This function finds the exceptional accounts that aren't initialized, to let a sysadmin approve expenses to them. List <int> result = new List <int>(); FinancialAccounts accounts = FinancialAccounts.ForOrganization(authData.CurrentOrganization); foreach (FinancialAccount account in accounts) { if (account.AccountType == FinancialAccountType.Cost) { if (account.OwnerPersonId == 0 && authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Administration))) { result.Add(account.Identity); } } } return(result.ToArray()); }
public BaseRequest(string userName, string password) { User = new AuthenticationData(userName, password); }
public static AjaxInputCallResult SwitchToggled(string cookie, bool newValue) { AuthenticationData authData = GetAuthenticationDataAndCulture(); if (authData.CurrentOrganization == null || authData.CurrentUser == null) { return(null); // just don't... don't anything, actually } AjaxInputCallResult result = new AjaxInputCallResult(); result.Success = true; result.NewValue = newValue? "true": "false"; bool bitcoinNative = (authData.CurrentOrganization.Currency.Code == "BTC"); FinancialAccounts workAccounts = new FinancialAccounts(); switch (cookie) { case "BitcoinCold": FinancialAccount coldAccount = authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinCold; if (coldAccount == null) { coldAccount = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_BitcoinCold", FinancialAccountType.Asset, null); FinancialAccount.Create(authData.CurrentOrganization, "Cold Address 1", FinancialAccountType.Asset, coldAccount); FinancialAccount.Create(authData.CurrentOrganization, "Cold Address 2 (rename these)", FinancialAccountType.Asset, coldAccount); FinancialAccount.Create(authData.CurrentOrganization, "Cold Address... etc", FinancialAccountType.Asset, coldAccount); authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinCold = coldAccount; result.DisplayMessage = "Bitcoin cold accounts were created. Edit names and addresses in Connected Accounts."; // LOC } else { workAccounts.Add(coldAccount); } break; case "BitcoinHot": FinancialAccount hotAccount = authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot; if (hotAccount == null) { authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_BitcoinHot", FinancialAccountType.Asset, null); result.DisplayMessage = "Bitcoin HD hotwallet was created along with an account for the hotwallet."; } else { workAccounts.Add(hotAccount); } break; case "Forex": FinancialAccount forexGain = authData.CurrentOrganization.FinancialAccounts.IncomeCurrencyFluctuations; FinancialAccount forexLoss = authData.CurrentOrganization.FinancialAccounts.CostsCurrencyFluctuations; if (forexGain == null) { if (forexLoss != null) { throw new InvalidOperationException(); } authData.CurrentOrganization.FinancialAccounts.IncomeCurrencyFluctuations = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Income_ForexGains", FinancialAccountType.Income, null); authData.CurrentOrganization.FinancialAccounts.CostsCurrencyFluctuations = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Cost_ForexLosses", FinancialAccountType.Cost, null); result.DisplayMessage = "Forex gain/loss accounts were created and will be used to account for currency fluctuations."; } else { if (forexLoss == null) { throw new InvalidOperationException(); } if (!bitcoinNative && newValue == false && ((authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinCold != null && authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinCold.Active) || (authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot != null && authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.Active))) { // bitcoin is active, and we're not bitcoin native, so we're not turning off forex result.Success = false; result.NewValue = "true"; result.DisplayMessage = "Cannot disable forex: bitcoin accounts are active in a non-bitcoin-native organization."; } else { workAccounts.Add(forexGain); workAccounts.Add(forexLoss); } } break; case "Vat": FinancialAccount vatInbound = authData.CurrentOrganization.FinancialAccounts.AssetsVatInbound; FinancialAccount vatOutbound = authData.CurrentOrganization.FinancialAccounts.DebtsVatOutbound; if (vatInbound == null) { if (vatOutbound != null) { throw new InvalidOperationException(); } authData.CurrentOrganization.FinancialAccounts.AssetsVatInbound = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_InboundVat", FinancialAccountType.Asset, null); authData.CurrentOrganization.FinancialAccounts.DebtsVatOutbound = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Debt_OutboundVat", FinancialAccountType.Debt, null); result.DisplayMessage = "Inbound and outbound VAT accounts were created."; } else { if (vatOutbound == null) { throw new InvalidOperationException(); } // If the VAT Inbound/Outbound already exist, but subaccounts don't: if (authData.CurrentOrganization.FinancialAccounts.AssetsVatInboundUnreported == null) { // create unreported/reported VAT inbound/outbound - four accounts total authData.CurrentOrganization.FinancialAccounts.AssetsVatInboundUnreported = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_InboundVatUnreported", FinancialAccountType.Asset, authData.CurrentOrganization.FinancialAccounts.AssetsVatInbound); authData.CurrentOrganization.FinancialAccounts.DebtsVatOutboundUnreported = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Debt_OutboundVatUnreported", FinancialAccountType.Debt, authData.CurrentOrganization.FinancialAccounts.DebtsVatOutbound); authData.CurrentOrganization.FinancialAccounts.AssetsVatInboundReported = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_InboundVatReported", FinancialAccountType.Asset, authData.CurrentOrganization.FinancialAccounts.AssetsVatInbound); authData.CurrentOrganization.FinancialAccounts.DebtsVatOutboundReported = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Debt_OutboundVatReported", FinancialAccountType.Debt, authData.CurrentOrganization.FinancialAccounts.DebtsVatOutbound); } else // the accounts exist, need to be re-enabled or disabled, as per the switch direction { workAccounts.Add(authData.CurrentOrganization.FinancialAccounts.AssetsVatInboundReported); workAccounts.Add(authData.CurrentOrganization.FinancialAccounts.AssetsVatInboundUnreported); workAccounts.Add(authData.CurrentOrganization.FinancialAccounts.DebtsVatOutboundReported); workAccounts.Add(authData.CurrentOrganization.FinancialAccounts.DebtsVatOutboundUnreported); } workAccounts.Add(vatInbound); workAccounts.Add(vatOutbound); } break; case "Paypal": FinancialAccount assetsPaypal = authData.CurrentOrganization.FinancialAccounts.AssetsPaypal; if (assetsPaypal == null) { authData.CurrentOrganization.FinancialAccounts.AssetsPaypal = FinancialAccount.Create(authData.CurrentOrganization, "[LOC]Asset_Paypal", FinancialAccountType.Asset, null); result.DisplayMessage = "An account was created for Paypal account tracking."; } else { workAccounts.Add(assetsPaypal); } break; case "ParticipantFinancials": authData.CurrentOrganization.ParticipantFinancialsEnabled = newValue; break; case "AskPartipantStreet": authData.CurrentOrganization.Parameters.AskParticipantStreet = newValue; break; default: throw new NotImplementedException(); } if (workAccounts.Count > 0 && String.IsNullOrEmpty(result.DisplayMessage)) { if (newValue) // switch has been turned on { // accounts can always be re-enabled. This is not a create, it is a re-enable. foreach (FinancialAccount account in workAccounts) { account.Active = true; } if (workAccounts.Count > 1) { result.DisplayMessage = "The accounts were re-enabled."; } else { result.DisplayMessage = "The account was re-enabled."; } } else // switch is being set to off position { // if the accounts are currently enabled, we must first check there aren't // any transactions in them before disabling bool transactionsOnAccount = false; foreach (FinancialAccount account in workAccounts) { if (account.GetLastRows(5).Count > 0) { transactionsOnAccount = true; } } if (transactionsOnAccount) { if (workAccounts.Count > 1) { result.DisplayMessage = "Can't disable these accounts: there are transactions"; } else { result.DisplayMessage = "Can't disable this account: there are transactions"; } result.Success = false; result.NewValue = "true"; } else { // Disable accounts foreach (FinancialAccount account in workAccounts) { account.Active = false; } if (workAccounts.Count > 1) { result.DisplayMessage = "The accounts were disabled."; } else { result.DisplayMessage = "The account was disabled."; } } } } return(result); }
private async void MainButton_Clicked(object sender, EventArgs e) { if (!CrossConnectivity.Current.IsConnected) { await Service.ErrorDisplay(Translate.TrMainPageEnterClubID, this); } else if (string.IsNullOrWhiteSpace(EntryClubID.Text)) { await Service.ErrorDisplay(Translate.TrMainPageEnterClubID, this); } else if (string.IsNullOrWhiteSpace(EntryCardNumber.Text)) { await Service.ErrorDisplay($"{Translate.TrMainPageEnterCardNumber}", this); } else if (!Service.IsCorrectCardNumber(EntryCardNumber.Text.Trim())) { await Service.ErrorDisplay($"{Translate.TrMainPageEnterCardValid}", this); } else if (string.IsNullOrWhiteSpace(EntryPass.Text)) { await Service.ErrorDisplay($"{Translate.TrMainPageEnterPassword}", this); } else if (!Service.IsConnectedToInternet(Settings.IpAddress)) { await Service.ErrorDisplay($"{Translate.TrMainPageErrorServer}", this); } else { CardInfo card = Service.SplitCardNumber(EntryCardNumber.Text.Trim()); AuthenticationData authorisationData = new AuthenticationData(EntryClubID.Text.ToLower().Trim(), card, EntryPass.Text); Package <ModelPlayerBalances> jsonOutput = null; this.ActivitySpinner.IsVisible = true; try { // Get the PlayerBalances info jsonOutput = await App.RestService.PostResponse <Package <ModelPlayerBalances> >(authorisationData, Settings.LogInSystem); if (jsonOutput == null) { Service.WriteToLog($"ModelPlayerBalances jsonOutput == null on MainPage page.", page: this); this.ActivitySpinner.IsVisible = false; return; } } catch (Exception exc) { Service.WriteToLog($"Failed to get ModelPlayerBalances data on MainPage page.", exc, this); this.ActivitySpinner.IsVisible = false; return; } if (jsonOutput.Status == Statuses.Succeed) { // Get the ClubName by ID Package <ModelClub> jsonOutputClub = null; try { jsonOutputClub = await App.RestService.GetResponse <Package <ModelClub> >(Settings.AboutClubInfo, authorisationData.ClubID); } catch (Exception exc) { Service.WriteToLog($"Failed to get ModelClub data on MainPage page.", exc); } // If it was not possible to get the name of the club, then we get its ID string clubName; if (jsonOutputClub != null) { clubName = jsonOutput.Status == Statuses.Succeed ? jsonOutputClub.Data.ClubName : authorisationData.ClubID; } else { clubName = authorisationData.ClubID; } try { BaseMDPage masterDetailPage = new BaseMDPage(jsonOutput.Data.PBIData, authorisationData, clubName); Application.Current.MainPage = masterDetailPage; } catch (Exception exc) { Service.WriteToLog($"Could not create BaseMDPage page.", exc, this); } this.ActivitySpinner.IsVisible = false; } else { try { if (jsonOutput.Data.ErrorData.TypeError == TypeError.User) { await Service.ErrorDisplay(CardInfo.CodesError[(int)jsonOutput.Data.ErrorData.Code], this); } else { Debug.WriteLine($"Type Error {jsonOutput.Data.ErrorData.TypeError}, Description {jsonOutput.Data.ErrorData.Description}, Code Error {jsonOutput.Data.ErrorData.Code}"); } this.ActivitySpinner.IsVisible = false; } catch (Exception exc) { Service.WriteToLog($"Don't get Error message on MainPage page.", exc, this); this.ActivitySpinner.IsVisible = false; } } } }
// POST api/registration public HttpResponseMessage Post(AuthenticationData value) { // checking whether new user already exist on database or not var subquery = from u in container.UserProfiles join p in container.webpages_Membership on u.UserId equals p.UserId where u.UserName == value.Email select u.UserId; var checkUser = (from t1 in container.STEPPY_API_m_user where subquery.Contains(t1.id_user_shesop) select t1).ToList(); if (checkUser.Count != 0) { return(Request.CreateResponse <string>(HttpStatusCode.Forbidden, "User already exist!")); } //create new user and then save to database shesop UserProfile newUserProfile = new UserProfile() { UserName = value.Email, NoTelp = value.TelpNumber, Umur = value.Age, BeratBadan = value.Weight, Tinggi = value.Height, JenisKelamin = value.Gender }; container.UserProfiles.Add(newUserProfile); container.SaveChanges(); webpages_Membership newUserWebpages = new webpages_Membership() { UserId = newUserProfile.UserId, IsConfirmed = true, Password = HashingPassword(value.Password), PasswordFailuresSinceLastSuccess = 0, PasswordSalt = "", PasswordVerificationToken = "", CreateDate = DateTime.Now, PasswordChangedDate = DateTime.Now, }; container.webpages_Membership.Add(newUserWebpages); container.SaveChanges(); webpages_UsersInRoles newUserRole = new webpages_UsersInRoles() { UserId = newUserProfile.UserId, RoleId = 3, }; container.webpages_UsersInRoles.Add(newUserRole); container.SaveChanges(); DCHANNEL_User_Patient profile = new DCHANNEL_User_Patient() { Patient_Name = newUserProfile.UserName, User_Id = newUserProfile.UserId, Email = newUserProfile.UserName, Join_date = DateTime.Now, generated_guid = Guid.NewGuid().ToString() }; container.DCHANNEL_User_Patient.Add(profile); container.SaveChanges(); //end of create new user and then save to database shesop // register to table user steppy STEPPY_API_m_user newUser = new STEPPY_API_m_user() { display_name = value.DisplayName, password = newUserWebpages.Password, telp_number = value.TelpNumber, join_date = DateTime.Now, last_login = DateTime.Now, id_user_shesop = newUserWebpages.UserId //id_country = countryData.id_country }; container.STEPPY_API_m_user.Add(newUser); container.SaveChanges(); //create new token data STEPPY_API_t_security_token tokenData = container.STEPPY_API_t_security_token.Create(); tokenData.id_user = newUser.id_user; tokenData.request_date = DateTime.Now; tokenData.expired_date = DateTime.Now.AddMonths(2); tokenData.is_logout = false; tokenData.security_token = Guid.NewGuid().ToString(); container.STEPPY_API_t_security_token.Add(tokenData); container.SaveChanges(); // create user profile STEPPY_API_t_user_profile newProfile = container.STEPPY_API_t_user_profile.Create(); newProfile.id_user = newUser.id_user; newProfile.hi_score = 0; newProfile.current_level = 1; newProfile.current_experience = 0; newProfile.next_level_experience = 100; newProfile.gold = 0; newProfile.diamond = 0; newProfile.current_score = 0; container.STEPPY_API_t_user_profile.Add(newProfile); container.SaveChanges(); // get all friends data var friends = container.STEPPY_API_v_user_friend.Where <STEPPY_API_v_user_friend>(friend => friend.id_user == tokenData.id_user).ToList(); var frienddto = (from fr in friends join pf in container.STEPPY_API_t_user_profile on fr.id_user equals pf.id_user select new FriendDataDTO { IdUser = fr.id_user, FriendIdUser = fr.friend_id_user, DisplayName = fr.display_name, HiScore = pf.hi_score, Level = pf.current_level, TelpNumber = fr.telp_number, FriendDetailUrl = Url.Link("TransactApi", new { controller = "friend", token = tokenData.security_token, id = fr.id_contact }), IdContact = fr.id_contact }).ToList(); //create user data to be transferred to cient UserDataDTO userdto = new UserDataDTO() { IdUser = newUser.id_user, IdUserShesop = newUser.id_user_shesop, Email = newUserProfile.UserName, DisplayName = newUser.display_name, TelpNumber = newUser.telp_number, Gender = newUserProfile.JenisKelamin, Age = newUserProfile.Umur, Weight = newUserProfile.BeratBadan, Height = newUserProfile.Tinggi, JoinDate = newUser.join_date, Token = tokenData.security_token, /*UserContacts = container.STEPPY_API_m_contact * .Select(c => new UserContactDTO() * { * IdContact = c.id_contact, * TelpNumber = c.telp_number * }).ToList(),*/ FriendProfiles = frienddto, Profile = new ProfileDTO() { IdUser = newProfile.id_user, IdProfile = newProfile.id_profile, DisplayName = newUser.display_name, HiScore = newProfile.hi_score, CurrentLevel = newProfile.current_level, CurrentExperience = newProfile.current_experience, NextLevelExperience = newProfile.next_level_experience, Gold = newProfile.gold, CurrentScore = newProfile.current_score, Diamond = newProfile.diamond }, FriendsUrl = Url.Link("TransactApi", new { controller = "friend", token = tokenData.security_token }), ProfileUrl = Url.Link("TransactApi", new { controller = "profile", token = tokenData.security_token }), }; /* * //update registration status of this new user in contact info * SqlParameter[] sqlParams = new SqlParameter[2]; * sqlParams[0] = new SqlParameter("@telp_number", newUser.telp_number); * sqlParams[1] = new SqlParameter("@countrycode", countryData.country_phone_prefix); * int effected = container.Database.ExecuteSqlCommand("UPDATE STEPPY_API_m_contact SET is_registered = 1 WHERE telp_number = '0' + @telp_number OR telp_number = @countrycode + @telp_number", * sqlParams);*/ var response = Request.CreateResponse <UserDataDTO>(HttpStatusCode.Created, userdto); return(response); }
private static AjaxCallResult HandleAttestationDeattestation(string identifier, AttestationMode mode) { AuthenticationData authData = GetAuthenticationDataAndCulture(); IApprovable approvableItem; string attestedTemplate; string deattestedTemplate; char costType = identifier[0]; int itemId = Int32.Parse(identifier.Substring(1)); Int64 amountCents; string beneficiary; string result; // Find the item we are attesting or deattesting switch (costType) { case 'A': // Case advance CashAdvance advance = CashAdvance.FromIdentity(itemId); if (advance.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if (advance.Budget.OwnerPersonId != authData.CurrentUser.Identity && advance.Budget.OwnerPersonId != Person.NobodyId) { throw new SecurityException("Called without attestation privileges"); } approvableItem = advance; attestedTemplate = Resources.Pages.Financial.AttestCosts_AdvanceAttested; deattestedTemplate = Resources.Pages.Financial.AttestCosts_AdvanceDeattested; beneficiary = advance.Person.Name; amountCents = advance.AmountCents; break; case 'E': // Expense claim ExpenseClaim expense = ExpenseClaim.FromIdentity(itemId); if (expense.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if (expense.Budget.OwnerPersonId != authData.CurrentUser.Identity && expense.Budget.OwnerPersonId != Person.NobodyId) { throw new SecurityException("Called without attestation privileges"); } approvableItem = expense; attestedTemplate = Resources.Pages.Financial.AttestCosts_ExpenseAttested; deattestedTemplate = Resources.Pages.Financial.AttestCosts_ExpenseDeattested; beneficiary = expense.Claimer.Name; amountCents = expense.AmountCents; break; case 'I': // Inbound invoice InboundInvoice invoice = InboundInvoice.FromIdentity(itemId); if (invoice.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if (invoice.Budget.OwnerPersonId != authData.CurrentUser.Identity && invoice.Budget.OwnerPersonId != Person.NobodyId) { throw new SecurityException("Called without attestation privileges"); } approvableItem = invoice; attestedTemplate = Resources.Pages.Financial.AttestCosts_InvoiceAttested; deattestedTemplate = Resources.Pages.Financial.AttestCosts_InvoiceDeattested; beneficiary = invoice.Supplier; amountCents = invoice.AmountCents; break; case 'S': // Salary payout Salary salary = Salary.FromIdentity(itemId); if (salary.PayrollItem.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if (salary.PayrollItem.Budget.OwnerPersonId != authData.CurrentUser.Identity && salary.PayrollItem.Budget.OwnerPersonId != Person.NobodyId) { throw new SecurityException("Called without attestation privileges"); } approvableItem = salary; attestedTemplate = Resources.Pages.Financial.AttestCosts_SalaryAttested; deattestedTemplate = Resources.Pages.Financial.AttestCosts_SalaryDeattested; beneficiary = salary.PayrollItem.PersonCanonical; amountCents = salary.GrossSalaryCents + salary.AdditiveTaxCents; break; case 'P': // Parley, aka Conference Parley parley = Parley.FromIdentity(itemId); if (parley.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if (parley.Budget.OwnerPersonId != authData.CurrentUser.Identity && parley.Budget.OwnerPersonId != Person.NobodyId) { throw new SecurityException("Called without attestation privileges"); } approvableItem = parley; attestedTemplate = Resources.Pages.Financial.AttestCosts_ParleyAttested; deattestedTemplate = Resources.Pages.Financial.AttestCosts_ParleyDeattested; beneficiary = parley.Person.Name; amountCents = parley.BudgetCents; break; default: throw new InvalidOperationException("Unknown Cost Type in HandleAttestationDeattestation: \"" + identifier + "\""); } // Finally, attest or deattest if (mode == AttestationMode.Attestation) { Int64 budgetRemaining = approvableItem.Budget.GetBudgetCentsRemaining(); result = string.Empty; if (amountCents > -budgetRemaining) { if ( authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Administration))) { // Admin rights, so allow (forced) overdraft // Unless budget was nonzero and allocated, set protest message if (approvableItem.Budget.Owner != null || approvableItem.Budget.GetBudgetCents() != 0) { result = Resources.Pages.Financial.AttestCosts_Overdrafted + " "; } } else { // Do not allow overdraft return(new AjaxCallResult { DisplayMessage = Resources.Pages.Financial.AttestCosts_OutOfBudget, Success = false }); } } approvableItem.Approve(authData.CurrentUser); result += string.Format(attestedTemplate, itemId, beneficiary, authData.CurrentOrganization.Currency.Code, amountCents / 100.0); } else if (mode == AttestationMode.Deattestation) { approvableItem.RetractApproval(authData.CurrentUser); result = string.Format(deattestedTemplate, itemId, beneficiary, authData.CurrentOrganization.Currency.Code, amountCents / 100.0); } else { throw new InvalidOperationException("Unknown Approval Mode: " + mode); } FinancialAccount.ClearApprovalAdjustmentsCache(authData.CurrentOrganization); return(new AjaxCallResult { DisplayMessage = result, Success = true }); }
public static void TestFoo(string input) { AuthenticationData authenticationData = GetAuthenticationDataAndCulture(); System.Diagnostics.Trace.WriteLine(input); }
public bool IsAuthorized(AuthenticationData data) { return data == null ? false : Authorized.ContainsKey(data.Id); }
protected void Page_Load(object sender, EventArgs e) { // Get auth data this._authenticationData = GetAuthenticationDataAndCulture(); string reportIdParameter = Request.QueryString["ReportId"]; string reportKeyParameter = Request.QueryString["ReportKey"]; if (!string.IsNullOrEmpty(reportIdParameter)) { this._reportId = Int32.Parse(reportIdParameter); // will throw if non-numeric - don't matter for app } else if (!string.IsNullOrEmpty(reportKeyParameter)) { this._reportId = SwarmDb.GetDatabaseForReading().GetVatReportIdFromGuid(reportKeyParameter.ToLowerInvariant().Trim()); } else { throw new ArgumentException("No Report Requested"); } VatReport report = VatReport.FromIdentity(_reportId); // TODO: AUTH CHECK Response.ContentType = "application/json"; Int64 turnoverCentsTotal = 0; Int64 inboundCentsTotal = 0; Int64 outboundCentsTotal = 0; StringBuilder response = new StringBuilder(16384); VatReportItems items = report.Items; items.Sort(VatItemSorterByDate); List <string> lines = new List <string>(); string hasDoxString = "<img data-txid='{0}' class='LocalViewDox action-icon' />" + "<img data-docid='{1}' data-docname=\\\"{2}\\\" class='LocalDownloadDox action-icon' />"; foreach (VatReportItem item in items) { FinancialTransaction transaction = item.Transaction; bool include = false; string element = string.Format("\"id\":\"{0}\",\"txid\":\"{1}\",\"datetime\":\"{2:MMM dd}\",\"description\":\"{3}\"", transaction.Identity, transaction.OrganizationSequenceId, transaction.DateTime, JsonSanitize(transaction.Description)); if (item.TurnoverCents != 0) { element += String.Format(",\"turnover\":\"{0:N2}\"", item.TurnoverCents / 100.0); turnoverCentsTotal += item.TurnoverCents; include = true; } if (item.VatInboundCents != 0) { element += String.Format(",\"inbound\":\"{0:N2}\"", item.VatInboundCents / 100.0); inboundCentsTotal += item.VatInboundCents; include = true; } if (item.VatOutboundCents != 0) { element += String.Format(",\"outbound\":\"{0:N2}\"", item.VatOutboundCents / 100.0); outboundCentsTotal += item.VatOutboundCents; include = true; } Documents documents = Documents.ForObject(transaction.Dependency ?? transaction); if (documents.Count > 0) { element += String.Format(",\"dox\":\"" + hasDoxString + "\"", transaction.Identity, documents[0].Identity, CurrentOrganization.Name + " - " + report.Description + " - " + Resources.Global.Financial_TransactionIdShort + transaction.OrganizationSequenceId.ToString("N0")); } if (include) { lines.Add("{" + element + "}"); } } if (lines.Count == 0) // add empty report line { lines.Add("{" + String.Format("\"id\":\"0\",\"description\":\"{0}\"", JsonSanitize(Resources.Pages.Ledgers.ViewVatReports_EmptyReport)) + "}"); } Response.Write("{\"rows\":[" + String.Join(",", lines.ToArray()) + "]"); Response.Write(",\"footer\":[{"); // needs to be on separate line to not trigger a String.Format warning Response.Write(String.Format("\"id\":\"0\",\"description\":\"{0}\",\"turnover\":\"{1:N2}\",\"inbound\":\"{2:N2}\",\"outbound\":\"{3:N2}\"", JsonSanitize(Resources.Pages.Ledgers.ViewVatReports_Footer_Total.ToUpperInvariant()), turnoverCentsTotal / 100.0, inboundCentsTotal / 100.0, outboundCentsTotal / 100.0)); Response.Write("}]}"); // needs to be separate to not trigger String.Format warning Response.End(); }
public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); string[] fields = new List<string>(data.Data.Keys).ToArray(); StringBuilder updateBuilder = new StringBuilder(); using (SqlConnection conn = new SqlConnection(m_ConnectionString)) using (SqlCommand cmd = new SqlCommand()) { updateBuilder.AppendFormat("update '{0}' set ", m_Realm); bool first = true; foreach (string field in fields) { if (!first) updateBuilder.Append(", "); updateBuilder.AppendFormat("'{0}' = @{0}",field); first = false; cmd.Parameters.AddWithValue("@" + field, data.Data[field]); } updateBuilder.Append(" where UUID = @principalID"); cmd.CommandText = updateBuilder.ToString(); cmd.Connection = conn; cmd.Parameters.AddWithValue("@principalID", data.PrincipalID.ToString()); conn.Open(); if (cmd.ExecuteNonQuery() < 1) { StringBuilder insertBuilder = new StringBuilder(); insertBuilder.AppendFormat("insert into '{0}' ('UUID', '", m_Realm); insertBuilder.Append(String.Join("', '", fields)); insertBuilder.Append("') values ( @principalID, @"); insertBuilder.Append(String.Join(", @", fields)); insertBuilder.Append(")"); cmd.CommandText = insertBuilder.ToString(); if (cmd.ExecuteNonQuery() < 1) { return false; } } } return true; }
public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] values = new string[data.Data.Count]; int i = 0; foreach (object o in data.Data.Values) values[i++] = o.ToString(); SqliteCommand cmd = new SqliteCommand(); if (Get(data.PrincipalID) != null) { string update = "update `" + m_Realm + "` set "; bool first = true; foreach (string field in fields) { if (!first) update += ", "; update += "`" + field + "` = :" + field; cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); first = false; } update += " where UUID = :UUID"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); cmd.CommandText = update; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { //CloseCommand(cmd); return false; } } catch (Exception e) { m_log.Error("[SQLITE]: Exception storing authentication data", e); //CloseCommand(cmd); return false; } } else { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); foreach (string field in fields) cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); cmd.CommandText = insert; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { //CloseCommand(cmd); return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); //CloseCommand(cmd); return false; } } //CloseCommand(cmd); return true; }
public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); if (data.Data.ContainsKey("uuid")) data.Data.Remove("uuid"); /* Dictionary<string, object> oAuth = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> oDado in data.Data) { if (oDado.Key != oDado.Key.ToLower()) { oAuth.Add(oDado.Key.ToLower(), oDado.Value); } } foreach (KeyValuePair<string, object> oDado in data.Data) { if (!oAuth.ContainsKey(oDado.Key.ToLower())) { oAuth.Add(oDado.Key.ToLower(), oDado.Value); } } */ string[] fields = new List<string>(data.Data.Keys).ToArray(); StringBuilder updateBuilder = new StringBuilder(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { updateBuilder.AppendFormat("update {0} set ", m_Realm); bool first = true; foreach (string field in fields) { if (!first) updateBuilder.Append(", "); updateBuilder.AppendFormat("\"{0}\" = :{0}",field); first = false; cmd.Parameters.Add(m_database.CreateParameter("" + field, data.Data[field])); } updateBuilder.Append(" where uuid = :principalID"); cmd.CommandText = updateBuilder.ToString(); cmd.Connection = conn; cmd.Parameters.Add(m_database.CreateParameter("principalID", data.PrincipalID)); conn.Open(); if (cmd.ExecuteNonQuery() < 1) { StringBuilder insertBuilder = new StringBuilder(); insertBuilder.AppendFormat("insert into {0} (uuid, \"", m_Realm); insertBuilder.Append(String.Join("\", \"", fields)); insertBuilder.Append("\") values (:principalID, :"); insertBuilder.Append(String.Join(", :", fields)); insertBuilder.Append(")"); cmd.CommandText = insertBuilder.ToString(); if (cmd.ExecuteNonQuery() < 1) { return false; } } } return true; }
protected static AuthenticationData GetAuthenticationDataAndCulture() { // This function is called from static page methods in AJAX calls to get // the current set of authentication data. Static page methods cannot access // the instance data of PageV5Base. AuthenticationData result = new AuthenticationData(); // Find various credentials string identity = HttpContext.Current.User.Identity.Name; string[] identityTokens = identity.Split(','); string userIdentityString = identityTokens[0]; string organizationIdentityString = identityTokens[1]; int currentUserId = Convert.ToInt32(userIdentityString); int currentOrganizationId = Convert.ToInt32(organizationIdentityString); result.CurrentUser = Person.FromIdentity(currentUserId); result.CurrentOrganization = Organization.FromIdentity(currentOrganizationId); string userCultureString = result.CurrentUser.PreferredCulture; if (!string.IsNullOrEmpty(userCultureString)) { CultureInfo userCulture = new CultureInfo(userCultureString); // may throw on invalid database data Thread.CurrentThread.CurrentCulture = userCulture; Thread.CurrentThread.CurrentUICulture = userCulture; } return result; }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { DateTime now = DateTime.UtcNow; string timestamp = now.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture); AuthenticationData authData = new AuthenticationData { Username = ClientAuthenticationHeaderContext.HeaderInformation.Username, Password = ClientAuthenticationHeaderContext.HeaderInformation.Password, Timespan = timestamp // This is the seed.. }; string serializedAuthData = Serializer.JsonSerializer<AuthenticationData>(authData); string signature = string.Empty; signature = Encryption.Encrypt(serializedAuthData, true); var encryptedHeader = new AuthenticationHeader { EncryptedSignature = signature }; var typedHeader = new MessageHeader<AuthenticationHeader>(encryptedHeader); var untypedHeader = typedHeader.GetUntypedHeader("authentication-header", "chsakell.com"); request.Headers.Add(untypedHeader); return null; }
static public AjaxInputCallResult StoreCallback(string newValue, string cookie) { AjaxInputCallResult result = new AjaxInputCallResult(); AuthenticationData authenticationData = GetAuthenticationDataAndCulture(); if (!authenticationData.Authority.HasAccess(new Access(authenticationData.CurrentOrganization, AccessAspect.Administration, AccessType.Write))) { result.Success = false; // this is the default on initialization, but let's be explicit about it result.FailReason = AjaxInputCallResult.ErrorAccessDenied; return(result); } switch (cookie) { case "VanityDomain": result.Success = true; result.NewValue = newValue.Trim(); authenticationData.CurrentOrganization.VanityDomain = result.NewValue; break; case "OpenLedgersDomain": result.Success = true; result.NewValue = newValue.Trim(); authenticationData.CurrentOrganization.OpenLedgersDomain = result.NewValue; break; case "PaypalAccountAddress": result.Success = true; result.NewValue = newValue.Trim(); authenticationData.CurrentOrganization.PaypalAccountMailAddress = result.NewValue; break; case "GovernmentRegistrationId": result.Success = true; result.NewValue = newValue.Trim(); authenticationData.CurrentOrganization.GovernmentRegistrationId = result.NewValue; break; case "TaxPaymentOcr": result.Success = true; result.NewValue = newValue.Trim(); authenticationData.CurrentOrganization.TaxPaymentOcr = result.NewValue; break; case "VatReportFrequency": result.Success = true; result.NewValue = newValue; authenticationData.CurrentOrganization.VatReportFrequencyMonths = Int32.Parse(newValue); break; case "ParticipationEntry": result.Success = true; result.NewValue = newValue; authenticationData.CurrentOrganization.Parameters.ParticipationEntry = newValue; break; case "ParticipationDuration": result.Success = true; result.NewValue = newValue; authenticationData.CurrentOrganization.Parameters.ParticipationDuration = newValue; break; case "SidebarOrgInfo": result.Success = true; authenticationData.CurrentOrganization.Parameters.SidebarOrgInfo = newValue; break; case "SignupFirstPage": result.Success = true; authenticationData.CurrentOrganization.Parameters.SignupFirstPage = newValue; break; case "SignupLastPage": result.Success = true; authenticationData.CurrentOrganization.Parameters.SignupLastPage = newValue; break; case "ApplicationCompleteMail": result.Success = true; authenticationData.CurrentOrganization.Parameters.ApplicationCompleteMail = newValue; break; case "ParticipationAcceptedMail": result.Success = true; authenticationData.CurrentOrganization.Parameters.ParticipationAcceptedMail = newValue; break; case "ApplicationQualifyingScore": int qualifyingScore = Int32.Parse(newValue, NumberStyles.Number); authenticationData.CurrentOrganization.Parameters.ApplicationQualifyingScore = qualifyingScore; result.NewValue = qualifyingScore.ToString("N0"); result.Success = true; // this comes last in this section, because parsing int may fail break; default: throw new NotImplementedException("Unknown cookie in StoreCallback"); } return(result); }
public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); string[] fields = new List<string>(data.Data.Keys).ToArray(); using (MySqlCommand cmd = new MySqlCommand()) { string update = "update `"+m_Realm+"` set "; bool first = true; foreach (string field in fields) { if (!first) update += ", "; update += "`" + field + "` = ?"+field; first = false; cmd.Parameters.AddWithValue("?"+field, data.Data[field]); } update += " where UUID = ?principalID"; cmd.CommandText = update; cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString()); if (ExecuteNonQuery(cmd) < 1) { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + "`) values (?principalID, ?" + String.Join(", ?", fields) + ")"; cmd.CommandText = insert; if (ExecuteNonQuery(cmd) < 1) return false; } } return true; }
public static ResyncResults ExecuteResync(string guid) { AuthenticationData authenticationData = GetAuthenticationDataAndCulture(); if ( !authenticationData.Authority.HasAccess(new Access(authenticationData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write))) { throw new UnauthorizedAccessException(); } ResyncResults results = new ResyncResults(); ExternalBankMismatchingDateTime[] mismatchArray = (ExternalBankMismatchingDateTime[]) HttpContext.Current.Session["LedgersResync" + guid + "MismatchArray"]; FinancialAccount account = (FinancialAccount)HttpContext.Current.Session["LedgersResync" + guid + "Account"]; long autoDepositDonationCents = 1000 * 100; FinancialAccount autoDonationAccount = account.Organization.FinancialAccounts.IncomeDonations; if (authenticationData.CurrentOrganization.Identity != account.OrganizationId) { throw new InvalidOperationException("Mismatching org"); } foreach (ExternalBankMismatchingDateTime mismatchDateTime in mismatchArray) { foreach ( ExternalBankMismatchingRecordDescription mismatchingRecord in mismatchDateTime.MismatchingRecords) { for (int index = 0; index < mismatchingRecord.MasterCents.Length; index++) { results.RecordsTotal++; long cents = mismatchingRecord.MasterCents[index]; bool unhandled = false; bool handlable = true; FinancialTransaction tx = mismatchingRecord.Transactions[index]; if (tx != null && tx.Dependency != null) { unhandled = true; IHasIdentity dependency = tx.Dependency; if (dependency is PaymentGroup && mismatchingRecord.ResyncActions[index] == ExternalBankMismatchResyncAction.RewriteSwarmops) { if (cents == (dependency as PaymentGroup).SumCents) { // Amount checks out with dependency; rewrite requested; this is handlable on auto Dictionary <int, long> newTx = new Dictionary <int, long>(); newTx[account.Identity] = cents; newTx[account.Organization.FinancialAccounts.AssetsOutboundInvoices.Identity] = -cents; tx.RecalculateTransaction(newTx, authenticationData.CurrentUser); unhandled = false; } } handlable = false; // need to fix this } if (handlable) { switch (mismatchingRecord.ResyncActions[index]) { case ExternalBankMismatchResyncAction.DeleteSwarmops: if (tx == null) { throw new InvalidOperationException( "Can't have Delete op on a null transaction"); } tx.Description = tx.Description + " (killed/zeroed in resync)"; tx.RecalculateTransaction(new Dictionary <int, long>(), authenticationData.CurrentUser); // zeroes out break; case ExternalBankMismatchResyncAction.RewriteSwarmops: if (tx == null) { throw new InvalidOperationException( "Can't have Rewrite op on a null transaction"); } Dictionary <int, long> newTx = new Dictionary <int, long>(); newTx[account.Identity] = cents; if (cents > 0 && cents < autoDepositDonationCents) { newTx[autoDonationAccount.Identity] = -cents; // negative; P&L account } tx.RecalculateTransaction(newTx, authenticationData.CurrentUser); break; case ExternalBankMismatchResyncAction.CreateSwarmops: if (tx != null) { throw new InvalidOperationException("Transaction seems to already exist"); } tx = FinancialTransaction.Create(account.OwnerPersonId, mismatchDateTime.DateTime, mismatchingRecord.Description); tx.AddRow(account, cents, authenticationData.CurrentUser); if (cents > 0 && cents < autoDepositDonationCents) { tx.AddRow(autoDonationAccount, -cents, authenticationData.CurrentUser); } break; case ExternalBankMismatchResyncAction.NoAction: // no action break; default: // not handled unhandled = true; break; } } if (unhandled) { results.RecordsFail++; } else { results.RecordsSuccess++; } } } } return(results); }
public bool Store(AuthenticationData data) { m_DataByUUID[data.PrincipalID] = data; return true; }
/// <inheritdoc /> public async Task SetAuthenticationData(CancellationToken ct, AuthenticationData authenticationData) { await Update(ct, s => s.WithAuthenticationData(authenticationData)); }
public ChiefProxy(AuthenticationData data) : base(data) { }
public static AjaxCallResult AttestCorrectedItem(string recordId, string amountString) { AuthenticationData authData = GetAuthenticationDataAndCulture(); Int64 amountCents = 0; try { amountCents = Formatting.ParseDoubleStringAsCents(amountString); } catch (Exception) { return(new AjaxCallResult { Success = false, DisplayMessage = String.Format(Resources.Global.Error_CurrencyParsing, 1000.00) }); } if (amountCents < 0) { return(new AjaxCallResult { Success = false, DisplayMessage = Resources.Pages.Financial.AttestCosts_CannotAttestNegative }); } if (amountCents == 0) { return(new AjaxCallResult { Success = false, DisplayMessage = Resources.Pages.Financial.AttestCosts_CannotAttestZero }); } IPayable payable = PayableFromRecordId(recordId); FinancialAccount budget = payable.Budget; if (budget.OrganizationId != authData.CurrentOrganization.Identity || budget.OwnerPersonId != authData.CurrentUser.Identity) { throw new UnauthorizedAccessException(); } Int64 centsRemaining = budget.GetBudgetCentsRemaining(); if (centsRemaining < amountCents) { // TODO: Handle the special case where the IPayable is not on current year, so against another (last) year's budget string notEnoughFunds; if (centsRemaining > 0) { notEnoughFunds = String.Format(Resources.Pages.Financial.AttestCosts_OutOfBudgetPrecise, authData.CurrentOrganization.Currency.DisplayCode, centsRemaining / 100.0, DateTime.UtcNow.Year); } else { notEnoughFunds = String.Format(Resources.Pages.Financial.AttestCosts_BudgetIsEmpty, DateTime.UtcNow.Year); } return(new AjaxCallResult { Success = false, DisplayMessage = notEnoughFunds }); } payable.SetAmountCents(amountCents, authData.CurrentUser); payable.Approve(authData.CurrentUser); return(new AjaxCallResult { Success = true }); }
/// <summary> /// Get the Atom entry for newly Email Campaign to be send to Constant server /// </summary> /// <param name="emailCampaign">EmailCampaign to be created</param> /// <param name="authenticationData">Account Owner EmailCampaign resource</param> /// <returns>Atom entry for creating specified EmailCampaign</returns> public static StringBuilder CreateNewEmailCampaign(EmailCampaign emailCampaign, AuthenticationData authenticationData) { return CreateAtomEntry(emailCampaign, authenticationData, null); }
public static StringBuilder ScheduleEmailXML(EmailCampaign emailCampaign, AuthenticationData authenticationData, string id) { //To schedule an email an hour out TimeZone localZone = TimeZone.CurrentTimeZone; System.DateTime now = localZone.ToUniversalTime(System.DateTime.Now); System.TimeSpan duration = new System.TimeSpan(0, 1, 0, 0); System.DateTime nowPlusAnHour = now.Add(duration); //System.DateTime nowPlusAnHour = System.DateTime.Now.Add(duration); StringBuilder data = new StringBuilder(); data.Append("<?xml version='1.0' encoding='UTF-8'?>"); data.AppendFormat("<entry xmlns=\"http://www.w3.org/2005/Atom\">"); data.AppendFormat("<link href=\"/ws/customers/{0}/campaigns/{1}/schedules/1\" rel=\"edit\" />", authenticationData.Username, emailCampaign.ID); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/campaigns/{1}/schedules/1</id>", authenticationData.Username, emailCampaign.ID); data.AppendFormat("<title type=\"text\">{0}</title>", emailCampaign.Name); data.AppendFormat("<updated>{0}</updated>", DateTime.Now.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' data.AppendFormat("<author><name>{0}</name></author>", "Constant Contact"); data.Append("<content type=\"application/vnd.ctct+xml\">"); data.AppendFormat("<Schedule xmlns=\"{0}\" id=\"http://api.constantcontact.com/ws/customers/{1}/campaigns/{2}/schedules/1\" >", ConstantNamespace, authenticationData.Username, emailCampaign.ID); data.AppendFormat("<ScheduledTime>{0}</ScheduledTime>", nowPlusAnHour.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' //data.AppendFormat("<ScheduledTime>2013-03-13T20:03:35.000Z</ScheduledTime>"); data.Append("</Schedule></content></entry>"); return data; }
/// <summary> /// Get the Atom entry for update Email Campaign to be send to Constant server /// </summary> /// <param name="emailCampaign">EmailCampaign to be updated</param> /// <param name="authenticationData">Account Owner EmailCampaign resource</param> /// <param name="id">Email Campaign Id for update</param> /// <returns>Atom entry for the specified EmailCampaign</returns> public static StringBuilder UpdateEmailCampaign(EmailCampaign emailCampaign, AuthenticationData authenticationData, string id) { return CreateAtomEntry(emailCampaign, authenticationData, id); }
private static string HandleValidationDevalidation(string identifier, ApprovalMode mode) { AuthenticationData authData = GetAuthenticationDataAndCulture(); IValidatable validatableItem = null; string validatedTemplate = string.Empty; string retractedTemplate = string.Empty; char costType = identifier[0]; int itemId = Int32.Parse(identifier.Substring(1)); Int64 amountCents; string beneficiary = string.Empty; string result = string.Empty; // A lot of this code was copied from attest/deattest, even though validation only concerns expense receipts switch (costType) { case 'E': // Expense claim ExpenseClaim expense = ExpenseClaim.FromIdentity(itemId); if (expense.OrganizationId != authData.CurrentOrganization.Identity) { throw new InvalidOperationException("Called to attest out-of-org line item"); } if ( !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Financials, AccessType.Write))) { throw new UnauthorizedAccessException(); } validatableItem = expense; validatedTemplate = Resources.Pages.Financial.ValidateReceipts_ReceiptsValidated; retractedTemplate = Resources.Pages.Financial.ValidateReceipts_ReceiptsDevalidated; amountCents = expense.AmountCents; break; default: throw new InvalidOperationException("Unknown Cost Type in HandleValidationDevalidation: \"" + identifier + "\""); } // Finally, attest or deattest if (mode == ApprovalMode.Approval) { validatableItem.Validate(authData.CurrentUser); result = string.Format(validatedTemplate, itemId, authData.CurrentOrganization.Currency.Code, amountCents / 100.0); } else if (mode == ApprovalMode.Retraction) { validatableItem.RetractValidation(authData.CurrentUser); result = string.Format(retractedTemplate, itemId, authData.CurrentOrganization.Currency.Code, amountCents / 100.0); } else { throw new InvalidOperationException("Unknown Approval Mode: " + mode); } return(result); }
/// <summary> /// Create an Atom entry used to create a new EmailCampaign /// </summary> /// <param name="emailCampaign">EmailCampaign to be created</param> /// <param name="authenticationData">Account Owner EmailCampaign resource</param> /// <param name="id">Account Owner EmailCampaign id - if its already created</param> /// <returns>Atom entry used to create new EmailCampaign /// </returns> private static StringBuilder CreateAtomEntry(EmailCampaign emailCampaign, AuthenticationData authenticationData, string id) { string atomId = string.IsNullOrEmpty(id) ? "0000000000000" : id; StringBuilder data = new StringBuilder(); data.Append("<?xml version='1.0' encoding='UTF-8'?>"); data.AppendFormat("<entry xmlns=\"{0}\">", AtomNamespace); if (atomId.Equals("0000000000000")) { data.AppendFormat("<link href=\"/ws/customers/{0}/{1}\" rel=\"{2}\" />", authenticationData.Username, authenticationData.CampaignsURI, EmailCampaignXmlAttributeValueEdit); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/{1}</id>", authenticationData.Username, authenticationData.CampaignsURI); } else { data.AppendFormat("<link href=\"/ws/customers/{0}/{1}/{3}\" rel=\"{2}\" />", authenticationData.Username, authenticationData.CampaignsURI, EmailCampaignXmlAttributeValueEdit, atomId); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/{1}/{2}</id>", authenticationData.Username, authenticationData.CampaignsURI, atomId); } data.AppendFormat("<title type=\"text\">{0}</title>", emailCampaign.Name); data.AppendFormat("<updated>{0}</updated>", DateTime.Now.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' data.AppendFormat("<author><name>{0}</name></author>", "Constant Contact"); data.Append("<content type=\"application/vnd.ctct+xml\">"); data.AppendFormat("<Campaign xmlns=\"{0}\" id=\"http://api.constantcontact.com/ws/customers/{1}/{2}/{3}\" >", ConstantNamespace, authenticationData.Username, authenticationData.CampaignsURI, atomId); data.AppendFormat("<Name>{0}</Name>", emailCampaign.Name); data.Append("<Status>Draft</Status>"); data.AppendFormat("<Date>{0}</Date>", emailCampaign.Date.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' if (!atomId.Equals("0000000000000")) { data.AppendFormat("<LastEditDate>{0}</LastEditDate>", emailCampaign.LastEditDate.ToString("o")); //data.AppendFormat("<NextRunDate>{0}</NextRunDate>", emailCampaign.NextRunDate.ToString("o")); data.AppendFormat("<Sent>{0}</Sent>", emailCampaign.Sent); data.AppendFormat("<Opens>{0}</Opens>", emailCampaign.Opens); data.AppendFormat("<Clicks>{0}</Clicks>", emailCampaign.Clicks); data.AppendFormat("<Bounces>{0}</Bounces>", emailCampaign.Bounces); data.AppendFormat("<Forwards>{0}</Forwards>", emailCampaign.Forwards); data.AppendFormat("<OptOuts>{0}</OptOuts>", emailCampaign.OptOuts); data.AppendFormat("<SpamReports>{0}</SpamReports>", emailCampaign.SpamReports); data.AppendFormat("<CampaignType>{0}</CampaignType>", emailCampaign.CampaignType); } data.AppendFormat("<Subject>{0}</Subject>", emailCampaign.Subject); data.AppendFormat("<FromName>{0}</FromName>", emailCampaign.FromName); data.AppendFormat("<ViewAsWebpage>{0}</ViewAsWebpage>", emailCampaign.ViewAsWebpage ? "YES" : "NO"); data.AppendFormat("<ViewAsWebpageLinkText>{0}</ViewAsWebpageLinkText>", emailCampaign.ViewAsWebpageLinkText); data.AppendFormat("<ViewAsWebpageText>{0}</ViewAsWebpageText>", emailCampaign.ViewAsWebpageText); data.AppendFormat("<PermissionReminder>{0}</PermissionReminder>", emailCampaign.PermissionReminder ? "YES" : "NO"); data.AppendFormat("<PermissionReminderText>{0}</PermissionReminderText>", emailCampaign.PermissionReminderText); data.AppendFormat("<GreetingSalutation>{0}</GreetingSalutation>", emailCampaign.GreetingSalutation); data.AppendFormat("<GreetingString>{0}</GreetingString>", emailCampaign.GreetingString); data.AppendFormat("<OrganizationName>{0}</OrganizationName>", emailCampaign.OrganizationName); data.AppendFormat("<OrganizationAddress1>{0}</OrganizationAddress1>", emailCampaign.OrganizationAddress1); data.AppendFormat("<OrganizationAddress2>{0}</OrganizationAddress2>", emailCampaign.OrganizationAddress2); data.AppendFormat("<OrganizationAddress3>{0}</OrganizationAddress3>", emailCampaign.OrganizationAddress3); data.AppendFormat("<OrganizationCity>{0}</OrganizationCity>", emailCampaign.OrganizationCity); data.AppendFormat("<OrganizationState>{0}</OrganizationState>", emailCampaign.OrganizationState); data.AppendFormat("<OrganizationInternationalState>{0}</OrganizationInternationalState>", emailCampaign.OrganizationInternationalState); data.AppendFormat("<OrganizationCountry>{0}</OrganizationCountry>", emailCampaign.OrganizationCountry); data.AppendFormat("<OrganizationPostalCode>{0}</OrganizationPostalCode>", emailCampaign.OrganizationPostalCode); data.AppendFormat("<IncludeForwardEmail>{0}</IncludeForwardEmail>", emailCampaign.IncludeForwardEmail ? "YES" : "NO"); data.AppendFormat("<ForwardEmailLinkText>{0}</ForwardEmailLinkText>", emailCampaign.ForwardEmailLinkText); data.AppendFormat("<IncludeSubscribeLink>{0}</IncludeSubscribeLink>", emailCampaign.IncludeSubscribeLink ? "YES" : "NO"); data.AppendFormat("<SubscribeLinkText>{0}</SubscribeLinkText>", emailCampaign.SubscribeLinkText); // These nodes are currently only supported in CUSTOM campaign types if (emailCampaign.CampaignType == CampaignType.CUSTOM) { data.AppendFormat("<GreetingName>{0}</GreetingName>", emailCampaign.GreetingName); data.AppendFormat("<EmailContentFormat>{0}</EmailContentFormat>", emailCampaign.EmailContentFormat); data.AppendFormat("<EmailContent>{0}</EmailContent>", emailCampaign.EmailContentFormat.Equals("HTML") ? emailCampaign.Content : emailCampaign.XContent); data.AppendFormat("<EmailTextContent>{0}</EmailTextContent>", emailCampaign.TextContent); data.AppendFormat("<StyleSheet>{0}</StyleSheet>", emailCampaign.StyleSheet); } data.Append("<ContactLists>"); if (emailCampaign.ContactLists.Count > 0) { foreach (var contact in emailCampaign.ContactLists) { data.AppendFormat("<ContactList id=\"http://api.constantcontact.com/ws/customers/{0}/lists/{1}\">", authenticationData.Username, contact.Id); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/lists/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, contact.Id); data.Append("</ContactList>"); } } data.Append("</ContactLists>"); data.Append("<FromEmail>"); data.AppendFormat("<Email id=\"http://api.constantcontact.com/ws/customers/{0}/settings/emailaddresses/{1}\">", authenticationData.Username, emailCampaign.FromEmailID); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/settings/emailaddresses/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, emailCampaign.FromEmailID); data.Append("</Email>"); data.AppendFormat("<EmailAddress>{0}</EmailAddress>", emailCampaign.FromEmail); data.Append("</FromEmail>"); data.Append("<ReplyToEmail>"); data.AppendFormat("<Email id=\"http://api.constantcontact.com/ws/customers/{0}/settings/emailaddresses/{1}\">", authenticationData.Username, emailCampaign.ReplyToEmailID); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/settings/emailaddresses/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, emailCampaign.ReplyToEmailID); data.Append("</Email>"); data.AppendFormat("<EmailAddress>{0}</EmailAddress>", emailCampaign.ReplyToEmail); data.Append("</ReplyToEmail>"); data.Append("</Campaign></content><source>"); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/campaigns</id>", authenticationData.Username); data.AppendFormat("<title type=\"text\">Campaigns for customer: {0}</title>", authenticationData.Username); data.AppendFormat("<link href=\"campaigns\" /><link href=\"campaigns\" rel=\"self\" /><author><name>{0}</name></author><updated>{1}</updated></source></entry>", authenticationData.Username, DateTime.Now.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' return data; }
public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) { data.Data.Remove("UUID"); } string[] fields = new List <string>(data.Data.Keys).ToArray(); string[] values = new string[data.Data.Count]; int i = 0; foreach (object o in data.Data.Values) { values[i++] = o.ToString(); } SqliteCommand cmd = new SqliteCommand(); if (Get(data.PrincipalID) != null) { string update = "update `" + m_Realm + "` set "; bool first = true; foreach (string field in fields) { if (!first) { update += ", "; } update += "`" + field + "` = :" + field; cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); first = false; } update += " where UUID = :UUID"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); cmd.CommandText = update; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { return(false); } } catch (Exception e) { m_log.Error("[SQLite]: Exception storing authentication data", e); return(false); } } else { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); foreach (string field in fields) { cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); } cmd.CommandText = insert; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { return(false); } } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } } return(true); }
public void SignIn(AuthenticationData data, bool ispersistent) { var ticket = _authenticationTicket.CreateTicket(data, ispersistent, AuthenticationType); this._authenticationProvider.SignIn(ticket); }
static ClientAuthenticationHeaderContext() { HeaderInformation = new AuthenticationData(); }
void CollectAuthInfo (HttpHeaderValueCollection <AuthenticationHeaderValue> headers) { var authData = new List <AuthenticationData> (headers.Count); foreach (AuthenticationHeaderValue ahv in headers) { var data = new AuthenticationData { Scheme = GetAuthScheme (ahv.Scheme), Challenge = $"{ahv.Scheme} {ahv.Parameter}", UseProxyAuthentication = ProxyAuthenticationRequested }; authData.Add (data); } RequestedAuthentication = authData.AsReadOnly (); }