protected MeekController(Configuration.Configuration config) { _config = config; _repository = config.GetRepository(); _auth = config.GetAuthorization(); _thumbnailGenerators = config.GetThumbnailGenerators(); }
public ContentVirtualFile(Repository repository, string requestedPath, string pathKey, Authorization auth) : base(requestedPath) { _pathKey = pathKey.Replace(".cshtml", string.Empty); _repository = repository; _auth = auth; }
public MeekController() { _config = BootStrapper.Configuration; _repository = BootStrapper.Configuration.GetRepository(); _auth = BootStrapper.Configuration.GetAuthorization(); _thumbnailGenerators = BootStrapper.Configuration.GetThumbnailGenerators(); }
public async Task RetriesWhenResendRequested() { var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp); var challengeResults = new Queue<TwoFactorChallengeResult>(new[] { TwoFactorChallengeResult.RequestResendCode, new TwoFactorChallengeResult("two-factor-code") }); var secondResponse = new Authorization { Token = "OAUTHSECRET" }; var client = Substitute.For<IObservableAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization) .Returns(Observable.Throw<Authorization>(firstResponse)); client.GetOrCreateApplicationAuthentication( Args.String, Args.String, Args.NewAuthorization, "two-factor-code") .Returns(Observable.Return(secondResponse)); var result = await client.GetOrCreateApplicationAuthentication( "clientId", "secret", new NewAuthorization { Note = "Was it this one?" }, _ => Observable.Return(challengeResults.Dequeue())); client.Received(2).GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "two-factor-code"); Assert.Equal("OAUTHSECRET", result.Token); }
public async Task UsesCallbackToRetrievTwoFactorCode() { var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp); var twoFactorChallengeResult = new TwoFactorChallengeResult("two-factor-code"); var secondResponse = new Authorization {Token = "OAUTHSECRET"}; var client = Substitute.For<IObservableAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization) .Returns(Observable.Throw<Authorization>(firstResponse)); client.GetOrCreateApplicationAuthentication( Args.String, Args.String, Args.NewAuthorization, "two-factor-code") .Returns(Observable.Return(secondResponse)); var result = await client.GetOrCreateApplicationAuthentication( "clientId", "secret", new NewAuthorization { Note = "Was it this one?"}, _ => Observable.Return(twoFactorChallengeResult)); Assert.Equal("OAUTHSECRET", result.Token); client.Received().GetOrCreateApplicationAuthentication( "clientId", "secret", Arg.Is<NewAuthorization>(a => a.Note == "Was it this one?")); client.Received().GetOrCreateApplicationAuthentication( "clientId", "secret", Arg.Is<NewAuthorization>(a => a.Note == "Was it this one?"), "two-factor-code"); }
protected MeekController(Configuration.Configuration config) { _config = config; _repository = config.GetRepository(); ; _auth = config.GetAuthorization(); _resizer = config.GetImageResizer(); }
public MeekController() { _repository = BootStrapper.Configuration.GetRepository(); _auth = BootStrapper.Configuration.GetAuthorization(); _resizer = BootStrapper.Configuration.GetImageResizer(); _config = BootStrapper.Configuration; }
/// <summary> /// Parse a message value. /// </summary> /// <param name="name">Name of header being parsed.</param> /// <param name="reader">Reader containing the string that should be parsed.</param> /// <returns>Newly created header.</returns> /// <exception cref="ParseException">Header value is malformed.</exception> /// <example> /// Authorization: Digest username="******", /// realm="biloxi.com", /// nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", /// uri="sip:[email protected]", /// qop=auth, /// nc=00000001, /// cnonce="0a4f113b", /// response="6629fae49393a05397450978507c4ef1", /// opaque="5ccc069c403ebaf9f0171e9517f40e41" /// </example> public IHeader Parse(string name, ITextReader reader) { reader.ConsumeWhiteSpaces(); string digest = reader.ReadWord().ToLower(); if (digest != "digest") throw new ParseException("Authorization header is not digest authentication"); reader.ConsumeWhiteSpaces(); var parameters = new KeyValueCollection(); UriParser.ParseParameters(parameters, reader, ','); var header = new Authorization(name) { UserName = parameters["username"], Realm = parameters["realm"], Nonce = parameters["nonce"], Qop = parameters["qop"], ClientNonce = parameters["cnonce"], Opaque = parameters["opaque"], Response = parameters["response"], Uri = UriParser.Parse(parameters["uri"]) }; try { header.NonceCounter = int.Parse(parameters["nc"]); } catch (Exception err) { throw new ParseException("Failed to parse 'nc' in Authorization header.", err); } return header; }
public TimeLine(Authorization auth) { _auth = auth; timeLine_NodeList = new Dictionary<string, XmlNodeList>(); profileImageList = new List<Bitmap>(); }
public void ShowDocumentation() { if (cbDocument.EditValue != null && cbProcedure.EditValue != null) { Authorization oAuthorization = new Authorization(); lstDocumentation = new BindingList<CDocumentation>(oAuthorization.GetDocumentation(Convert.ToInt16(cbDocument.EditValue), Convert.ToChar(cbProcedure.EditValue))); treeAuthorization.DataSource = lstDocumentation; } }
protected override void OnCreateDependencies() { // create a user var userResponse = Client.Post("/user", new { login = "******", password = NewUserPassword, role = 1, status = 0 }, auth: Admin); Assert.That(userResponse.Status, Is.EqualTo(ExpectedCreatedStatus)); var userId = (int)userResponse.Json["id"]; User = new Authorization("User", "_ut", NewUserPassword, userId); RegisterForDeletion("/user/" + userId); }
public static void Ctor() { var a = new Authorization("token"); Assert.Equal("token", a.Message); Assert.True(a.Complete); Assert.Null(a.ConnectionGroupId); Assert.Null(a.ProtectionRealm); Assert.False(a.MutuallyAuthenticated); }
public System.Threading.Tasks.Task<Authorization.AuthorizationResult> GetTask(Authorization.Requests.ResourceRequest arg1) { return new Task<Authorization.AuthorizationResult>( () => { return provider.authorize(arg1); } ); }
protected bool contains(IList<AuthorizationModel> model, Authorization authorization) { return model.ToList().Exists(m => ( m.CanAdmin == authorization.IsAdmin && m.CanOwn == authorization.IsOwner && m.CanPublish == authorization.IsPublisher && m.User.Name == authorization.User.Name)); }
internal static void addAuth(User user, Project project, bool isAdmin = true, bool isPublisher = true, bool isOwner = true) { Authorization auth = new Authorization { User = user, Project = project }; setAuth(auth, isAdmin, isPublisher, isOwner); user.Authorizations.Add(auth); }
protected override void OnCreateDependencies() { var userResponse = Client.Post("/user", new { login = "******", password = NewUserPassword, role = 1, status = 0 }, auth: Admin); Assert.That(userResponse.Status, Is.EqualTo(ExpectedCreatedStatus)); var userId = (int)userResponse.Json["id"]; RegisterForDeletion("/user/" + userId); ResourceUri = "/user/" + userId + "/accesskey"; Owner = User("_ut_u", NewUserPassword); }
internal static void createAuth(User user, Project project, bool isAdmin = true, bool isPublisher = true, bool isOwner = true) { Authorization auth = new Authorization { User = user, Project = project }; user.Authorizations = new List<Authorization> { auth }; setAuth(auth, isAdmin, isPublisher, isOwner); }
private static void setAuth(Authorization auth, bool isAdmin = true, bool isPublisher = true, bool isOwner = true) { auth.IsAdmin = isAdmin; auth.IsPublisher = isPublisher; auth.IsOwner = isOwner; }
public void Load_directories() { // --- Authorization oAuthorization = new Authorization(); root_path = oAuthorization.GetRootDirectory().Path; btRootDirectory.Text = root_path; // --- gcDirectories.DataSource = oAuthorization.GetListConfiguration_folder(); }
public virtual void Join(Project project) { Authorization auth = new Authorization { User = this, Project = project }; Add(project, auth); }
private Authorization create_authorization(Project project) { Authorization auth = new Authorization { Project = project }; Save(auth); return auth; }
public static void FilledBy(this AuthorizationModel model, Authorization authorization) { model.Id = authorization.Id; model.CanAdmin = authorization.IsAdmin; model.CanOwn = authorization.IsOwner; model.CanPublish = authorization.IsPublisher; UserModel user = new UserModel(); user.FilledBy(authorization.User); model.User = user; }
public void Load_process() { Authorization oAuthorization = new Authorization(); cbDocument.Properties.DataSource = oAuthorization.GetDocument(); cbDocument.Properties.DisplayMember = "Folder_name"; cbDocument.Properties.ValueMember = "Idconfiguration_folder"; cbProcedure.Properties.DataSource = oAuthorization.GetProcedure(); cbProcedure.Properties.DisplayMember = "Name"; cbProcedure.Properties.ValueMember = "Id"; ShowDocumentation(); }
public IObservable<Authorization> GetAuthorizationToken() { var authorization = new Authorization { Token = MobileMilk.Common.Constants.AuthorizationToken, Permissions = Permissions.delete, User = new User { Id = string.Empty, UserName = string.Empty, FullName = string.Empty } }; return (IObservable<Authorization>) authorization; }
protected override void OnCreateDependencies() { var userResponse = Client.Post("/user", new { login = "******", password = NewUserPassword, role = 1, status = 0 }, auth: Admin); Assert.That(userResponse.Status, Is.EqualTo(ExpectedCreatedStatus)); var userId = (int)userResponse.Json["id"]; RegisterForDeletion("/user/" + userId); ResourceUri = "/user/" + userId + "/oauth/grant"; User = new Authorization("User", "_ut", NewUserPassword, userId.ToString()); var clientResponse = Client.Post("/oauth/client", new { name = "_ut", oauthId = "_ut_", domain = "_ut.com", redirectUri = "_ut.com", subnet = "127.0.0.0/24" }, auth: Admin); Assert.That(clientResponse.Status, Is.EqualTo(ExpectedCreatedStatus)); ClientID = (int)clientResponse.Json["id"]; RegisterForDeletion("/oauth/client/" + ClientID); }
public virtual void Create(Project project) { Authorization auth = new Authorization { User = this, Project = project, IsFounder = true, IsPublisher = true, IsOwner = true, IsAdmin = true }; Add(project, auth); }
public Authorization ToAuthorization () { Authorization authorization = new Authorization (); authorization.code = codigo; authorization.message = mensagem; authorization.dateTime = dataHora; authorization.total = valor; authorization.lr = lr; authorization.arp = arp; authorization.nsu = nsu; return authorization; }
protected virtual void Add(Project project, Authorization auth) { Authorizations = Authorizations ?? new List<Authorization>(); Authorizations.Add(auth); project.Authorizations = project.Authorizations ?? new List<Authorization>(); project.Authorizations.Add(auth); //TODO: not sure if (project.Parent != null) { project.Parent.AddChild(project); } }
public String publishingBulkEmail(String apiKey, String contactfileName, String fromName, String fromAddress, String subject, String reportReceiveAddress, String mailBody) { DialogueSettingDao DialogueSettingDao = new DialogueSettingDao(); DialogueSettingBO DB_DialogueSetting = DialogueSettingDao.Get(apiKey); Authorization authorization = new Authorization(); authorization.client = DB_DialogueSetting.client; authorization.username = DB_DialogueSetting.username; authorization.password = DB_DialogueSetting.password; DialogueSetting dialogueSetting = new DialogueSetting(); dialogueSetting.contactDatabaseId = DB_DialogueSetting.contactDatabaseId; dialogueSetting.workspaceId = DB_DialogueSetting.workspaceId; dialogueSetting.emailTypeId = DB_DialogueSetting.emailTypeId; dialogueSetting.ftpAccountId = DB_DialogueSetting.ftpAccountId; String prefix = DB_DialogueSetting.prefix; String sequence = DateTime.Now.ToString("yyyyMMddHHmmssfffffff"); ContactGroup contactGroup = new ContactGroup(); contactGroup.groupLabel = prefix + sequence; contactGroup.groupName = prefix + sequence; DirectEmail directEmail = new DirectEmail(); directEmail.emailLabel = prefix + sequence; directEmail.emailName = prefix + sequence; directEmail.subject = subject; directEmail.description = subject; directEmail.fromName = fromName; directEmail.fromAddress = fromAddress; if (String.IsNullOrEmpty(reportReceiveAddress)) { directEmail.reportReceiveAddress = fromAddress; } else { directEmail.reportReceiveAddress = reportReceiveAddress; } directEmail.htmlContent = mailBody; DialogueService_new dialogueService_new = new DialogueService_new(authorization.client, authorization.username, authorization.password, null); return dialogueService_new.publishingBulkEmail(dialogueSetting, contactGroup, contactfileName, directEmail); }
/* [Randy] Delete a specific authorization document */ public bool deleteDocument(Authorization auth) { try { using (conferenceadminContext context = new conferenceadminContext()) { authorizationsubmitted authorization = context.authorizationsubmitteds.Where(a => a.authorizationSubmittedID == auth.authorizationID).FirstOrDefault(); authorization.deleted = true; context.SaveChanges(); return true; } } catch (Exception ex) { Console.Write("ProfileAuthorizationManager.deleteDocument error " + ex); return false; } }
private void ParseAuthorizationHeader() { string logMessage = ""; if (String.IsNullOrEmpty(Authorization)) { return; } string exceptionMsg = "Invalid authorization header format: " + Authorization; try { #region Retrieve-Outer-Values // [encryption] [values] string[] valsOuter = Authorization.Split(new[] { ' ' }, 2); if (valsOuter == null || valsOuter.Length < 2) { throw new ArgumentException(exceptionMsg); } logMessage += _Header + "Authorization header : " + Authorization + Environment.NewLine; logMessage += _Header + "Outer header values :" + Environment.NewLine; for (int i = 0; i < valsOuter.Length; i++) { logMessage += " " + i + ": " + valsOuter[i].Trim() + Environment.NewLine; } #endregion if (valsOuter[0].Equals("AWS")) { #region Signature-V2 // see https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#ConstructingTheAuthenticationHeader // Authorization: AWS AWSAccessKeyId:Signature string[] valsInner = valsOuter[1].Split(':'); logMessage += _Header + "Inner header values" + Environment.NewLine; for (int i = 0; i < valsInner.Length; i++) { logMessage += " " + i + ": " + valsInner[i].Trim() + Environment.NewLine; } if (valsInner.Length != 2) { throw new ArgumentException(exceptionMsg); } SignatureVersion = S3SignatureVersion.Version2; AccessKey = valsInner[0].Trim(); Signature = valsInner[1].Trim(); logMessage += _Header + "Signature version : " + SignatureVersion.ToString() + Environment.NewLine + _Header + "Access key : " + AccessKey + Environment.NewLine + _Header + "Signature : " + Signature; return; #endregion } else if (valsOuter[0].Equals("AWS4-HMAC-SHA256")) { #region Signature-V4 // see https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html // // AWS4-HMAC-SHA256 Credential=access/20190418/us-east-1/s3/aws4_request, SignedHeaders=content-length;content-type;host;user-agent;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length, Signature=66946e06895806f4e32d32217c1a02313b9d9235b759f3a690742c8f9971daa0 // // valsOuter[0] AWS4-HMAC-SHA256 // valsOuter[1] everything else... SignatureVersion = S3SignatureVersion.Version4; string[] keyValuePairs = valsOuter[1].Split(','); List <string> keyValuePairsTrimmed = new List <string>(); logMessage += _Header + "Inner header values" + Environment.NewLine; for (int i = 0; i < keyValuePairs.Length; i++) { string currKey = keyValuePairs[i]; if (String.IsNullOrEmpty(currKey)) { continue; } currKey = currKey.Trim(); keyValuePairsTrimmed.Add(currKey); logMessage += i + ": " + keyValuePairs[i].Trim() + Environment.NewLine; } foreach (string currKey in keyValuePairsTrimmed) { if (currKey.StartsWith("Credential=")) { #region Credentials string credentialString = currKey.Replace("Credential=", "").Trim(); string[] credentialVals = credentialString.Split('/'); if (credentialVals.Length < 5) { throw new ArgumentException(exceptionMsg); } AccessKey = credentialVals[0].Trim(); Region = credentialVals[2].Trim(); #endregion } else if (currKey.StartsWith("SignedHeaders=")) { #region Signed-Headers string signedHeadersString = currKey.Replace("SignedHeaders=", "").Trim(); string[] signedHeaderVals = signedHeadersString.Split(';'); if (signedHeaderVals != null && signedHeaderVals.Length > 0) { foreach (string currSignedHeader in signedHeaderVals) { SignedHeaders.Add(currSignedHeader.Trim()); } SignedHeaders.Sort(); } #endregion } else if (currKey.StartsWith("Signature=")) { #region Signature Signature = currKey.Replace("Signature=", "").Trim(); #endregion } else if (currKey.StartsWith("Expires=")) { #region Expires Expires = currKey.Replace("Expires=", "").Trim(); #endregion } } logMessage += _Header + "Signature version : " + SignatureVersion.ToString() + Environment.NewLine + _Header + "Access key : " + AccessKey + Environment.NewLine + _Header + "Region : " + Region + Environment.NewLine + _Header + "Signature : " + Signature; return; #endregion } else { throw new ArgumentException(exceptionMsg + Authorization); } } finally { _Logger?.Invoke(logMessage); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.RegisterAddonServices(Configuration); services.Decorate <IContextDriver>((driver, provider) => new TimedContextDriver(driver, provider.GetService <IMetrics>())); services.Decorate <IRulesDriver>((driver, provider) => new TimedRulesDriver(driver, provider.GetService <IMetrics>)); services.AddSingleton <HealthCheck, RulesRepositoryHealthCheck>(); services.AddSingleton <HealthCheck, EnvironmentHealthCheck>(); services.AddSingleton(CreateParserResolver()); var rulesetVersionProvider = Configuration.GetValue("RulesetVersionProvider", "SampleVersionProvider"); services.AddSingleton <IRulesetVersionProvider>(provider => { switch (rulesetVersionProvider) { case "NatsVersionProvider": return(new NatsVersionProvider(provider.GetService <IRulesDriver>(), Configuration.GetValue <string>("Rules:Nats:Endpoint"), provider.GetService <ILoggerFactory>().CreateLogger("NatsVersionProvider"))); default: return(new SampleVersionProvider(provider.GetService <IRulesDriver>(), TimeSpan.FromMilliseconds(Configuration.GetValue("Rules:SampleIntervalInMs", 30000)))); } }); var failureDelayInMs = Configuration.GetValue("Rules:FailureDelayInMs", 60000); services.AddSingleton <IRulesRepository>(provider => new RulesRepository(provider.GetService <IRulesDriver>(), provider.GetService <IRulesetVersionProvider>(), TimeSpan.FromMilliseconds(failureDelayInMs), TimeSpan.FromMilliseconds(failureDelayInMs * 3), provider.GetService <ILoggerFactory>().CreateLogger("RulesRepository"))); services.AddSingleton(provider => { var parserResolver = provider.GetService <GetRuleParser>(); var rulesDriver = provider.GetService <IRulesRepository>(); return(Task.Run(async() => await Engine.Tweek.Create(rulesDriver, parserResolver)).Result); }); services.AddSingleton(provider => { var rulesDriver = provider.GetService <IRulesRepository>(); return(Task.Run(async() => await TweekIdentityProvider.Create(rulesDriver)).Result); }); services.AddSingleton(provider => Authorization.CreateReadConfigurationAccessChecker(provider.GetService <ITweek>(), provider.GetService <TweekIdentityProvider>())); services.AddSingleton(provider => Authorization.CreateWriteContextAccessChecker(provider.GetService <ITweek>(), provider.GetService <TweekIdentityProvider>())); services.AddSingleton(provider => Validator.GetValidationDelegate(provider.GetService <GetRuleParser>())); var tweekContactResolver = new TweekContractResolver(); var jsonSerializer = new JsonSerializer() { ContractResolver = tweekContactResolver }; services.AddSingleton(jsonSerializer); services.AddMvc(options => options.AddMetricsResourceFilter()) .AddJsonOptions(opt => { opt.SerializerSettings.ContractResolver = tweekContactResolver; }); services.SetupCors(Configuration); RegisterMetrics(services); services.AddSwaggerGen(options => { options.SwaggerDoc("api", new Info { Title = "Tweek Api", License = new License { Name = "MIT", Url = "https://github.com/Soluto/tweek/blob/master/LICENSE" }, Version = Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>() .InformationalVersion }); // Generate Dictionary<string,JsonValue> as JSON object in Swagger options.MapType(typeof(Dictionary <string, JsonValue>), () => new Schema { Type = "object" }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "Tweek.ApiService.xml"); options.IncludeXmlComments(xmlPath); }); services.ConfigureAuthenticationProviders(Configuration, loggerFactory.CreateLogger("AuthenticationProviders")); }
private void CreateAccountButton_Click(object sender, RoutedEventArgs e) { Authorization authorization = CreateAuthentication(); CreateAccount(authorization); }
/// <summary> /// Authorizes recovery as a trusted agent. /// </summary> /// <param name="authorization">the authorization</param> /// <returns>the signature</returns> public Signature AuthorizeRecoveryBlocking(Authorization authorization) { return(AuthorizeRecovery(authorization).Result); }
static void Main(string[] args) { //read config file string strApplicationKey; string strClientKey; string strDebug; string strOutFileName; string strOutDelimiter; string strMaxRecords; int intMaxRecords; strApplicationKey = ConfigurationManager.AppSettings["applicationkey"]; strClientKey = ConfigurationManager.AppSettings["clientkey"]; strDebug = ConfigurationManager.AppSettings["debug"]; strOutFileName = ConfigurationManager.AppSettings["outfilename"]; strOutDelimiter = ConfigurationManager.AppSettings["outdelimiter"]; strMaxRecords = ConfigurationManager.AppSettings["maxrecords"]; intMaxRecords = 1000; if (!Int32.TryParse(strMaxRecords, out intMaxRecords)) { intMaxRecords = 50; } try { var applicationkey = strApplicationKey; //"b2585956-025f-45a7-8ea4-b386144419b2"; var clientkey = strClientKey; //"0e7dc82e-32f1-4a02-9f49-a5dce055f5b8"; //GoApi.Core.Global.Settings.Mode = EndPointMode.Production; var authorizationSettings = new AuthorizationSettings { ApplicationKey = applicationkey, ClientKey = clientkey, TokenStore = new BasicTokenStore(@"my.tokenstore"), EndPointHost = EndPointMode.Production }; //var api = Go.CreateAsync(authorizationSettings); var authorization = new Authorization(authorizationSettings); //Go api = new Go(authorization); Go api = new Go(authorizationSettings); //Console.WriteLine("Getting customers starting with A. Max 50"); var customers = api.Customer.Get() //.Where(c => c.Name.StartsWith("A")) .Where(c => c.IsPerson == false) .Skip(0) .Take(50); // Create list of Customers class instances var records = new List <PowerOfficeCust> { }; foreach (var customer1 in customers) { var lstAddress = customer1.StreetAddress; var contactFirstName = ""; var contactLastName = ""; var contactUserName = "******"; var contactPhoneNumber = ""; var contactEmailAddress = ""; if (true) { /* Console.WriteLine("1 C Firstname: " + contactFirstName); * Console.WriteLine("2 C Lastname: " + contactLastName); * Console.WriteLine("3 C Username: "******"4 Middlename : " + ""); * Console.WriteLine("5 CompanyName: " + customer1.Name); * Console.WriteLine("6 C PhoneNumber: " + contactPhoneNumber); * Console.WriteLine("7 Cell : " + ""); * Console.WriteLine("8 Title : " + ""); * Console.WriteLine("9 Department : " + ""); * Console.WriteLine("10 C Email: " + contactEmailAddress); * Console.WriteLine("11 City : " + lstAddress.City); * Console.WriteLine("12 Country " + lstAddress.CountryCode); * Console.WriteLine("13 Adresse 1: " + lstAddress.Address1); * //Console.WriteLine("Adresse 2: " + lstAddress.Address2); * Console.WriteLine("14 Postal Code: " + lstAddress.ZipCode); * Console.WriteLine("15 locaton : " + ""); * Console.WriteLine("16 id: " + customer1.Id); * Console.WriteLine("17 Notes : " + ""); * Console.WriteLine("18 CompanyEmail: " + customer1.EmailAddress); * Console.WriteLine("19 CompanyPhone: " + customer1.PhoneNumber); * Console.WriteLine("20 OrgNumber: " + customer1.VatNumber); * Console.WriteLine("21 website : " + ""); * Console.WriteLine("22 suppportwebsite : " + ""); * Console.WriteLine("23 CompanyNotes : " + ""); * Console.WriteLine("24 CustomerNumber: " + customer1.Code); * Console.WriteLine("-----------------------------------------------------------------------"); */ } //Get all contacts on current customer record var contacts = api.Customer.ContactPerson.Get(customer1); Console.WriteLine("18 CompanyEmail: " + customer1.EmailAddress); Console.WriteLine("24 CustomerNumber: " + customer1.Code); Console.WriteLine("16 id: " + customer1.Id); //Create class instance of customer records, one for each contact on customer foreach (var contact in contacts) { Console.WriteLine("contactFirstName" + contact.FirstName); Console.WriteLine("contactLastName" + contact.LastName); Console.WriteLine("ContactID" + contact.Id.ToString()); Console.WriteLine("contactEmailAddress" + contact.EmailAddress); //contactUserName = contactEmailAddress; // Construct class instance of customer record PowerOfficeCust loopCust = new PowerOfficeCust( contact.FirstName, contact.LastName, contact.EmailAddress, "", //middlename "", //disabled customer1.Name, contact.PhoneNumber, "", //cell "", //title "", //department contact.EmailAddress, lstAddress.City, lstAddress.CountryCode, lstAddress.Address1, lstAddress.ZipCode, "",//location //customer1.Id.ToString(), contact.Id.ToString(), "", //notes customer1.EmailAddress, customer1.PhoneNumber, customer1.VatNumber, "", "", "", customer1.Code.ToString()); // add customer record to list of records records.Add(loopCust); } } // Now write all records to text file using (StreamWriter sw = new StreamWriter(@strOutFileName, false, Encoding.UTF8)) { CsvWriter writer = new CsvWriter(sw, System.Globalization.CultureInfo.CurrentCulture); writer.Configuration.ShouldQuote = (field, context) => true; writer.Configuration.IncludePrivateMembers = true; writer.Configuration.RegisterClassMap <POCustomerMap>(); //writer.Configuration.QuoteAllFields = true; writer.WriteRecords(records); writer.Flush(); } Console.WriteLine("Done"); } catch (ApiException e) { Console.WriteLine("Error: " + e.Message); } //Wait for userinput //Console.WriteLine("\n\nPress any key ..."); //Console.ReadKey(); }
internal async Task <IChallengeValidationDetails> DecodeChallengeValidation(Authorization auth, Challenge challenge) { var client = await GetClient(); return(AuthorizationDecoder.DecodeChallengeValidation(auth, challenge.Type, client.Signer)); }
protected override void Seed(TPITextSharp.Data.DAL.ModelContext context) { // Gwin Roles // Role RoleGuest = null; Role RoleRoot = null; Role RoleAdmin = null; context.Roles.AddOrUpdate( r => r.Reference , new Role { Reference = nameof(Role.Roles.Guest), Name = new LocalizedString() { Current = nameof(Role.Roles.Guest) } }, new Role { Reference = nameof(Role.Roles.User), Name = new LocalizedString() { Current = nameof(Role.Roles.User) } }, new Role { Reference = nameof(Role.Roles.Admin), Name = new LocalizedString() { Current = nameof(Role.Roles.Admin) } }, new Role { Reference = nameof(Role.Roles.Root), Name = new LocalizedString() { Current = nameof(Role.Roles.Root) }, Hidden = true } ); // Save Change to Select RoleRoot and RoleGuest context.SaveChanges(); RoleRoot = context.Roles.Where(r => r.Reference == nameof(Role.Roles.Root)).SingleOrDefault(); RoleGuest = context.Roles.Where(r => r.Reference == nameof(Role.Roles.Guest)).SingleOrDefault(); RoleAdmin = context.Roles.Where(r => r.Reference == nameof(Role.Roles.Admin)).SingleOrDefault(); // // Giwn Autorizations // // Guest Autorization Authorization FindUserAutorization = new Authorization(); FindUserAutorization.BusinessEntity = typeof(User).FullName; FindUserAutorization.ActionsNames = new List <string>(); FindUserAutorization.ActionsNames.Add(nameof(IGwinBaseBLO.Recherche)); RoleGuest.Authorizations = new List <Authorization>(); RoleGuest.Authorizations.Add(FindUserAutorization); // Admin Autorization RoleAdmin.Authorizations = new List <Authorization>(); Authorization UserAutorization = new Authorization(); UserAutorization.BusinessEntity = typeof(User).FullName; RoleAdmin.Authorizations.Add(UserAutorization); context.SaveChanges(); //-- Giwn Users context.Users.AddOrUpdate( u => u.Reference, new User() { Reference = nameof(User.Users.Root), Login = nameof(User.Users.Root), Password = nameof(User.Users.Root), LastName = new LocalizedString() { Current = nameof(User.Users.Root) }, Roles = new List <Role>() { RoleRoot } }, new User() { Reference = nameof(User.Users.Admin), Login = nameof(User.Users.Admin), Password = nameof(User.Users.Admin), LastName = new LocalizedString() { Current = nameof(User.Users.Admin) }, Roles = new List <Role>() { RoleAdmin } }, new User() { Reference = nameof(User.Users.Guest), Login = nameof(User.Users.Guest), Password = nameof(User.Users.Guest), LastName = new LocalizedString() { Current = nameof(User.Users.Guest) }, Roles = new List <Role>() { RoleGuest } } ); //-- Gwin Menu context.MenuItemApplications.AddOrUpdate( r => r.Code , new MenuItemApplication { Id = 1, Code = "Configuration", Title = new LocalizedString { Arab = "إعدادات", English = "Configuration", French = "Configuration" } }, new MenuItemApplication { Id = 2, Code = "Admin", Title = new LocalizedString { Arab = "تدبير البرنامج", English = "Admin", French = "Administration" } }, new MenuItemApplication { Id = 3, Code = "Root", Title = new LocalizedString { Arab = "مصمم اليرنامج", English = "Application Constructor", French = "Rélisateur de l'application" } } ); // // Group Autorization // // Group Authorization GroupAuthorizations = new Authorization(); GroupAuthorizations.BusinessEntity = typeof(Group).FullName; RoleAdmin.Authorizations.Add(GroupAuthorizations); // add Groups data context.Groups.AddOrUpdate( g => g.Id, new Group { Name = "TSDI", Description = "Technicien specialise en developpement informatique" }, new Group { Name = "TSRI", Description = "Technicien specialise en Reseaux informatique" }, new Group { Name = "TSI", Description = "Technicien specialise en Informatique" } ); }
public bool TryGetAuthorization(string authorizationId, out Authorization authorization) { return(_authLookup.TryGetValue(authorizationId, out authorization)); }
public async Task <SearchTweetsExtModel> Get([FromUri] string query) { query += " AND -RT"; var secretModel = new SecretModel { ApiKey = _apiKey, ApiSecret = _apiSecret, AccessToken = _accessToken, AccessTokenSecret = _accessTokenSecret }; var authorization = new Authorization(secretModel); var httpClient = new HttpClient(); var uri = new Uri(string.Format("{0}?{1}", Urls.SearchTweets, string.Format("q={0}&count=5", HttpUtility.UrlEncode(query)))); var authHeader = authorization.GetHeader(uri); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", authHeader); var request = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get }; var responseMessage = await httpClient.SendAsync(request).ConfigureAwait(false); var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var jObject = JObject.Parse(response); var searchTweets = JsonConvert.DeserializeObject <SearchTweetsExtModel>(jObject.ToString()); foreach (var status in searchTweets.statuses) { var alchemyUrl = string.Format( "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?showSourceText=1&outputMode=json&apikey={0}&text={1}", status.text, _alchemyApiKey); var alchemyRequest = new HttpRequestMessage { RequestUri = new Uri(alchemyUrl), Method = HttpMethod.Get }; var httpClient2 = new HttpClient(); var alchemyResponseMessage = await httpClient2.SendAsync(alchemyRequest).ConfigureAwait(false); var alchemyResponse = await alchemyResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var jAlchemyObject = JObject.Parse(alchemyResponse); var sentiment = JsonConvert.DeserializeObject <Sentiment>(jAlchemyObject.ToString()); status.sentiment_score = Convert.ToDouble(sentiment.docSentiment.score); status.positive = (status.sentiment_score > 0); } return(searchTweets); }
public virtual Boolean IsAuthorizedFor(String permission) { return(Authorization.IsGrantedFor(CurrentAccountId, permission)); }
/// <summary> /// Updates the bulk update security. /// </summary> private static void UpdateBulkUpdateSecurity() { var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); var bulkUpdateBlockType = BlockTypeCache.Get(Rock.SystemGuid.BlockType.BULK_UPDATE.AsGuid()); var bulkUpdateBlocks = new BlockService(rockContext).Queryable().Where(a => a.BlockTypeId == bulkUpdateBlockType.Id).ToList(); foreach (var bulkUpdateBlock in bulkUpdateBlocks) { var alreadyUpdated = authService.Queryable().Where(a => (a.Action == "EditConnectionStatus" || a.Action == "EditRecordStatus") && a.EntityTypeId == bulkUpdateBlock.TypeId && a.EntityId == bulkUpdateBlock.Id).Any(); if (alreadyUpdated) { // EditConnectionStatus and/or EditRecordStatus has already been set, so don't copy VIEW auth to it continue; } var groupIdAuthRules = new HashSet <int>(); var personIdAuthRules = new HashSet <int>(); var specialRoleAuthRules = new HashSet <SpecialRole>(); var authRulesToAdd = new List <AuthRule>(); Dictionary <ISecured, List <AuthRule> > parentAuthRulesList = new Dictionary <ISecured, List <AuthRule> >(); ISecured secured = bulkUpdateBlock; while (secured != null) { var entityType = secured.TypeId; List <AuthRule> authRules = Authorization.AuthRules(secured.TypeId, secured.Id, Authorization.VIEW).OrderBy(a => a.Order).ToList(); foreach (var rule in authRules) { if (rule.GroupId.HasValue) { if (!groupIdAuthRules.Contains(rule.GroupId.Value)) { groupIdAuthRules.Add(rule.GroupId.Value); authRulesToAdd.Add(rule); } } else if (rule.PersonId.HasValue) { if (!personIdAuthRules.Contains(rule.PersonId.Value)) { personIdAuthRules.Add(rule.PersonId.Value); authRulesToAdd.Add(rule); } } else if (rule.SpecialRole != SpecialRole.None) { if (!specialRoleAuthRules.Contains(rule.SpecialRole)) { specialRoleAuthRules.Add(rule.SpecialRole); authRulesToAdd.Add(rule); } } } secured = secured.ParentAuthority; } List <Auth> authsToAdd = new List <Auth>(); foreach (var auth in authRulesToAdd) { authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditConnectionStatus")); authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditRecordStatus")); } int authOrder = 0; authsToAdd.ForEach(a => a.Order = authOrder++); authService.AddRange(authsToAdd); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditConnectionStatus"); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditRecordStatus"); } rockContext.SaveChanges(); }
/// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); if (customer == null) { throw new Exception("Customer cannot be loaded"); } try { var apiContext = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings); var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); var payment = new Payment() { #region payer payer = new Payer() { payment_method = "credit_card", #region credit card info funding_instruments = new List <FundingInstrument> { new FundingInstrument { credit_card = new CreditCard { type = processPaymentRequest.CreditCardType.ToLowerInvariant(), number = processPaymentRequest.CreditCardNumber, cvv2 = processPaymentRequest.CreditCardCvv2, expire_month = processPaymentRequest.CreditCardExpireMonth, expire_year = processPaymentRequest.CreditCardExpireYear } } }, #endregion #region payer info payer_info = new PayerInfo { #region billing address billing_address = customer.BillingAddress == null ? null : new Address { country_code = customer.BillingAddress.Country != null ? customer.BillingAddress.Country.TwoLetterIsoCode : null, state = customer.BillingAddress.StateProvince != null ? customer.BillingAddress.StateProvince.Abbreviation : null, city = customer.BillingAddress.City, line1 = customer.BillingAddress.Address1, line2 = customer.BillingAddress.Address2, phone = customer.BillingAddress.PhoneNumber, postal_code = customer.BillingAddress.ZipPostalCode }, #endregion email = customer.BillingAddress != null ? customer.BillingAddress.Email : null, first_name = customer.BillingAddress != null ? customer.BillingAddress.FirstName : null, last_name = customer.BillingAddress != null ? customer.BillingAddress.LastName : null } #endregion }, #endregion #region transaction transactions = new List <Transaction>() { new Transaction { #region amount amount = new Amount { total = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US")), currency = currency != null ? currency.CurrencyCode : null }, #endregion #region shipping address item_list = customer.ShippingAddress == null ? null : new ItemList { shipping_address = new ShippingAddress { country_code = customer.ShippingAddress.Country != null ? customer.ShippingAddress.Country.TwoLetterIsoCode : null, state = customer.ShippingAddress.StateProvince != null ? customer.ShippingAddress.StateProvince.Abbreviation : null, city = customer.ShippingAddress.City, line1 = customer.ShippingAddress.Address1, line2 = customer.ShippingAddress.Address2, phone = customer.ShippingAddress.PhoneNumber, postal_code = customer.ShippingAddress.ZipPostalCode, recipient_name = string.Format("{0} {1}", customer.ShippingAddress.FirstName, customer.ShippingAddress.LastName) } }, #endregion invoice_number = processPaymentRequest.OrderGuid != Guid.Empty ? processPaymentRequest.OrderGuid.ToString() : null } }, #endregion intent = _paypalDirectPaymentSettings.TransactMode == TransactMode.Authorize ? "authorize" : "sale", }.Create(apiContext); if (payment.transactions[0].related_resources.Any() && payment.transactions[0].related_resources[0] != null) { if (_paypalDirectPaymentSettings.TransactMode == TransactMode.Authorize) { var authorization = payment.transactions[0].related_resources[0].authorization; if (authorization != null) { if (authorization.fmf_details != null && !string.IsNullOrEmpty(authorization.fmf_details.filter_id)) { result.AuthorizationTransactionResult = string.Format("Authorization is {0}. Based on fraud filter: {1}. {2}", authorization.fmf_details.filter_type, authorization.fmf_details.name, authorization.fmf_details.description); result.NewPaymentStatus = GetPaymentStatus(Authorization.Get(apiContext, authorization.id).state); } else { result.AuthorizationTransactionResult = authorization.state; result.NewPaymentStatus = GetPaymentStatus(authorization.state); } result.AuthorizationTransactionId = authorization.id; } } else { var sale = payment.transactions[0].related_resources[0].sale; if (sale != null) { if (sale.fmf_details != null && !string.IsNullOrEmpty(sale.fmf_details.filter_id)) { result.CaptureTransactionResult = string.Format("Sale is {0}. Based on fraud filter: {1}. {2}", sale.fmf_details.filter_type, sale.fmf_details.name, sale.fmf_details.description); result.NewPaymentStatus = GetPaymentStatus(Sale.Get(apiContext, sale.id).state); } else { result.CaptureTransactionResult = sale.state; result.NewPaymentStatus = GetPaymentStatus(sale.state); } result.CaptureTransactionId = sale.id; result.AvsResult = sale.processor_response != null ? sale.processor_response.avs_code : string.Empty; } } } else { result.AddError("PayPal error"); } } catch (PayPal.PayPalException exc) { if (exc is PayPal.ConnectionException) { var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response); if (error != null) { result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name)); if (error.details != null) { error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue))); } } } //if there are not the specific errors add exception message if (result.Success) { result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message); } } return(result); }
/// <summary> /// Gets a list of person IDs that should be notified of something happening in the org. /// Defaults to collecting Local roles with Permission.CanSeePeople /// </summary> /// <param name="organizationId">The organization where something happened.</param> /// <param name="geographyId">The geonode where something happened.</param> /// <returns>A list of person Ids that hold roles above this point.</returns> public static int[] GetAllUpwardRoles(int organizationId, int geographyId) { return(GetAllUpwardRoles(organizationId, geographyId, Authorization.RoleTypesWithPermission(Permission.CanSeePeople))); }
public SwaggerSpecConfig Authorization(string name, Authorization authorization) { _authorizations = _authorizations ?? new Dictionary <string, Authorization>(); _authorizations[name] = authorization; return(this); }
public void SetData(Authorization data) { ObjectSupport.CopyData(data, this); OriginalName = ResourceName; }
/// <summary> /// Handles the Click event of the lbAddRole control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbAddRole_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var authService = new AuthService(rockContext); foreach (ListItem li in cblRoleActionList.Items) { if (li.Selected) { Rock.Model.SpecialRole specialRole = Rock.Model.SpecialRole.None; int?groupId = ddlRoles.SelectedValue.AsIntegerOrNull(); switch (groupId) { case -1: specialRole = Rock.Model.SpecialRole.AllUsers; break; case -2: specialRole = Rock.Model.SpecialRole.AllAuthenticatedUsers; break; case -3: specialRole = Rock.Model.SpecialRole.AllUnAuthenticatedUsers; break; default: specialRole = Rock.Model.SpecialRole.None; break; } if (groupId < 0) { groupId = null; } var existingAuths = authService.GetAuths(iSecured.TypeId, iSecured.Id, li.Text).ToList(); if (!existingAuths.Any(a => a.SpecialRole == specialRole && a.GroupId.Equals(groupId))) { int order = existingAuths.Count > 0 ? existingAuths.Last().Order + 1 : 0; Rock.Model.Auth auth = new Rock.Model.Auth(); auth.EntityTypeId = iSecured.TypeId; auth.EntityId = iSecured.Id; auth.Action = li.Text; auth.AllowOrDeny = "A"; auth.SpecialRole = specialRole; auth.GroupId = groupId; auth.Order = order; authService.Add(auth); rockContext.SaveChanges(); Authorization.ReloadAction(iSecured.TypeId, iSecured.Id, li.Text); } } } } pnlAddRole.Visible = false; phList.Visible = true; BindGrid(); }
public Authorization GetData(Authorization data) { ObjectSupport.CopyData(this, data); return(data); }
private void submitLoginBtn_Click(object sender, RoutedEventArgs e) { Authorization sesion = new Authorization(this.usrNameTextBox.Text, this.passTextBox.Password); sesion.GetAccess(); }
public static void Mapping(this AuthorizationDTO f, Authorization f1) { f1.IDAdmin = f.IDAdmin; f1.IDCN = f.IDCN; }
public async Task CanProcessCommand() { var domain = "www.certes.com"; var orderLoc = new Uri("http://acme.com/o/1"); var resourceGroup = "resGroup"; var challengeLoc = new Uri("http://acme.com/o/1/c/2"); var authzLoc = new Uri("http://acme.com/o/1/a/1"); var authz = new Authorization { Identifier = new Identifier { Type = IdentifierType.Dns, Value = domain }, Challenges = new[] { new Challenge { Token = "dns-token", Type = ChallengeTypes.Dns01, }, new Challenge { Token = "http-token", Type = ChallengeTypes.Http01, }, } }; var expectedRecordSetId = Guid.NewGuid().ToString(); var expectedRecordSet = new { data = new RecordSetInner(id: expectedRecordSetId) }; var settingsMock = new Mock <IUserSettings>(MockBehavior.Strict); settingsMock.Setup(m => m.GetDefaultServer()).ReturnsAsync(LetsEncryptV2); settingsMock.Setup(m => m.GetAccountKey(LetsEncryptV2)).ReturnsAsync(GetKeyV2()); settingsMock.Setup(m => m.GetAzureSettings()).ReturnsAsync(new AzureSettings { ClientId = "clientId", ClientSecret = "secret", SubscriptionId = Guid.NewGuid().ToString("N"), TenantId = Guid.NewGuid().ToString("N"), }); var challengeMock = new Mock <IChallengeContext>(MockBehavior.Strict); challengeMock.SetupGet(m => m.Location).Returns(challengeLoc); challengeMock.SetupGet(m => m.Type).Returns(ChallengeTypes.Dns01); challengeMock.SetupGet(m => m.Token).Returns(authz.Challenges[0].Token); var authzMock = new Mock <IAuthorizationContext>(MockBehavior.Strict); authzMock.Setup(m => m.Resource()).ReturnsAsync(authz); authzMock.Setup(m => m.Challenges()) .ReturnsAsync(new[] { challengeMock.Object }); var orderMock = new Mock <IOrderContext>(MockBehavior.Strict); orderMock.Setup(m => m.Authorizations()).ReturnsAsync(new[] { authzMock.Object }); var ctxMock = new Mock <IAcmeContext>(MockBehavior.Strict); ctxMock.Setup(m => m.GetDirectory()).ReturnsAsync(MockDirectoryV2); ctxMock.Setup(m => m.Order(orderLoc)).Returns(orderMock.Object); ctxMock.SetupGet(m => m.AccountKey).Returns(GetKeyV2()); var fileMock = new Mock <IFileUtil>(MockBehavior.Strict); var dnsMock = new Mock <IDnsManagementClient>(MockBehavior.Strict); var zonesOpMock = new Mock <IZonesOperations>(MockBehavior.Strict); var recordSetsOpMock = new Mock <IRecordSetsOperations>(MockBehavior.Strict); dnsMock.Setup(m => m.Dispose()); dnsMock.SetupSet(m => m.SubscriptionId); dnsMock.SetupGet(m => m.Zones).Returns(zonesOpMock.Object); dnsMock.SetupGet(m => m.RecordSets).Returns(recordSetsOpMock.Object); zonesOpMock.Setup(m => m.ListWithHttpMessagesAsync(default, default, default))
/// <summary> /// Make sure we have authorization for every host in target /// </summary> /// <param name="target"></param> /// <returns></returns> private Challenge Authorize(ILifetimeScope execute, RunLevel runLevel, OrderDetails order, ValidationPluginOptions options, TargetPart targetPart, Authorization authorization) { var invalid = new Challenge { Status = _authorizationInvalid }; var valid = new Challenge { Status = _authorizationValid }; var client = execute.Resolve <AcmeClient>(); var identifier = authorization.Identifier.Value; try { _log.Information("Authorize identifier: {identifier}", identifier); if (authorization.Status == _authorizationValid && !runLevel.HasFlag(RunLevel.Test)) { _log.Information("Cached authorization result: {Status}", authorization.Status); return(valid); } else { using (var validation = _scopeBuilder.Validation(execute, options, targetPart, identifier)) { IValidationPlugin validationPlugin = null; try { validationPlugin = validation.Resolve <IValidationPlugin>(); } catch (Exception ex) { _log.Error(ex, "Error resolving validation plugin"); } if (validationPlugin == null) { _log.Error("Validation plugin not found or not created."); return(invalid); } var challenge = authorization.Challenges.FirstOrDefault(c => c.Type == options.ChallengeType); if (challenge == null) { _log.Error("Expected challenge type {type} not available for {identifier}.", options.ChallengeType, authorization.Identifier.Value); return(invalid); } if (challenge.Status == _authorizationValid && !runLevel.HasFlag(RunLevel.Test)) { _log.Information("{dnsIdentifier} already validated by {challengeType} validation ({name})", authorization.Identifier.Value, options.ChallengeType, options.Name); return(valid); } _log.Information("Authorizing {dnsIdentifier} using {challengeType} validation ({name})", identifier, options.ChallengeType, options.Name); try { var details = client.DecodeChallengeValidation(authorization, challenge); validationPlugin.PrepareChallenge(details); } catch (Exception ex) { _log.Error(ex, "Error preparing for challenge answer"); return(invalid); } _log.Debug("Submitting challenge answer"); challenge = client.AnswerChallenge(challenge); // Have to loop to wait for server to stop being pending var tries = 0; var maxTries = 4; while (challenge.Status == _authorizationPending) { _log.Debug("Refreshing authorization"); Thread.Sleep(2000); // this has to be here to give ACME server a chance to think challenge = client.GetChallengeDetails(challenge.Url); tries += 1; if (tries > maxTries) { _log.Error("Authorization timed out"); return(invalid); } } if (challenge.Status != _authorizationValid) { if (challenge.Error != null) { _log.Error(challenge.Error.ToString()); } _log.Error("Authorization result: {Status}", challenge.Status); return(invalid); } else { _log.Information("Authorization result: {Status}", challenge.Status); return(valid); } } } } catch (Exception ex) { _log.Error("Error authorizing {renewal}", targetPart); HandleException(ex); return(invalid); } }
public object GetData() { try { var data = new AbnormalReportData(); using (var connection = SqlConnections.NewFor <DeclarationDataRow>()) { var flds = DeclarationDataRow.Fields; var instance = Activator.CreateInstance <DeclarationDataRow>(); var query = new SqlQuery().From(instance).Select(flds.TenantId, flds.TenantName, flds.MasterAwb, flds.SubAwb, flds.Amount, flds.IsChecked, flds.Flight); if (MasterAwb != null && MasterAwb.Count != 0) { string whereStr = string.Empty; foreach (var masterAwb in MasterAwb) { whereStr = $"MasterAwb in ('{masterAwb}',"; } whereStr = whereStr.TrimEnd(',') + ")"; query.Where(whereStr); } if (!string.IsNullOrWhiteSpace(SubAwb)) { query.Where($"SubAwb='{SubAwb}'"); } if (Authorization.HasPermission(PermissionKeys.Tenants)) { //管理员 } else { var user = (UserDefinition)Authorization.UserDefinition; query.Where($"T0.TenantId={user.TenantId}"); } var rows = connection.Query <DeclarationDataRow>(query); var declarationDataRows = rows as IList <DeclarationDataRow> ?? rows.ToList(); var q = from p in declarationDataRows orderby p.TenantName, p.MasterAwb, p.Flight group p by new { p.TenantName, p.MasterAwb, p.Flight } into grouped select new ReportData1 { ApplicationUnit = grouped.Key.TenantName, Flight = grouped.Key.Flight, MasterAwb = grouped.Key.MasterAwb, Amount = grouped.Sum(m => m.Amount) }; var dataReportData = q as IList <ReportData1> ?? q.ToList(); foreach (var qr in dataReportData) { qr.RealAmount = declarationDataRows.Where(p => p.TenantName == qr.ApplicationUnit && p.Flight == qr.Flight && p.MasterAwb == qr.MasterAwb && (p.IsChecked == StateKind.Checked || p.IsChecked == StateKind.OverChecked)) .Sum(p => p.Amount); qr.Details = declarationDataRows.Where(p => p.TenantName == qr.ApplicationUnit && p.Flight == qr.Flight && p.MasterAwb == qr.MasterAwb && (p.IsChecked == StateKind.NoChecked || p.IsChecked == StateKind.OverChecked)); } data.ReportData = dataReportData; } return(data); } catch (Exception ex) { ex.Log(); return(new NormalReportData()); } }
/// <summary> /// Authorizes recovery as a trusted agent. /// </summary> /// <param name="authorization">the authorization</param> /// <returns>the signature</returns> public Task <Signature> AuthorizeRecovery(Authorization authorization) { return(client.AuthorizeRecovery(authorization)); }
protected override void Seed(AuthorizationDbContext context) { base.Seed(context); var subdivision = new Subdivision { Id = 1, Name = "SA Cimislia", Phone = "068753456", LeaderFirstName = "Vasile", LeaderLastName = "Popa", }; context.Subdivisions.Add(subdivision); var agent = new Agent { Id = 1, Name = "Tudor Trandafir", Address = "str.Uzinelor", Phone = "068345678" }; context.Agents.Add(agent); var authorization = new Authorization { Id = 1, ASVF = "12344FRD34F43DWP5", EliberationDate = DateTime.Now.Date, ExpireDate = new DateTime(2013, 3, 4), AuthorizatedObjectName = "SA Bordei", AuthorizatedObjectAddress = "Str.Stefan Cel Mare", AuthorizatedObjectPhone = "079543478", SubdivisionId = 1, AgentId = 1, }; context.Authorizations.Add(authorization); //var subdivision1 = new Subdivision //{ // Id = 2, // Name = "SA Chisinau", // Phone = "068753456", // LeaderFirstName = "Vaseile", // LeaderLastName = "Popa", //}; //context.Subdivisions.Add(subdivision1); //var agent1 = new Agent //{ // Id = 2, // Name = "Vasea Trandafir", // Address = "str.Uzinelor", // Phone = "4235312" //}; //context.Agents.Add(agent1); //var authorization1 = new Authorization //{ // Id = 2, // ASVF = "sadsaas", // EliberationDate = DateTime.Now.Date, // ExpireDate = new DateTime(2013, 3, 4), // AuthorizatedObjectName = "SA Bordei", // AuthorizatedObjectAddress = "Str.Stefan Cel Mare", // AuthorizatedObjectPhone = "435324", // SubdivisionId = 2, // AgentId = 2 //}; //context.Authorizations.Add(authorization1); var activitiesList = new List <ActivityProfile> { new ActivityProfile { Activity = Activity.Abataj }, new ActivityProfile { Activity = Activity.Achizitionare }, new ActivityProfile { Activity = Activity.ComercializareAnimalelor }, new ActivityProfile { Activity = Activity.Distribuire }, new ActivityProfile { Activity = Activity.Fabricare }, new ActivityProfile { Activity = Activity.Pastrare }, new ActivityProfile { Activity = Activity.Preluare }, new ActivityProfile { Activity = Activity.ProduseAlimentare }, new ActivityProfile { Activity = Activity.Transport } }; foreach (var item in activitiesList) { context.ActivityProfiles.Add(item); } context.SaveChanges(); }
static void Main(string[] args) { var loginPage = new Authorization(); loginPage.ChooseAction(); }
/// <summary> /// Make sure we have authorization for every host in target /// </summary> /// <param name="target"></param> /// <returns></returns> private async Task <Challenge> Authorize( ILifetimeScope execute, RunLevel runLevel, ValidationPluginOptions options, TargetPart targetPart, Authorization authorization) { var invalid = new Challenge { Status = AcmeClient.AuthorizationInvalid }; var valid = new Challenge { Status = AcmeClient.AuthorizationValid }; var client = execute.Resolve <AcmeClient>(); var identifier = authorization.Identifier.Value; try { _log.Information("Authorize identifier: {identifier}", identifier); if (authorization.Status == AcmeClient.AuthorizationValid && !runLevel.HasFlag(RunLevel.Test) && !runLevel.HasFlag(RunLevel.IgnoreCache)) { _log.Information("Cached authorization result: {Status}", authorization.Status); return(valid); } else { using var validation = _scopeBuilder.Validation(execute, options, targetPart, identifier); IValidationPlugin?validationPlugin = null; try { validationPlugin = validation.Resolve <IValidationPlugin>(); } catch (Exception ex) { _log.Error(ex, "Error resolving validation plugin"); } if (validationPlugin == null) { _log.Error("Validation plugin not found or not created."); return(invalid); } if (validationPlugin.Disabled) { _log.Error("Validation plugin is not available to the current user, try running as administrator."); return(invalid); } var challenge = authorization.Challenges.FirstOrDefault(c => c.Type == options.ChallengeType); if (challenge == null) { _log.Error("Expected challenge type {type} not available for {identifier}.", options.ChallengeType, authorization.Identifier.Value); return(invalid); } if (challenge.Status == AcmeClient.AuthorizationValid && !runLevel.HasFlag(RunLevel.Test) && !runLevel.HasFlag(RunLevel.IgnoreCache)) { _log.Information("{dnsIdentifier} already validated by {challengeType} validation ({name})", authorization.Identifier.Value, options.ChallengeType, options.Name); return(valid); } _log.Information("Authorizing {dnsIdentifier} using {challengeType} validation ({name})", identifier, options.ChallengeType, options.Name); try { var details = await client.DecodeChallengeValidation(authorization, challenge); await validationPlugin.PrepareChallenge(details); } catch (Exception ex) { _log.Error(ex, "Error preparing for challenge answer"); return(invalid); } _log.Debug("Submitting challenge answer"); challenge = await client.AnswerChallenge(challenge); if (challenge.Status != AcmeClient.AuthorizationValid) { if (challenge.Error != null) { _log.Error(challenge.Error.ToString()); } _log.Error("Authorization result: {Status}", challenge.Status); return(invalid); } else { _log.Information("Authorization result: {Status}", challenge.Status); return(valid); } } } catch (Exception ex) { _log.Error("Error authorizing {renewal}", targetPart); _exceptionHandler.HandleException(ex); return(invalid); } }
public async Task EtpClient_v11_OpenSession_Can_Authenticate_Using_Json_Web_Token() { var headers = Authorization.Basic(TestSettings.Username, TestSettings.Password); var etpSubProtocol = EtpSettings.Etp11SubProtocol; string token; using (var client = new System.Net.WebClient()) { foreach (var header in headers) { client.Headers[header.Key] = header.Value; } var response = await client.UploadStringTaskAsync(TestSettings.AuthTokenUrl, "grant_type=password"); var json = JObject.Parse(response); token = json["access_token"].Value <string>(); } _client.Dispose(); _client = CreateClient(TestSettings.WebSocketType, etpSubProtocol, _server.Uri.ToWebSocketUri().ToString(), Authorization.Bearer(token)); var onOpenSession = HandleAsync <OpenSession>(x => _client.Handler <ICoreClient>().OnOpenSession += x); var opened = await _client.OpenAsyncWithTimeout(); Assert.IsTrue(opened, "EtpClient connection not opened"); var args = await onOpenSession.WaitAsync(); Assert.IsNotNull(args); Assert.IsNotNull(args.Message); Assert.IsNotNull(args.Message.SessionId); }
public TokenMessage() { Auth = new Authorization(); }
internal void GetConnection(string host, int port) { if (_isConnected) { throw new InvalidOperationException(SR.SmtpAlreadyConnected); } InitializeConnection(host, port); _responseReader = new SmtpReplyReaderFactory(_networkStream); LineInfo info = _responseReader.GetNextReplyReader().ReadLine(); switch (info.StatusCode) { case SmtpStatusCode.ServiceReady: break; default: throw new SmtpException(info.StatusCode, info.Line, true); } try { _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } catch (SmtpException e) { if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) { throw; } HelloCommand.Send(this, _client.clientDomain); //if ehello isn't supported, assume basic login _supportedAuth = SupportedAuth.Login; } if (_enableSsl) { if (!_serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(_networkStream is TlsStream)) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } } StartTlsCommand.Send(this); TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates); tlsStream.AuthenticateAsClient(); _networkStream = tlsStream; _responseReader = new SmtpReplyReaderFactory(_networkStream); // According to RFC 3207: The client SHOULD send an EHLO command // as the first command after a successful TLS negotiation. _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } // if no credentials were supplied, try anonymous // servers don't appear to anounce that they support anonymous login. if (_credentials != null) { for (int i = 0; i < _authenticationModules.Length; i++) { //only authenticate if the auth protocol is supported - chadmu if (!AuthSupported(_authenticationModules[i])) { continue; } NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType); if (credential == null) { continue; } Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null); if (auth != null && auth.Message != null) { info = AuthCommand.Send(this, _authenticationModules[i].AuthenticationType, auth.Message); if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented) { continue; } while ((int)info.StatusCode == 334) { auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken); if (auth == null) { throw new SmtpException(SR.SmtpAuthenticationFailed); } info = AuthCommand.Send(this, auth.Message); if ((int)info.StatusCode == 235) { _authenticationModules[i].CloseContext(this); _isConnected = true; return; } } } } } _isConnected = true; }
void Write(BinaryWriter writer, Authorization auth) { writer.Write(Base32.Encode(auth.Actor)); writer.Write(Base32.Encode(auth.Permission)); }