private void btnLogon_Click(object sender, EventArgs e) { GetComputerInfomation(); var service = new AuthenticationServices(); var filter = new AuthenticationFilter { UserName = txtUsername.Text, Password = txtPassword.Text }; var container = new ContainerAuthentication { Filter = filter }; var res = service.Retrieve(container); if (res.Status) { //USER = txtUsername.Text; var obj = (MEMBER_LOGON)res.ResultObj; var frm = new FrmMain(); LOGIN = txtUsername.Text; ROLE = res.ResultObj.ROLE; frm.User = txtUsername.Text; frm.Show(this); this.Hide(); OnClearScreen(); } else { MessageBox.Show(res.Message + res.ExceptionMessage); } }
public override Task <Authreply> Authenticate(AuthRequest request, ServerCallContext context) { Usuario usuarioRespuesta = new Usuario(); Authreply respuesta = new Authreply() { Response = false, Token = string.Empty }; if (AuthenticationServices.AuthenticateUserCredentials(request.Name, request.Password)) { UVFYSesion.AdministradorDeSesiones.AdministradorDeSesionesClient clienteDeSesiones = new AdministradorDeSesiones.AdministradorDeSesionesClient(ServicioDeSesiones); usuarioRespuesta = UsuarioDAO.CargarUsuarioPorCorreo(request.Name); TipoDeUsuario tipoDeUsuario = UsuarioDAO.ObtenerTipoDeUsuarioPorID(usuarioRespuesta.Id); UsuarioDeSesion usuarioDeSesion = new UsuarioDeSesion() { IdUsuario = usuarioRespuesta.Id }; SesionCreada sesionCreada = clienteDeSesiones.NuevaSesion(usuarioDeSesion); respuesta = new Authreply() { Response = true, Token = sesionCreada.IdSesion, IdUsuario = usuarioRespuesta.Id, TipoDeUsuario = (TipoDeUsuarioRespuesta)(int)tipoDeUsuario }; } return(Task.FromResult(respuesta)); }
public async Task WhenSendingMetricQueryThenTheResultsAreAsExpected() { // Authenticate (set real values in resourceIdentifier to run this test). var authenticationServices = new AuthenticationServices(); await authenticationServices.AuthenticateUserAsync(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); var resourceId = $"/subscriptions/{this.resourceIdentifier.SubscriptionId}/resourceGroups/{this.resourceIdentifier.ResourceGroupName}/providers/Microsoft.Storage/storageAccounts/{this.resourceIdentifier.ResourceName}/queueServices/default"; MetricClient client = new MetricClient(this.tracerMock.Object, credentialsFactory); var parameters = new QueryParameters() { StartTime = DateTime.UtcNow.Date.AddDays(-1), EndTime = DateTime.UtcNow.Date, Aggregations = new List <Aggregation> { Aggregation.Total }, MetricNames = new List <string>() { "QueueMessageCount" }, Interval = TimeSpan.FromMinutes(60) }; var metrics1 = (await client.GetResourceMetricsAsync(resourceId, parameters)).ToList(); var metrics2 = (await client.GetResourceMetricsAsync(this.resourceIdentifier, StorageServiceType.Queue, parameters)).ToList(); Assert.IsTrue(metrics1.Any() && metrics2.Any(), "Lists are not full with data"); Assert.IsTrue(metrics1.First().Timeseries.Any() && metrics2.First().Timeseries.Any(), "Metrics do not contain Time series"); Assert.IsTrue(metrics1[0].Timeseries[0].Data.Any() && metrics2[0].Timeseries[0].Data.Any(), "Time series are not full with data"); }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var auth = new AuthenticationServices(); var validationResult = auth.GlobalLogin(context.UserName, context.Password, "Web"); if (validationResult.Success) { var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); context.Validated(oAuthIdentity); var user = new UserServices().GetUser(context.UserName); oAuthIdentity.AddClaim(new Claim("user_id", user.Id.ToString())); //set different time spans here if (user.Membership == "Service Account") { context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60); } context.Validated(oAuthIdentity); } else { context.SetError("invalid_grant", validationResult.ErrorMessage); } return(Task.FromResult <object>(null)); }
private void button1_Click(object sender, EventArgs e) { var service = new AuthenticationServices(); var filter = new AuthenticationFilter { UserName = "******", Password = "******" }; var container = new ContainerAuthentication { Filter = filter }; var res = service.Retrieve(container); if (res.Status) { //USER = txtUsername.Text; var obj = (MEMBER_LOGON)res.ResultObj; var frm = new FrmMain(); LOGIN = obj.USERNAME; frm.User = obj.USERNAME; frm.Show(this); this.Hide(); OnClearScreen(); } else { MessageBox.Show(res.Message + res.ExceptionMessage); } }
public async Task sendemail(AuthenticationParameters model) { //var message = new MailMessage(); // var ToEmailId = AuthenticationServices.sendmail(model._user_code); //message.To.Add(new MailAddress(ToEmailId)); //message.From = new MailAddress("*****@*****.**"); //message.Subject = "Reset Password"; //message.Body = "Reset Password Link http://localhost:4200/ResetPassword?Usercode=" + model._user_code; //message.IsBodyHtml = true; //using (var smtp = new SmtpClient("smtp.gmail.com", 587)) //{ // smtp.Host = "10.2.202.42"; // smtp.Credentials = new NetworkCredential("*****@*****.**", "Mumbai@12345"); // smtp.EnableSsl = true; // //smtp.Send(message); // await smtp.SendMailAsync(message); // await Task.FromResult(0); //below code commented by Kirti on 16-06-2021 for reset password mail send functioanlity //var message = new MailMessage(); //message.To.Add(new MailAddress(ToEmailId)); //message.From = new MailAddress("*****@*****.**"); //message.Subject = "Reset Password"; //message.Body = "Reset Password Link http://localhost:4200/ResetPassword"; //message.IsBodyHtml = true; //using (var smtp = new SmtpClient("smtp.gmail.com", 587)) //{ // //smtp.Credentials = new NetworkCredential("*****@*****.**", "Mumbai@12345"); // smtp.EnableSsl = true; // //smtp.Send(message); // await smtp.SendMailAsync(message); // await Task.FromResult(0); ////} //} try { var ToEmailId = AuthenticationServices.sendmail(model._user_code); EmailSendingProperties EP = new EmailSendingProperties(); EP.SendTo = new List <EmailToCCParameters>(); EP.SendCC = new List <EmailToCCParameters>(); EP.Attachment = new List <EmailAttachmentParameters>(); EmailToCCParameters To = new EmailToCCParameters(); To.email_id = ToEmailId; EP.SendTo.Add(To); EP.subject = "Reset Password"; EP.body = "Reset Password Link http://localhost:4200/ResetPassword"; EmailSender ES = new EmailSender(); ES.sendEmail(EP); } catch (Exception ex) { throw ex; } }
public MainWindowViewModel(AlertsRepository alertsRepository, AuthenticationServices authenticationServices, SmartDetectorRunner smartDetectorRunner) { this.NumberOfAlertssFound = 0; alertsRepository.Alerts.CollectionChanged += (sender, args) => { this.NumberOfAlertssFound = args.NewItems.Count; }; this.UserName = authenticationServices.AuthenticationResult.UserInfo.GivenName; this.SmartDetectorRunner = smartDetectorRunner; }
/// <summary> /// Raises the <see cref="E:System.Windows.Application.Startup" /> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { ITracer stringTracer = new StringTracer(string.Empty); ITracer consoleTracer = new ConsoleTracer(string.Empty); var smartDetectorLoader = new SmartDetectorLoader(consoleTracer); // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection. // This option should be removed before launching version for customers (bug for tracking: 1177247) string smartDetectorPackagePath = e.Args.Length != 1 ? this.GetSmartDetectorPackagePath() : Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]); SmartDetectorPackage smartDetectorPackage; using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open)) { smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream, consoleTracer); } SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest; ISmartDetector detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage); // Authenticate the user to Active Directory var authenticationServices = new AuthenticationServices(); authenticationServices.AuthenticateUser(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); IAzureResourceManagerClient azureResourceManagerClient = new AzureResourceManagerClient(credentialsFactory, consoleTracer); // Create analysis service factory var queryRunInroProvider = new QueryRunInfoProvider(azureResourceManagerClient); var httpClientWrapper = new HttpClientWrapper(); IAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient, queryRunInroProvider); // Create state repository factory IStateRepositoryFactory stateRepositoryFactory = new InMemoryStateRepositoryFactory(); var smartDetectorRunner = new SmartDetectorRunner(detector, analysisServicesFactory, queryRunInroProvider, smartDetectorManifest, stateRepositoryFactory, smartDetectorManifest.Id, stringTracer); // Create a Unity container with all the required models and view models registrations Container = new UnityContainer(); Container .RegisterInstance(stringTracer) .RegisterInstance(new AlertsRepository()) .RegisterInstance(authenticationServices) .RegisterInstance(azureResourceManagerClient) .RegisterInstance(detector) .RegisterInstance(smartDetectorManifest) .RegisterInstance(analysisServicesFactory) .RegisterInstance(smartDetectorRunner) .RegisterInstance(stateRepositoryFactory); }
public bool CheckIsAuthorized(string _token, string user_code) { AuthenticationParameters _auth = new AuthenticationParameters(); _auth._user_code = user_code; _auth._token = _token; string result = AuthenticationServices.GetToken(_auth); if (result != "Authorised") { return(false); } return(true); }
public HttpResponseMessage VerifyLogin(AuthenticationParameters model) { if (model == null)// Incase Post Object Is Null or Not Match and Object value is null { result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "Object is null"); return(Request.CreateResponse(HttpStatusCode.BadRequest, result)); } if (ModelState.IsValid) { string password = AuthenticationServices.DecryptStringAES(model._SecretKey, model._password); model._password = password; List <AuthenticationDetailParameters> _AuthenticationDetailParameters = AuthenticationServices.GetAuthenticateUser(model); foreach (AuthenticationDetailParameters auth in _AuthenticationDetailParameters) { if (auth.status != "success") { result = new ReponseMessage(MsgNo: HttpStatusCode.Unauthorized.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: auth.status, Validation: ModelState.AllErrors()); return(Request.CreateResponse(HttpStatusCode.Unauthorized, result)); } else { LoginResponse login = new LoginResponse(); string key = Utility.SecretkeyGenerator.CreateToken(auth.user_code, auth.password); login.user.Api_Key = key; login.user.UserCode = auth.user_code; login.user.privilege_name = auth.privilege_name; login.user.role_name = auth.role_name; login.user.UserName = auth.UserName; login.user.UserId = auth.user_id; model._token = key; int tokeupdated = AuthenticationServices.UpdateToken(model); // result = new ReponseMessage(KeyName: "api_key", Code: key, MsgNo: HttpStatusCode.OK.ToCode(), MsgType: MsgTypeEnum.S.ToString(), Message: "Success"); //Provided username and password is incorrect return(Request.CreateResponse(HttpStatusCode.OK, login)); } } return(Request.CreateResponse(HttpStatusCode.OK, _AuthenticationDetailParameters)); } else { result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "", Validation: ModelState.AllErrors()); return(Request.CreateResponse(HttpStatusCode.BadRequest, result)); } return(null); }
private void btnok_Click(object sender, EventArgs e) { AuthenticationServices.AuthenticationUser(tbusername.Text, tbpassword.Text); if (AuthenticationServices.LoggedUser != null) { DialogResult = DialogResult.OK; return; } else { MessageBox.Show("Invalid user", "Authentication", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1); } }
public HttpResponseMessage ResetPassword(AuthenticationParameters model) { if (model == null)// Incase Post Object Is Null or Not Match and Object value is null { result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "Object is null"); return(Request.CreateResponse(HttpStatusCode.BadRequest, result)); } if (ModelState.IsValid) { string Authenticated = AuthenticationServices.ResetPassword(model); return(Request.CreateResponse(HttpStatusCode.OK, Authenticated)); } else { result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "", Validation: ModelState.AllErrors()); return(Request.CreateResponse(HttpStatusCode.BadRequest, result)); } return(null); }
public AsynchronousSocketListener() { this.connectionHandle = new ManualResetEvent(false); this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.Clients = new ConcurrentDictionary <Guid, Client>(); this.Players = new ConcurrentDictionary <Guid, PlayerDTO>(); this.Battles = new ConcurrentDictionary <Guid, BattleInfo>(); //this.BlockedIps = new ConcurrentDictionary<string, DateTime>(); this.Context = new SimpleWarsContext(); this.Auth = new AuthenticationServices(this); this.Game = new GameServices(this); this.Reader = new DefaultReader(this); this.Writer = new DefaultWriter(this); this.Responses = new PredefinedResponses(this); this.Parser = new DefaultParser(this); this.Buffers = new Buffers(BufferPoolSize, MaxBufferSize); this.PingByte = SerManager.SerializeWithLengthPrefix(Messages.Ping); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient <IEmailSender, EmailSender>(); var authService = new AuthenticationServices(null, null); authService.InitializeContext(services, Configuration); services.AddScoped <IAuthentication, AuthenticationServices>(); //Add persistence service services.AddScoped <IPersistenceContext, PersistenceContext>(); var dataService = services.BuildServiceProvider().GetService <IPersistenceContext>(); dataService.InitializeContext(services, Configuration); //Add Business Layer services.AddScoped <IBusinessLayer, BusinessLogic>(s => new BusinessLogic(dataService)); services.AddMvc(); }
public MainWindowViewModel(SignalsResultsRepository signalsResultsRepository, AuthenticationServices authenticationServices, SmartSignalRunner signalRunner) { this.NumberOfResultsFound = 0; signalsResultsRepository.Results.CollectionChanged += (sender, args) => { this.NumberOfResultsFound = args.NewItems.Count; }; this.UserName = authenticationServices.AuthenticationResult.UserInfo.GivenName; this.SignalRunner = signalRunner; }
/// <summary> /// Raises the <see cref="Application.Startup" /> event. /// </summary> /// <param name="e">A <see cref="StartupEventArgs" /> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { // Cleanup previous temp folders (that are at least 2 days old), and create a new temp folder FileSystemExtensions.CleanupTempFolders(TempSubFolderName, 48); tempFolder = FileSystemExtensions.CreateTempFolder(TempSubFolderName); NotificationService notificationService = new NotificationService(); ITracer consoleTracer = new ConsoleTracer(string.Empty); var smartDetectorLoader = new SmartDetectorLoader(tempFolder, consoleTracer); // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection. // This option should be removed before launching version for customers (bug for tracking: 1177247) string smartDetectorPackagePath = e.Args.Length != 1 ? GetSmartDetectorPackagePath() : Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]); SmartDetectorPackage smartDetectorPackage; using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open)) { smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream); } try { SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest; ISmartDetector detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage); // Authenticate the user to Active Directory IAuthenticationServices authenticationServices = new AuthenticationServices(); authenticationServices.AuthenticateUserAsync().Wait(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); IHttpClientWrapper httpClientWrapper = new HttpClientWrapper(); IExtendedAzureResourceManagerClient azureResourceManagerClient = new ExtendedAzureResourceManagerClient(httpClientWrapper, credentialsFactory, consoleTracer); // Create analysis service factory IInternalAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient); // Create state repository factory IStateRepositoryFactory stateRepositoryFactory = new EmulationStateRepositoryFactory(); // Load user settings var userSettings = UserSettings.LoadUserSettings(); // Create the detector runner IPageableLogArchive logArchive = new PageableLogArchive(smartDetectorManifest.Name); IEmulationSmartDetectorRunner smartDetectorRunner = new SmartDetectorRunner( detector, analysisServicesFactory, smartDetectorManifest, stateRepositoryFactory, azureResourceManagerClient, logArchive); // Create a Unity container with all the required models and view models registrations Container = new UnityContainer(); Container .RegisterInstance(notificationService) .RegisterInstance <ITracer>(consoleTracer) .RegisterInstance(new AlertsRepository()) .RegisterInstance(authenticationServices) .RegisterInstance(azureResourceManagerClient) .RegisterInstance(detector) .RegisterInstance(smartDetectorManifest) .RegisterInstance(analysisServicesFactory) .RegisterInstance(logArchive) .RegisterInstance(smartDetectorRunner) .RegisterInstance(stateRepositoryFactory) .RegisterInstance(userSettings); } catch (Exception exception) { var message = $"{exception.Message}. {Environment.NewLine}{exception.InnerException?.Message}"; MessageBox.Show(message); System.Diagnostics.Trace.WriteLine(message); Environment.Exit(1); } }
public bool DisconnectAuthAccount(AuthenticationServices authService, Guid userId) { try { new UserAuthenticationProfileService().DisconnectService(authService, userId, "Mobile"); return true; } catch(Exception) { return false; } }
static void Main(string[] args) { var users = new List <User>(); { users.Add(new User(userName: "******", passWord: "******", role: "Administrator")); users.Add(new User(userName: "******", passWord: "******", role: "Receptionist")); } var loginView = new LoginView(); var receptionistMainView = new ReceptionistMainView(); var adminMainMenu = new AdminMainMenu(); var adminAddUser = new AdminAddView(); var adminDeleteUser = new AdminDeleteView(); var manageUser = new ManageUserView(); var registerUser = new RegisterUser(); var printUser = new PrintUser(); var authentication = new AuthenticationServices(); var deleteUser = new DeleteUser(); string result; User onlineUser = null; do { result = loginView.Display(); if (result.ToUpper() == "Y") { Console.Clear(); onlineUser = authentication.Authenticate(loginView.Username, loginView.Password, users); if (onlineUser == null) { Console.Clear(); Console.WriteLine("Login failed, try again!"); Thread.Sleep(1000); } } }while (onlineUser == null); do { if (onlineUser.Role == "Receptionist") { result = receptionistMainView.Display(); switch (result) { case "D1": result = printUser.Display(); printUser.ListAllUsers(users); break; case "D2": Environment.Exit(0); break; default: Console.WriteLine("Wrong input, try again!"); Thread.Sleep(2000); break; } } else if (onlineUser.Role == "Administrator") { result = adminMainMenu.Display(); switch (result) { case "1": result = manageUser.Display(); if (result == "1") { adminAddUser.Display(); registerUser.AddNewUser(adminAddUser.UserName, adminAddUser.Password, adminAddUser.Role, users); } else if (result == "2") { adminDeleteUser.Display(); deleteUser.RemoveUser(users); } break; case "2": loginView.Display(); break; case "3": Environment.Exit(0); break; default: Console.WriteLine("Wrong input"); Thread.Sleep(2000); break; } } } while (onlineUser != null); }
private Guid CheckConnectedAccountUserExists(string userScreenName, AuthenticationServices authService, string token, string tokenSecret) { try { var userAuthService = new UserAuthenticationProfileService(); var userAuth = userAuthService.UserAuthorizationByServiceScreenNameAndPlatform(userScreenName, "Web", authService); if (userAuth != null) { string logInMethod = null; switch (authService) { case AuthenticationServices.TWITTER: userAuth.Token = token; userAuth.TokenSecret = tokenSecret; logInMethod = "Twitter"; break; case AuthenticationServices.FACEBOOK: userAuth.Token = token; logInMethod = "Facebook"; break; } userAuthService.Save(userAuth); var user = userAuth.Users.FirstOrDefault(); if (user != null) { //Record the Login var ut = new UserLoginTracking() { UserId = user.ID, LoginMethod = logInMethod, DateTime = DateTime.UtcNow, IPAddress = HttpContext.Request.UserHostAddress }; new UserLoginTrackingService().Save(ut); return user.ID; } } return Guid.Empty; } catch (Exception) { return Guid.Empty; } }
public UserAuthenticationProfile UserAuthorizationByService(AuthenticationServices serviceType) { return(GetData().Where(ua => ua.Service == serviceType.ToString()).FirstOrDefault()); }
public void DisconnectService(AuthenticationServices serviceType, Guid userId) { UserAuthenticationProfile profile = GetData().Where(p => p.UserID == userId && p.Service == serviceType.ToString()).FirstOrDefault(); GetRepository <UserAuthenticationProfile>().Delete(profile); }