public void SendMail(string worldGroup, MailDTO mail) { if (!IsCharacterConnected(worldGroup, mail.ReceiverId)) { DaoFactory.MailDao.InsertOrUpdate(ref mail); } else { AccountSession account = MsManager.Instance.ConnectedAccounts.FirstOrDefault(a => a.CharacterId.Equals(mail.ReceiverId)); if (account?.ConnectedWorld == null) { DaoFactory.MailDao.InsertOrUpdate(ref mail); return; } account.ConnectedWorld.ServiceClient.GetClientProxy <ICommunicationClient>().SendMail(mail); } }
public int?SendMessageToCharacter(SCSCharacterMessage message) { if (!MsManager.Instance.AuthentificatedClients.Any(s => s.Equals(CurrentClient.ClientId))) { return(null); } WorldServer sourceWorld = MsManager.Instance.WorldServers.FirstOrDefault(s => s.Id.Equals(message.SourceWorldId)); if (message?.Message == null || sourceWorld == null) { return(null); } switch (message.Type) { case MessageType.Family: case MessageType.FamilyChat: foreach (WorldServer world in MsManager.Instance.WorldServers.Where(w => w.WorldGroup.Equals(sourceWorld.WorldGroup))) { world.ServiceClient.GetClientProxy <ICommunicationClient>().SendMessageToCharacter(message); } return(-1); case MessageType.PrivateChat: case MessageType.Whisper: case MessageType.WhisperGM: if (message.DestinationCharacterId.HasValue) { AccountSession account = MsManager.Instance.ConnectedAccounts.FirstOrDefault(a => a.CharacterId.Equals(message.DestinationCharacterId.Value)); if (account?.ConnectedWorld != null) { account.ConnectedWorld.ServiceClient.GetClientProxy <ICommunicationClient>().SendMessageToCharacter(message); return(account.ConnectedWorld.ChannelId); } } break; case MessageType.Shout: foreach (WorldServer world in MsManager.Instance.WorldServers) { world.ServiceClient.GetClientProxy <ICommunicationClient>().SendMessageToCharacter(message); } return(-1); } return(null); }
public async Task SignOutAsync() { var accountSession = new AccountSession { AccessToken = "accessToken", CanSignOut = true, ClientId = "12345", }; this.authenticationProvider.CurrentAccountSession = accountSession; this.webAuthenticationUi.OnAuthenticateAsync = this.OnAuthenticateAsync_SignOut; await this.authenticationProvider.SignOutAsync(); Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared."); Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called."); }
public bool ChangeAuthority(string worldGroup, string characterName, AuthorityType authority) { CharacterDTO character = DaoFactory.CharacterDao.LoadByName(characterName); if (character == null) { return(false); } LogVIPDTO log = DaoFactory.LogVipDao.GetLastByAccountId(character.AccountId); if (log == null) { log = new LogVIPDTO { AccountId = character.AccountId, Timestamp = DateTime.Now, VipPack = authority.ToString() }; DaoFactory.LogVipDao.InsertOrUpdate(ref log); // FIRST TIME VIP } else { // PRO RATA LogVIPDTO newlog = new LogVIPDTO { AccountId = character.AccountId, Timestamp = log.Timestamp.Date.AddMonths(1), VipPack = authority.ToString(), }; DaoFactory.LogVipDao.InsertOrUpdate(ref log); } if (!IsAccountConnected(character.AccountId)) { AccountDTO account = DaoFactory.AccountDao.LoadById(character.AccountId); account.Authority = authority; DaoFactory.AccountDao.InsertOrUpdate(ref account); } else { AccountSession account = MsManager.Instance.ConnectedAccounts.FirstOrDefault(s => s.AccountId == character.AccountId); account?.ConnectedWorld.ServiceClient.GetClientProxy <ICommunicationClient>().ChangeAuthority(account.AccountId, authority); } return(true); }
public async Task <ActionResult <List <StudentScore> > > scoreView([FromBody] ScoreViewRequest scoreView) { AccountSession session = await _repository.GetAccountBySessionToken(scoreView.Token); var account = await _repository.GetAccountById(session.AccountId); if (account.RoleId == (int)Roles.Student) { return(await _repository.GetScoresByStudentId(scoreView)); } if (account.RoleId == (int)Roles.Student) { return(await _repository.GetScores(scoreView)); } throw new Exception("NoPermission"); }
public void DeleteFromCache() { var accountSession = new AccountSession { ClientId = "1", UserId = "id", }; var mockCacheItem1 = new MockTokenCacheItem(); mockCacheItem1.Setup(item => item.AccessToken).Returns("token 1"); mockCacheItem1.Setup(item => item.ClientId).Returns(accountSession.ClientId); mockCacheItem1.Setup(item => item.UniqueId).Returns(accountSession.UserId); var mockCacheItem2 = new MockTokenCacheItem(); mockCacheItem2.Setup(item => item.AccessToken).Returns("token 2"); mockCacheItem2.Setup(item => item.ClientId).Returns(accountSession.ClientId); var mockCacheItem3 = new MockTokenCacheItem(); mockCacheItem3.Setup(item => item.AccessToken).Returns("token 3"); mockCacheItem3.Setup(item => item.UniqueId).Returns(accountSession.UserId); this.tokenCache.Setup(cache => cache.ReadItems()) .Returns(new List <ITokenCacheItem> { mockCacheItem1.Object, mockCacheItem2.Object, mockCacheItem3.Object }); this.tokenCache.Setup(cache => cache.DeleteItem( It.Is <ITokenCacheItem>(item => string.Equals(accountSession.ClientId, item.ClientId)))); this.tokenCache.ResetCalls(); this.credentialCache.DeleteFromCache(accountSession); this.tokenCache.Verify(cache => cache.DeleteItem( It.Is <ITokenCacheItem>(item => string.Equals("token 1", item.AccessToken))), Times.Once, "DeleteItem not called with expected item."); }
protected async Task AuthenticateWithRefreshToken(AccountSession refreshedAccountSession) { using (var httpResponseMessage = new HttpResponseMessage()) using (var responseStream = new MemoryStream()) using (var streamContent = new StreamContent(responseStream)) { httpResponseMessage.Content = streamContent; this.httpProvider.Setup( provider => provider.SendAsync( It.Is <HttpRequestMessage>( request => request.RequestUri.ToString().Equals(this.serviceInfo.TokenServiceUrl)))) .Returns(Task.FromResult <HttpResponseMessage>(httpResponseMessage)); this.serializer.Setup( serializer => serializer.DeserializeObject <IDictionary <string, string> >(It.IsAny <Stream>())) .Returns(new Dictionary <string, string> { { Constants.Authentication.AccessTokenKeyName, refreshedAccountSession.AccessToken }, { Constants.Authentication.RefreshTokenKeyName, refreshedAccountSession.RefreshToken }, }); var accountSession = await this.authenticationProvider.AuthenticateAsync(); Assert.IsNotNull(accountSession, "No account session returned."); Assert.AreEqual( refreshedAccountSession.AccessToken, accountSession.AccessToken, "Unexpected access token returned."); Assert.AreEqual( refreshedAccountSession.RefreshToken, accountSession.RefreshToken, "Unexpected refresh token returned."); Assert.AreEqual( refreshedAccountSession.AccessToken, this.authenticationProvider.CurrentAccountSession.AccessToken, "Unexpected cached access token."); Assert.AreEqual( refreshedAccountSession.RefreshToken, this.authenticationProvider.CurrentAccountSession.RefreshToken, "Unexpected cached refresh token."); } }
public async Task AppendAuthenticationHeader() { var cachedAccountSession = new AccountSession { AccessToken = "token", }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; using (var httpRequestMessage = new HttpRequestMessage()) { await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage); Assert.AreEqual( string.Format("{0} {1}", Constants.Headers.Bearer, cachedAccountSession.AccessToken), httpRequestMessage.Headers.Authorization.ToString(), "Unexpected authorization header set."); } }
internal async Task<AccountSession> GetAccountSessionAsync() { await this.SignOutAsync(); var serviceTicketRequest = new OnlineIdServiceTicketRequest(string.Join(" ", this.ServiceInfo.Scopes), "DELEGATION"); var authenticationResponse = await this.authenticator.AuthenticateUserAsync(serviceTicketRequest); var ticket = authenticationResponse.Tickets.FirstOrDefault(); var accountSession = new AccountSession { AccessToken = ticket == null ? null : ticket.Value, AccountType = this.ServiceInfo.AccountType, CanSignOut = this.authenticator.CanSignOut, ClientId = this.authenticator.ApplicationId.ToString(), UserId = authenticationResponse.SafeCustomerId, }; return accountSession; }
private async void LogOffClick(object sender, RoutedEventArgs e) { if (_client == null || _session?.AccessToken == null) { var dialog = new MessageDialog("Please authenticate first!", "Sorry!"); await dialog.ShowAsync(); return; } Exception error = null; ShowBusy(true); try { await _client.SignOutAsync(); } catch (Exception ex) { error = ex; } if (error != null) { var dialog = new MessageDialog(error.Message, "Error!"); await dialog.ShowAsync(); ShowBusy(false); return; } _session = null; _savedId = null; _client = null; var successDialog = new MessageDialog("You are now logged off", "Success"); await successDialog.ShowAsync(); ShowBusy(false); }
public async Task AuthenticateRequestAsync() { var cachedAccountSession = new AccountSession { AccessToken = "token", ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(60), }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; using (var httpRequestMessage = new HttpRequestMessage()) { await this.authenticationProvider.AuthenticateRequestAsync(httpRequestMessage).ConfigureAwait(false); Assert.AreEqual( string.Format("{0} {1}", OAuthConstants.Headers.Bearer, cachedAccountSession.AccessToken), httpRequestMessage.Headers.Authorization.ToString(), "Unexpected authorization header set."); } }
internal async Task <AccountSession> GetAccountSessionAsync() { await this.SignOutAsync(); var serviceTicketRequest = new OnlineIdServiceTicketRequest(string.Join(" ", this.ServiceInfo.Scopes), "DELEGATION"); var authenticationResponse = await this.authenticator.AuthenticateUserAsync(serviceTicketRequest); var ticket = authenticationResponse.Tickets.FirstOrDefault(); var accountSession = new AccountSession { AccessToken = ticket == null ? null : ticket.Value, AccountType = this.ServiceInfo.AccountType, CanSignOut = this.authenticator.CanSignOut, ClientId = this.authenticator.ApplicationId.ToString(), UserId = authenticationResponse.SafeCustomerId, }; return(accountSession); }
public async Task AuthenticateRequestAsync() { var accountSession = new AccountSession { AccessToken = "token", ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(60) }; this.AuthenticationProvider.CurrentAccountSession = accountSession; using (HttpRequestMessage request = new HttpRequestMessage()) { await this.AuthenticationProvider.AuthenticateRequestAsync(request); Assert.AreEqual( string.Format("{0} {1}", OAuthConstants.Headers.Bearer, accountSession.AccessToken), request.Headers.Authorization.ToString(), "Unexpected authorization header set."); } }
public async Task<bool> Claim(Uri uri, string documentTitle) { var authenticationResponseValues = UrlHelper.GetQueryOptions(uri); OAuthErrorHandler.ThrowIfError(authenticationResponseValues); string code; if (authenticationResponseValues != null && authenticationResponseValues.TryGetValue("code", out code)) { using (var httpProvider = new HttpProvider()) { _accountSession = await _oAuthHelper.RedeemAuthorizationCodeAsync(code, OneDriveHelper.OneDriveClientId, OneDriveHelper.OneDriveClientSecret, this.RedirectionUrl.ToString(), OneDriveHelper.Scopes, httpProvider).ConfigureAwait(false); } } return (_accountSession != null); }
/// <inheritdoc/> public async Task <bool> TryAuthenticateAsync() { var refreshToken = GetRefreshToken(); if (string.IsNullOrWhiteSpace(refreshToken)) { IsAuthenticated = false; return(false); } var session = new AccountSession { ClientId = SecurityHelper.ToUnsecureString(_clientId), RefreshToken = SecurityHelper.ToUnsecureString(SecurityHelper.DecryptString(refreshToken)) }; var msaAuthProvider = new MsaAuthenticationProvider(SecurityHelper.ToUnsecureString(_clientId), "https://login.live.com/oauth20_desktop.srf", _scope) { CurrentAccountSession = session }; try { var httpProvider = new HttpProvider(new Serializer()); httpProvider.OverallTimeout = TimeSpan.FromMinutes(20); _client = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider, httpProvider); await msaAuthProvider.AuthenticateUserAsync(); IsAuthenticated = msaAuthProvider.IsAuthenticated; TokenProvider.SetToken("RefreshToken", SecurityHelper.EncryptString(SecurityHelper.ToSecureString(msaAuthProvider.CurrentAccountSession.RefreshToken))); Logger.Instance.Information($"User authenticated to {CloudServiceName}."); } catch (Exception exception) { Logger.Instance.Error(exception); IsAuthenticated = false; } return(IsAuthenticated); }
public async Task AuthenticateUserAsync_RefreshToken() { var cachedAccountSession = new AccountSession { ClientId = "1", AccessToken = "token", ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(4), RefreshToken = "refresh", }; var refreshedAccountSession = new AccountSession { ClientId = "1", AccessToken = "token2", RefreshToken = "refresh2", }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; await this.AuthenticateWithRefreshToken(refreshedAccountSession).ConfigureAwait(false); }
public async Task AppendAuthenticationHeaderDifferentType() { var cachedAccountSession = new AccountSession { AccessToken = "token", AccessTokenType = "test", ExpiresOnUtc = DateTimeOffset.UtcNow.AddHours(1), }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; using (var httpRequestMessage = new HttpRequestMessage()) { await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage); Assert.AreEqual( string.Format("{0} {1}", cachedAccountSession.AccessTokenType, cachedAccountSession.AccessToken), httpRequestMessage.Headers.Authorization.ToString(), "Unexpected authorization header set."); } }
private void Login() { using (var context = UnitOfWork.Factory.Instance()) { var login = context.Accounts.Login(txtUserName.Text, txtUserPass.Text); if (!login.Exists) { LoginErrorMessage(); return; } AccountSession.SetAccount(login.Account); this.Hide(); var main = new MainView(); main.FormClosed += (s, e) => { this.Show(); }; main.Show(); } }
public async Task AuthenticateByAccountSessionAsync(AccountSession accountSession) { if (accountSession == null) { throw new ArgumentNullException("accountSession"); } accountSession = await this.ProcessCachedAccountSessionAsync(accountSession); if (accountSession == null || string.IsNullOrEmpty(accountSession.AccessToken)) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = "Failed to retrieve a valid access token" }); } this.AccountSession = accountSession; }
private async void AuthenticateClick(object sender, RoutedEventArgs e) { ShowBusy(true); Exception error = null; try { _session = null; // Using the OnlineIdAuthenticator _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator( _scopes); // Using the WebAuthenticationBroker //_client = OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker( // "000000004C172C3F", // _scopes); _session = await _client.AuthenticateAsync(); Debug.WriteLine($"Token: {_session.AccessToken}"); var dialog = new MessageDialog("You are authenticated!", "Success!"); await dialog.ShowAsync(); ShowBusy(false); } catch (Exception ex) { error = ex; } if (error != null) { var dialog = new MessageDialog("Problem when authenticating!", "Sorry!"); await dialog.ShowAsync(); ShowBusy(false); } }
public async Task SignOutAsync_SingleSignOn() { this.signOut = true; var expectedSignOutUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", this.serviceInfo.SignOutUrl, this.serviceInfo.AppId, this.serviceInfo.ReturnUrl); var accountSession = new AccountSession { AccessToken = "accessToken", ClientId = "12345", }; this.authenticationProvider.CurrentAccountSession = accountSession; await this.authenticationProvider.SignOutAsync(); Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared."); Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called."); }
public async Task <bool> Claim(Uri uri, string documentTitle) { var authenticationResponseValues = UrlHelper.GetQueryOptions(uri); OAuthErrorHandler.ThrowIfError(authenticationResponseValues); string code; if (authenticationResponseValues != null && authenticationResponseValues.TryGetValue("code", out code)) { using (var httpProvider = new HttpProvider(ProxyTools.CreateHttpClientHandler(), true)) { _accountSession = await _oAuthHelper.RedeemAuthorizationCodeAsync(code, OneDriveHelper.OneDriveClientId, OneDriveHelper.OneDriveClientSecret, this.RedirectionUrl.ToString(), OneDriveHelper.Scopes, httpProvider).ConfigureAwait(false); } } return(_accountSession != null); }
public async Task SignOutAsync() { var accountSession = new AccountSession { AccessToken = "accessToken", CanSignOut = true, ClientId = "12345", }; this.authenticationProvider.CurrentAccountSession = accountSession; await this.authenticationProvider.SignOutAsync(); this.httpProvider.Verify( provider => provider.SendAsync( It.Is <HttpRequestMessage>(message => message.RequestUri.ToString().Equals(this.serviceInfo.SignOutUrl))), Times.Once); Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared."); this.credentialCache.Verify(cache => cache.OnDeleteFromCache(), Times.Once); }
public void LinkAccountAccountAlreadyLinkedEx() { Assert.Throws<System.InvalidOperationException>(() => { ISessionFacade f = this.DumbAss; //we need to override the db behavior to mock a resultset AccountSession mAcctSess = new AccountSession() { accountID = 1 , sessionID = 1 , id = 1 }; Mock<IRepository<AccountSession>> mAccountSessionRepo = new Mock<IRepository<AccountSession>>(); mAccountSessionRepo.Setup(m => m.Get(It.IsAny<Expression<Func<AccountSession, bool>>>(), null, It.IsAny<string>())) .Returns(new List<AccountSession>() { mAcctSess }); ((SessionFacade)f).AccountSessionRepo = mAccountSessionRepo.Object; f.LinkAccount(new Mock<ISession>().Object, new Mock<intrinsic.security.model.IAccount>().Object); }); }
/// <summary> /// Tests logging into MobileService with Microsoft Account token (via OneDrive SDK). /// App needs to be assosciated with a WindowsStoreApp /// </summary> private async Task TestClientDirectedMicrosoftAccountLogin() { try { Task <AccountSession> sessionTask = null; // Force AuthenticateAsync() to run on the UI thread. await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { IOneDriveClient oneDriveClient = OneDriveClientExtensions.GetUniversalClient(new string[] { "wl.signin" }); sessionTask = oneDriveClient.AuthenticateAsync(); }); AccountSession session = await sessionTask; if (session != null && session.AccessToken != null) { JObject accessToken = new JObject(); accessToken["access_token"] = session.AccessToken; MobileServiceUser user = await this.GetClient().LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, accessToken); Log(string.Format("Log in with Microsoft Account OneDrive SDK succeeded - userId {0}", user.UserId)); } else { Assert.Fail("Log in with Microsoft Account OneDrive SDK failed"); } } catch (Exception exception) { Log(string.Format("ExceptionType: {0} Message: {1} StackTrace: {2}", exception.GetType().ToString(), exception.Message, exception.StackTrace)); Assert.Fail("Log in with Microsoft Account OneDrive SDK failed"); } }
private async Task HandleRealmlist() { if (!this.isReconnect) // TODO: This should not be done in here? { var account = this.accountService.GetAccount(this.srp.I); // for development, create new account if not found if (account is null) { account = new Account { Identifier = this.srp.I }; this.accountService.AddAccount(account); } var session = new AccountSession(this.srp.I, this.srp.SessionKey); this.accountService.AddSession(session); } var realms = this.realmlistService.GetRealms(); await this.Send(ServerRealmlist.Get(realms, this.Build)); }
public bool ConnectAccountInternal(Guid worldId, long accountId, int sessionId) { if (!MsManager.Instance.AuthentificatedClients.Any(s => s.Equals(CurrentClient.ClientId))) { return(false); } AccountSession account = MsManager.Instance.ConnectedAccounts.FirstOrDefault(a => a.AccountId.Equals(accountId) && a.SessionId.Equals(sessionId)); if (account == null) { return(false); } { account.CanSwitchChannel = false; account.PreviousChannel = account.ConnectedWorld; account.ConnectedWorld = MsManager.Instance.WorldServers.FirstOrDefault(s => s.Id.Equals(worldId)); if (account.ConnectedWorld != null) { return(true); } } return(false); }
public async Task AuthenticateAsync_RefreshToken() { var cachedAccountSession = new AccountSession { AccountType = AccountType.MicrosoftAccount, ClientId = "1", AccessToken = "token", ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(4), RefreshToken = "refresh", }; var refreshedAccountSession = new AccountSession { AccountType = AccountType.MicrosoftAccount, ClientId = "1", AccessToken = "token2", RefreshToken = "refresh2", }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; await this.AuthenticateWithRefreshToken(refreshedAccountSession); }
public async Task AuthenticateUserAsync_CachedCurrentAccountSession() { var cachedAccountSession = new AccountSession { AccessToken = "token", ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(10), }; this.authenticationProvider.CurrentAccountSession = cachedAccountSession; await this.authenticationProvider.AuthenticateUserAsync(this.httpProvider.Object).ConfigureAwait(false); Assert.IsNotNull(this.authenticationProvider.CurrentAccountSession, "No account session returned."); Assert.AreEqual( cachedAccountSession.AccessToken, this.authenticationProvider.CurrentAccountSession.AccessToken, "Unexpected access token returned."); Assert.AreEqual( cachedAccountSession.ExpiresOnUtc, this.authenticationProvider.CurrentAccountSession.ExpiresOnUtc, "Unexpected expiration returned."); }
public async Task SignOutAsync_SingleSignOn() { var applicationCallbackUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); this.signOut = true; var expectedSignOutUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", OAuthConstants.MicrosoftAccountSignOutUrl, this.clientId, applicationCallbackUrl); this.webAuthenticationUi.OnAuthenticateAsync = (Uri requestUri, Uri callbackUri) => { Assert.AreEqual(expectedSignOutUrl, requestUri.ToString(), "Unexpected request Uri."); Assert.AreEqual(applicationCallbackUrl, callbackUri.ToString(), "Unexpected callback Uri."); }; var accountSession = new AccountSession { AccessToken = "accessToken", ClientId = "12345", }; this.authenticationProvider = new MsaAuthenticationProvider( this.clientId, /* returnUrl */ null, this.scopes, this.credentialCache); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi; this.authenticationProvider.CurrentAccountSession = accountSession; await this.authenticationProvider.SignOutAsync().ConfigureAwait(false); Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared."); Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called."); }
public void LinkAccountAccountAlreadyLinkedEx() { Assert.Throws <System.InvalidOperationException>(() => { ISessionFacade f = this.DumbAss; //we need to override the db behavior to mock a resultset AccountSession mAcctSess = new AccountSession() { accountID = 1 , sessionID = 1 , id = 1 }; Mock <IRepository <AccountSession> > mAccountSessionRepo = new Mock <IRepository <AccountSession> >(); mAccountSessionRepo.Setup(m => m.Get(It.IsAny <Expression <Func <AccountSession, bool> > >(), null, It.IsAny <string>())) .Returns(new List <AccountSession>() { mAcctSess }); ((SessionFacade)f).AccountSessionRepo = mAccountSessionRepo.Object; f.LinkAccount(new Mock <ISession>().Object, new Mock <intrinsic.security.model.IAccount>().Object); }); }
public async Task <RenewTokenModel> Handle(AuthenticateAccountCommand request, CancellationToken cancellationToken) { var acc = await _repo.Accounts.SingleOrDefaultAsync(x => x.Alias == request.Alias, cancellationToken : cancellationToken); var hashOfPass = _hash.Encode(request.Password); if (acc?.PasswordHash != hashOfPass) { throw new UnableAuthoriseAccountException($"Unable to authorise account:{request.Alias}"); } var oldsession = await _repo.AccountSessions.SingleOrDefaultAsync(x => x.AccountId == acc.Id); if (oldsession != null) { _repo.Remove(oldsession); } var dtNow = DateTime.Now; var session = new AccountSession() { AccountId = acc.Id, RenewToken = _token.IssueToken(), IssuedOn = dtNow, SessionExpired = dtNow.AddSeconds(_authConfig.sessionExpiredInSec), RenewExpired = dtNow.AddSeconds(_authConfig.renewExpiredInSec) }; _repo.AccountSessions.Add(session); await _repo.SaveChangesAsync(cancellationToken); await _mediator.Publish(new AuthenticateSuccessAccountDomainEvent(acc.Id, session.IssuedOn, session.RenewToken, session.SessionExpired, acc.Role), cancellationToken); return(RenewTokenModel.Create(session)); }
public void AddToCache_CacheChangeNotifications() { var accountSession = new AccountSession { AccessToken = "token", UserId = "1", }; this.credentialCache.AfterAccess = this.AfterAccess; this.credentialCache.BeforeAccess = this.BeforeAccess; this.credentialCache.BeforeWrite = this.BeforeWrite; Assert.IsNotNull(this.credentialCache.AfterAccess, "AfterAccess delegate not set."); Assert.IsNotNull(this.credentialCache.BeforeAccess, "BeforeAccess delegate not set."); Assert.IsNotNull(this.credentialCache.BeforeWrite, "BeforeWrite delegate not set."); this.credentialCache.AddToCache(accountSession); Assert.IsTrue(this.afterAccessCalled, "AfterAccess not called."); Assert.IsTrue(this.beforeAccessCalled, "BeforeAccess not called."); Assert.IsTrue(this.beforeWriteCalled, "BeforeWrite not called."); Assert.IsTrue(this.credentialCache.HasStateChanged, "State changed flag not set."); }
private void AccountSessions_Detach(AccountSession entity) { this.SendPropertyChanging(); entity.Account = null; }
public void Insert(AccountSession session) { lock (m_ClearSessionList) { if (m_ClearSessionList != session.ListNode.List) { m_ClearSessionList.AddLast(session.ListNode); } else { m_ClearSessionList.Remove(session.ListNode); m_ClearSessionList.AddLast(session.ListNode); } session.ListNode.Value.InsertTime = DateTime.Now; } }
public ClearSessionNode(int user, string sessionid, AccountSession session) { _userID = user; _sessionID = sessionid; _session = session; }
void ISessionFacade.LinkAccount(ISession session, IAccount account) { if (session == null) { throw new ArgumentNullException("session"); } if (account == null) { throw new ArgumentNullException("account"); } AccountSession current = AccountSessionRepo.Get(g => g.sessionID == session.id, null, null).FirstOrDefault(); if (current != null) throw new InvalidOperationException("Session is already associated with an account"); AccountSession joined = new AccountSession() { accountID = account.ID , sessionID = session.id }; this.AccountSessionRepo.Insert(joined); this.Dimension.SaveChanges(); }