public ChatUser AddUser(string userName, string clientId, string password) { if (!IsValidUserName(userName)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName)); } EnsureUserNameIsAvailable(userName); var user = new ChatUser { Name = userName, Status = (int)UserStatus.Active, Id = Guid.NewGuid().ToString("d"), Salt = _crypto.CreateSalt(), LastActivity = DateTime.UtcNow }; if (String.IsNullOrEmpty(password)) { throw new InvalidOperationException("A password is required."); } ValidatePassword(password); user.HashedPassword = password.ToSha256(user.Salt); _repository.Add(user); AddClient(user, clientId); return(user); }
public ChatRoom AddRoom(ChatUser user, string name) { if (name.Equals("Lobby", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Lobby is not a valid chat room."); } if (!IsValidRoomName(name)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid room name.", name)); } var room = new ChatRoom { Name = name, Creator = user }; room.Owners.Add(user); _repository.Add(room); user.OwnedRooms.Add(room); return(room); }
public ChatRoom AddRoom(ChatUser user, string name) { if (!_settings.AllowRoomCreation && !user.IsAdmin) { throw new HubException(LanguageResources.RoomCreationDisabled); } if (name.Equals("Lobby", StringComparison.OrdinalIgnoreCase)) { throw new HubException(LanguageResources.RoomCannotBeNamedLobby); } if (!IsValidRoomName(name)) { throw new HubException(String.Format(LanguageResources.RoomInvalidName, name)); } var room = new ChatRoom { Name = name, Creator = user }; room.Owners.Add(user); _repository.Add(room); user.OwnedRooms.Add(room); return room; }
public ChatUser AddUser(string userName, string identity, string email) { if (!IsValidUserName(userName)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName)); } // This method is used in the auth workflow. If the username is taken it will add a number // to the user name. if (UserExists(userName)) { var usersWithNameLikeMine = _repository.Users.Count(u => u.Name.StartsWith(userName)); userName += usersWithNameLikeMine; } var user = new ChatUser { Name = userName, Status = (int)UserStatus.Active, Email = email, Hash = email.ToMD5(), Identity = identity, Id = Guid.NewGuid().ToString("d"), LastActivity = DateTime.UtcNow }; _repository.Add(user); _repository.CommitChanges(); return(user); }
public ApplicationSettings Load() { var settings = _cache.Get <ApplicationSettings>(_jabbrSettingsCacheKey); if (settings == null) { Settings dbSettings = _repository.Settings.FirstOrDefault(); if (dbSettings == null) { // Create the initial app settings settings = ApplicationSettings.GetDefaultSettings(); dbSettings = new Settings { RawSettings = JsonConvert.SerializeObject(settings) }; _repository.Add(dbSettings); } else { try { settings = JsonConvert.DeserializeObject <ApplicationSettings>(dbSettings.RawSettings); if (settings.ContentProviders == null) { // this will apply the default for the case where ApplicationSettings exists from prior to // when this property was introduced. settings.ContentProviders = ContentProviderSetting.GetDefaultContentProviders(); } } catch { // TODO: Record the exception // We failed to load the settings from the db so go back to using the default settings = ApplicationSettings.GetDefaultSettings(); dbSettings.RawSettings = JsonConvert.SerializeObject(settings); _repository.CommitChanges(); } } // Cache the settings forever (until it changes) _cache.Set(_jabbrSettingsCacheKey, settings, _settingsCacheTimespan); } return(settings); }
public ApplicationSettings Load() { var settings = _cache.Get <ApplicationSettings>(_jabbrSettingsCacheKey); if (settings == null) { Settings dbSettings = _repository.Settings.FirstOrDefault(); if (dbSettings == null) { // Create the initial app settings settings = ApplicationSettings.GetDefaultSettings(); dbSettings = new Settings { RawSettings = JsonConvert.SerializeObject(settings) }; _repository.Add(dbSettings); } else { try { settings = JsonConvert.DeserializeObject <ApplicationSettings>(dbSettings.RawSettings); } catch { // TODO: Record the exception // We failed to load the settings from the db so go back to using the default settings = ApplicationSettings.GetDefaultSettings(); dbSettings.RawSettings = JsonConvert.SerializeObject(settings); _repository.CommitChanges(); } } // Cache the settings forever (until it changes) _cache.Set(_jabbrSettingsCacheKey, settings, _settingsCacheTimespan); } return(settings); }
private ChatUser AddUser(string userName, string providerName, string identity, string email) { if (!IsValidUserName(userName)) { throw new InvalidOperationException(String.Format(LanguageResources.UserInvalidName, userName)); } EnsureProviderAndIdentityAvailable(providerName, identity); // This method is used in the auth workflow. If the username is taken it will add a number // to the user name. if (UserExists(userName)) { var usersWithNameLikeMine = _repository.Users.Count(u => u.Name.StartsWith(userName)); userName += usersWithNameLikeMine; } var user = new ChatUser { Name = userName, Status = (int)UserStatus.Active, Hash = email.ToMD5(), Id = Guid.NewGuid().ToString("d"), LastActivity = DateTime.UtcNow, IsAdmin = IsFirstUser() }; var chatUserIdentity = new ChatUserIdentity { User = user, Email = email, Identity = identity, ProviderName = providerName }; _repository.Add(user); _repository.Add(chatUserIdentity); _repository.CommitChanges(); return(user); }
public ChatUser AddUser(WindowsPrincipal windowsPrincipal) { string fullName = windowsPrincipal.Identity.Name; int domainSlash = fullName.IndexOf('\\'); string userName = domainSlash != -1 ? fullName.Substring(domainSlash + 1) : fullName; if (UserExists(userName)) { userName = fullName; } var user = new ChatUser { Name = userName, Status = (int)UserStatus.Active, Id = fullName, LastActivity = DateTime.UtcNow }; _repository.Add(user); _repository.CommitChanges(); return(user); }
public void PostNotification(ClientNotification notification, bool executeContentProviders) { string userId = Context.User.GetUserId(); ChatUser user = _repository.GetUserById(userId); ChatRoom room = _repository.VerifyUserRoom(_cache, user, notification.Room); // User must be an owner if (room == null || !room.Owners.Contains(user) || (room.Private && !user.AllowedRooms.Contains(room))) { throw new InvalidOperationException("You're not allowed to post a notification"); } var chatMessage = new ChatMessage { Id = Guid.NewGuid().ToString("d"), Content = notification.Content, User = user, Room = room, HtmlEncoded = false, ImageUrl = notification.ImageUrl, Source = notification.Source, When = DateTimeOffset.UtcNow, MessageType = (int)MessageType.Notification }; _repository.Add(chatMessage); _repository.CommitChanges(); Clients.Group(room.Name).addMessage(new MessageViewModel(chatMessage), room.Name); if (executeContentProviders) { var urls = UrlExtractor.ExtractUrls(chatMessage.Content); if (urls.Count > 0) { _resourceProcessor.ProcessUrls(urls, Clients, room.Name, chatMessage.Id); } } }
// This is an uber hack to make sure the db is in sync with SignalR private void EnsureClientConnected(ILogger logger, IJabbrRepository repo, ITrackingConnection connection) { var contextField = connection.GetType().GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance); if (contextField == null) { return; } var context = contextField.GetValue(connection) as HostContext; if (context == null) { return; } string connectionData = context.Request.QueryString["connectionData"]; if (String.IsNullOrEmpty(connectionData)) { return; } var hubs = JsonConvert.DeserializeObject<HubConnectionData[]>(connectionData); if (hubs.Length != 1) { return; } // We only care about the chat hub if (!hubs[0].Name.Equals("chat", StringComparison.OrdinalIgnoreCase)) { return; } logger.Log("Connection {0} exists but isn't tracked.", connection.ConnectionId); string userId = context.Request.User.GetUserId(); ChatUser user = repo.GetUserById(userId); if (user == null) { logger.Log("Unable to find user with id {0}", userId); return; } var client = new ChatClient { Id = connection.ConnectionId, User = user, UserAgent = context.Request.Headers["User-Agent"], LastActivity = DateTimeOffset.UtcNow, LastClientActivity = user.LastActivity }; repo.Add(client); repo.CommitChanges(); }
// This is an uber hack to make sure the db is in sync with SignalR private void EnsureClientConnected(ILogger logger, IJabbrRepository repo, ITrackingConnection connection) { var contextField = connection.GetType().GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance); if (contextField == null) { return; } var context = contextField.GetValue(connection) as HostContext; if (context == null) { return; } string connectionData = context.Request.QueryString["connectionData"]; if (String.IsNullOrEmpty(connectionData)) { return; } var hubs = JsonConvert.DeserializeObject <HubConnectionData[]>(connectionData); if (hubs.Length != 1) { return; } // We only care about the chat hub if (!hubs[0].Name.Equals("chat", StringComparison.OrdinalIgnoreCase)) { return; } logger.Log("Connection {0} exists but isn't tracked.", connection.ConnectionId); string userId = context.Request.User.GetUserId(); ChatUser user = repo.GetUserById(userId); if (user == null) { logger.Log("Unable to find user with id {0}", userId); return; } var client = new ChatClient { Id = connection.ConnectionId, User = user, UserAgent = context.Request.Headers["User-Agent"], LastActivity = DateTimeOffset.UtcNow, LastClientActivity = user.LastActivity }; repo.Add(client); repo.CommitChanges(); }
public ChatTest() { // Fetch new instances of the required objects _context = new JabbrContext(new DbContextOptions <JabbrContext>()); _repository = new InMemoryRepository(_context); _cache = new DefaultCache(); _recentMessageCache = new RecentMessageCache(); _settings = new OptionsManager <ApplicationSettings>(new List <IConfigureOptions <ApplicationSettings> >() { }); _chatService = new ChatService(_cache, _recentMessageCache, _repository); // Create Mocks of the objects being passed into SignalR var request = new Mock <HttpRequest>(); var connection = new Mock <IConnection>(); var pipeline = new Mock <IHubPipelineInvoker>(); // Taken from normal JabbR-Core execution var connectionId = "79482a87-8d16-42bc-b5ce-1fb7b309ad1e"; // Establish new Chat hub with normal SignalR connection + pipeline var chat = new TestableChat(_repository, _settings, _chatService, connection); chat.Clients = new HubConnectionContext(pipeline.Object, chat.MockConnection.Object, "Chat", connectionId); // Include required claims with request for authentication // Adam's LoginFakerMiddleware runs but doesn't establish Hub context // so we can put the same code here to establish an identity var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, "James")); claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "provider")); claims.Add(new Claim(ClaimTypes.NameIdentifier, "identity")); claims.Add(new Claim(ClaimTypes.Email, "*****@*****.**")); claims.Add(new Claim(JabbRClaimTypes.Identifier, "2")); var claimsIdentity = new ClaimsIdentity(claims, Constants.JabbRAuthType); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); ChatUser user = new ChatUser() { Name = "James", Email = "*****@*****.**", Id = "2", Identity = claimsIdentity.ToString() }; // Add to repository for methods that perform user verification _repository.Add(user); // Establish request properties here, investigate query string request.Setup(r => r.Cookies).Returns(new Mock <IRequestCookieCollection>().Object); request.Setup(r => r.HttpContext.User).Returns(claimsPrincipal); // Register the real SignalR context to the TestableChat. chat.Context = new HubCallerContext(request.Object, connectionId); chat.Groups = new GroupManager(connection.Object, "mygroup"); // Instantiate Chat hub. _chat = chat; }
public void GetUserSuccessfully() { // Create ChatUser var user = new ChatUser() { Id = "12345", Name = "Test", LastActivity = Convert.ToDateTime("2016-08-23 00:00:00.000"), IsAdmin = true, IsAfk = true }; _repository.Add((user)); // Create Auth Identity // Not yet implemented (Login Auth) // Test to see if same ChatUser is returned //Assert.Equal(user, _repository.GetUser(_principal)); // Clean up _repository.Remove(user); Console.WriteLine("\tRepositoryExtensionTest.GetUserSuccessfully: Complete"); }