Esempio n. 1
0
        private void HandleLogins(RestDataRequestMessage message, ref RestResponse response, RestRequestMessage request)
        {
            var loginMessage = message.GetMessage() as InitializeSession;

            var session = new SessionCredentials(loginMessage.PeerId, SessionKey.NewGuid());

            var playerdata = new PlayerData();

            playerdata.FillWithNewPlayer(loginMessage.PlayerId, new [] { "FreeForAll", "Captain", "Siege", "Duel", "TeamDeathMatch", "FreeForAll" });
            playerdata.LastPlayerName = loginMessage.PlayerName;
            playerdata.LastGameTypes  = new[] { "Captain" };
            var user = new User {
                Id = session, QueuedMessages = new Queue <RestResponseMessage>(), PlayerData = playerdata
            };

            this._context.Users.Add(user);
            var initializeSessionResponse = new InitializeSessionResponse(playerdata,
                                                                          _context.Status);

            response.FunctionResult =
                new RestDataFunctionResult(new LoginResult(session.PeerId, session.SessionKey,
                                                           initializeSessionResponse));
            response.UserCertificate = session.SessionKey.ToByteArray();
            response.SetSuccessful(true, "ResultFromServerTask");
        }
        /// <summary>
        /// Fills the system ASP.NET session from NCache.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="cache"></param>
        /// <param name="strict"></param>
        void IDistributionStrategy.FillSessionFromCache(ISessionCache cache, HttpSessionState session, NSessionStateModule module, bool strict)
        {
            try
            {
                string sessionId = session.SessionID;
                if (strict)
                {
                    session.Clear();
                }

                IDictionaryEnumerator i = (IDictionaryEnumerator)cache.GetEnumerator();
                while (i != null && i.MoveNext())
                {
                    SessionKey key = i.Key as SessionKey;
                    if (key != null && key.SessionID == sessionId)
                    {
                        session[key.Key] = i.Value;
                    }
                }
            }
            catch (Exception exc)
            {
                if (strict)
                {
                    session.Clear();
                }
                module.RaiseExceptions(exc, "SingleValueDistribution.FillSessionFromCache");
            }
        }
 /// <summary>
 /// Get session holder from the cache.
 /// </summary>
 /// <param name="key">
 /// Session key.
 /// </param>
 /// <param name="exclusive">
 /// Flag specifying whether to obtain exclusive access to the specified
 /// session.
 /// </param>
 /// <returns>
 /// The <b>SessionHolder</b> object.
 /// </returns>
 protected virtual SessionHolder GetSessionHolder(SessionKey key, bool exclusive)
 {
     return((SessionHolder)
            (exclusive
             ? SessionCache.Invoke(key, new AcquireSessionProcessor())
             : SessionCache[key]));
 }
Esempio n. 4
0
        public async Task <TaskSession> OpenSession(SessionKey sessionKey, MazeTask mazeTask, string description)
        {
            using (await _readerWriterLock.ReaderLockAsync())
            {
                var file = _fileSystem.FileInfo.FromFileName(GetTaskDbFilename(mazeTask));
                if (file.Exists)
                {
                    using (var dbStream = file.OpenRead())
                        using (var db = new LiteDatabase(dbStream))
                        {
                            var collection = db.GetCollection <TaskSession>(nameof(TaskSession));
                            collection.EnsureIndex(x => x.TaskSessionId, true);

                            var taskSession = collection.IncludeAll().FindById(sessionKey.Hash);
                            if (taskSession != null)
                            {
                                return(taskSession);
                            }
                        }
                }
            }

            return(new TaskSession
            {
                TaskSessionId = sessionKey.Hash,
                Description = description,
                CreatedOn = DateTimeOffset.UtcNow,
                TaskReference = new TaskReference {
                    TaskId = mazeTask.Id
                },
                TaskReferenceId = mazeTask.Id,
                Executions = ImmutableList <TaskExecution> .Empty
            });
        }
Esempio n. 5
0
        /// <summary>
        /// Encrypts data captured for authentication.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="key">The key to encrypt data.</param>
        public override void Encrypt(PersonalInfo data, SessionKey key)
        {
            ValidateNull(data, nameof(data));
            ValidateNull(key, nameof(key));

            // Create Pid bytes.
            var pidXml   = data.ToXml().ToString(SaveOptions.DisableFormatting);
            var pidBytes = pidXml.GetBytes();

            using (var sha = SHA256.Create())
            {
                // Encrypt data.
                var encryptedPid     = key.Encrypt(pidBytes);
                var encryptedPidHash = key.Encrypt(sha.ComputeHash(pidBytes));
                KeyInfo = key.KeyInfo;

                // Set related properties.
                AadhaarNumber = data.AadhaarNumber;
                Uses          = data.Uses;
                Data          = new EncryptedData {
                    Data = Convert.ToBase64String(encryptedPid)
                };
                Hmac      = Convert.ToBase64String(encryptedPidHash);
                Timestamp = data.Timestamp;
                if (DeviceInfo != null)
                {
                    if (data.Biometrics.All(b => b.Type != BiometricType.Iris))
                    {
                        DeviceInfo.IrisDeviceCode = Metadata.DeviceNotApplicable;
                    }
                    if (!data.Biometrics.Any(b => b.Type == BiometricType.Fingerprint || b.Type == BiometricType.Minutiae))
                    {
                        DeviceInfo.FingerprintDeviceCode = Metadata.DeviceNotApplicable;
                    }
                }

                // Set meta information.
                if (Info != null)
                {
                    Info.AadhaarNumberHash = sha.ComputeHash(AadhaarNumber.GetBytes()).ToHex();
                    Info.Timestamp         = data.Timestamp;
                    Info.TerminalHash      = sha.ComputeHash(Terminal.GetBytes()).ToHex();

                    const string demoStart = "<Demo", demoEnd = "</Demo";
                    var          startOfDemoStart = pidXml.LastIndexOf(demoStart, StringComparison.Ordinal);
                    if (startOfDemoStart >= 0)
                    {
                        var startOfDemoEnd = pidXml.IndexOf(demoEnd, startOfDemoStart + demoStart.Length, StringComparison.Ordinal);
                        var realEnd        = pidXml.IndexOf(">", startOfDemoEnd + demoEnd.Length, StringComparison.Ordinal);
                        var demoXml        = pidXml.Substring(startOfDemoStart, realEnd - startOfDemoStart + 1);
                        var demoBytes      = demoXml.GetBytes();
                        var demoHash       = sha.ComputeHash(demoBytes);
                        Info.DemographicHash = demoHash.ToHex();
                        Array.Clear(demoBytes, 0, demoBytes.Length);
                    }
                    Info.Encode();
                }
            }
            Array.Clear(pidBytes, 0, pidBytes.Length);
        }
Esempio n. 6
0
        /// <summary>
        /// Encrypts finger data captured for best finger detection.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="key">The key to encrypt data.</param>
        public override void Encrypt(BestFingerInfo data, SessionKey key)
        {
            ValidateNull(data, nameof(data));
            ValidateNull(key, nameof(key));

            // Create Rbd bytes.
            var rbdBytes = data.ToXml().ToString(SaveOptions.DisableFormatting).GetBytes();

            using (var sha = SHA256.Create())
            {
                var rbdHash = sha.ComputeHash(rbdBytes);

                // Encrypt data.
                var encryptedRbd  = key.Encrypt(rbdBytes);
                var encryptedHash = key.Encrypt(rbdHash);
                KeyInfo = key.KeyInfo;

                // Set related properties.
                AadhaarNumber = data.AadhaarNumber;
                Data          = new EncryptedData {
                    Data = Convert.ToBase64String(encryptedRbd)
                };
                Hmac      = Convert.ToBase64String(encryptedHash);
                Timestamp = data.Timestamp;
                if (DeviceInfo != null)
                {
                    DeviceInfo.IrisDeviceCode = Metadata.DeviceNotApplicable;
                }
            }
            Array.Clear(rbdBytes, 0, rbdBytes.Length);
        }
Esempio n. 7
0
        public static Session GetLastSession(Account account)
        {
            var ids = Config.instance.mainConnection.LoadIdsByConditions(
                TableSpec.instance,
                new ComparisonCondition(
                    TableSpec.instance.getColumnSpec(TableSpec.FIELD_ACCOUNTID),
                    ComparisonType.EQUAL,
                    account.id.ToString()
                    ),
                Diapasone.first,
                new JoinSpec[0],
                new SortSpec[] {
                new SortSpec(
                    TableSpec.instance.getColumnSpec(TableSpec.FIELD_LASTHUMANACTIVITY),
                    false
                    )
            }
                );

            if (ids.Count < 1)
            {
                throw new NotFoundInDBException(TableSpec.instance.getColumnSpec(TableSpec.FIELD_ACCOUNTID), account.id.ToString());
            }

            return(Session.LoadById(SessionKey.Parse(ids[0])));
        }
Esempio n. 8
0
 internal ClientWorker(SessionKey key)
 {
     this.r                  = EntityRepository.Instance;
     lastActivity            = DateTime.MinValue;
     r.PetOwners.HasChanged += OnCacheChanged;
     r.Pets.HasChanged      += OnCacheChanged;
 }
Esempio n. 9
0
        public ActionResult LoginPart(string email, string password)
        {
            var admin = db.Person.Where(w => w.Email == email || w.Phone == email).FirstOrDefault();

            if (admin != null)
            {
                string HashPassword = PasswordExtention.HashPassword(password);
                if (admin.Password == password && (admin.Email == email || admin.Phone == email))
                {
                    var adminSession = new SessionKey();
                    Session[SessionKey.Admin] = email;

                    var x = Session[SessionKey.Admin];
                    return(RedirectToAction("Index", "Admin"));
                }
                else
                {
                    ViewBag.Login = "******";
                    return(View());
                }
            }
            else
            {
                ViewBag.Login = "******";
                return(View());
            }
        }
Esempio n. 10
0
 public void UnregisterClient(SessionKey key)
 {
     if (Clients.ContainsKey(key))
     {
         Clients.Remove(key);
     }
 }
Esempio n. 11
0
 public LoginServAcceptPlayer(IServiceProvider serviceProvider, Packet p, AuthThread login) : base(serviceProvider)
 {
     _accountCrudService = serviceProvider.GetService <ICrudService <AccountContract> >();
     _login     = login;
     _accountId = p.ReadInt();
     _key       = new SessionKey(p.ReadInt(), p.ReadInt(), p.ReadInt(), p.ReadInt());
 }
Esempio n. 12
0
 public ActionResult LoginPartForAdminSubmit([Bind(Include = "Email, Password")] Manager manager)
 {
     if (!(string.IsNullOrWhiteSpace(manager.Email) || string.IsNullOrWhiteSpace(manager.Password)))
     {
         var findAdmin = db.Manager.Where(w => w.DeletedDate == null && w.Email == manager.Email).FirstOrDefault();
         if (findAdmin != null)
         {
             if (manager.Password == findAdmin.Password)
             {
                 var newAdminSession = new SessionKey();
                 Session[SessionKey.Admin] = manager.Email;
                 var x = Session[SessionKey.Admin];
             }
             else
             {
                 TempData["wrongPassword"] = "******";
                 return(View("LoginPartForAdmin"));
             }
         }
         else
         {
             TempData["emaildoesnexist"] = "Email tapılmadı";
             return(View("LoginPartForAdmin"));
         }
         return(RedirectToAction("Index", "Admin"));
     }
     else
     {
         return(RedirectToAction("LoginPartForAdmin", "Admin"));
     }
 }
Esempio n. 13
0
 public void UpdatePetOwner(SessionKey key, PetOwner model)
 {
     if (Clients.ContainsKey(key))
     {
         Clients[key].UpdatePetOwner(model);
     }
 }
Esempio n. 14
0
 public void DeletePetOwner(SessionKey key, long id)
 {
     if (Clients.ContainsKey(key))
     {
         Clients[key].DeletePetOwner(id);
     }
 }
Esempio n. 15
0
        public static Session create(Account account)
        {
            string key = null;

            Config.Transactional(transaction => {
                Config.instance.mainConnection.lockTable(transaction, TableSpec.instance);

                do
                {
                    key = Util.RandomString(32, Util.RandomSource.LETTERS_DIGITS);
                } while(Config.instance.mainConnection.LoadByIds(transaction, TableSpec.instance, new List <string>()
                {
                    key
                }).Count > 0);

                Config.instance.mainConnection.insert(
                    transaction,
                    TableSpec.instance,
                    new Dictionary <string, string>()
                {
                    { TableSpec.FIELD_SESSIONKEY, key },
                    { TableSpec.FIELD_ACCOUNTID, account.id.ToString() },
                    { TableSpec.FIELD_LASTACTIVITY, DateTime.Now.ToUTCString() },
                    { TableSpec.FIELD_LASTHUMANACTIVITY, DateTime.Now.ToUTCString() },
                    { TableSpec.FIELD_LASTURL, "" },
                    { TableSpec.FIELD_ISDELETED, "0" },
                }
                    );
            });
            return(Session.LoadById(SessionKey.Parse(key)));
        }
Esempio n. 16
0
/// <summary>
/// Fills the system ASP.NET session from NCache.
/// </summary>
/// <param name="session"></param>
/// <param name="cache"></param>
/// <param name="strict"></param>

        void IDistributionStrategy.FillSessionFromCache(ISessionCache cache, HttpSessionState session, NSessionStateModule module, bool strict)
        {
            string sessionId = session.SessionID;

            SessionKey key = new SessionKey(sessionId, module.ApplicationId);

            if (strict)
            {
                session.Clear();
            }

            /// save the binary form of data, for comparision on FillCacheFromAspNet()
            _table = (byte[])cache.Get(key.ToString());

            if (_table == null)
            {
                _isNewSession = true;
                return;
            }

            Hashtable ht = (Hashtable)CompactBinaryFormatter.FromByteBuffer(_table, module.CacheID);

            if (ht == null)
            {
                return;
            }

            IDictionaryEnumerator i = ht.GetEnumerator();

            while (i.MoveNext())
            {
                session[i.Key.ToString()] = i.Value;
            }
        }
        public ActionResult <string> Getkey()
        {
            var ss  = new SessionKey(173, 211);
            var key = ss.key();

            return(key);
        }
Esempio n. 18
0
        private byte[] Decrypt(byte[] cipherTextBytes, out int byteCount)
        {
            string password = SessionKey.ToHexString();
            string salt     = Salt.ToHexString();

            if (cipherTextBytes == null)
            {
                byteCount = 0;
                return(null);
            }
            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] saltValueBytes     = Encoding.ASCII.GetBytes(salt);
            var    derivedPassword    = new PasswordDeriveBytes(password, saltValueBytes, HashAlgorithm, PasswordIterations);
            var    keyBytes           = derivedPassword.GetBytes(KeySize / 8);
            var    symmetricKey       = new RijndaelManaged {
                Mode = CipherMode.CBC
            };
            var plainTextBytes = new byte[cipherTextBytes.Length];

            using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
            {
                using (var memStream = new MemoryStream(cipherTextBytes))
                {
                    using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();
            return(plainTextBytes);
        }
Esempio n. 19
0
        public async Task InvokeAsync(ScheduledTriggerInfo triggerInfo, TriggerContext context, CancellationToken cancellationToken)
        {
            while (true)
            {
                var synchronizedTime = GetNextTriggerTime(triggerInfo, DateTimeOffset.UtcNow);
                if (synchronizedTime == null)
                {
                    return;
                }

                var nextTriggerTime = synchronizedTime.Value;
                if (!triggerInfo.SynchronizeTimeZone)
                {
                    //ignore offset
                    nextTriggerTime = new DateTimeOffset(nextTriggerTime.DateTime, DateTimeOffset.UtcNow.Offset);
                }

                context.ReportNextTrigger(nextTriggerTime);
                await Task.Delay(nextTriggerTime - DateTimeOffset.UtcNow, cancellationToken);

                //important: use synchronized time
                var session = await context.CreateSession(SessionKey.Create("ScheduledTrigger", synchronizedTime.Value));

                await session.Invoke();
            }
        }
Esempio n. 20
0
/// <summary>
/// Fills NCache from the system ASP.NET session.
/// </summary>
/// <param name="cache"></param>
/// <param name="session"></param>
/// <param name="strict"></param>
/// <param name="async"></param>

        void IDistributionStrategy.FillCacheFromSession(ISessionCache cache, HttpSessionState session, NSessionStateModule module, bool strict, bool isAbandoned)
        {
            string     sessionId = session.SessionID;
            SessionKey key       = new SessionKey(sessionId, module.ApplicationId);

            try
            {
                if (session.IsReadOnly && cache.Contains(sessionId, key.ToString()) && !isAbandoned)
                {
                    return;
                }

                if (/*session.Count == 0 ||*/ isAbandoned)//[Ata]: Session is not removed from store if it is cleared
                {
                    cache.Remove(sessionId, key.ToString(), false);
                    if (module.DetailedLogsEnabled)
                    {
                        NSessionStateModule.NCacheLog.Debug(sessionId + " :session removed from cache");
                    }
                    return;
                }

                //use-case: A session my get emptied while doing different updates... although whien added first time is is not empty
                //So we must update that session rather doing no operation thinking it is empty session and need not to be added.
                if (session.Count == 0 && _isNewSession) //We need not to keep any new empty session in the cache. [Asif Imam] April 09, 08
                {
                    return;
                }

                IDictionary ht = new Hashtable();
                foreach (string skey in session.Keys)
                {
                    ht[skey] = session[skey];
                }

                byte[] _stable = CompactBinaryFormatter.ToByteBuffer(ht, module.CacheID);

                if (_table != null)
                {
                    if (BinaryComparer(_stable, _table))
                    {
                        return;
                    }
                }

                CacheItem sessionItem = new CacheItem(_stable);
                sessionItem.Priority = CacheItemPriority.NotRemovable;

                sessionItem.Expiration = new Runtime.Caching.Expiration(Runtime.Caching.ExpirationType.Sliding, TimeSpan.FromMinutes(session.Timeout));
                cache.Insert(sessionId, key.ToString(), sessionItem, false);
            }
            finally
            {
                if (session != null && strict)
                {
                    session.Clear();
                }
            }
        }
Esempio n. 21
0
 public static T Data <T>(SessionKey key)
 {
     if (System.Web.HttpContext.Current.Session[key.ToString()] == null)
     {
         return(default(T));
     }
     return((T)System.Web.HttpContext.Current.Session[key.ToString()]);
 }
Esempio n. 22
0
        public Account GetAccount(string lowellReference)
        {
            var account = _session.GetString(SessionKey.Account(lowellReference));

            return(string.IsNullOrWhiteSpace(account)
                ? null
                : JsonConvert.DeserializeObject <Account>(account));
        }
 public static bool contains(this HttpSessionStateBase session, SessionKey key)
 {
     if (session[key.ToString()] != null)
     {
         return(true);
     }
     return(false);
 }
Esempio n. 24
0
        public async Task InvokeAsync(OnAppStartupTriggerInfo triggerInfo, TriggerContext context, CancellationToken cancellationToken)
        {
            var session = await context.CreateSession(SessionKey.Create("OnAppStartup", DateTimeOffset.UtcNow));

            await session.Invoke();

            await Task.Delay(int.MaxValue, cancellationToken);
        }
Esempio n. 25
0
        public IActionResult HospitalNegativeStat()
        {
            SessionKey sessionKey = new SessionKey();

            sessionKey           = HttpContext.Session.GetObjectFromJson <SessionKey>("SessionKey");
            TempData["username"] = sessionKey.UserName;
            return(View(sessionKey));
        }
Esempio n. 26
0
        public IActionResult PharmacistProfile()
        {
            SessionKey sessionKey = new SessionKey();

            sessionKey           = HttpContext.Session.GetObjectFromJson <SessionKey>("SessionKey");
            TempData["username"] = sessionKey.UserName;
            return(View(sessionKey));
        }
Esempio n. 27
0
 public static HttpCookie GetCookie(SessionKey key)
 {
     if (Exists(key))
     {
         return(_context.Request.Cookies.Get(key.ToString()));
     }
     return(null);
 }
Esempio n. 28
0
        public IActionResult ViewAppoinments()
        {
            SessionKey sessionKey = new SessionKey();

            sessionKey           = HttpContext.Session.GetObjectFromJson <SessionKey>("SessionKey");
            TempData["username"] = sessionKey.UserName;
            return(View(sessionKey));
        }
Esempio n. 29
0
 public ActionResult <bool> Put([FromBody] SessionKey sessionKey)
 {
     if (DASessionKey.Update(sessionKey, out error))
     {
         return(new CreatedAtRouteResult(null, null, true));
     }
     return(BadRequest(error));
 }
Esempio n. 30
0
        public static T GetValue <T>(this HttpSessionState sessionState, SessionKey sessionKey)
        {
            if (sessionState[sessionKey.ToString()] == null)
            {
                return(default(T));
            }

            return((T)sessionState[sessionKey.ToString()]);
        }
Esempio n. 31
0
        public CDEFSession(SessionDescriptor to, SessionDescriptor from, 
                           CDEFConsumer parent, ILogger errorlLog, bool isConnected, bool autoConnect)
        {
            mOwner = parent;
            mLogger = errorlLog;
            mAutoConnect = autoConnect;
            mTo = to;
            mFrom = from;
            mkey = new SessionKey(to, from);
            mSessionPermConnected = isConnected;

            if (mSessionPermConnected)
            {
                mSessionEstablished.Set();
            }

            TimerCallback timerSessDelegate = new TimerCallback(ReconnectSessionCb);
            mReconSessTimer = new Timer(timerSessDelegate, null, Timeout.Infinite, Timeout.Infinite);
        }
 private static void set(SessionKey sessionKey, HttpSessionState session, object item)
 {
     session[sessionKey.ToString()] = item;
 }
Esempio n. 33
0
 public object Get(SessionKey key)
 {
     return Session[key.ToString()];
 }
Esempio n. 34
0
 public void Set(SessionKey key, object source)
 {
     Session[key.ToString()] = source;
 }
Esempio n. 35
0
 public ServiceSetAction(Controller controller, SessionKey sessionKey)
 {
     _controller = controller;
     _sessionKey = sessionKey;
 }
 private static object get(SessionKey sessionKey, HttpSessionState session)
 {
     return session[sessionKey.ToString()];
 }
Esempio n. 37
0
 public IServiceGetAction Fetch(SessionKey sessionKey)
 {
     _serviceGetAction = new ServiceGetAction(sessionKey);
     return _serviceGetAction;
 }
Esempio n. 38
0
 public void Initialize(Controller controller, SessionKey sessionKey)
 {
     _controller = controller;
     _controller.Session.RemoveValue(sessionKey);
 }
Esempio n. 39
0
 public IServiceSetAction Put(SessionKey sessionKey)
 {
     _serviceSetAction = new ServiceSetAction(_controller, sessionKey);
     return _serviceSetAction;
 }