Inheritance: IApplicationSettings
コード例 #1
1
ファイル: Startup.cs プロジェクト: bartsipes/JabbR
        public void Configuration(IAppBuilder app)
        {
            var settings = new ApplicationSettings();

            if (settings.MigrateDatabase)
            {
                // Perform the required migrations
                DoMigrations();
            }

            var kernel = SetupNinject(settings);

            app.Use(typeof(DetectSchemeHandler));

            if (settings.RequireHttps)
            {
                app.Use(typeof(RequireHttpsHandler));
            }

            app.UseShowExceptions();

            // This needs to run before everything
            app.Use(typeof(AuthorizationHandler), kernel.Get<IAuthenticationTokenService>());

            SetupSignalR(kernel, app);
            SetupWebApi(kernel, app);
            SetupMiddleware(settings, app);
            SetupNancy(kernel, app);

            SetupErrorHandling();
        }
コード例 #2
0
        public void Save(ApplicationSettings settings)
        {
            string rawSettings = JsonConvert.SerializeObject(settings);

            // Update the database
            Settings dbSettings = _repository.Settings.FirstOrDefault();

            if (dbSettings == null)
            {
                dbSettings = new Settings
                {
                    RawSettings = rawSettings
                };

                _repository.Add(dbSettings);
            }
            else
            {
                dbSettings.RawSettings = rawSettings;
            }

            _repository.CommitChanges();

            // Clear the cache
            _cache.Remove(_jabbrSettingsCacheKey);
        }
コード例 #3
0
 public LoginViewModel(ApplicationSettings settings, IEnumerable<IAuthenticationProvider> configuredProviders, IEnumerable<ChatUserIdentity> userIdentities)
 {
     SocialDetails = new SocialLoginViewModel(configuredProviders, userIdentities);
     AllowUserRegistration = settings.AllowUserRegistration;
     AllowUserResetPassword = settings.AllowUserResetPassword;
     HasEmailSender = !string.IsNullOrWhiteSpace(settings.EmailSender);
 }
コード例 #4
0
ファイル: Startup.cs プロジェクト: buybackoff/JabbR
        public void Configuration(IAppBuilder app)
        {
            var settings = new ApplicationSettings();

            if (settings.MigrateDatabase)
            {
                // Perform the required migrations
                DoMigrations();
            }

            var kernel = SetupNinject(settings);

            app.Use(typeof(DetectSchemeHandler));

            if (settings.RequireHttps)
            {
                app.Use(typeof(RequireHttpsHandler));
            }

            app.UseShowExceptions();

            SetupAuth(app, kernel);
            SetupSignalR(kernel, app);
            SetupWebApi(kernel, app);
            SetupMiddleware(kernel, app, settings);
            SetupNancy(kernel, app);

            SetupErrorHandling();
        }
コード例 #5
0
ファイル: ChatFacts.cs プロジェクト: CloudMetal/JabbR
        public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<ContentProviderProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();
            var settings = new ApplicationSettings();
            var mockPipeline = new Mock<IHubPipelineInvoker>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState);

            var prinicipal = new Mock<IPrincipal>();

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);
            request.Setup(m => m.User).Returns(prinicipal.Object);

            // setup context
            chat.Context = new HubCallerContext(request.Object, connectionId);

            return chat;
        }
コード例 #6
0
ファイル: EmailService.cs プロジェクト: QuinntyneBrown/JabbR
 public EmailService(ApplicationSettings applicationSettings,
                     IEmailTemplateEngine templateEngine,
                     IEmailSender sender)
 {
     _applicationSettings = applicationSettings;
     _templateEngine = templateEngine;
     _sender = sender;
 }
コード例 #7
0
        public AdministrationModule(ApplicationSettings applicationSettings,
                                    ISettingsManager settingsManager)
            : base("/administration")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                return View["index", applicationSettings];
            };

            Post["/"] = _ =>
            {
                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                try
                {
                    var settings = this.Bind<ApplicationSettings>();

                    IDictionary<string, string> errors;
                    if (ApplicationSettings.TryValidateSettings(settings, out errors))
                    {
                        settingsManager.Save(settings);
                    }
                    else
                    {
                        foreach (var error in errors)
                        {
                            this.AddValidationError(error.Key, error.Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.SettingsSaveSuccess);
                    return Response.AsRedirect("~/administration");
                }

                return View["index", applicationSettings];
            };
        }
コード例 #8
0
        public SettingsKeyProvider(ApplicationSettings settings)
        {
            if (String.IsNullOrEmpty(settings.EncryptionKey))
            {
                throw new ArgumentException("Missing encryptionKey");
            }

            if (String.IsNullOrEmpty(settings.VerificationKey))
            {
                throw new ArgumentException("Missing validationKey");
            }

            EncryptionKey = CryptoHelper.FromHex(settings.EncryptionKey);
            VerificationKey = CryptoHelper.FromHex(settings.VerificationKey);
        }
コード例 #9
0
ファイル: ChatFacts.cs プロジェクト: QuinntyneBrown/JabbR
 public TestableChat(Mock<ContentProviderProcessor> mockedResourceProcessor, Mock<IChatService> mockedChatService, IJabbrRepository repository, Mock<IConnection> connection, ApplicationSettings settings)
     : base(mockedResourceProcessor.Object,
            mockedChatService.Object,
            new Mock<IRecentMessageCache>().Object, 
            repository, 
            new Mock<ICache>().Object, 
            new Mock<ILogger>().Object,
            settings)
 {
     MockedResourceProcessor = mockedResourceProcessor;
     MockedChatService = mockedChatService;
     Repository = repository;
     MockedConnection = connection;
     Settings = settings;
 }
コード例 #10
0
        public override bool IsValidContent(Uri uri)
        {
            if(_settings == null)
                _settings = _kernel.Get<ApplicationSettings>();

            if (_settings.EmbedlyKey.IsNullOrWhiteSpace())
                return false;

            if (HostExceptions.Contains(uri.Host))
                return false;

            // valid for everything, requires a request to actually determine what
            // embedding is available.
            return true;
        }
コード例 #11
0
ファイル: Chat.cs プロジェクト: renangrativol/JabbR
 public Chat(ContentProviderProcessor resourceProcessor,
             IChatService service,
             IRecentMessageCache recentMessageCache,
             IJabbrRepository repository,
             ICache cache,
             ILogger logger,
             ApplicationSettings settings)
 {
     _resourceProcessor = resourceProcessor;
     _service = service;
     _recentMessageCache = recentMessageCache;
     _repository = repository;
     _cache = cache;
     _logger = logger;
     _settings = settings;
 }
コード例 #12
0
        public static bool TryValidateSettings(ApplicationSettings settings, out IDictionary<string, string> errors)
        {
            errors = new Dictionary<string, string>();

            if (!String.IsNullOrEmpty(settings.LocalFileSystemStoragePath))
            {
                if (!Path.IsPathRooted(settings.LocalFileSystemStoragePath))
                {
                    errors.Add("LocalFileSystemStoragePath", "The path must be an absolute path");
                }
                else if (settings.LocalFileSystemStoragePath.StartsWith(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, StringComparison.OrdinalIgnoreCase))
                {
                    errors.Add("LocalFileSystemStoragePath", "The path must not be under the JabbR root.");
                }
            }

            // TODO: Add more validation

            return errors.Count == 0;
        }
コード例 #13
0
        public AuthenticationService(AuthenticationProviderFactory factory, ApplicationSettings appSettings)
        {
            _factory = factory;

            if (!String.IsNullOrWhiteSpace(appSettings.FacebookAppId) && !String.IsNullOrWhiteSpace(appSettings.FacebookAppSecret))
            {
                _factory.AddProvider(new FacebookProvider(new ProviderParams
                {
                    PublicApiKey = appSettings.FacebookAppId,
                    SecretApiKey = appSettings.FacebookAppSecret
                }));
            }
            else
            {
                _factory.RemoveProvider("facebook");
            }
            if (!String.IsNullOrWhiteSpace(appSettings.TwitterConsumerKey) && !String.IsNullOrWhiteSpace(appSettings.TwitterConsumerSecret))
            {
                _factory.AddProvider(new TwitterProvider(new ProviderParams
                {
                    PublicApiKey = appSettings.TwitterConsumerKey,
                    SecretApiKey = appSettings.TwitterConsumerSecret
                }));
            }
            else
            {
                _factory.RemoveProvider("twitter");
            }
            if (!String.IsNullOrWhiteSpace(appSettings.GoogleClientID) && !String.IsNullOrWhiteSpace(appSettings.GoogleClientSecret))
            {
                _factory.AddProvider(new GoogleProvider(new ProviderParams
                {
                    PublicApiKey = appSettings.GoogleClientID,
                    SecretApiKey = appSettings.GoogleClientSecret
                }));
            }
            else
            {
                _factory.RemoveProvider("google");
            }
        }
コード例 #14
0
        public AdministrationModule(ApplicationSettings applicationSettings,
                                    ISettingsManager settingsManager)
            : base("/administration")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                return View["index", applicationSettings];
            };

            Post["/"] = _ =>
            {
                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                try
                {
                    var settings = this.Bind<ApplicationSettings>();

                    settingsManager.Save(settings);
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully saved the settings.");
                    return Response.AsRedirect("~/administration");
                }

                return View["index", applicationSettings];
            };
        }
コード例 #15
0
        private Task<ContentProviderResult> GetResult(ContentProviderHttpRequest request)
        {
            if (_settings == null)
                _settings = _kernel.Get<ApplicationSettings>();

            var url = string.Format(
                "http://api.embed.ly/1/oembed?key={0}&url={1}&maxwidth=425&format=json",
                _settings.EmbedlyKey,
                Uri.EscapeDataString(request.RequestUri.AbsoluteUri)
            );

            return Http.GetJsonAsync(url).Then<dynamic, ContentProviderResult>(result =>
            {
                if (result == null)
                    return (ContentProviderResult) null;

                return ParseResult(result);
            });
        }
コード例 #16
0
ファイル: AccountModule.cs プロジェクト: phillip-haydon/JabbR
        private LoginViewModel GetLoginViewModel(ApplicationSettings applicationSettings,
                                                 IJabbrRepository repository,
                                                 IAuthenticationService authService)
        {
            ChatUser user = null;

            if (IsAuthenticated)
            {
                user = repository.GetUserById(Principal.GetUserId());
            }

            var viewModel = new LoginViewModel(applicationSettings, authService.GetProviders(), user != null ? user.Identities : null);
            return viewModel;
        }
コード例 #17
0
            public void ThrowsIfRoomCreationDisabledAndNotAdmin()
            {
                var repository = new InMemoryRepository();
                var user = new ChatUser
                {
                    Name = "foo"
                };
                repository.Add(user);
                var settings = new ApplicationSettings
                {
                    AllowRoomCreation = false
                };

                var service = new ChatService(new Mock<ICache>().Object, repository, settings);

                Assert.Throws<HubException>(() => service.AddRoom(user, "NewRoom"));
            }
コード例 #18
0
 public AzureBlobStorageHandler(ApplicationSettings settings)
 {
     _settingsFunc = () => settings;
 }
コード例 #19
0
ファイル: HomeModule.cs プロジェクト: phillip-haydon/JabbR
        public HomeModule(ApplicationSettings settings, 
                          IJabbrConfiguration configuration, 
                          UploadCallbackHandler uploadHandler)
        {
            Get["/"] = _ =>
            {
                if (IsAuthenticated)
                {
                    var viewModel = new SettingsViewModel
                    {
                        GoogleAnalytics = settings.GoogleAnalytics,
                        Sha = configuration.DeploymentSha,
                        Branch = configuration.DeploymentBranch,
                        Time = configuration.DeploymentTime,
                        DebugMode = (bool)Context.Items["_debugMode"],
                        Version = Constants.JabbRVersion,
                        IsAdmin = Principal.HasClaim(JabbRClaimTypes.Admin)
                    };

                    return View["index", viewModel];
                }

                if (Principal.HasPartialIdentity())
                {
                    // If the user is partially authenticated then take them to the register page
                    return Response.AsRedirect("~/account/register");
                }

                return HttpStatusCode.Unauthorized;
            };

            Get["/monitor"] = _ =>
            {
                ClaimsPrincipal principal = Principal;

                if (principal == null ||
                    !principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return 403;
                }

                return View["monitor"];
            };

            Post["/upload"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return 403;
                }

                string roomName = Request.Form.room;
                string connectionId = Request.Form.connectionId;
                HttpFile file = Request.Files.First();

                // This blocks since we're not using nancy's async support yet
                UploadFile(
                    uploadHandler,
                    Principal.GetUserId(),
                    connectionId,
                    roomName,
                    file.Name,
                    file.ContentType,
                    file.Value).Wait();

                return 200;
            };

            Post["/upload-clipboard"] = _ =>
                {
                    if (!IsAuthenticated)
                    {
                        return 403;
                    }

                    string roomName = Request.Form.room;
                    string connectionId = Request.Form.connectionId;
                    string file = Request.Form.file;
                    string fileName = "clipboard_" + Guid.NewGuid().ToString("N");
                    string contentType = "image/jpeg";

                    var info = Regex.Match(file, @"data:image/(?<type>.+?);base64,(?<data>.+)");

                    var binData = Convert.FromBase64String(info.Groups["data"].Value);
                    contentType = info.Groups["type"].Value;

                    fileName = fileName + "." + contentType.Substring(contentType.IndexOf("/") + 1);

                    UploadFile(
                        uploadHandler,
                        Principal.GetUserId(),
                        connectionId,
                        roomName,
                        fileName,
                        contentType,
                        new MemoryStream(binData)).Wait();

                    return 200;
                };
        }
コード例 #20
0
            public void DoesNotThrowIfRoomCreationDisabledAndUserAdmin()
            {
                var repository = new InMemoryRepository();
                var user = new ChatUser
                {
                    Name = "foo",
                    IsAdmin = true
                };
                repository.Add(user);
                var settings = new ApplicationSettings
                {
                    AllowRoomCreation = false
                };

                var service = new ChatService(new Mock<ICache>().Object, repository, settings);
                ChatRoom room = service.AddRoom(user, "NewRoom");

                Assert.NotNull(room);
                Assert.Equal("NewRoom", room.Name);
                Assert.Same(room, repository.GetRoomByName("NewRoom"));
                Assert.True(room.Owners.Contains(user));
                Assert.Same(room.Creator, user);
                Assert.True(user.OwnedRooms.Contains(room));
            }
コード例 #21
0
ファイル: AdministrationModule.cs プロジェクト: yadyn/JabbR
        public AdministrationModule(ApplicationSettings applicationSettings,
                                    ISettingsManager settingsManager,
                                    IEnumerable<IContentProvider> contentProviders)
            : base("/administration")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                var allContentProviders = contentProviders
                    .OrderBy(provider => provider.GetType().Name)
                    .ToList();
                var model = new
                {
                    AllContentProviders = allContentProviders,
                    ApplicationSettings = applicationSettings
                };
                return View["index", model];
            };

            Post["/"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!IsAuthenticated || !Principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                try
                {
                    var settings = this.Bind<ApplicationSettings>();

                    // filter out empty/null providers. The values posted may contain 'holes' due to removals.
                    settings.ContentProviders = this.Bind<ContentProviderSetting[]>()
                        .Where(cp => !string.IsNullOrEmpty(cp.Name))
                        .ToList();

                    var enabledContentProvidersResult = this.Bind<EnabledContentProvidersResult>();

                    // we posted the enabled ones, but we store the disabled ones. Flip it around...
                    settings.DisabledContentProviders =
                        new HashSet<string>(contentProviders
                            .Select(cp => cp.GetType().Name)
                            .Where(typeName => enabledContentProvidersResult.EnabledContentProviders == null ||
                                !enabledContentProvidersResult.EnabledContentProviders.Contains(typeName))
                            .ToList());

                    IDictionary<string, string> errors;
                    if (ApplicationSettings.TryValidateSettings(settings, out errors))
                    {
                        settingsManager.Save(settings);
                    }
                    else
                    {
                        foreach (var error in errors)
                        {
                            this.AddValidationError(error.Key, error.Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.SettingsSaveSuccess);
                    return Response.AsRedirect("~/administration");
                }

                return View["index", applicationSettings];
            };
        }
コード例 #22
0
ファイル: Startup.cs プロジェクト: nprovencher/JabbR
        public void Configuration(IAppBuilder app)
        {
            var settings = new ApplicationSettings();

            if (settings.MigrateDatabase)
            {
                // Perform the required migrations
                DoMigrations();
            }

            var kernel = new StandardKernel(new[] { new FactoryModule() });

            kernel.Bind<JabbrContext>()
                .To<JabbrContext>();

            kernel.Bind<IJabbrRepository>()
                .To<PersistedRepository>();

            kernel.Bind<IChatService>()
                  .To<ChatService>();

            kernel.Bind<IAuthenticationTokenService>()
                  .To<AuthenticationTokenService>();

            // We're doing this manually since we want the chat repository to be shared
            // between the chat service and the chat hub itself
            kernel.Bind<Chat>()
                  .ToMethod(context =>
                  {
                      var resourceProcessor = context.Kernel.Get<IResourceProcessor>();
                      var repository = context.Kernel.Get<IJabbrRepository>();
                      var cache = context.Kernel.Get<ICache>();

                      var service = new ChatService(cache, repository);

                      return new Chat(resourceProcessor,
                                      service,
                                      repository,
                                      cache);
                  });

            kernel.Bind<ICryptoService>()
                .To<CryptoService>()
                .InSingletonScope();

            kernel.Bind<IResourceProcessor>()
                .To<ResourceProcessor>()
                .InSingletonScope();

            kernel.Bind<IApplicationSettings>()
                  .ToConstant(settings);

            kernel.Bind<IJavaScriptMinifier>()
                  .To<AjaxMinMinifier>()
                  .InSingletonScope();

            kernel.Bind<IMembershipService>()
                  .To<MembershipService>();

            kernel.Bind<IAuthenticationService>()
                  .ToConstant(new AuthenticationService());

            kernel.Bind<IAuthenticationCallbackProvider>()
                      .To<JabbRAuthenticationCallbackProvider>();

            kernel.Bind<ICache>()
                  .To<DefaultCache>()
                  .InSingletonScope();

            kernel.Bind<IChatNotificationService>()
                  .To<ChatNotificationService>();

            if (String.IsNullOrEmpty(settings.VerificationKey) ||
                String.IsNullOrEmpty(settings.EncryptionKey))
            {
                kernel.Bind<IKeyProvider>()
                      .ToConstant(new FileBasedKeyProvider());
            }
            else
            {
                kernel.Bind<IKeyProvider>()
                      .To<AppSettingKeyProvider>()
                      .InSingletonScope();
            }

            try
            {
                if (app.IsRunningUnderSystemWeb())
                {
                    BindSystemWebDependencies(kernel);
                }
            }
            catch (Exception ex)
            {
                // If we were unable to load the system web specific dependencies don't cry about it
                ReportError(ex);
            }

            var serializer = new JsonNetSerializer(new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            });

            kernel.Bind<IJsonSerializer>()
                  .ToConstant(serializer);

            app.Use(typeof(DetectSchemeHandler));

            if (settings.RequireHttps)
            {
                app.Use(typeof(RequireHttpsHandler));
            }

            app.UseShowExceptions();

            // This needs to run before everything
            app.Use(typeof(AuthorizationHandler), kernel.Get<IAuthenticationTokenService>());

            SetupSignalR(kernel, app);
            SetupWebApi(kernel, app);
            SetupMiddleware(app);
            SetupNancy(kernel, app);

            SetupErrorHandling();
        }
コード例 #23
0
        public CrossOriginHubHandler(AppFunc next, IKernel kernel)
        {
            _next = next;

            _settings = kernel.Get<ApplicationSettings>();
        }
コード例 #24
0
ファイル: AccountModule.cs プロジェクト: phillip-haydon/JabbR
        public AccountModule(ApplicationSettings applicationSettings,
                             IMembershipService membershipService,
                             IJabbrRepository repository,
                             IAuthenticationService authService,
                             IChatNotificationService notificationService,
                             IUserAuthenticator authenticator)
            : base("/account")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                return GetProfileView(authService, user);
            };

            Get["/login"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/login"] = param =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                string username = Request.Form.username;
                string password = Request.Form.password;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(password))
                {
                    this.AddValidationError("password", "Password is required");
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        IList<Claim> claims;
                        if (authenticator.TryAuthenticateUser(username, password, out claims))
                        {
                            return this.SignIn(claims);
                        }
                    }
                }
                catch
                {
                    // Swallow the exception
                }

                this.AddValidationError("_FORM", "Login failed. Check your username/password.");

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/logout"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                var response = Response.AsJson(new { success = true });

                this.SignOut();

                return response;
            };

            Get["/register"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                ViewBag.requirePassword = requirePassword;

                return View["register"];
            };

            Post["/create"] = _ =>
            {
                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                ViewBag.requirePassword = requirePassword;

                string username = Request.Form.username;
                string email = Request.Form.email;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(email))
                {
                    this.AddValidationError("email", "Email is required");
                }

                try
                {
                    if (requirePassword)
                    {
                        ValidatePassword(password, confirmPassword);
                    }

                    if (ModelValidationResult.IsValid)
                    {
                        if (requirePassword)
                        {
                            ChatUser user = membershipService.AddUser(username, email, password);

                            return this.SignIn(user);
                        }
                        else
                        {
                            // Add the required claims to this identity
                            var identity = Principal.Identity as ClaimsIdentity;

                            if (!Principal.HasClaim(ClaimTypes.Name))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                            }

                            if (!Principal.HasClaim(ClaimTypes.Email))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Email, email));
                            }

                            return this.SignIn(Principal.Claims);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return View["register"];
            };

            Post["/unlink"] = param =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string provider = Request.Form.provider;
                ChatUser user = repository.GetUserById(Principal.GetUserId());

                if (user.Identities.Count == 1 && !user.HasUserNameAndPasswordCredentials())
                {
                    Request.AddAlertMessage("error", "You cannot unlink this account because you would lose your ability to login.");
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                var identity = user.Identities.FirstOrDefault(i => i.ProviderName == provider);

                if (identity != null)
                {
                    repository.Remove(identity);

                    Request.AddAlertMessage("success", String.Format("Successfully unlinked {0} account.", provider));
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                return HttpStatusCode.BadRequest;
            };

            Post["/newpassword"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.SetUserPassword(user, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully added a password.");
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changepassword"] = _ =>
            {
                if (!applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string oldPassword = Request.Form.oldPassword;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(oldPassword))
                {
                    this.AddValidationError("oldPassword", "Old password is required");
                }

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserPassword(user, oldPassword, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully changed your password.");
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changeusername"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string username = Request.Form.username;
                string confirmUsername = Request.Form.confirmUsername;

                ValidateUsername(username, confirmUsername);

                ChatUser user = repository.GetUserById(Principal.GetUserId());
                string oldUsername = user.Name;

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserName(user, username);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    notificationService.OnUserNameChanged(user, oldUsername, username);

                    Request.AddAlertMessage("success", "Successfully changed your username.");
                    return Response.AsRedirect("~/account/#changeUsername");
                }

                return GetProfileView(authService, user);
            };
        }
コード例 #25
0
        private static KernelBase SetupNinject(ApplicationSettings settings)
        {
            var kernel = new StandardKernel(new[] { new FactoryModule() });

            kernel.Bind<JabbrContext>()
                .To<JabbrContext>();

            kernel.Bind<IJabbrRepository>()
                .To<PersistedRepository>();

            kernel.Bind<IChatService>()
                  .To<ChatService>();

            kernel.Bind<IDataProtection>()
                  .To<JabbRDataProtection>();

            kernel.Bind<IFormsAuthenticationProvider>()
                  .To<JabbRFormsAuthenticationProvider>();

            kernel.Bind<ILogger>()
                  .To<RealtimeLogger>();

            // We're doing this manually since we want the chat repository to be shared
            // between the chat service and the chat hub itself
            kernel.Bind<Chat>()
                  .ToMethod(context =>
                  {
                      var resourceProcessor = context.Kernel.Get<ContentProviderProcessor>();
                      var repository = context.Kernel.Get<IJabbrRepository>();
                      var cache = context.Kernel.Get<ICache>();

                      var service = new ChatService(cache, repository);

                      return new Chat(resourceProcessor,
                                      service,
                                      repository,
                                      cache);
                  });

            kernel.Bind<ICryptoService>()
                .To<CryptoService>()
                .InSingletonScope();

            kernel.Bind<IResourceProcessor>()
                .To<ResourceProcessor>()
                .InSingletonScope();

            kernel.Bind<IApplicationSettings>()
                  .ToConstant(settings);

            kernel.Bind<IJavaScriptMinifier>()
                  .To<AjaxMinMinifier>()
                  .InSingletonScope();

            kernel.Bind<IMembershipService>()
                  .To<MembershipService>();

            kernel.Bind<IAuthenticationService>()
                  .ToConstant(new AuthenticationService());

            kernel.Bind<IAuthenticationCallbackProvider>()
                      .To<JabbRAuthenticationCallbackProvider>();

            kernel.Bind<ICache>()
                  .To<DefaultCache>()
                  .InSingletonScope();

            kernel.Bind<IChatNotificationService>()
                  .To<ChatNotificationService>();

            if (String.IsNullOrEmpty(settings.VerificationKey) ||
                String.IsNullOrEmpty(settings.EncryptionKey))
            {
                kernel.Bind<IKeyProvider>()
                      .ToConstant(new FileBasedKeyProvider());
            }
            else
            {
                kernel.Bind<IKeyProvider>()
                      .To<AppSettingKeyProvider>()
                      .InSingletonScope();
            }

            var serializer = new JsonNetSerializer(new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat
            });

            kernel.Bind<IJsonSerializer>()
                  .ToConstant(serializer);

            kernel.Bind<UploadCallbackHandler>()
                  .ToSelf()
                  .InSingletonScope();

            kernel.Bind<UploadProcessor>()
                  .ToSelf()
                  .InSingletonScope();

            kernel.Bind<ContentProviderProcessor>()
                  .ToConstant(new ContentProviderProcessor(kernel));

            return kernel;
        }
コード例 #26
0
 public PushNotificationService(ApplicationSettings settings, ILogger logger)
 {
     _httpClient = new HttpClient();
     _settings = settings;
     _logger = logger;
 }
コード例 #27
0
ファイル: HomeModule.cs プロジェクト: CloudMetal/JabbR
        public HomeModule(ApplicationSettings settings,
                          IJabbrConfiguration configuration,
                          UploadCallbackHandler uploadHandler,
                          IConnectionManager connectionManager,
                          IJabbrRepository jabbrRepository)
        {
            Get["/"] = _ =>
            {
                if (IsAuthenticated)
                {
                    var viewModel = new SettingsViewModel
                    {
                        GoogleAnalytics = settings.GoogleAnalytics,
                        Sha = configuration.DeploymentSha,
                        Branch = configuration.DeploymentBranch,
                        Time = configuration.DeploymentTime,
                        DebugMode = (bool)Context.Items["_debugMode"],
                        Version = Constants.JabbRVersion,
                        IsAdmin = Principal.HasClaim(JabbRClaimTypes.Admin),
                        ClientLanguageResources = BuildClientResources()
                    };

                    return View["index", viewModel];
                }

                if (Principal != null && Principal.HasPartialIdentity())
                {
                    // If the user is partially authenticated then take them to the register page
                    return Response.AsRedirect("~/account/register");
                }

                return HttpStatusCode.Unauthorized;
            };

            Get["/monitor"] = _ =>
            {
                ClaimsPrincipal principal = Principal;

                if (principal == null ||
                    !principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                return View["monitor"];
            };

            Get["/status"] = _ =>
            {
                var model = new StatusViewModel();

                // Try to send a message via SignalR
                // NOTE: Ideally we'd like to actually receive a message that we send, but right now
                // that would require a full client instance. SignalR 2.1.0 plans to add a feature to
                // easily support this on the server.
                var signalrStatus = new SystemStatus { SystemName = "SignalR messaging" };
                model.Systems.Add(signalrStatus);

                try
                {
                    var hubContext = connectionManager.GetHubContext<Chat>();
                    var sendTask = (Task)hubContext.Clients.Client("doesn't exist").noMethodCalledThis();
                    sendTask.Wait();

                    signalrStatus.SetOK();
                }
                catch (Exception ex)
                {
                    signalrStatus.SetException(ex.GetBaseException());
                }

                // Try to talk to database
                var dbStatus = new SystemStatus { SystemName = "Database" };
                model.Systems.Add(dbStatus);

                try
                {
                    var roomCount = jabbrRepository.Rooms.Count();
                    dbStatus.SetOK();
                }
                catch (Exception ex)
                {
                    dbStatus.SetException(ex.GetBaseException());
                }

                // Try to talk to storage
                var azureStorageStatus = new SystemStatus { SystemName = "Upload storage" };
                model.Systems.Add(azureStorageStatus);

                try
                {
                    if (!String.IsNullOrEmpty(settings.AzureblobStorageConnectionString))
                    {
                        var azure = new AzureBlobStorageHandler(settings);
                        UploadResult result;
                        using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test")))
                        {
                            result = azure.UploadFile("statusCheck.txt", "text/plain", stream)
                                          .Result;
                        }
                        azureStorageStatus.SetOK();
                    }
                    else
                    {
                        azureStorageStatus.StatusMessage = "Not configured";
                    }
                }
                catch (Exception ex)
                {
                    azureStorageStatus.SetException(ex.GetBaseException());
                }

                // Force failure
                if (Context.Request.Query.fail)
                {
                    var failedSystem = new SystemStatus { SystemName = "Forced failure" };
                    failedSystem.SetException(new ApplicationException("Forced failure for test purposes"));
                    model.Systems.Add(failedSystem);
                }

                var view = View["status", model];

                if (!model.AllOK)
                {
                    return view.WithStatusCode(HttpStatusCode.InternalServerError);
                }

                return view;
            };

            Post["/upload-file"] = _ =>
                {
                    if (!IsAuthenticated)
                    {
                        return 403;
                    }

                    string roomName = Request.Form.room;
                    string connectionId = Request.Form.connectionId;
                    string file = Request.Form.file;
                    //string fileName = "clipboard_" + Guid.NewGuid().ToString("N");
                    string fileName = Request.Form.filename;
                    string contentType = Request.Form.type;
                    byte[] binData = null;

                    var info = Regex.Match(file, @"data:(?:(?<unkown>.+?)/(?<type>.+?))?;base64,(?<data>.+)");

                    binData = Convert.FromBase64String(info.Groups["data"].Value);
                    contentType = info.Groups["type"].Value;

                    if (String.IsNullOrWhiteSpace(contentType))
                    {
                        contentType = "application/octet-stream";
                    }

                    UploadFile(
                        uploadHandler,
                        Principal.GetUserId(),
                        connectionId,
                        roomName,
                        fileName,
                        contentType,
                        new MemoryStream(binData)).Wait();

                    return 200;
                };
        }
コード例 #28
0
ファイル: ChatService.cs プロジェクト: Virgil-Imbrea/fixitnao
 public ChatService(ICache cache,
                    IRecentMessageCache recentMessageCache,
                    IJabbrRepository repository,
                    ApplicationSettings settings)
 {
     _cache = cache;
     _recentMessageCache = recentMessageCache;
     _repository = repository;
     _settings = settings;
 }
コード例 #29
0
 public LoginViewModel(ApplicationSettings settings, IEnumerable<IAuthenticationProvider> configuredProviders, IEnumerable<ChatUserIdentity> userIdentities)
 {
     SocialDetails = new SocialLoginViewModel(configuredProviders, userIdentities);
     AllowUserRegistration = settings.AllowUserRegistration;
 }
コード例 #30
0
ファイル: HomeModule.cs プロジェクト: BrianRosamilia/JabbR
        public HomeModule(ApplicationSettings settings,
                          IJabbrConfiguration configuration,
                          IConnectionManager connectionManager,
                          IJabbrRepository jabbrRepository)
        {
            Get["/"] = _ =>
            {
                if (IsAuthenticated)
                {
                    var viewModel = new SettingsViewModel
                    {
                        GoogleAnalytics = settings.GoogleAnalytics,
                        Sha = configuration.DeploymentSha,
                        Branch = configuration.DeploymentBranch,
                        Time = configuration.DeploymentTime,
                        DebugMode = (bool)Context.Items["_debugMode"],
                        Version = Constants.JabbRVersion,
                        IsAdmin = Principal.HasClaim(JabbRClaimTypes.Admin),
                        ClientLanguageResources = BuildClientResources(),
                        MaxMessageLength = settings.MaxMessageLength
                    };

                    return View["index", viewModel];
                }

                if (Principal != null && Principal.HasPartialIdentity())
                {
                    // If the user is partially authenticated then take them to the register page
                    return Response.AsRedirect("~/account/register");
                }

                return HttpStatusCode.Unauthorized;
            };

            Get["/monitor"] = _ =>
            {
                ClaimsPrincipal principal = Principal;

                if (principal == null ||
                    !principal.HasClaim(JabbRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                return View["monitor"];
            };

            Get["/status", runAsync: true] = async (_, token) =>
            {
                var model = new StatusViewModel();

                // Try to send a message via SignalR
                // NOTE: Ideally we'd like to actually receive a message that we send, but right now
                // that would require a full client instance. SignalR 2.1.0 plans to add a feature to
                // easily support this on the server.
                var signalrStatus = new SystemStatus { SystemName = "SignalR messaging" };
                model.Systems.Add(signalrStatus);

                try
                {
                    var hubContext = connectionManager.GetHubContext<Chat>();
                    await (Task)hubContext.Clients.Client("doesn't exist").noMethodCalledThis();
                    
                    signalrStatus.SetOK();
                }
                catch (Exception ex)
                {
                    signalrStatus.SetException(ex.GetBaseException());
                }

                // Try to talk to database
                var dbStatus = new SystemStatus { SystemName = "Database" };
                model.Systems.Add(dbStatus);

                try
                {
                    var roomCount = jabbrRepository.Rooms.Count();
                    dbStatus.SetOK();
                }
                catch (Exception ex)
                {
                    dbStatus.SetException(ex.GetBaseException());
                }

                // Try to talk to azure storage
                var azureStorageStatus = new SystemStatus { SystemName = "Azure Upload storage" };
                model.Systems.Add(azureStorageStatus);

                try
                {
                    if (!String.IsNullOrEmpty(settings.AzureblobStorageConnectionString))
                    {
                        var azure = new AzureBlobStorageHandler(settings);
                        UploadResult result;
                        using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test")))
                        {
                            result = await azure.UploadFile("statusCheck.txt", "text/plain", stream);
                        }

                        azureStorageStatus.SetOK();
                    }
                    else
                    {
                        azureStorageStatus.StatusMessage = "Not configured";
                    }
                }
                catch (Exception ex)
                {
                    azureStorageStatus.SetException(ex.GetBaseException());
                }

                //try to talk to local storage
                var localStorageStatus = new SystemStatus { SystemName = "Local Upload storage" };
                model.Systems.Add(localStorageStatus);

                try
                {
                    if (!String.IsNullOrEmpty(settings.LocalFileSystemStoragePath) && !String.IsNullOrEmpty(settings.LocalFileSystemStorageUriPrefix))
                    {
                        var local = new LocalFileSystemStorageHandler(settings);
                        UploadResult localResult;
                        using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test")))
                        {
                            localResult = await local.UploadFile("statusCheck.txt", "text/plain", stream);
                        }

                        localStorageStatus.SetOK();
                    }
                    else
                    {
                        localStorageStatus.StatusMessage = "Not configured";
                    }
                }
                catch (Exception ex)
                {
                    localStorageStatus.SetException(ex.GetBaseException());
                }

                // Force failure
                if (Context.Request.Query.fail)
                {
                    var failedSystem = new SystemStatus { SystemName = "Forced failure" };
                    failedSystem.SetException(new ApplicationException("Forced failure for test purposes"));
                    model.Systems.Add(failedSystem);
                }

                var view = View["status", model];

                if (!model.AllOK)
                {
                    return view.WithStatusCode(HttpStatusCode.InternalServerError);
                }

                return view;
            };
        }
コード例 #31
0
ファイル: ChatService.cs プロジェクト: yreynhout/JabbR
 public ChatService(ICache cache, IJabbrRepository repository)
     : this(cache, repository, ApplicationSettings.GetDefaultSettings())
 {
 }