public Stream UpdateAuthenticationSession(AuthenticationSession authenticationSessionForm) { BaseBusinessService <AuthenticationSession> businessService = (BaseBusinessService <AuthenticationSession>)BusinessFactory.Create(Keywords.UpdateAuthenticationSession); OperationResult result = businessService.Update(authenticationSessionForm); return(result.ToJsonStream()); }
public AuthenticationSessionCachedChange(MessageServer server, AuthenticationSession session) { Contract.Requires(session != null); Contract.Requires(server != null); Server = server; Session = session; }
public void Track(MessageServer server, AuthenticationSession toTrack) { Contract.Requires(toTrack != null); Contract.Requires(server != null); if (toTrack.NeverExpires()) return; ScheduleDecache(server, toTrack); }
public string GetLoginHtml(string clientID, AuthenticationSession session, string loginFile) { string htmlFile = loginFile; string content = System.IO.File.ReadAllText(htmlFile); content = content.Replace("{{AuthenticationSession}}", session.AuthenticationSessionString); content = content.Replace("{{ClientID}}", session.ClientID); return(content); }
public AuthenticationSession GenerateAuthenticationSession(string clientID) { AuthenticationSession session = new AuthenticationSession(); session.AuthenticationSessionString = StringUtility.GenerateRandom(10); session.ClientID = clientID; session.SessionCreatedDate = DateTime.Now; session.SessionExpiredDate = DateTime.Now.AddHours(1); return(session); }
private static AuthenticationSession GetAuthenticationSession(AuthenticationSessionRepository authenticationSessionRepository, DateTime now) { DateTime dateTime = new DateTime(2012, 12, 12); var account1 = TestHelper.AccountMock(); var accountRepository = new AccountRepository(); accountRepository.Add(account1); var authenticationSession = new AuthenticationSession(account1, "testToken" + now.Ticks, dateTime); authenticationSessionRepository.Add(authenticationSession); Assert.That(authenticationSession.Id != 0); return(authenticationSession); }
private static void ValidateUser(ValidateUserNamePasswordParams parameters) { AuthenticationProvider provider = new AuthenticationProvider(); provider.Initialize(parameters.Password); AuthenticateUserAction aua = new AuthenticateUserAction(); AuthenticateUserParams p = new AuthenticateUserParams(); p.UserName = parameters.UserName; p.Salt = provider.Salt; p.Data = provider.SessionData; p.Product = productName; p.NodeIdentity = ""; //TODO loose this p.TerminalIdentity = ""; //TODO loose this // Authenticate AuthenticateUserResultParams r = aua.Execute(p); if (!String.IsNullOrEmpty(r.Almid)) { throw new AlarmException(r.Almid, r.AlarmText1, null); } AuthenticationSession authenticationSession = provider.DecryptSession(r.SessionData); // Logon application LogonUserParams lp = new LogonUserParams(); lp.TerminalIdentity = ""; //TODO loose this lp.UserName = parameters.UserName; lp.SessionIdentity = authenticationSession.SessionId; LogonUserAction lua = new LogonUserAction(); LogonUserResultParams lr = lua.Execute(lp); if (!String.IsNullOrEmpty(lr.Almid)) { throw new AlarmException(lr.Almid, lr.AlarmText1, null); } }
public Stream HandleAuthorizationRequest(string clientID) { IAuthorizationBusinessService businessService = (IAuthorizationBusinessService)BusinessFactory.Create("Tools.OAuthServerManager.Authorization"); bool result = businessService.CheckClientID(clientID); if (result) { OperationResult accessTokenResult = CheckAccessTokenHeader(); if (accessTokenResult.Result) { return(accessTokenResult.ToJsonStream()); } AuthenticationSession session = businessService.GenerateAuthenticationSession(clientID); OperationResult res = businessService.SaveAuthenticationSession(session); string loginFile = ConfigurationManager.AppSettings["LoginFile"]; loginFile = HostingEnvironment.MapPath("~/" + loginFile); string html = businessService.GetLoginHtml(clientID, session, loginFile); string baseUrl = AppDomain.CurrentDomain.BaseDirectory; var baseAddress = "" + OperationContext.Current.Host.BaseAddresses[0].AbsoluteUri + ""; baseAddress = baseAddress.Replace("OAuthService.svc", ""); html = html.Replace("{baseurl}", baseAddress + "/Resources"); html = html.Replace("{authenticationSession}", session.AuthenticationSessionString); html = html.Replace("{url}", baseAddress + "/OAuthService.svc/oauth/login"); html = html.Replace("{clientID}", clientID); var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(html); writer.Flush(); stream.Position = 0; return(stream); } return(new OperationResult(false, "Client : " + clientID + " does not exist!").ToJsonStream()); }
public static void SetAuthenticationSession(this MessagePayload payload, AuthenticationSession toSet) { Contract.Requires(toSet != null); payload.RemoveHeader(typeof(AuthenticationSessionHeader)); payload.AddHeader(new AuthenticationSessionHeader(toSet)); }
public static ClientSession GetClientSession(AuthenticationSession authenticationSession, string clientPublicKey) { return(new ClientSession(authenticationSession, clientPublicKey)); }
static async Task Main(string[] args) { const string fn = "auth.json"; AuthenticatedDevice cDevice; // discover and auth if there's no file if (!File.Exists(fn)) { Console.WriteLine("Discovery starting..."); Console.WriteLine(); var devices = await DeviceDiscovery.Discover(); for (var index = 0; index < devices.Count; index++) { var device = devices[index]; Console.WriteLine($"[{index}] {device}"); } Console.Write("Pick device to auth:"); var line = Console.ReadLine(); // ReSharper disable once AssignNullToNotNullAttribute var pick = int.Parse(line); var authDev = devices[pick]; Console.WriteLine($"picked {authDev}"); Console.WriteLine("hold power for 5-7 seconds on device until light starts blinking then press enter to continue"); Console.ReadLine(); var asession = AuthenticationSession.CreateFromDiscovery(devices); var authedDev = await asession.Authenticate(authDev, "pc"); Console.WriteLine(authedDev); var content = asession.SerializeAuthenticatedDevices(); File.WriteAllText(fn, content); cDevice = authedDev; } else { Console.WriteLine("Loading pre-authed devices from file..."); Console.WriteLine(); var s = File.ReadAllText(fn); var psession = AuthenticationSession.RestoreFromFile(s); cDevice = psession.AuthenticatedDevices[0]; } Console.WriteLine("controlling device..."); Console.WriteLine(); Console.WriteLine(cDevice); Console.WriteLine(); var loop = true; var cs = new ControlSession(cDevice); while (loop) { Console.Write($"Q - exit; A - query on/off; W - turn on; S - turn off: "); var line = Console.ReadLine(); switch (line.ToUpper()) { case "Q": loop = false; break; case "A": Console.WriteLine(await cs.QueryOnOff()); break; case "W": await cs.SetOnOff(true); break; case "S": await cs.SetOnOff(false); break; } } Console.ReadLine(); }
/// <summary> /// Invokes the subscriber. /// </summary> /// <param name="msg">A reference to the subscribed message.</param> /// <param name="session">The current <see cref="VocollectSession"/> object.</param> /// <exception cref="WarehouseAdapterException"> /// </exception> /// <exception cref="MessageEngineException"> /// </exception> public override void Invoke(MultiPartMessage msg, VocollectSession session) { MultiPartMessage responseMsg = CreateResponseMessage(msg); responseMsg.Properties.Write("Interleave", 0); responseMsg.Properties.Write("ErrorCode", VocollectErrorCodeNoError); responseMsg.Properties.Write("Message", ""); try { using (TransactionScope transactionScope = new TransactionScope()) { /* Fetch user's language code */ MultiPartMessage langMsg = CreateRequestMessage("wlvoicepick", "get_user_languagecode", session); langMsg.Properties.Write("EMPID_I", msg.Properties.ReadAsString("Operator")); langMsg.Properties.Write("NLANGCOD_O", ""); CorrelationContext context; MessageEngine.Instance.TransmitRequestMessage(langMsg, langMsg.MessageId, out context); string languageCode = context.ResponseMessages[0].Properties.ReadAsString("NLANGCOD_O"); AuthenticationProvider provider = new AuthenticationProvider(); provider.Initialize(msg.Properties.ReadAsString("Password")); MultiPartMessage authMsg = CreateRequestMessage("wlvoicepick", "authenticate", session); authMsg.Properties.Write("EMPID_I", msg.Properties.ReadAsString("Operator")); authMsg.Properties.Write("SALT_I", provider.Salt); authMsg.Properties.Write("DATA_I", provider.SessionData); authMsg.Properties.Write("WHID_I", ""); authMsg.Properties.Write("COMPANY_ID_I", ""); authMsg.Properties.Write("PRODUCT_I", "VOICE"); authMsg.Properties.Write("TERID_I", msg.Properties.ReadAsString("SerialNumber")); authMsg.Properties.Write("SESSION_DATA_O", ""); authMsg.Properties.Write("ALMID_O", ""); authMsg.Properties.Write("ALMTXT1_O", ""); authMsg.Properties.Write("ALMTXT2_O", ""); authMsg.Properties.Write("ALMTXT3_O", ""); /* Set language code since we do not yet have a session */ authMsg.Metadata.Write("LanguageCode", languageCode); MessageEngine.Instance.TransmitRequestMessage(authMsg, authMsg.MessageId, out context); string sessionData = context.ResponseMessages[0].Properties.ReadAsString("SESSION_DATA_O"); AuthenticationSession authenticationSession = provider.DecryptSession(sessionData); MultiPartMessage whMsg = CreateRequestMessage("wlvoicepick", "logon", session); whMsg.Properties.Write("TERID_I", msg.Properties.ReadAsString("SerialNumber")); whMsg.Properties.Write("EMPID_I", msg.Properties.ReadAsString("Operator")); whMsg.Properties.Write("SESSIONID_I", authenticationSession.SessionId); whMsg.Properties.Write("WHID_O", ""); whMsg.Properties.Write("NLANGCOD_O", ""); whMsg.Properties.Write("ALMID_O", ""); /* Set language code since we do not yet have a session */ whMsg.Metadata.Write("LanguageCode", languageCode); MessageEngine.Instance.TransmitRequestMessage(whMsg, whMsg.MessageId, out context); //Create session object session = SessionManager.Instance.CreateSession(msg.Properties.ReadAsString("SerialNumber")); /* Clear session if already exists */ session.Clear(); //Set session variables session.Write("TERID", msg.Properties.ReadAsString("SerialNumber")); session.Write("WHID", context.ResponseMessages[0].Properties.Read("WHID_O")); session.Write("NLANGCOD", context.ResponseMessages[0].Properties.Read("NLANGCOD_O")); session.Write("EMPID", msg.Properties.ReadAsString("Operator")); session.Write("TUID", ""); session.Write("PBHEADID", ""); session.Write("PZID", ""); session.Write("PZGRPID", ""); session.Write("ITEID", ""); try { //Check if there is a temporarily stopped pick order available PrTaskLUTGetAssignment.RequestPickOrder(PickOrderHoldType.Temporarily, session); responseMsg.Properties.Write("ErrorCode", ErrorTempInterruptedPickOrderFound); } catch (WarehouseAdapterException ex) { if (ex.AlarmId != "PBHEAD030" && ex.AlarmId != "PBHEAD057") { throw; } } transactionScope.Complete(); } } catch (WarehouseAdapterException ex) { responseMsg.Properties.Write("ErrorCode", WarehouseAlarm); responseMsg.Properties.Write("Message", ex.Message); throw; } catch (Exception) { responseMsg.Properties.Write("ErrorCode", VocollectErrorCodeCritialError); responseMsg.Properties.Write("Message", GetCriticalErrorMessageText(msg)); throw; } finally { TransmitResponseMessage(responseMsg, session); } }
public OperationResult SaveAuthenticationSession(AuthenticationSession session) { Com.Wiseape.Framework.BaseBusinessService <AuthenticationSession> authenticationSession = (Com.Wiseape.Framework.BaseBusinessService <AuthenticationSession>)BusinessFactory.Create("Find.Tools.OAuthServerManager.AuthenticationSession"); return(authenticationSession.Add(session)); }
public IActionResult Login([FromBody] DTOs.LoginRequestDTO dto) { using (var transaction = DBSession.BeginTransaction()) { try { var person = DBSession.QueryOver <Person>().Where(x => x.Username == dto.Username).SingleOrDefault(); if (person == null) { return(Unauthorized()); } if (!PasswordHash.ValidatePassword(dto.Password, person.PasswordHash)) { if (person.EmailAddresses.Any()) { var model = new Email.Models.FailedAccountLoginEmailModel { FriendlyName = person.ToString() }; //Ok, so we have an email we can use to contact the person! Email.EmailInterface.CCEmailMessage .CreateDefault() .To(person.EmailAddresses.Select(x => new System.Net.Mail.MailAddress(x.Address, person.ToString()))) .Subject("Security Alert : Failed Login") .HTMLAlternateViewUsingTemplateFromEmbedded("CommandCentral.Email.Templates.FailedAccountLogin_HTML.html", model) .SendWithRetryAndFailure(TimeSpan.FromSeconds(1)); //Now we also need to add the event to client's account history. person.AccountHistory.Add(new AccountHistoryEvent { AccountHistoryEventType = ReferenceListHelper <AccountHistoryType> .Find("Failed Login"), EventTime = this.CallTime }); DBSession.Update(person); } transaction.Commit(); return(Unauthorized()); } //The client is who they claim to be so let's make them an authentication session. AuthenticationSession ses = new AuthenticationSession { Id = Guid.NewGuid(), IsActive = true, LastUsedTime = CallTime, LoginTime = CallTime, Person = person }; //Now insert it DBSession.Save(ses); //Also put the account history on the client. person.AccountHistory.Add(new AccountHistoryEvent { AccountHistoryEventType = ReferenceListHelper <AccountHistoryType> .Find("Login"), EventTime = CallTime }); Response.Headers.Add("sessionId", new Microsoft.Extensions.Primitives.StringValues(ses.Id.ToString())); transaction.Commit(); return(Ok()); } catch (Exception e) { LogException(e); transaction.Rollback(); return(StatusCode(500)); } } }
TimeSpan GetDecacheTime(AuthenticationSession toTrack) { return toTrack.ExpiresOn.Subtract(systemTime.GetCurrentDate()); }
static void ExpireSession(MessageServer server, AuthenticationSession toTrack) { Logger.Debug("Expiring authentication session {0}", toTrack.Id); Messenger.Send(new AuthenticationSessionExpired {Server = server, Session = toTrack}); }
void ScheduleDecache(MessageServer server, AuthenticationSession toTrack) { taskScheduler.ScheduleTask(GetDecacheTime(toTrack), () => ExpireSession(server, toTrack)); }
public ServerSession(MessageServer server, AuthenticationSession session) { Server = server; Session = session; }
public void Add(AuthenticationSession item) { _authenticationSessions.Add(item.Token, item); }
public AuthenticationSessionHeader(AuthenticationSession session) { Contract.Requires(session != null); Session = session; }
public bool TryGetByToken(string token, out AuthenticationSession result) { return(_authenticationSessions.TryGetValue(token, out result)); }