public void TestPersist() { Session s1 = new SessionBuilder().StartDefault("S1").Build(); Session s2 = new SessionBuilder().StartDefault("S2").Build(); Session s3 = new SessionBuilder().StartDefault("S3").Build(); var mockUnitOfWork = new Mock <IUnitOfWork>(); var mockRepository = new Mock <ISessionRepository>(); mockRepository.Setup(sm => sm.GetUnitOfWork()).Returns(mockUnitOfWork.Object); var manager = new SessionManager(mockRepository.Object); manager.AddSession(s1); manager.AddSession(s2); manager.AddSession(s3); manager.RemoveSession(s3); manager.CurrentSession = s1; manager.Persist(); mockUnitOfWork.Verify(uow => uow.RegisterSavedOrUpdated(It.Is <Session>(o => o.Equals(s1))), Times.Once()); mockUnitOfWork.Verify(uow => uow.RegisterSavedOrUpdated(It.Is <Session>(o => o.Equals(s2))), Times.Once()); mockUnitOfWork.Verify(uow => uow.RegisterRemoved(It.Is <Session>(o => o.Equals(s3))), Times.Once()); mockUnitOfWork.Verify(uow => uow.RegisterSavedOrUpdated(It.Is <CurrentSessionInfo>(o => o.CurrentSessionName.Equals(s1.Name))), Times.Once()); mockUnitOfWork.Verify(uow => uow.Commit(), Times.Once()); }
public void TestGetSessionNames() { var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); Session newSession = new SessionBuilder().StartDefault("S1").Build(); manager.AddSession(newSession); newSession = new SessionBuilder().StartDefault("S2").Build(); manager.AddSession(newSession); newSession = new SessionBuilder().StartDefault("S3").Build(); manager.AddSession(newSession); var names = manager.GetSessionNames(); const int QTY_SESSIONS_ADDED = 3; Assert.AreEqual(QTY_SESSIONS_ADDED, names.Count()); Assert.AreEqual(1, names.Where(n => n.Equals("S1")).Count()); Assert.AreEqual(1, names.Where(n => n.Equals("S2")).Count()); Assert.AreEqual(1, names.Where(n => n.Equals("S3")).Count()); }
// Test adding a session twice should only really add it once // It should act like a set public void AddASessionTwice() { SessionManager sessionManager = new SessionManager(); Guid sessionId = new Guid(); Assert.IsTrue(sessionManager.AddSession(sessionId, mTestServerAccount)); Assert.IsTrue(sessionManager.ContainsSession(sessionId)); // This should return false because it has already been added Assert.IsFalse(sessionManager.AddSession(sessionId, mTestServerAccount)); Assert.IsTrue(sessionManager.ContainsSession(sessionId)); Assert.IsTrue(sessionManager.RemoveSession(sessionId)); // Now it should be gone, if it only got added once Assert.IsFalse(sessionManager.ContainsSession(sessionId)); }
public void TestAddDuplicatedSession() { const string DUPLICATED_NAME = "S1"; var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); Session newSession = new SessionBuilder().StartDefault(DUPLICATED_NAME).Build(); manager.AddSession(newSession); Session newSession2 = new SessionBuilder().StartDefault(DUPLICATED_NAME).Build(); manager.AddSession(newSession2); }
public void TestGetSession() { var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); Session otherSession = new SessionBuilder().StartDefault("S1").Build(); Session expectedSession = new SessionBuilder().StartDefault("S2").Build(); manager.AddSession(otherSession); manager.AddSession(expectedSession); var actualSession = manager.GetSession(expectedSession.Name); Assert.AreSame(expectedSession, actualSession); }
public void TestAddNullSession() { var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); manager.AddSession(null); }
private void Server_ClientEstablishing(IPEndPoint ep) { string host = ep.Address.ToString(); int port = ep.Port; sessions.AddSession(host, port); }
public void TestLoggingIn() { var sessionManager = new SessionManager(); var afterLogIn = Observable.FromEventPattern <SessionEventArgs>( h => sessionManager.AfterLogin += h, h => sessionManager.AfterLogin -= h) .Select(x => x.EventArgs.UserId); var beforeLogOff = Observable.FromEventPattern <SessionEventArgs>( h => sessionManager.BeforeLogoff += h, h => sessionManager.BeforeLogoff -= h) .Select(x => x.EventArgs.UserId); var loggedIn = afterLogIn.GroupByUntil( userId => userId, login => beforeLogOff.Where(y => y == login.Key)); Func <IGroupedObservable <int, int>, IObservable <string> > whileLoggedIn = login => Observable.Using( () => sessionManager.AddSession(new Session(login.Key)), session => Observable.FromEventPattern( h => session.SomeEvent += h, h => session.SomeEvent -= h) .Select(x => "User " + login.Key + " had SomeEvent!") .TakeUntil(login.LastAsync())); // Single non-terminating stream that captures // all events occuring during any login var loggedInEvents = loggedIn.SelectMany(whileLoggedIn); loggedInEvents.Subscribe(Console.WriteLine); sessionManager.Login(1); sessionManager.Sessions[1].RaiseSomeEvent(); sessionManager.Login(2); sessionManager.Sessions[1].RaiseSomeEvent(); sessionManager.Sessions[2].RaiseSomeEvent(); sessionManager.Logoff(2); sessionManager.Logoff(1); }
public void SessionManagerTest() { System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); //initialize Logger Logger.InitializeLogger(LogManager.GetLogger(typeof(CoreTest))); //initialilize maps ServerManager.Initialize(); //register mappings for items DAOFactory.InventoryDAO.RegisterMapping(typeof(SpecialistInstance)); DAOFactory.InventoryDAO.RegisterMapping(typeof(WearableInstance)); DAOFactory.InventoryDAO.RegisterMapping(typeof(UsableInstance)); DAOFactory.InventoryDAO.InitializeMapper(typeof(ItemInstance)); //initialize PacketSerialization PacketFactory.Initialize <WalkPacket>(); //initialize new manager SessionManager manager = new SessionManager(typeof(CharacterScreenPacketHandler), true); FakeNetworkClient client = new FakeNetworkClient(); manager.AddSession(client); }
private void OpenConnection(object sender, ConnectionOpenEventArgs e) { sessionManager.AddSession(new Session(e.Connection.Id)); e.Connection.Received += ReceivedData; e.Formatter.DeserializedMessage += DeserializedMessage; formatters[e.Connection.Id] = e.Formatter; }
// Test adding and removing interest in a couple zones public void OpenAndCloseInterest() { SessionManager sessionManager = new SessionManager(); Guid sessionId = new Guid(); ZoneId zoneId1 = new ZoneId(100); ZoneId zoneId2 = new ZoneId(200); Assert.IsTrue(sessionManager.AddSession(sessionId, mTestServerAccount)); // List should start out empty Assert.IsTrue(sessionManager.GetSessionIdsInterestedInZoneId(zoneId1).Count == 0); // Session should not already have interest Assert.IsFalse(sessionManager.SessionIdHasInterest(sessionId, zoneId1)); Assert.IsFalse(sessionManager.SessionIdHasInterest(sessionId, zoneId2)); sessionManager.AddZoneIdInterestToSessionId(sessionId, zoneId1); // List should now contain one session Assert.IsTrue(sessionManager.GetSessionIdsInterestedInZoneId(zoneId1).Count == 1); // Session should now have interest Assert.IsTrue(sessionManager.SessionIdHasInterest(sessionId, zoneId1)); // Session should be interested in that single zone List <ZoneId> zoneIds = sessionManager.GetZoneIdsFromInterestedSessionId(sessionId); Assert.IsTrue(zoneIds.Count == 1); Assert.IsTrue(zoneIds.Contains(zoneId1)); // Lets test a second zone sessionManager.AddZoneIdInterestToSessionId(sessionId, zoneId2); // Session should now have interest Assert.IsTrue(sessionManager.SessionIdHasInterest(sessionId, zoneId2)); // Session should be interested in two zones Assert.IsTrue(sessionManager.GetZoneIdsFromInterestedSessionId(sessionId).Count == 2); // Remove interest in first zone sessionManager.RemoveZoneIdInterestFromSessionId(sessionId, zoneId1); // Session should no longer have interest Assert.IsFalse(sessionManager.SessionIdHasInterest(sessionId, zoneId1)); // Back to one Assert.IsTrue(sessionManager.GetSessionIdsInterestedInZoneId(zoneId2).Count == 1); // Remove interest in the second zone sessionManager.RemoveZoneIdInterestFromSessionId(sessionId, zoneId2); // Session should no longer have interest Assert.IsFalse(sessionManager.SessionIdHasInterest(sessionId, zoneId2)); // Back to empty Assert.IsTrue(sessionManager.GetSessionIdsInterestedInZoneId(zoneId1).Count == 0); sessionManager.RemoveSession(sessionId); }
public static FakeNetworkClient CreateFakeNetworkClient() { FakeNetworkClient client = new FakeNetworkClient(); _sessionManager.AddSession(client); long id = ServerManager.RandomNumber(0, 999999); AccountDTO account = new AccountDTO { AccountId = id, Authority = AuthorityType.Admin, LastSession = 12345, Name = "test" + id, Password = "******" }; DAOFactory.AccountDAO.InsertOrUpdate(ref account); // register for account login ServerCommunicationClient.Instance.HubProxy.Invoke("RegisterAccountLogin", account.Name, 12345); // OpenNosEntryPoint -> LoadCharacterList client.ReceivePacket("12345"); client.ReceivePacket(account.Name); client.ReceivePacket("test"); string clistStart = WaitForPacket(client); string clistEnd = WaitForPacket(client); // creation of character client.ReceivePacket($"Char_NEW {account.Name} 2 1 0 9"); List <string> clistAfterCreate = WaitForPackets(client, 3); CListPacket cListPacket = PacketFactory.Deserialize <CListPacket>(clistAfterCreate[1]); // select character client.ReceivePacket($"select {cListPacket.Slot}"); string okPacket = WaitForPacket(client); // start game client.ReceivePacket("game_start"); List <string> gameStartPacketsFirstPart = WaitForPackets(client, "p_clear"); List <string> gameStartPacketsSecondPart = WaitForPackets(client, "p_clear"); // wait 100 milliseconds to be sure initialization has been finished Thread.Sleep(100); return(client); }
public void TestSimpleAddRemoveSession() { var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); Session newSession = new SessionBuilder().StartDefault().Build(); manager.AddSession(newSession); Assert.AreEqual(1, manager.GetSessions().Count()); Assert.AreSame(newSession, manager.GetSessions().First()); manager.RemoveSession(newSession); Assert.AreEqual(0, manager.GetSessions().Count()); }
// Test adding and removing a session from the manager public void AddAndRemoveSessionId() { SessionManager sessionManager = new SessionManager(); Guid sessionId = new Guid(); Assert.IsTrue(sessionManager.AddSession(sessionId, mTestServerAccount)); Assert.IsTrue(sessionManager.ContainsSession(sessionId)); ServerAccount returnedServerAccount = sessionManager.GetServerAccountFromSessionId(sessionId); Assert.Equals(returnedServerAccount, mTestServerAccount); Assert.IsTrue(sessionManager.RemoveSession(sessionId)); Assert.IsFalse(sessionManager.ContainsSession(sessionId)); // Trying to remove it again should return false Assert.IsFalse(sessionManager.RemoveSession(sessionId)); }
public static IActionResult Twitch(RequestHandler <IActionResult> req) { string code = req.Request.Query["code"]; string state = req.Request.Query["state"]; // Create a new streamkit account for this user. string token = TwitchOAuth.GetToken(code, state); Tuple <string, string> accountInfo = TwitchOAuth.Validate(token); User user = UserManager.UpsertUser(accountInfo.Item1, accountInfo.Item2, token); req.Controller.HttpContext.Session.Set("init", new byte[] { 0 }); SessionManager.AddSession(req.Controller.HttpContext.Session.Id, user); return(req.Controller.RedirectToAction("Index", "MyAccount")); }
bool IAppServer.AddSession(IAppSession appSession) { var session = appSession as TAppSession; if (session == null) { return(false); } if (!_sessionManager.AddSession(session)) { return(false); } OnSessionConnected(session); return(true); }
public void TestSetCurrentSessionByName() { var mock = new Mock <ISessionRepository>(); var manager = new SessionManager(mock.Object); Session newSession = new SessionBuilder().StartDefault().Build(); manager.AddSession(newSession); Assert.IsNull(manager.CurrentSession); bool result = manager.SetCurrentSessionByName(newSession.Name); Assert.AreSame(newSession, manager.CurrentSession); Assert.IsTrue(result); result = manager.SetCurrentSessionByName(newSession.Name); Assert.IsFalse(result); }
public ActionResult Create([Bind(Include = "SessionId,ShowDate,ShowTime,MovieId,HallId")] Session session) { try { if ((session.ShowTime != "21:00") && (session.ShowTime != "18:00") && (session.ShowTime != "15:00")) { return(View()); } else { sessionManager.AddSession(session); return(RedirectToAction("Index")); } } catch (Exception) { ModelState.AddModelError("error", "unable to save the session"); return(View(session)); } }
public void TestPersistWithRollback() { Session s1 = new SessionBuilder().StartDefault("S1").Build(); var mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork.Setup(uow => uow.Commit()).Throws(new Exception(STR_ExceptionOnCommitForTestingPurposes)); var mockRepository = new Mock <ISessionRepository>(); mockRepository.Setup(sm => sm.GetUnitOfWork()).Returns(mockUnitOfWork.Object); var manager = new SessionManager(mockRepository.Object); manager.AddSession(s1); manager.Persist(); mockUnitOfWork.Verify(uow => uow.Rollback(), Times.Once()); }
public void DisconnectSession() { // Setup the server engine and its required dependencies ServerStateMachine serverStateMachine = new TestServerStateMachine(); SessionManager sessionManager = new SessionManager(); ServerObjectRepository objectRepo = new ServerObjectRepository(serverStateMachine); ServerEngine serverEngine = new ServerEngine(sessionManager, objectRepo, MockSendMessageToReflector); // Create a distributed object to play with DistributedObjectId doId = new DistributedObjectId(100); DistributedTestObject obj = new DistributedTestObject(doId); ZoneId zoneId = new ZoneId(200); Guid sessionId = new Guid(); Assert.IsTrue(sessionManager.AddSession(sessionId, new ServerAccount(new AccountId(0), 0, "0", "0", "schmear", "mein", "schmeer", null))); objectRepo.AddObjectToSessionId(sessionId, obj); serverEngine.ProcessOpenZoneInterest(sessionId, zoneId); serverEngine.ProcessZoneChange(obj, zoneId); serverEngine.ProcessDisconnectSession(sessionId); // See if the object repo got cleaned up // Object repo should no longer have the object Assert.IsFalse(objectRepo.ContainsObject(obj)); Assert.IsTrue(objectRepo.GetObject(doId) == null); // Object should not be in the zone Assert.IsFalse(objectRepo.GetObjectsInZone(zoneId).Contains(obj)); Assert.IsTrue(objectRepo.GetDistributedObjectIdsOwnedBySessionId(sessionId).Count == 0); // See if the session manager got cleaned up // Session manager should no longer have the session Assert.IsFalse(sessionManager.ContainsSession(sessionId)); // Zone interest should be cleaned up Assert.IsFalse(sessionManager.SessionIdHasInterest(sessionId, zoneId)); Assert.IsFalse(sessionManager.GetSessionIdsInterestedInZoneId(zoneId).Contains(sessionId)); Assert.IsFalse(sessionManager.GetZoneIdsFromInterestedSessionId(sessionId).Contains(zoneId)); }
public string Execute() { LogConsole.Break(); string message = string.Empty; Session newSession = new Session(); if (SessionManager.AddSession(newSession, this.Parameters[0], true) == true) { LogConsole.Write(newSession.Details()); message = newSession.Id + "&" + newSession.MediaServer.GetPortNumber().ToString(); } else { newSession.Stop(); newSession.Terminate(); LogConsole.WriteLine("// EXECUTED " + this.CommandWord + " " + this.Parameters[0] + " //"); LogConsole.WriteLine("// ERROR ::: USER IS ALREADY REGISTERD AS HOST " + " //"); LogConsole.Break(); message = "ERROR"; } return(message); }
public Task Load(PluginServerContext pluginServerContext, ILogger logger) { Logger = logger; string path = Path.Combine(pluginServerContext.PluginsPath, "ELPanel.conf"); if (!File.Exists(path)) { using var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); using var streamWriter = new StreamWriter(fileStream); streamWriter.Write(JsonConvert.SerializeObject(new { MySqlString = "Server=127.0.0.1;Port=3306;Database=elpanel;Uid=root;Pwd=root;" }, Formatting.Indented)); } var config = JsonUtils.GetJsonFile(path); MySqlString = config.GetValue("MySqlString", StringComparison.CurrentCultureIgnoreCase).Value <string>(); MySqlManager = new MySqlManager(MySqlString); ServerManager = new ServerManager(); SessionManager = new SessionManager(); SessionManager.AddSession("86b13566-91ff-4ae3-b92e-aa1887b87574"); return(Task.CompletedTask); }
/// <summary> /// Executes any given command if known to the parser /// </summary> /// <param name="cmd"></param> public static string ExecuteCommand(ConsoleCommand cmd) { string param1 = cmd.Parameters[0]; string param2 = cmd.Parameters[1]; string param3 = cmd.Parameters[2]; string command = cmd.CommandWord; string parserMessage = string.Empty; if (!Parser.CanInterpret(cmd, out parserMessage)) { LogConsole.WriteLine("ERROR WHILE PARSING COMMAND: " + command + " ::: INVALID"); LogConsole.Break(); return("PARSER_ERROR"); } UserAuthorization userAuthorization = UserAuthorization.None; UserAuthorization requiredAuthorization = ConsoleCommandWords.FindCommand(command).RequiredAuthorization; if (requiredAuthorization != UserAuthorization.None) { userAuthorization = UserManager.GetUserAuthorization(param1); if (userAuthorization != requiredAuthorization) { LogConsole.WriteLine(UserManager.GetUserAuthorizationErrorMessage(requiredAuthorization, userAuthorization, param1)); LogConsole.Break(); return("UNAUTHORIZED"); } } switch (command) { case "terminate": { LogConsole.PrintCommand(cmd); Actions.TerminateServer(); return(string.Empty); } case "clear": { LogConsole.PrintCommand(cmd); LogConsole.Clear(); return(string.Empty); } case "help": { LogConsole.PrintCommand(cmd); LogConsole.Break(); LogConsole.Write(ConsoleCommandWords.CommandList()); return(string.Empty); } case "add": { LogConsole.PrintCommand(cmd); LogConsole.Break(); switch (param1) { case "session": { LogConsole.Break(); Session newSession = new Session(); SessionManager.AddSession(newSession, string.Empty, false); LogConsole.Write(newSession.Details()); return(newSession.Id); } default: { LogConsole.Break(); LogConsole.ThrowParseError("Invalid Type", param1); return(string.Empty); } } } /// DEPRECATED //case "select": // { // LogConsole.PrintCommand(cmd); // LogConsole.Break(); // switch (param1) // { // case "session": // { // if (LogConsole.SelectSession(param2, SessionManager.Sessions) != false) // { // LogConsole.Break(); // LogConsole.Write("Selected session is now " + param2.ToUpper()); // SessionManager.OnSelectedSessionChanged(); // } // else // { // LogConsole.Break(); // LogConsole.ThrowParseError("Unknown Session!", param2.ToUpper()); // } // return string.Empty; // } // default: // { // LogConsole.Break(); // LogConsole.ThrowParseError("Invalid Type", param1); // return string.Empty; // } // } // } case "selected": { LogConsole.PrintCommand(cmd); LogConsole.Break(); if (LogConsole.currentSession == null) { LogConsole.Write("No selected session"); } else { LogConsole.Write("Selected session is " + LogConsole.currentSession.Id); } return(string.Empty); } case "stop": { switch (param1) { case "session": { LogConsole.Break(); if (SessionManager.SessionExists(param2)) { SessionManager.FindSessionBySessionId(param2).Stop(); LogConsole.Write("Stopped Session " + param2); } else { LogConsole.ThrowParseError("unknown " + param1 + " : " + param2 + " - Session does not exist", cmd.CommandWord); } return(string.Empty); } default: { LogConsole.Break(); LogConsole.ThrowParseError("Invalid Type", param1); return(string.Empty); } } } case "delete": { switch (param1) { case "session": { LogConsole.Break(); if (SessionManager.SessionExists(param2)) { if (SessionManager.FindSessionBySessionId(param2).isStopped) { SessionManager.FindSessionBySessionId(param2).Terminate(); SessionManager.DeleteSession(param2); LogConsole.Write("Deleted Session " + param2); } else { LogConsole.ThrowException(SessionManager.FindSessionBySessionId(param2).Id, "Session is still running! Session must be stopped before termination"); } return(string.Empty); } else { LogConsole.ThrowParseError("unknown " + param1 + " : " + param2 + " - Session does not exist", cmd.CommandWord); } return(string.Empty); } default: { LogConsole.Break(); LogConsole.ThrowParseError("Invalid Type", param1); return(string.Empty); } } } default: { return(string.Empty); } } }
public static FakeNetworkClient InitializeTestEnvironment() { System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); // initialize Logger Logger.InitializeLogger(LogManager.GetLogger(typeof(BasicPacketHandlerTest))); // create server entities (this values would have been imported) CreateServerItems(); CreateServerMaps(); CreateServerSkills(); // initialize servermanager ServerManager.Initialize(); // initialize WCF ServiceFactory.Instance.Initialize(); // register mappings for items DAOFactory.InventoryDAO.RegisterMapping(typeof(SpecialistInstance)); DAOFactory.InventoryDAO.RegisterMapping(typeof(WearableInstance)); DAOFactory.InventoryDAO.RegisterMapping(typeof(UsableInstance)); DAOFactory.InventoryDAO.InitializeMapper(typeof(ItemInstance)); // initialize PacketSerialization PacketFactory.Initialize <WalkPacket>(); // initialize new manager _sessionManager = new NetworkManager <TestEncryption>("127.0.0.1", 1234, typeof(CharacterScreenPacketHandler), typeof(TestEncryption), true); FakeNetworkClient client = new FakeNetworkClient(); _sessionManager.AddSession(client); AccountDTO account = new AccountDTO() { AccountId = 1, Authority = AuthorityType.Admin, LastSession = 12345, Name = "test", Password = "******" }; DAOFactory.AccountDAO.InsertOrUpdate(ref account); // register for account login ServiceFactory.Instance.CommunicationService.RegisterAccountLogin("test", 12345); // OpenNosEntryPoint -> LoadCharacterList client.ReceivePacket("12345"); client.ReceivePacket("test"); client.ReceivePacket("test"); string clistStart = WaitForPacket(client); string clistEnd = WaitForPacket(client); // creation of character client.ReceivePacket("Char_NEW Test 2 1 0 9"); List <string> clistAfterCreate = WaitForPackets(client, 3); CListPacket cListPacket = PacketFactory.Serialize <CListPacket>(clistAfterCreate[1]); // select character client.ReceivePacket($"select {cListPacket.Slot}"); string okPacket = WaitForPacket(client); // start game client.ReceivePacket("game_start"); List <string> gameStartPacketsFirstPart = WaitForPackets(client, "p_clear"); List <string> gameStartPacketsSecondPart = WaitForPackets(client, "p_clear"); return(client); }
public void CreateSession() { sessionManager.AddSession(dayInput.value, hourInput.value, minuteInput.value, durationInput.value); pageManager.ChangePage(3); }
public ActionResult Login() { LoginRequest args = ApiRequestBase.ParseRequest <LoginRequest>(this); ServerSession session = args.GetSession(); bool isNewSession = false; if (session == null) { isNewSession = true; session = ServerSession.CreateUnauthenticated(); SessionManager.AddSession(session); } // Initialize challenge data if (session.authChallenge == null || session.authChallenge.Length == 0) { session.authChallenge = ByteUtil.GenerateRandomBytes(32); } // Get user if (string.IsNullOrEmpty(args.user)) { return(ApiError("missing parameter: \"user\"")); } User user = Settings.data.GetUser(args.user); string salt; if (user != null) { salt = user.Salt; } else { salt = Util.GenerateFakeUserSalt(args.user); Logger.Info("Fake salt \"" + salt + "\" created for user name \"" + args.user + "\". Remote IP: " + Context.httpProcessor.RemoteIPAddressStr); } if (string.IsNullOrEmpty(args.token)) { // No response token was provided, so we are on step 1 of authentication, where the client requests information necessary to build the response token. return(Json(new LoginChallengeResponse(session, salt, null))); } else { // A response token was provided. This token can be used to authenticate the user. if (user != null) { if (user.AuthenticateUser(args.token, session.authChallenge)) { // Delete challenge data -- it is no longer needed and should not be reused. session.authChallenge = null; session.userName = user.Name; using (GlobalDb db = new GlobalDb()) db.AddLoginRecord(user.Name, Context.httpProcessor.RemoteIPAddressStr, session.sid); return(Json(new LoginSuccessResponse(session))); } } if (isNewSession) { return(Json(new LoginFailedResponse(session, "Authentication protocol timed out. Please try again."))); } return(Json(new LoginFailedResponse(session, "Authentication failed. Please check inputs."))); } }