private static IEntityServices SetupConnection(int connectionId, string domainName) { ConnectionDto connection; using (var db = new TenantDb(ConnectionString.ForDomain(domainName))) { var conn = db.Connections.Single(x => x.ConnectionId == connectionId && x.IsActive); connection = new ConnectionDto { ConnectionId = conn.ConnectionId, Url = conn.Url.Trim(), UserName = conn.UserName.Trim(), Password = conn.Password.Trim() }; } IAuthenticator authenticator = new Authentication(); IOrganizationService organizationService = authenticator.Authenticate(new AuthenticationInformation { OrganizationUri = connection.Url, UserName = connection.UserName, Password = connection.Password }); IEntityServices entityService = new EntityServices(organizationService); return entityService; }
/// <summary> /// Authentication event arguments /// </summary> /// <param name="requestUri"></param> /// <param name="realm"></param> /// <param name="authType"></param> internal AuthenticationArgs(Uri requestUri, string realm, Authentication authType) { this.Realm = realm; this.AuthType = authType; this.RequestUri = requestUri; this.ProcessAuthorization = true; }
public void EscapeValues() { var authentication = new Authentication(); var versionBuilder = new MyGet(authentication); var message = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##myget[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", message[0]); }
public void TestInitialize() { _testTarget = new Authentication(); _sucessfulAuthenticationRequests = new TestAuthenticationRequests(); _testTarget.AuthenticationRequestInterface = _sucessfulAuthenticationRequests; }
public static VersionVariables GetVersion(string directory, Authentication authentication, bool noFetch, IFileSystem fileSystem) { var gitDir = GitDirFinder.TreeWalkForDotGitDir(directory); using (var repo = RepositoryLoader.GetRepo(gitDir)) { var ticks = DirectoryDateFinder.GetLastDirectoryWrite(directory); var key = string.Format("{0}:{1}:{2}", repo.Head.CanonicalName, repo.Head.Tip.Sha, ticks); CachedVersion result; if (versionCacheVersions.TryGetValue(key, out result)) { if (result.Timestamp != ticks) { Logger.WriteInfo("Change detected. flushing cache."); result.VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null); } return result.VersionVariables; } Logger.WriteInfo("Version not in cache. Calculating version."); return (versionCacheVersions[key] = new CachedVersion { VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null), Timestamp = ticks }).VersionVariables; } }
public void Develop_branch() { var authentication = new Authentication(); var versionBuilder = new MyGet(authentication); var message = versionBuilder.GenerateSetVersionMessage("0.0.0-Unstable4"); Assert.AreEqual(null, message); }
public void Develop_branch() { var authentication = new Authentication(); var versionBuilder = new TeamCity(authentication); var tcVersion = versionBuilder.GenerateSetVersionMessage("0.0.0-Unstable4"); Assert.AreEqual("##teamcity[buildNumber '0.0.0-Unstable4']", tcVersion); }
public static bool TryGetVersion(string directory, out SemanticVersion versionAndBranch) { var gitDirectory = GitDirFinder.TreeWalkForGitDir(directory); if (string.IsNullOrEmpty(gitDirectory)) { var message = "No .git directory found in provided solution path. This means the assembly may not be versioned correctly. " + "To fix this warning either clone the repository using git or remove the `GitVersionTask` nuget package. " + "To temporarily work around this issue add a AssemblyInfo.cs with an appropriate `AssemblyVersionAttribute`. " + "If it is detected that this build is occurring on a CI server an error may be thrown."; Logger.WriteWarning(message); versionAndBranch = null; return false; } if (!processedDirectories.Contains(directory)) { processedDirectories.Add(directory); var authentication = new Authentication(); foreach (var buildServer in BuildServerList.GetApplicableBuildServers(authentication)) { Logger.WriteInfo(string.Format("Executing PerformPreProcessingSteps for '{0}'.", buildServer.GetType().Name)); buildServer.PerformPreProcessingSteps(gitDirectory); } } versionAndBranch = VersionCache.GetVersion(gitDirectory); return true; }
public virtual Authentication Build() { Support.LogMethodEntry(); Authentication result = new Authentication(AuthenticationMethod.EMAIL); Support.LogMethodExit(result); return result; }
public void GenerateBuildVersion() { var authentication = new Authentication(); var versionBuilder = new ContinuaCi(authentication); var continuaCiVersion = versionBuilder.GenerateSetVersionMessage("0.0.0-Beta4.7"); Assert.AreEqual("@@continua[setBuildVersion value='0.0.0-Beta4.7']", continuaCiVersion); }
public void BuildNumber() { var authentication = new Authentication(); var versionBuilder = new MyGet(authentication); var message = versionBuilder.GenerateSetParameterMessage("LegacySemVerPadded", "0.8.0-unstable568"); Assert.AreEqual("##myget[buildNumber '0.8.0-unstable568']", message[1]); }
public void CreateCustomMonitor() { authentication = new Authentication(apiKey: MonitisAccountInformation.ApiKey, secretKey: MonitisAccountInformation.SekretKey); customMonitor = new CustomMonitor(); customMonitor.SetAuthenticationParams(authentication); agent = new CustomUserAgent(); agent.SetAuthenticationParams(authentication); var a1 = agent.AddAgent("TestAgent1" + DateTime.Now.Ticks.ToString(), "internal", new JObject(), 100000, OutputType.JSON); _agentID = JObject.Parse(a1.Content).Value<int>("data"); customMonitor = new CustomMonitor(); customMonitor.SetAuthenticationParams(authentication); MonitorParameter param = new MonitorParameter("param1", "param1d", "val", DataType.String, false); MonResultParameter resParam = new MonResultParameter("MonResparam1", "MonResparam1d", "MonResval", DataType.String); MonResultParameter resAddParam = new MonResultParameter("MonAddResparam1", "MonAddResparam1d", "MonAddResval", DataType.String); var s = customMonitor.AddMonitor(_agentID, TestCustomMonitorName + DateTime.Now.Ticks.ToString(), "Test", "internal", new List<MonitorParameter>() { param }, new List<MonResultParameter>() { resParam }, new List<MonResultParameter>() { resAddParam }); _customMonitorID = JObject.Parse(s.Content).Value<int>("data"); GetTestMonitor(); }
public override Authentication Build() { Asserts.NotEmptyOrNull (phoneNumber, "phoneNumber"); Authentication result = new Authentication(phoneNumber); return result; }
public MatchingService() { dbContext = new ShowMeAroundContext(); userDA = new UserDA(); provider = new MatchingProvider(); auth = new Authentication(); }
public void SignInRedirect() { // Create an instance of Yahoo.Authentication Yahoo.Authentication auth = new Authentication("myappid", "mysharedsecret"); // Redirect the user to the use sign-in page Response.Redirect(auth.GetUserLogOnAddress().ToString()); }
/// <summary> /// WebDAV Http Module /// </summary> /// <param name="sourceAssembly"> /// Assembly containing the base class implementations /// </param> /// <param name="moduleAuthentication"> /// Authentication to use during requests /// </param> public WebDAVModule(Assembly sourceAssembly, Authentication moduleAuthentication) { this.ModuleAuthentication = moduleAuthentication; this.WebDavProcessor = new WebDavProcessor(sourceAssembly); //Set the default this.DebugFilePath = Settings.Default.WebDAVDebugOutputFilePath; }
public UserService() { userDA = new UserDA(); sessionDA = new SessionDA(); auth = new Authentication(); interestDA = new InterestDA(); languageDA = new LanguageDA(); }
public override Authentication Build() { Support.LogMethodEntry(); Asserts.NotEmptyOrNull (phoneNumber, "phoneNumber"); Authentication result = new Authentication(phoneNumber); Support.LogMethodExit(result); return result; }
public void Authenticate_Valid_XML_ReturnsTrue() { var authentication = new Authentication(); authentication.Authenticate(MonitisAccountInformation.Login, MonitisAccountInformation.Password, OutputType.XML); Assert.IsTrue(( MonitisAccountInformation.ApiKey == authentication.apiKey&& MonitisAccountInformation.SekretKey == authentication.secretKey&& !string.IsNullOrEmpty(authentication.authToken)), "Authenticate (XML output) returns invalid value."); }
/// <summary> /// Constructor /// </summary> /// <param name="useLogicalNameReferencing">Is Logical or short name referencing used.</param> /// <param name="clientAddress">Client address. Default is 16 (0x10)</param> /// <param name="serverAddress">Server ID. Default is 1.</param> /// <param name="authentication">Authentication type. Default is None</param> /// <param name="password">Password if authentication is used.</param> /// <param name="interfaceType">Interface type. Default is general.</param> public GXDLMSSecureClient(bool useLogicalNameReferencing, int clientAddress, int serverAddress, Authentication authentication, string password, InterfaceType interfaceType) : base(useLogicalNameReferencing, clientAddress, serverAddress, authentication, password, interfaceType) { Ciphering = new GXCiphering(ASCIIEncoding.ASCII.GetBytes("ABCDEFGH")); Settings.Cipher = Ciphering; }
public RestController(string strUserAgent = "BauRest", int intTimeOut = 20000, Authentication.IAuthenticator objAuthenticator = null) { // Asigna las propiedades UserAgent = strUserAgent; TimeOut = intTimeOut; Authenticator = objAuthenticator; // Inicializa los objetos Proxy = new Proxies.ProxyData(null, null, null, true); }
public void Should_Lock_User_If_Makes_Three_Invalid_Login_Attempts() { Authentication authentication = new Authentication(new UserValidator()); authentication.Login("username", "invalidpassword"); authentication.Login("username", "invalidpassword"); authentication.Login("username", "invalidpassword"); Assert.That(authentication.Login("username", "password"), Is.False); }
public WiFi(string SSID, string password, Authentication authenticationMode, bool isHiddenSSID = false) { this.SSID = escapeInput(SSID); this.SSID = isHexStyle(this.SSID) ? "\"" + this.SSID + "\"" : this.SSID; this.password = escapeInput(password); this.password = isHexStyle(this.password) ? "\"" + this.password + "\"" : this.password; this.authenticationMode = authenticationMode.ToString(); this.isHiddenSSID = isHiddenSSID; }
static void Main(string[] args) { Select select = new Select(); Authentication auth = new Authentication(); auth.version = "1.1"; // Specify which Select API Version (1.0 or 1.1) PropertyFile rb = PropertyFile.getBundle("Environment"); select.Url = rb.get("soap_url"); auth.login = rb.get("soap_login"); auth.password = rb.get("soap_password"); // ProdTest //select.Url = "https://soap.prodtest.sj.vindicia.com/v1.0/soap.pl"; //select.Url = "https://soap.prodtest.sj.vindicia.com/soap.pl"; //auth.login = "******"; //auth.password = ""; // Staging: //select.Url = https://soap.staging.sj.vindicia.com/soap.pl //auth.login = xxx_soap //auth.password = ""; // Production: //select.Url = https://soap.vindicia.com/soap.pl //auth.login = xxx_soap //auth.password = ""; Console.WriteLine("soapVersion=" + SEL001BillSelect.getSelectVersion(auth)); Console.WriteLine(); Console.WriteLine("Using version=" + auth.version); Console.WriteLine("soapURL=" + select.Url); Console.WriteLine("soapLogin="******"FAILED" + DateTime.Now.DayOfYear + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; string soapId = bill.run(select, auth, startMerchantTransactionId); Console.WriteLine("billTransactions soapId=" + soapId + "\n"); } if (bFetch) { SEL002FetchSelect.run(select, auth); Console.WriteLine("fetchBillingResults completed.\n"); } Console.ReadLine(); }
/// <summary> /// Fetch an unathorized request token for an API account /// </summary> public AuthenticationToken GetToken(Authentication authentication) { var parameters = new SortedDictionary<string, string>(); ApiHelper.AddRequiredParams(parameters, GetTokenMethodName, authentication, false); var navigator = RestApi.SendGetRequest(ApiHelper.LastFmWebServiceRootUrl, parameters); ApiHelper.CheckLastFmStatus(navigator); return new AuthenticationToken(ApiHelper.SelectSingleNode(navigator, AuthGetTokenXPath).Value); }
public Authentication populateAttributes(Authentication authentication, Credentials credentials) { string credentialsClass = credentials.GetType().FullName; string authenticationMethod = this.authenticationMethods.First(x => x.Key == credentialsClass).Value; authentication.getAttributes().Add(ATTRIBUTE_AUTHENTICATION_METHOD, authenticationMethod); return authentication; }
public override Authentication Build() { if (QuestionProvided () && challenges.Count == 0) { throw new EslException ("Question challenge was provided with no answer",null); } Authentication result = new Authentication(challenges); return result; }
private void CreateCustomUserAgent() { authentication = new Authentication(apiKey: MonitisAccountInformation.ApiKey, secretKey: MonitisAccountInformation.SekretKey); _agent = new CustomUserAgent(); _agent.SetAuthenticationParams(authentication); var a1 = _agent.AddAgent("agent" + DateTime.Now.Ticks.ToString(), "internal", new JObject(), 100000, OutputType.JSON); _agentID = JObject.Parse(a1.Content).Value<int>("data"); }
public override Authentication Build() { Support.LogMethodEntry(); if (QuestionProvided () && challenges.Count == 0) { throw new EslException ("Question challenge was provided with no answer"); } Authentication result = new Authentication(challenges); Support.LogMethodExit(result); return result; }
public static void GetUserCredentials() { // Create an instance of Yahoo.Authentication Yahoo.Authentication auth = new Authentication("myappid", "mysharedsecret"); // You must set the token before calling UpdateCredentials auth.Token = "storedusertoken"; // Attempt to get user credentials auth.UpdateCredentials(); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } UserProfile user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); // FIX var info = await Authentication.GetExternalLoginInfoAsync(); var username = info.Email ?? (info.DefaultUserName + "@vk.com"); user = new UserProfile { Email = username, UserName = info.DefaultUserName }; var result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return(GetErrorResult(result)); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return(GetErrorResult(result)); } } return(Ok()); }
public static async Task <bool> EditColumnsAsync(ITableTemplate template, Authentication authentication) { var columnCount = template.Dispatcher.Invoke(() => template.Count); var dataTypes = template.Dispatcher.Invoke(() => template.SelectableTypes); var columnList = new List <JsonColumnInfos.ItemInfo>(columnCount); var idToColumn = new Dictionary <Guid, ITableColumn>(columnCount); template.Dispatcher.Invoke(() => { foreach (var item in template) { var column = new JsonColumnInfos.ItemInfo() { ID = Guid.NewGuid(), Name = item.Name, IsKey = item.IsKey, DataType = item.DataType, Comment = item.Comment, IsUnique = item.IsUnique, AutoIncrement = item.AutoIncrement, DefaultValue = item.DefaultValue, Tags = (string)item.Tags, IsReadOnly = item.IsReadOnly, DisallowNull = !item.AllowNull, }; idToColumn.Add(column.ID, item); columnList.Add(column); } }); var schema = JsonSchemaUtility.CreateSchema(typeof(JsonColumnInfos)); var itemsSchema = schema.Properties[nameof(JsonColumnInfos.Items)]; var itemSchema = itemsSchema.Items.First(); var dataTypeSchema = itemSchema.Properties[nameof(JsonColumnInfos.ItemInfo.DataType)]; dataTypeSchema.SetEnums(dataTypes); var tagSchema = itemSchema.Properties[nameof(JsonColumnInfos.ItemInfo.Tags)]; tagSchema.SetEnums(TagInfoUtility.Names); var columns = new JsonColumnInfos() { Items = columnList.ToArray() }; using (var editor = new JsonEditorHost(columns, schema)) { if (editor.Execute() == false) { return(false); } columns = editor.Read <JsonColumnInfos>(); } //template.Dispatcher.Invoke(() => //{ foreach (var item in idToColumn.Keys.ToArray()) { if (columns.Items.Any(i => i.ID == item) == false) { var column = idToColumn[item]; await column.DeleteAsync(authentication); idToColumn.Remove(item); } } for (var i = 0; i < columns.Items.Length; i++) { var item = columns.Items[i]; if (item.ID == Guid.Empty) { var column = await template.AddNewAsync(authentication); item = await InitializeFieldsAsync(authentication, item, column); await template.EndNewAsync(authentication, column); item.ID = Guid.NewGuid(); idToColumn.Add(item.ID, column); columns.Items[i] = item; } else if (idToColumn.ContainsKey(item.ID) == true) { var column = idToColumn[item.ID]; await SetFieldsAsync(authentication, item, column); } else { throw new InvalidOperationException($"{item.ID} is not existed column."); } } for (var i = 0; i < columns.Items.Length; i++) { var item = columns.Items[i]; var column = idToColumn[item.ID]; await column.SetIndexAsync(authentication, i); } //}); return(true); }
public static Task AddColumnAsync(this ITableTemplate template, Authentication authentication, string name, string typeName) { return(AddColumnAsync(template, authentication, name, typeName, string.Empty)); }
public IHttpActionResult Post([FromBody] CreateIndividualModel model) { if (model.IsMalaysian) { ModelState.Remove("model.PassportNo"); ModelState.Remove("model.CitizenshipId"); ModelState.Remove("model.PostCodeNonMalaysian"); ModelState.Remove("model.State"); } else { ModelState.Remove("model.ICNo"); ModelState.Remove("model.PostCodeMalaysian"); ModelState.Remove("model.StateId"); } if (ModelState.IsValid) { var countryCode = db.Country.Where(c => c.Id == model.CountryId && c.Display).FirstOrDefault(); if (countryCode == null) { return(InternalServerError()); } var password = "******"; if (FEPHelperMethod.CurrentSystemMode() != SystemMode.Development) { password = Authentication.RandomString(10, true); } Authentication.GeneratePassword(password); var account = new UserAccount { LoginId = model.Email, IsEnable = false, HashPassword = Authentication.HashPassword, Salt = Authentication.Salt, LoginAttempt = 0 }; var individual = new IndividualProfile { IsMalaysian = model.IsMalaysian, CitizenshipId = model.CitizenshipId, Address1 = model.Address1, Address2 = model.Address2, PostCode = model.IsMalaysian ? model.PostCodeMalaysian : model.PostCodeNonMalaysian, City = model.City, StateName = model.State, StateId = model.StateId, CountryId = model.CountryId }; var user = new User { UserType = UserType.Individual, Name = model.Name, Email = model.Email, ICNo = model.IsMalaysian ? model.ICNo : model.PassportNo, MobileNo = model.MobileNo, CountryCode = countryCode.CountryCode1, Display = true, CreatedBy = null, CreatedDate = DateTime.Now, UserAccount = account, IndividualProfile = individual }; foreach (var roleid in model.RoleIds) { var userrole = new UserRole { RoleId = roleid, UserAccount = account, }; db.UserRole.Add(userrole); } db.User.Add(user); ActivateAccount activateaccount = new ActivateAccount { UID = Authentication.RandomString(50, true),//random alphanumeric UserId = user.Id, CreatedDate = DateTime.Now, IsActivate = false }; db.ActivateAccount.Add(activateaccount); db.SaveChanges(); return(Ok(new { UserId = user.Id, Password = password, UID = activateaccount.UID })); } return(BadRequest(ModelState)); }
public CompanyClient(Authentication authentication) : base(INTERCOM_API_BASE_URL, COMPANIES_RESOURCE, authentication) { }
private bool HandleWorldFile(RequestMethod method, HttpRequestEventArgs args, Authentication auth, World world) { //If it is a get, then return the file if (AllowDownloads && method == RequestMethod.Get) { //Trigger a auth request auth.RecordAction("world:download"); args.Response.WriteFile(world.GetAbsolutePath(API.Starwatch.Server)); return(true); } //If it is a post, then upload the file (if allowed) if (AllowUploads && method == RequestMethod.Post) { //Make sure we have permission if (auth.AuthLevel < AuthLevel.SuperBot) { args.Response.WriteRest(RestStatus.Forbidden, "Only super-bot or super-users may upload world files."); return(true); } //Make sure we have a body if (!args.Request.HasEntityBody) { args.Response.WriteRest(RestStatus.BadRequest, "Request has no body."); return(true); } //Trigger a auth request auth.RecordAction("world:upload"); //Make sure its a valid multipart var multipart = args.Request.ReadMultipart(); if (!multipart.Success) { args.Response.WriteRest(RestStatus.BadRequest, "Uploaded multi-part data was invalid."); return(true); } //Make sure we start with the header if (!multipart.Content.Take(WORLD_MAGICK.Length).SequenceEqual(WORLD_MAGICK)) { args.Response.WriteRest(RestStatus.BadRequest, "Uploaded file is not a world file."); return(true); } //Make sure the world isn't loaded if (API.Starwatch.Server.IsRunning && API.Starwatch.Server.Connections.GetCopiedPlayersEnumerable().Any(p => (p.Location?.Equals(world)).GetValueOrDefault(false))) { args.Response.WriteRest(RestStatus.BadRequest, "World is in use."); return(true); } //World is loaded, its passed all our checks... I guess finally upload it File.WriteAllBytes(world.GetAbsolutePath(API.Starwatch.Server), multipart.Content); //Tell the world to delete its shit if (world is CelestialWorld celestial) { celestial.DeleteDetailsAsync(API.Starwatch.Server).Wait(); } //Return the json, fully loaded return(HandleWorldJson(RequestMethod.Get, args, auth, world)); } if (AllowDeletion && method == RequestMethod.Delete) { //Make sure we have permission if (auth.AuthLevel < AuthLevel.SuperBot) { args.Response.WriteRest(RestStatus.Forbidden, "Only super-bot or super-users may delete world files."); return(true); } //Make sure the world isn't loaded if (API.Starwatch.Server.IsRunning && API.Starwatch.Server.Connections.GetCopiedPlayersEnumerable().Any(p => (p.Location?.Equals(world)).GetValueOrDefault(false))) { args.Response.WriteRest(RestStatus.BadRequest, "World is in use."); return(true); } //Trigger a auth request auth.RecordAction("world:delete"); //Delete the world File.Delete(world.GetAbsolutePath(API.Starwatch.Server)); //Make sure the json exists, if it does delete that too if (File.Exists(world.GetAbsoluteJsonPath(API.Starwatch.Server))) { File.Delete(world.GetAbsoluteJsonPath(API.Starwatch.Server)); } } //Bad Method args.Response.WriteRest(RestStatus.BadMethod, "Bad Method"); return(true); }
public bool IsAvailableForUser(Guid itemId, Guid @for) { var id = itemId.ToString(); var result = false; var tenant = TenantManager.GetCurrentTenant(); var dic = WebItemSecurityCache.GetOrInsert(tenant.TenantId); if (dic != null) { lock (dic) { if (dic.ContainsKey(id + @for)) { return dic[id + @for]; } } } // can read or administrator var securityObj = WebItemSecurityObject.Create(id, WebItemManager); if (CoreBaseSettings.Personal && securityObj.WebItemId != WebItemManager.DocumentsProductID) { // only files visible in your-docs portal result = false; } else { var webitem = WebItemManager[securityObj.WebItemId]; if (webitem != null) { if ((webitem.ID == WebItemManager.CRMProductID || webitem.ID == WebItemManager.PeopleProductID || webitem.ID == WebItemManager.BirthdaysProductID || webitem.ID == WebItemManager.MailProductID) && UserManager.GetUsers(@for).IsVisitor(UserManager)) { // hack: crm, people, birtthday and mail products not visible for collaborators result = false; } else if ((webitem.ID == WebItemManager.CalendarProductID || webitem.ID == WebItemManager.TalkProductID) && UserManager.GetUsers(@for).IsOutsider(UserManager)) { // hack: calendar and talk products not visible for outsider result = false; } else if (webitem is IModule) { result = PermissionContext.PermissionResolver.Check(Authentication.GetAccountByID(tenant.TenantId, @for), securityObj, null, Read) && IsAvailableForUser(WebItemManager.GetParentItemID(webitem.ID), @for); } else { var hasUsers = AuthorizationManager.GetAces(Guid.Empty, Read.ID, securityObj).Any(a => a.SubjectId != ASC.Core.Users.Constants.GroupEveryone.ID); result = PermissionContext.PermissionResolver.Check(Authentication.GetAccountByID(tenant.TenantId, @for), securityObj, null, Read) || (hasUsers && IsProductAdministrator(securityObj.WebItemId, @for)); } } else { result = false; } } dic = WebItemSecurityCache.Get(tenant.TenantId); if (dic != null) { lock (dic) { dic[id + @for] = result; } } return result; }
private void authenticationToolStripMenuItem_Click(object sender, EventArgs e) { Authentication auth = new Authentication(this); auth.Show(); }
protected override void ModifyConfiguration(Database.Config.InMemoryRavenConfiguration configuration) { configuration.AnonymousUserAccessMode = AnonymousUserAccessMode.None; Authentication.EnableOnce(); }
// Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration) { // Put first to avoid issues with OPTIONS when calling from Angular/Browser. app.UseCors("allReady"); // todo: in RC update we can read from a logging.json config file loggerFactory.AddConsole((category, level) => { if (category.StartsWith("Microsoft.")) { return(level >= LogLevel.Information); } return(true); }); if (env.IsDevelopment()) { // this will go to the VS output window loggerFactory.AddDebug((category, level) => { if (category.StartsWith("Microsoft.")) { return(level >= LogLevel.Information); } return(true); }); } app.UseSession(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else if (env.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Error/500"); } app.UseStatusCodePagesWithReExecute("/Error/{0}"); // Add static files to the request pipeline. app.UseStaticFiles(); app.UseRequestLocalization(); Authentication.ConfigureAuthentication(app, Configuration); //call Migrate here to force the creation of the AllReady database so Hangfire can create its schema under it if (!env.IsProduction()) { context.Database.Migrate(); } //Hangfire app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangireDashboardAuthorizationFilter() } }); app.UseHangfireServer(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Add sample data and test admin accounts if specified in Config.Json. // for production applications, this should either be set to false or deleted. if (Configuration["SampleData:InsertSampleData"] == "true") { sampleData.InsertTestData(); } if (Configuration["SampleData:InsertTestUsers"] == "true") { await sampleData.CreateAdminUser(); } }
public override int GetHashCode() { return(Type.GetHashCode() ^ Hostname.GetHashCode() ^ Port.GetHashCode() ^ SocketType.GetHashCode() ^ Username.GetHashCode() ^ Authentication.GetHashCode()); }
public IHttpActionResult Logout() { Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return(Ok()); }
public bool HandleRequest(RequestMethod method, HttpRequestEventArgs args, Authentication auth) { //This isnt a auth request if (args.Request.Url.Segments.Length < 3) { return(false); } if (args.Request.Url.Segments[1] != "universe/") { return(false); } if (args.Request.Url.Segments[2] != "world/") { return(false); } //Admin users only. Bots are forbidden. if (auth.AuthLevel < AuthLevel.Admin) { args.Response.StatusCode = (int)HttpStatusCode.Forbidden; args.Response.Close(); return(true); } //Get the world part string whereami = args.Request.Url.Segments[3]; //Strip the extension string extension = Path.GetExtension(whereami); if (extension.Equals(".json")) { whereami = Path.GetFileNameWithoutExtension(whereami); } //Get the world var world = World.Parse(whereami); if (world == null) { args.Response.WriteRest(new RestResponse(RestStatus.BadRequest, msg: "World is invalid format.")); return(true); } //Make sure it has a file if (string.IsNullOrWhiteSpace(world.Filename)) { args.Response.WriteRest(new RestResponse(RestStatus.BadRequest, msg: "World does nto have a file. It is actually a " + world.GetType().FullName)); return(true); } //Switch the extension switch (extension) { default: case ".json": return(HandleWorldJson(method, args, auth, world)); case ".system": case ".world": return(HandleWorldFile(method, args, auth, world)); } }
private void butLogin_Click(object sender, EventArgs e) { Userod userEntered; string password; try { bool useEcwAlgorithm = Programs.UsingEcwTightOrFullMode(); //ecw requires hash, but non-ecw requires actual password password = textPassword.Text; if (useEcwAlgorithm) { //It doesn't matter what Security.CurUser is when it is null because we are technically trying to set it for the first time. //It cannot be null before invoking HashPassword because middle needs it to NOT be null when creating the credentials for DtoGetString. if (Security.CurUser == null) { Security.CurUser = new Userod(); } password = Authentication.HashPasswordMD5(password, true); } string username = textUser.Text; #if DEBUG if (username == "") { username = "******"; password = "******"; } #endif //Set the PasswordTyped property prior to checking the credentials for Middle Tier. Security.PasswordTyped = password; userEntered = Userods.CheckUserAndPassword(username, password, useEcwAlgorithm); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } //successful login. Security.CurUser = userEntered; Security.IsUserLoggedIn = true; RemotingClient.HasLoginFailed = false; UserOdPrefs.SetThemeForUserIfNeeded(); if (RemotingClient.RemotingRole == RemotingRole.ClientWeb && string.IsNullOrEmpty(userEntered.PasswordHash) && string.IsNullOrEmpty(textPassword.Text)) { MsgBox.Show(this, "When using the web service, not allowed to log in with no password. A password should be added for this user."); if (!SecurityL.ChangePassword(true)) //Failed password update. { return; } } if (PrefC.GetBool(PrefName.PasswordsMustBeStrong) && PrefC.GetBool(PrefName.PasswordsWeakChangeToStrong) && Userods.IsPasswordStrong(textPassword.Text) != "") //Password is not strong { MsgBox.Show(this, "You must change your password to a strong password due to the current Security settings."); if (!SecurityL.ChangePassword(true)) //Failed password update. { return; } } SecurityLogs.MakeLogEntry(Permissions.UserLogOnOff, 0, "User: "******" has logged on."); DialogResult = DialogResult.OK; }
/// <summary> /// Read Invocation counter (frame counter) from the meter and update it. /// </summary> private void UpdateFrameCounter() { //Read frame counter if GeneralProtection is used. if (!string.IsNullOrEmpty(InvocationCounter) && Client.Ciphering != null && Client.Ciphering.Security != Security.None) { InitializeOpticalHead(); byte[] data; GXReplyData reply = new GXReplyData(); Client.ProposedConformance |= Conformance.GeneralProtection; int add = Client.ClientAddress; Authentication auth = Client.Authentication; Security security = Client.Ciphering.Security; byte[] challenge = Client.CtoSChallenge; try { Client.ClientAddress = 16; Client.Authentication = Authentication.None; Client.Ciphering.Security = Security.None; data = Client.SNRMRequest(); if (data != null) { if (Trace > TraceLevel.Info) { Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true)); } ReadDataBlock(data, reply); if (Trace == TraceLevel.Verbose) { Console.WriteLine("Parsing UA reply." + reply.ToString()); } //Has server accepted client. Client.ParseUAResponse(reply.Data); if (Trace > TraceLevel.Info) { Console.WriteLine("Parsing UA reply succeeded."); } } //Generate AARQ request. //Split requests to multiple packets if needed. //If password is used all data might not fit to one packet. foreach (byte[] it in Client.AARQRequest()) { if (Trace > TraceLevel.Info) { Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true)); } reply.Clear(); ReadDataBlock(it, reply); } if (Trace > TraceLevel.Info) { Console.WriteLine("Parsing AARE reply" + reply.ToString()); } try { //Parse reply. Client.ParseAAREResponse(reply.Data); reply.Clear(); GXDLMSData d = new GXDLMSData(InvocationCounter); Read(d, 2); Client.Ciphering.InvocationCounter = 1 + Convert.ToUInt32(d.Value); Console.WriteLine("Invocation counter: " + Convert.ToString(Client.Ciphering.InvocationCounter)); reply.Clear(); Disconnect(); } catch (Exception Ex) { Disconnect(); throw Ex; } } finally { Client.ClientAddress = add; Client.Authentication = auth; Client.Ciphering.Security = security; Client.CtoSChallenge = challenge; } } }
public SignerBuilder WithAuthentication(Authentication authentication) { this.authentication = authentication; return(this); }
private bool HandleWorldJson(RequestMethod method, HttpRequestEventArgs args, Authentication auth, World world) { //Make sure it has a file if (string.IsNullOrWhiteSpace(world.Filename)) { args.Response.WriteRest(RestStatus.BadRequest, "World does not have a file. It is actually a " + world.GetType().FullName); return(true); } //Wait for it to finish args.Response.KeepAlive = true; //Try to load the file var task = Task.Run(async() => { try { //Trigger a auth request auth.RecordAction("world:json:download"); //Export the json data. We won't allow overwrites so it wont even attempt to generate a new one. string filepath = await world.ExportJsonDataAsync(API.Starwatch.Server, overwrite: false); //Write the file that we get back args.Response.WriteFile(filepath); } catch (FileNotFoundException) { //We failed to find a file args.Response.WriteRest(RestStatus.ResourceNotFound, "The world hasn't generated a save file yet."); } }); //Wait for the task to finish task.Wait(); return(true); }