Moved the plex auth token to the plex settings where it should belong.

pull/470/head
tidusjar 8 years ago
parent ffe6bc41ac
commit 57ec940d5a

@ -1,67 +1,69 @@
#region Copyright #region Copyright
// /************************************************************************ // /************************************************************************
// Copyright (c) 2016 Jamie Rees // Copyright (c) 2016 Jamie Rees
// File: AuthenticationSettings.cs // File: AuthenticationSettings.cs
// Created By: Jamie Rees // Created By: Jamie Rees
// //
// Permission is hereby granted, free of charge, to any person obtaining // Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the // a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including // "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, // without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to // distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to // permit persons to whom the Software is furnished to do so, subject to
// the following conditions: // the following conditions:
// //
// The above copyright notice and this permission notice shall be // The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. // included in all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace PlexRequests.Core.SettingModels namespace PlexRequests.Core.SettingModels
{ {
public class AuthenticationSettings : Settings public class AuthenticationSettings : Settings
{ {
public bool UserAuthentication { get; set; } public bool UserAuthentication { get; set; }
public bool UsePassword { get; set; } public bool UsePassword { get; set; }
public string PlexAuthToken { get; set; } [JsonProperty("PlexAuthToken")]
[Obsolete("This should be migrated over into the Plex Settings and then removed in the next release")]
public string OldPlexAuthToken { get; set; }
/// <summary>
/// A comma separated list of users.
/// </summary> /// <summary>
public string DeniedUsers { get; set; } /// A comma separated list of users.
/// </summary>
[JsonIgnore] public string DeniedUsers { get; set; }
public List<string> DeniedUserList
{ [JsonIgnore]
get public List<string> DeniedUserList
{ {
var users = new List<string>(); get
if (string.IsNullOrEmpty(DeniedUsers)) {
{ var users = new List<string>();
return users; if (string.IsNullOrEmpty(DeniedUsers))
} {
return users;
var splitUsers = DeniedUsers.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
foreach (var user in splitUsers)
{ var splitUsers = DeniedUsers.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (!string.IsNullOrWhiteSpace(user)) foreach (var user in splitUsers)
users.Add(user.Trim()); {
} if (!string.IsNullOrWhiteSpace(user))
return users; users.Add(user.Trim());
} }
} return users;
} }
} }
}
}

@ -1,57 +1,59 @@
#region Copyright #region Copyright
// /************************************************************************ // /************************************************************************
// Copyright (c) 2016 Jamie Rees // Copyright (c) 2016 Jamie Rees
// File: CouchPotatoSettings.cs // File: CouchPotatoSettings.cs
// Created By: Jamie Rees // Created By: Jamie Rees
// //
// Permission is hereby granted, free of charge, to any person obtaining // Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the // a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including // "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, // without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to // distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to // permit persons to whom the Software is furnished to do so, subject to
// the following conditions: // the following conditions:
// //
// The above copyright notice and this permission notice shall be // The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. // included in all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using Newtonsoft.Json; using Newtonsoft.Json;
using PlexRequests.Helpers; using PlexRequests.Helpers;
namespace PlexRequests.Core.SettingModels namespace PlexRequests.Core.SettingModels
{ {
public class PlexSettings : Settings public class PlexSettings : Settings
{ {
public string Ip { get; set; } public string Ip { get; set; }
public int Port { get; set; } public int Port { get; set; }
public bool Ssl { get; set; } public bool Ssl { get; set; }
public string SubDir { get; set; } public string SubDir { get; set; }
public bool AdvancedSearch { get; set; } public bool AdvancedSearch { get; set; }
[JsonIgnore] public string PlexAuthToken { get; set; }
public Uri FullUri
{ [JsonIgnore]
get public Uri FullUri
{ {
if (!string.IsNullOrEmpty(SubDir)) get
{ {
var formattedSubDir = Ip.ReturnUriWithSubDir(Port, Ssl, SubDir); if (!string.IsNullOrEmpty(SubDir))
return formattedSubDir; {
} var formattedSubDir = Ip.ReturnUriWithSubDir(Port, Ssl, SubDir);
var formatted = Ip.ReturnUri(Port, Ssl); return formattedSubDir;
return formatted; }
} var formatted = Ip.ReturnUri(Port, Ssl);
} return formatted;
} }
}
}
} }

@ -61,6 +61,10 @@ namespace PlexRequests.Core
{ {
MigrateToVersion1800(); MigrateToVersion1800();
} }
if (version > 1899 && version <= 1900)
{
MigrateToVersion1900();
}
} }
return Db.DbConnection().ConnectionString; return Db.DbConnection().ConnectionString;
@ -167,11 +171,23 @@ namespace PlexRequests.Core
Log.Error(ex, "Failed to cache CouchPotato quality profiles!"); Log.Error(ex, "Failed to cache CouchPotato quality profiles!");
} }
} }
public void MigrateToVersion1700() public void MigrateToVersion1900()
{ {
// Drop old tables // Need to change the Plex Token location
TableCreation.DropTable(Db.DbConnection(), "User"); var authSettings = new SettingsServiceV2<AuthenticationSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
TableCreation.DropTable(Db.DbConnection(), "Log"); var auth = authSettings.GetSettings();
var plexSettings = new SettingsServiceV2<PlexSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var currentSettings = plexSettings.GetSettings();
if (!string.IsNullOrEmpty(auth.OldPlexAuthToken))
{
currentSettings.PlexAuthToken = auth.OldPlexAuthToken;
plexSettings.SaveSettings(currentSettings);
// Clear out the old value
auth.OldPlexAuthToken = string.Empty;
authSettings.SaveSettings(auth);
}
} }
/// <summary> /// <summary>

File diff suppressed because it is too large Load Diff

@ -36,7 +36,6 @@ using PlexRequests.Core;
using PlexRequests.Core.Models; using PlexRequests.Core.Models;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers; using PlexRequests.Helpers;
using PlexRequests.Helpers.Analytics;
using PlexRequests.Services.Interfaces; using PlexRequests.Services.Interfaces;
using PlexRequests.Services.Models; using PlexRequests.Services.Models;
using PlexRequests.Services.Notification; using PlexRequests.Services.Notification;
@ -52,11 +51,10 @@ namespace PlexRequests.Services.Jobs
{ {
public class PlexAvailabilityChecker : IJob, IAvailabilityChecker public class PlexAvailabilityChecker : IJob, IAvailabilityChecker
{ {
public PlexAvailabilityChecker(ISettingsService<PlexSettings> plexSettings, ISettingsService<AuthenticationSettings> auth, IRequestService request, IPlexApi plex, ICacheProvider cache, public PlexAvailabilityChecker(ISettingsService<PlexSettings> plexSettings, IRequestService request, IPlexApi plex, ICacheProvider cache,
INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users) INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users)
{ {
Plex = plexSettings; Plex = plexSettings;
Auth = auth;
RequestService = request; RequestService = request;
PlexApi = plex; PlexApi = plex;
Cache = cache; Cache = cache;
@ -66,7 +64,6 @@ namespace PlexRequests.Services.Jobs
} }
private ISettingsService<PlexSettings> Plex { get; } private ISettingsService<PlexSettings> Plex { get; }
private ISettingsService<AuthenticationSettings> Auth { get; }
private IRequestService RequestService { get; } private IRequestService RequestService { get; }
private static Logger Log = LogManager.GetCurrentClassLogger(); private static Logger Log = LogManager.GetCurrentClassLogger();
private IPlexApi PlexApi { get; } private IPlexApi PlexApi { get; }
@ -77,15 +74,14 @@ namespace PlexRequests.Services.Jobs
public void CheckAndUpdateAll() public void CheckAndUpdateAll()
{ {
var plexSettings = Plex.GetSettings(); var plexSettings = Plex.GetSettings();
var authSettings = Auth.GetSettings();
if (!ValidateSettings(plexSettings, authSettings)) if (!ValidateSettings(plexSettings))
{ {
Log.Debug("Validation of the plex settings failed."); Log.Debug("Validation of the plex settings failed.");
return; return;
} }
var libraries = CachedLibraries(authSettings, plexSettings, true); //force setting the cache (10 min intervals via scheduler) var libraries = CachedLibraries(plexSettings, true); //force setting the cache (10 min intervals via scheduler)
if (libraries == null || !libraries.Any()) if (libraries == null || !libraries.Any())
{ {
@ -140,7 +136,7 @@ namespace PlexRequests.Services.Jobs
if (modifiedModel.Any()) if (modifiedModel.Any())
{ {
NotifyUsers(modifiedModel, authSettings.PlexAuthToken); NotifyUsers(modifiedModel, plexSettings.PlexAuthToken);
RequestService.BatchUpdate(modifiedModel); RequestService.BatchUpdate(modifiedModel);
} }
@ -275,11 +271,11 @@ namespace PlexRequests.Services.Jobs
x.Artist.Equals(artist, StringComparison.CurrentCultureIgnoreCase)); x.Artist.Equals(artist, StringComparison.CurrentCultureIgnoreCase));
} }
private List<PlexSearch> CachedLibraries(AuthenticationSettings authSettings, PlexSettings plexSettings, bool setCache) private List<PlexSearch> CachedLibraries(PlexSettings plexSettings, bool setCache)
{ {
var results = new List<PlexSearch>(); var results = new List<PlexSearch>();
if (!ValidateSettings(plexSettings, authSettings)) if (!ValidateSettings(plexSettings))
{ {
Log.Warn("The settings are not configured"); Log.Warn("The settings are not configured");
return results; // don't error out here, just let it go! let it goo!!! return results; // don't error out here, just let it go! let it goo!!!
@ -289,7 +285,7 @@ namespace PlexRequests.Services.Jobs
{ {
if (setCache) if (setCache)
{ {
results = GetLibraries(authSettings, plexSettings); results = GetLibraries(plexSettings);
if (plexSettings.AdvancedSearch) if (plexSettings.AdvancedSearch)
{ {
for (var i = 0; i < results.Count; i++) for (var i = 0; i < results.Count; i++)
@ -297,7 +293,7 @@ namespace PlexRequests.Services.Jobs
for (var j = 0; j < results[i].Directory.Count; j++) for (var j = 0; j < results[i].Directory.Count; j++)
{ {
var currentItem = results[i].Directory[j]; var currentItem = results[i].Directory[j];
var metaData = PlexApi.GetMetadata(authSettings.PlexAuthToken, plexSettings.FullUri, var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
currentItem.RatingKey); currentItem.RatingKey);
var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid); var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid);
results[i].Directory[j].ProviderId = providerId; results[i].Directory[j].ProviderId = providerId;
@ -305,7 +301,7 @@ namespace PlexRequests.Services.Jobs
for (var j = 0; j < results[i].Video.Count; j++) for (var j = 0; j < results[i].Video.Count; j++)
{ {
var currentItem = results[i].Video[j]; var currentItem = results[i].Video[j];
var metaData = PlexApi.GetMetadata(authSettings.PlexAuthToken, plexSettings.FullUri, var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
currentItem.RatingKey); currentItem.RatingKey);
var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid); var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid);
results[i].Video[j].ProviderId = providerId; results[i].Video[j].ProviderId = providerId;
@ -320,7 +316,7 @@ namespace PlexRequests.Services.Jobs
else else
{ {
results = Cache.GetOrSet(CacheKeys.PlexLibaries, () => results = Cache.GetOrSet(CacheKeys.PlexLibaries, () =>
GetLibraries(authSettings, plexSettings), CacheKeys.TimeFrameMinutes.SchedulerCaching); GetLibraries(plexSettings), CacheKeys.TimeFrameMinutes.SchedulerCaching);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -331,16 +327,16 @@ namespace PlexRequests.Services.Jobs
return results; return results;
} }
private List<PlexSearch> GetLibraries(AuthenticationSettings authSettings, PlexSettings plexSettings) private List<PlexSearch> GetLibraries(PlexSettings plexSettings)
{ {
var sections = PlexApi.GetLibrarySections(authSettings.PlexAuthToken, plexSettings.FullUri); var sections = PlexApi.GetLibrarySections(plexSettings.PlexAuthToken, plexSettings.FullUri);
List<PlexSearch> libs = new List<PlexSearch>(); List<PlexSearch> libs = new List<PlexSearch>();
if (sections != null) if (sections != null)
{ {
foreach (var dir in sections.Directories) foreach (var dir in sections.Directories)
{ {
var lib = PlexApi.GetLibrary(authSettings.PlexAuthToken, plexSettings.FullUri, dir.Key); var lib = PlexApi.GetLibrary(plexSettings.PlexAuthToken, plexSettings.FullUri, dir.Key);
if (lib != null) if (lib != null)
{ {
libs.Add(lib); libs.Add(lib);
@ -351,9 +347,9 @@ namespace PlexRequests.Services.Jobs
return libs; return libs;
} }
private bool ValidateSettings(PlexSettings plex, AuthenticationSettings auth) private bool ValidateSettings(PlexSettings plex)
{ {
if (plex?.Ip == null || auth?.PlexAuthToken == null) if (plex?.Ip == null || plex?.PlexAuthToken == null)
{ {
Log.Warn("A setting is null, Ensure Plex is configured correctly, and we have a Plex Auth token."); Log.Warn("A setting is null, Ensure Plex is configured correctly, and we have a Plex Auth token.");
return false; return false;

@ -1,365 +1,365 @@
#region Copyright //#region Copyright
// /************************************************************************ //// /************************************************************************
// Copyright (c) 2016 Jamie Rees //// Copyright (c) 2016 Jamie Rees
// File: UserLoginModuleTests.cs //// File: UserLoginModuleTests.cs
// Created By: Jamie Rees //// Created By: Jamie Rees
// ////
// Permission is hereby granted, free of charge, to any person obtaining //// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the //// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including //// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, //// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to //// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to //// permit persons to whom the Software is furnished to do so, subject to
// the following conditions: //// the following conditions:
// ////
// The above copyright notice and this permission notice shall be //// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. //// included in all copies or substantial portions of the Software.
// ////
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND //// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE //// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION //// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION //// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ //// ************************************************************************/
#endregion //#endregion
using System.Collections.Generic; //using System.Collections.Generic;
using System.Linq; //using System.Linq;
using Moq; //using Moq;
using Nancy; //using Nancy;
using Nancy.Testing; //using Nancy.Testing;
using Newtonsoft.Json; //using Newtonsoft.Json;
using Newtonsoft.Json.Linq; //using Newtonsoft.Json.Linq;
using NUnit.Framework; //using NUnit.Framework;
using PlexRequests.Api.Interfaces; //using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex; //using PlexRequests.Api.Models.Plex;
using PlexRequests.Core; //using PlexRequests.Core;
using PlexRequests.Core.SettingModels; //using PlexRequests.Core.SettingModels;
using PlexRequests.Services.Interfaces; //using PlexRequests.Services.Interfaces;
using PlexRequests.Store.Models; //using PlexRequests.Store.Models;
using PlexRequests.Store.Repository; //using PlexRequests.Store.Repository;
using PlexRequests.UI.Models; //using PlexRequests.UI.Models;
using PlexRequests.UI.Modules; //using PlexRequests.UI.Modules;
using PlexRequests.Helpers; //using PlexRequests.Helpers;
using PlexRequests.Helpers.Analytics; //using PlexRequests.Helpers.Analytics;
using PlexRequests.UI.Helpers; //using PlexRequests.UI.Helpers;
namespace PlexRequests.UI.Tests //namespace PlexRequests.UI.Tests
{ //{
[TestFixture] // [TestFixture]
public class AdminModuleTests // public class AdminModuleTests
{ // {
private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; } // private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; }
private Mock<ISettingsService<CouchPotatoSettings>> CpMock { get; set; } // private Mock<ISettingsService<CouchPotatoSettings>> CpMock { get; set; }
private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; } // private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; }
private Mock<ISettingsService<PlexSettings>> PlexSettingsMock { get; set; } // private Mock<ISettingsService<PlexSettings>> PlexSettingsMock { get; set; }
private Mock<ISettingsService<SonarrSettings>> SonarrSettingsMock { get; set; } // private Mock<ISettingsService<SonarrSettings>> SonarrSettingsMock { get; set; }
private Mock<ISettingsService<SickRageSettings>> SickRageSettingsMock { get; set; } // private Mock<ISettingsService<SickRageSettings>> SickRageSettingsMock { get; set; }
private Mock<ISettingsService<ScheduledJobsSettings>> ScheduledJobsSettingsMock { get; set; } // private Mock<ISettingsService<ScheduledJobsSettings>> ScheduledJobsSettingsMock { get; set; }
private Mock<ISettingsService<EmailNotificationSettings>> EmailMock { get; set; } // private Mock<ISettingsService<EmailNotificationSettings>> EmailMock { get; set; }
private Mock<ISettingsService<PushbulletNotificationSettings>> PushbulletSettings { get; set; } // private Mock<ISettingsService<PushbulletNotificationSettings>> PushbulletSettings { get; set; }
private Mock<ISettingsService<PushoverNotificationSettings>> PushoverSettings { get; set; } // private Mock<ISettingsService<PushoverNotificationSettings>> PushoverSettings { get; set; }
private Mock<ISettingsService<HeadphonesSettings>> HeadphonesSettings { get; set; } // private Mock<ISettingsService<HeadphonesSettings>> HeadphonesSettings { get; set; }
private Mock<IPlexApi> PlexMock { get; set; } // private Mock<IPlexApi> PlexMock { get; set; }
private Mock<ISonarrApi> SonarrApiMock { get; set; } // private Mock<ISonarrApi> SonarrApiMock { get; set; }
private Mock<IPushbulletApi> PushbulletApi { get; set; } // private Mock<IPushbulletApi> PushbulletApi { get; set; }
private Mock<IPushoverApi> PushoverApi { get; set; } // private Mock<IPushoverApi> PushoverApi { get; set; }
private Mock<ICouchPotatoApi> CpApi { get; set; } // private Mock<ICouchPotatoApi> CpApi { get; set; }
private Mock<IJobRecord> RecorderMock { get; set; } // private Mock<IJobRecord> RecorderMock { get; set; }
private Mock<IRepository<LogEntity>> LogRepo { get; set; } // private Mock<IRepository<LogEntity>> LogRepo { get; set; }
private Mock<INotificationService> NotificationService { get; set; } // private Mock<INotificationService> NotificationService { get; set; }
private Mock<ICacheProvider> Cache { get; set; } // private Mock<ICacheProvider> Cache { get; set; }
private Mock<ISettingsService<LogSettings>> Log { get; set; } // private Mock<ISettingsService<LogSettings>> Log { get; set; }
private Mock<ISettingsService<SlackNotificationSettings>> SlackSettings { get; set; } // private Mock<ISettingsService<SlackNotificationSettings>> SlackSettings { get; set; }
private Mock<ISettingsService<LandingPageSettings>> LandingPageSettings { get; set; } // private Mock<ISettingsService<LandingPageSettings>> LandingPageSettings { get; set; }
private Mock<ISlackApi> SlackApi { get; set; } // private Mock<ISlackApi> SlackApi { get; set; }
private Mock<IAnalytics> IAnalytics { get; set; } // private Mock<IAnalytics> IAnalytics { get; set; }
private ConfigurableBootstrapper Bootstrapper { get; set; } // private ConfigurableBootstrapper Bootstrapper { get; set; }
[SetUp] // [SetUp]
public void Setup() // public void Setup()
{ // {
AuthMock = new Mock<ISettingsService<AuthenticationSettings>>(); // AuthMock = new Mock<ISettingsService<AuthenticationSettings>>();
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock = new Mock<IPlexApi>(); // PlexMock = new Mock<IPlexApi>();
PlexMock.Setup(x => x.SignIn("Username1", "Password1")) // PlexMock.Setup(x => x.SignIn("Username1", "Password1"))
.Returns(new PlexAuthentication { user = new User { authentication_token = "abc", title = "Username1" } }); // .Returns(new PlexAuthentication { user = new User { authentication_token = "abc", title = "Username1" } });
PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>(); // PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>();
PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings()); // PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings());
CpMock = new Mock<ISettingsService<CouchPotatoSettings>>(); // CpMock = new Mock<ISettingsService<CouchPotatoSettings>>();
PlexSettingsMock = new Mock<ISettingsService<PlexSettings>>(); // PlexSettingsMock = new Mock<ISettingsService<PlexSettings>>();
SonarrApiMock = new Mock<ISonarrApi>(); // SonarrApiMock = new Mock<ISonarrApi>();
SonarrSettingsMock = new Mock<ISettingsService<SonarrSettings>>(); // SonarrSettingsMock = new Mock<ISettingsService<SonarrSettings>>();
EmailMock = new Mock<ISettingsService<EmailNotificationSettings>>(); // EmailMock = new Mock<ISettingsService<EmailNotificationSettings>>();
PushbulletApi = new Mock<IPushbulletApi>(); // PushbulletApi = new Mock<IPushbulletApi>();
PushbulletSettings = new Mock<ISettingsService<PushbulletNotificationSettings>>(); // PushbulletSettings = new Mock<ISettingsService<PushbulletNotificationSettings>>();
CpApi = new Mock<ICouchPotatoApi>(); // CpApi = new Mock<ICouchPotatoApi>();
SickRageSettingsMock = new Mock<ISettingsService<SickRageSettings>>(); // SickRageSettingsMock = new Mock<ISettingsService<SickRageSettings>>();
LogRepo = new Mock<IRepository<LogEntity>>(); // LogRepo = new Mock<IRepository<LogEntity>>();
PushoverSettings = new Mock<ISettingsService<PushoverNotificationSettings>>(); // PushoverSettings = new Mock<ISettingsService<PushoverNotificationSettings>>();
PushoverApi = new Mock<IPushoverApi>(); // PushoverApi = new Mock<IPushoverApi>();
NotificationService = new Mock<INotificationService>(); // NotificationService = new Mock<INotificationService>();
HeadphonesSettings = new Mock<ISettingsService<HeadphonesSettings>>(); // HeadphonesSettings = new Mock<ISettingsService<HeadphonesSettings>>();
Cache = new Mock<ICacheProvider>(); // Cache = new Mock<ICacheProvider>();
Log = new Mock<ISettingsService<LogSettings>>(); // Log = new Mock<ISettingsService<LogSettings>>();
SlackApi = new Mock<ISlackApi>(); // SlackApi = new Mock<ISlackApi>();
SlackSettings = new Mock<ISettingsService<SlackNotificationSettings>>(); // SlackSettings = new Mock<ISettingsService<SlackNotificationSettings>>();
LandingPageSettings = new Mock<ISettingsService<LandingPageSettings>>(); // LandingPageSettings = new Mock<ISettingsService<LandingPageSettings>>();
ScheduledJobsSettingsMock = new Mock<ISettingsService<ScheduledJobsSettings>>(); // ScheduledJobsSettingsMock = new Mock<ISettingsService<ScheduledJobsSettings>>();
RecorderMock = new Mock<IJobRecord>(); // RecorderMock = new Mock<IJobRecord>();
IAnalytics = new Mock<IAnalytics>(); // IAnalytics = new Mock<IAnalytics>();
Bootstrapper = new ConfigurableBootstrapper(with => // Bootstrapper = new ConfigurableBootstrapper(with =>
{ // {
with.Module<AdminModule>(); // with.Module<AdminModule>();
with.Dependency(AuthMock.Object); // with.Dependency(AuthMock.Object);
with.Dependency(PlexRequestMock.Object); // with.Dependency(PlexRequestMock.Object);
with.Dependency(CpMock.Object); // with.Dependency(CpMock.Object);
with.Dependency(PlexSettingsMock.Object); // with.Dependency(PlexSettingsMock.Object);
with.Dependency(SonarrApiMock.Object); // with.Dependency(SonarrApiMock.Object);
with.Dependency(SonarrSettingsMock.Object); // with.Dependency(SonarrSettingsMock.Object);
with.Dependency(PlexMock.Object); // with.Dependency(PlexMock.Object);
with.Dependency(EmailMock.Object); // with.Dependency(EmailMock.Object);
with.Dependency(PushbulletApi.Object); // with.Dependency(PushbulletApi.Object);
with.Dependency(PushbulletSettings.Object); // with.Dependency(PushbulletSettings.Object);
with.Dependency(CpApi.Object); // with.Dependency(CpApi.Object);
with.Dependency(SickRageSettingsMock.Object); // with.Dependency(SickRageSettingsMock.Object);
with.Dependency(LogRepo.Object); // with.Dependency(LogRepo.Object);
with.Dependency(PushoverSettings.Object); // with.Dependency(PushoverSettings.Object);
with.Dependency(PushoverApi.Object); // with.Dependency(PushoverApi.Object);
with.Dependency(NotificationService.Object); // with.Dependency(NotificationService.Object);
with.Dependency(IAnalytics.Object); // with.Dependency(IAnalytics.Object);
with.Dependency(HeadphonesSettings.Object); // with.Dependency(HeadphonesSettings.Object);
with.Dependency(Cache.Object); // with.Dependency(Cache.Object);
with.Dependency(Log.Object); // with.Dependency(Log.Object);
with.Dependency(SlackApi.Object); // with.Dependency(SlackApi.Object);
with.Dependency(LandingPageSettings.Object); // with.Dependency(LandingPageSettings.Object);
with.Dependency(SlackSettings.Object); // with.Dependency(SlackSettings.Object);
with.Dependency(ScheduledJobsSettingsMock.Object); // with.Dependency(ScheduledJobsSettingsMock.Object);
with.Dependency(RecorderMock.Object); // with.Dependency(RecorderMock.Object);
with.RootPathProvider<TestRootPathProvider>(); // with.RootPathProvider<TestRootPathProvider>();
with.RequestStartup((container, pipelines, context) => // with.RequestStartup((container, pipelines, context) =>
{ // {
context.CurrentUser = new UserIdentity { UserName = "user", Claims = new List<string> {"Admin"} }; // context.CurrentUser = new UserIdentity { UserName = "user", Claims = new List<string> {"Admin"} };
}); // });
}); // });
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
} // }
[Test] // [Test]
public void RequestAuthTokenTestNewSettings() // public void RequestAuthTokenTestNewSettings()
{ // {
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/admin/requestauth", with => // var result = browser.Post("/admin/requestauth", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Once); // PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Once); // AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Once);
} // }
[Test] // [Test]
public void RequestAuthTokenTestEmptyCredentials() // public void RequestAuthTokenTestEmptyCredentials()
{ // {
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/admin/requestauth", with => // var result = browser.Post("/admin/requestauth", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", string.Empty); // with.FormValue("username", string.Empty);
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
Assert.That(body.Message, Is.Not.Empty); // Assert.That(body.Message, Is.Not.Empty);
PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Never); // PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Never);
AuthMock.Verify(x => x.GetSettings(), Times.Never); // AuthMock.Verify(x => x.GetSettings(), Times.Never);
AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Never); // AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Never);
} // }
[Test] // [Test]
public void RequestAuthTokenTesPlexSignInFail() // public void RequestAuthTokenTesPlexSignInFail()
{ // {
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/admin/requestauth", with => // var result = browser.Post("/admin/requestauth", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Badusername"); // with.FormValue("username", "Badusername");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
Assert.That(body.Message, Is.Not.Empty); // Assert.That(body.Message, Is.Not.Empty);
PlexMock.Verify(x => x.SignIn("Badusername", "Password1"), Times.Once); // PlexMock.Verify(x => x.SignIn("Badusername", "Password1"), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Never); // AuthMock.Verify(x => x.GetSettings(), Times.Never);
AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Never); // AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Never);
} // }
[Test] // [Test]
public void RequestAuthTokenTestExistingSettings() // public void RequestAuthTokenTestExistingSettings()
{ // {
AuthMock.Setup(x => x.GetSettings()).Returns(() => null); // AuthMock.Setup(x => x.GetSettings()).Returns(() => null);
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/admin/requestauth", with => // var result = browser.Post("/admin/requestauth", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Once); // PlexMock.Verify(x => x.SignIn("Username1", "Password1"), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Once); // AuthMock.Verify(x => x.SaveSettings(It.IsAny<AuthenticationSettings>()), Times.Once);
} // }
[Test] // [Test]
public void GetUsersSuccessfully() // public void GetUsersSuccessfully()
{ // {
var users = new PlexFriends { User = new[] { new UserFriends { Title = "abc2" }, } }; // var users = new PlexFriends { User = new[] { new UserFriends { Title = "abc2" }, } };
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users);
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Get("/admin/getusers", with => // var result = browser.Get("/admin/getusers", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JObject>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JObject>(result.Body.AsString());
var user = body["users"]; // var user = body["users"];
Assert.That(body, Is.Not.Null); // Assert.That(body, Is.Not.Null);
Assert.That(user.ToString().Contains("abc"), Is.True); // Assert.That(user.ToString().Contains("abc"), Is.True);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
} // }
[Test] // [Test]
public void GetUsersReturnsNoUsers() // public void GetUsersReturnsNoUsers()
{ // {
var users = new PlexFriends(); // var users = new PlexFriends();
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(users);
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Get("/admin/getusers", with => // var result = browser.Get("/admin/getusers", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<string>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<string>(result.Body.AsString());
Assert.That(body, Is.Not.Null); // Assert.That(body, Is.Not.Null);
Assert.That(string.IsNullOrWhiteSpace(body), Is.True); // Assert.That(string.IsNullOrWhiteSpace(body), Is.True);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
} // }
[Test] // [Test]
public void GetUsersReturnsNull() // public void GetUsersReturnsNull()
{ // {
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(() => null); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(() => null);
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Get("/admin/getusers", with => // var result = browser.Get("/admin/getusers", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<string>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<string>(result.Body.AsString());
Assert.That(body, Is.Not.Null); // Assert.That(body, Is.Not.Null);
Assert.That(string.IsNullOrWhiteSpace(body), Is.True); // Assert.That(string.IsNullOrWhiteSpace(body), Is.True);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
} // }
[Test] // [Test]
public void GetUsersTokenIsNull() // public void GetUsersTokenIsNull()
{ // {
AuthMock.Setup(x => x.GetSettings()).Returns(new AuthenticationSettings()); // AuthMock.Setup(x => x.GetSettings()).Returns(new AuthenticationSettings());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Get("/admin/getusers", with => // var result = browser.Get("/admin/getusers", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("username", "Username1"); // with.FormValue("username", "Username1");
with.FormValue("password", "Password1"); // with.FormValue("password", "Password1");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JObject>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JObject>(result.Body.AsString());
var user = (string)body["users"]; // var user = (string)body["users"];
Assert.That(body, Is.Not.Null); // Assert.That(body, Is.Not.Null);
Assert.That(string.IsNullOrWhiteSpace(user), Is.True); // Assert.That(string.IsNullOrWhiteSpace(user), Is.True);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
} // }
} // }
} //}

File diff suppressed because it is too large Load Diff

@ -1,441 +1,441 @@
#region Copyright //#region Copyright
// /************************************************************************ //// /************************************************************************
// Copyright (c) 2016 Jamie Rees //// Copyright (c) 2016 Jamie Rees
// File: UserLoginModuleTests.cs //// File: UserLoginModuleTests.cs
// Created By: Jamie Rees //// Created By: Jamie Rees
// ////
// Permission is hereby granted, free of charge, to any person obtaining //// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the //// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including //// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, //// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to //// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to //// permit persons to whom the Software is furnished to do so, subject to
// the following conditions: //// the following conditions:
// ////
// The above copyright notice and this permission notice shall be //// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. //// included in all copies or substantial portions of the Software.
// ////
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND //// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE //// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION //// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION //// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ //// ************************************************************************/
#endregion //#endregion
using System.Collections.Generic; //using System.Collections.Generic;
using System.Threading.Tasks; //using System.Threading.Tasks;
using Moq; //using Moq;
using Nancy; //using Nancy;
using Nancy.Testing; //using Nancy.Testing;
using Newtonsoft.Json; //using Newtonsoft.Json;
using NUnit.Framework; //using NUnit.Framework;
using PlexRequests.Api.Interfaces; //using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex; //using PlexRequests.Api.Models.Plex;
using PlexRequests.Core; //using PlexRequests.Core;
using PlexRequests.Core.SettingModels; //using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers.Analytics; //using PlexRequests.Helpers.Analytics;
using PlexRequests.UI.Models; //using PlexRequests.UI.Models;
using PlexRequests.UI.Modules; //using PlexRequests.UI.Modules;
namespace PlexRequests.UI.Tests //namespace PlexRequests.UI.Tests
{ //{
[TestFixture] // [TestFixture]
public class UserLoginModuleTests // public class UserLoginModuleTests
{ // {
private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; } // private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; }
private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; } // private Mock<ISettingsService<PlexRequestSettings>> PlexRequestMock { get; set; }
private Mock<ISettingsService<LandingPageSettings>> LandingPageMock { get; set; } // private Mock<ISettingsService<LandingPageSettings>> LandingPageMock { get; set; }
private ConfigurableBootstrapper Bootstrapper { get; set; } // private ConfigurableBootstrapper Bootstrapper { get; set; }
private Mock<IPlexApi> PlexMock { get; set; } // private Mock<IPlexApi> PlexMock { get; set; }
private Mock<IAnalytics> IAnalytics { get; set; } // private Mock<IAnalytics> IAnalytics { get; set; }
[SetUp] // [SetUp]
public void Setup() // public void Setup()
{ // {
AuthMock = new Mock<ISettingsService<AuthenticationSettings>>(); // AuthMock = new Mock<ISettingsService<AuthenticationSettings>>();
PlexMock = new Mock<IPlexApi>(); // PlexMock = new Mock<IPlexApi>();
LandingPageMock = new Mock<ISettingsService<LandingPageSettings>>(); // LandingPageMock = new Mock<ISettingsService<LandingPageSettings>>();
PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>(); // PlexRequestMock = new Mock<ISettingsService<PlexRequestSettings>>();
PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings()); // PlexRequestMock.Setup(x => x.GetSettings()).Returns(new PlexRequestSettings());
PlexRequestMock.Setup(x => x.GetSettingsAsync()).Returns(Task.FromResult(new PlexRequestSettings())); // PlexRequestMock.Setup(x => x.GetSettingsAsync()).Returns(Task.FromResult(new PlexRequestSettings()));
LandingPageMock.Setup(x => x.GetSettings()).Returns(new LandingPageSettings()); // LandingPageMock.Setup(x => x.GetSettings()).Returns(new LandingPageSettings());
IAnalytics = new Mock<IAnalytics>(); // IAnalytics = new Mock<IAnalytics>();
Bootstrapper = new ConfigurableBootstrapper(with => // Bootstrapper = new ConfigurableBootstrapper(with =>
{ // {
with.Module<UserLoginModule>(); // with.Module<UserLoginModule>();
with.Dependency(PlexRequestMock.Object); // with.Dependency(PlexRequestMock.Object);
with.Dependency(AuthMock.Object); // with.Dependency(AuthMock.Object);
with.Dependency(PlexMock.Object); // with.Dependency(PlexMock.Object);
with.Dependency(LandingPageMock.Object); // with.Dependency(LandingPageMock.Object);
with.Dependency(IAnalytics.Object); // with.Dependency(IAnalytics.Object);
with.RootPathProvider<TestRootPathProvider>(); // with.RootPathProvider<TestRootPathProvider>();
}); // });
} // }
[Test] // [Test]
public void LoginWithoutAuthentication() // public void LoginWithoutAuthentication()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc")); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc"));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
} // }
[Test] // [Test]
public void LoginWithoutAuthenticationWithEmptyUsername() // public void LoginWithoutAuthenticationWithEmptyUsername()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", string.Empty); // with.FormValue("Username", string.Empty);
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
AuthMock.Verify(x => x.GetSettings(), Times.Never); // AuthMock.Verify(x => x.GetSettings(), Times.Never);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
} // }
[Test] // [Test]
public void LoginWithUsernameSuccessfully() // public void LoginWithUsernameSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends // new UserFriends
{ // {
Title = "abc", // Title = "abc",
}, // },
} // }
}; // };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); // PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc")); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc"));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
} // }
[Test] // [Test]
public void LoginWithUsernameUnSuccessfully() // public void LoginWithUsernameUnSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends // new UserFriends
{ // {
Username = "aaaa", // Username = "aaaa",
}, // },
} // }
}; // };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); // PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null);
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
Assert.That(body.Message, Is.Not.Empty); // Assert.That(body.Message, Is.Not.Empty);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
} // }
[Test] // [Test]
public void LoginWithUsernameAndPasswordSuccessfully() // public void LoginWithUsernameAndPasswordSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends // new UserFriends
{ // {
Title = "abc", // Title = "abc",
} // }
} // }
}; // };
var plexAuth = new PlexAuthentication // var plexAuth = new PlexAuthentication
{ // {
user = new User // user = new User
{ // {
authentication_token = "abc" // authentication_token = "abc"
} // }
}; // };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); // PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount()); // PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(new PlexAccount());
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
with.FormValue("Password", "abc"); // with.FormValue("Password", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc")); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc"));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
} // }
[Test] // [Test]
public void LoginWithUsernameAndPasswordUnSuccessfully() // public void LoginWithUsernameAndPasswordUnSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends // new UserFriends
{ // {
Username = "abc", // Username = "abc",
}, // },
} // }
}; // };
var plexAuth = new PlexAuthentication // var plexAuth = new PlexAuthentication
{ // {
user = null // user = null
}; // };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); // PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
with.FormValue("Password", "abc"); // with.FormValue("Password", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null);
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
Assert.That(body.Message, Is.Not.Empty); // Assert.That(body.Message, Is.Not.Empty);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
} // }
[Test] // [Test]
public void AttemptToLoginAsDeniedUser() // public void AttemptToLoginAsDeniedUser()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = false, DeniedUsers = "abc", PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = false, DeniedUsers = "abc", PlexAuthToken = "abc" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "abc"); // with.FormValue("Username", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null);
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(false)); // Assert.That(body.Result, Is.EqualTo(false));
Assert.That(body.Message, Is.Not.Empty); // Assert.That(body.Message, Is.Not.Empty);
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
} // }
[Test] // [Test]
public void Logout() // public void Logout()
{ // {
Bootstrapper.WithSession(new Dictionary<string, object> { { SessionKeys.UsernameKey, "abc" } }); // Bootstrapper.WithSession(new Dictionary<string, object> { { SessionKeys.UsernameKey, "abc" } });
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Get("/userlogin/logout", with => // var result = browser.Get("/userlogin/logout", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
}); // });
Assert.That(HttpStatusCode.SeeOther, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.SeeOther, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null);
} // }
[Test] // [Test]
public void LoginWithOwnerUsernameSuccessfully() // public void LoginWithOwnerUsernameSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends() // new UserFriends()
} // }
}; // };
var account = new PlexAccount { Username = "Jamie" }; // var account = new PlexAccount { Username = "Jamie" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account); // PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(new PlexAuthentication { user = new User { username = "Jamie" } }); // PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(new PlexAuthentication { user = new User { username = "Jamie" } });
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "Jamie"); // with.FormValue("Username", "Jamie");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("Jamie")); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("Jamie"));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Once);
} // }
[Test] // [Test]
public void LoginWithOwnerUsernameAndPasswordSuccessfully() // public void LoginWithOwnerUsernameAndPasswordSuccessfully()
{ // {
var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" }; // var expectedSettings = new AuthenticationSettings { UserAuthentication = true, UsePassword = true, PlexAuthToken = "abc" };
var plexFriends = new PlexFriends // var plexFriends = new PlexFriends
{ // {
User = new[] // User = new[]
{ // {
new UserFriends() // new UserFriends()
} // }
}; // };
var plexAuth = new PlexAuthentication // var plexAuth = new PlexAuthentication
{ // {
user = new User // user = new User
{ // {
authentication_token = "abc", // authentication_token = "abc",
username = "Jamie" // username = "Jamie"
} // }
}; // };
var account = new PlexAccount { Username = "Jamie" }; // var account = new PlexAccount { Username = "Jamie" };
AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); // AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings);
PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends); // PlexMock.Setup(x => x.GetUsers(It.IsAny<string>())).Returns(plexFriends);
PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth); // PlexMock.Setup(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>())).Returns(plexAuth);
PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account); // PlexMock.Setup(x => x.GetAccount(It.IsAny<string>())).Returns(account);
Bootstrapper.WithSession(new Dictionary<string, object>()); // Bootstrapper.WithSession(new Dictionary<string, object>());
var browser = new Browser(Bootstrapper); // var browser = new Browser(Bootstrapper);
var result = browser.Post("/userlogin", with => // var result = browser.Post("/userlogin", with =>
{ // {
with.HttpRequest(); // with.HttpRequest();
with.Header("Accept", "application/json"); // with.Header("Accept", "application/json");
with.FormValue("Username", "jamie"); // with.FormValue("Username", "jamie");
with.FormValue("Password", "abc"); // with.FormValue("Password", "abc");
}); // });
Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); // Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode));
Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("jamie")); // Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("jamie"));
var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString()); // var body = JsonConvert.DeserializeObject<JsonResponseModel>(result.Body.AsString());
Assert.That(body.Result, Is.EqualTo(true)); // Assert.That(body.Result, Is.EqualTo(true));
AuthMock.Verify(x => x.GetSettings(), Times.Once); // AuthMock.Verify(x => x.GetSettings(), Times.Once);
PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once); // PlexMock.Verify(x => x.SignIn(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never); // PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
} // }
} // }
} //}

@ -46,7 +46,6 @@ namespace PlexRequests.UI.ModelDataProviders
.Description("The blacklisted users, this is for internal use by the application, do not modify this list.") .Description("The blacklisted users, this is for internal use by the application, do not modify this list.")
.Required(false); .Required(false);
with.Property(x => x.DeniedUsers).Description("The blacklisted users, comma separated.").Required(false); with.Property(x => x.DeniedUsers).Description("The blacklisted users, comma separated.").Required(false);
with.Property(x => x.PlexAuthToken).Description("The Plex authentication token").Required(false);
with.Property(x => x.UsePassword) with.Property(x => x.UsePassword)
.Description("Require users to use a password to login when authentication is enabled") .Description("Require users to use a password to login when authentication is enabled")
.Required(false) .Required(false)

@ -290,19 +290,19 @@ namespace PlexRequests.UI.Modules
return Response.AsJson(new { Result = false, Message = "Incorrect username or password!" }); return Response.AsJson(new { Result = false, Message = "Incorrect username or password!" });
} }
var oldSettings = AuthService.GetSettings(); var oldSettings = PlexService.GetSettings();
if (oldSettings != null) if (oldSettings != null)
{ {
oldSettings.PlexAuthToken = model.user.authentication_token; oldSettings.PlexAuthToken = model.user.authentication_token;
AuthService.SaveSettings(oldSettings); PlexService.SaveSettings(oldSettings);
} }
else else
{ {
var newModel = new AuthenticationSettings var newModel = new PlexSettings
{ {
PlexAuthToken = model.user.authentication_token PlexAuthToken = model.user.authentication_token
}; };
AuthService.SaveSettings(newModel); PlexService.SaveSettings(newModel);
} }
return Response.AsJson(new { Result = true, AuthToken = model.user.authentication_token }); return Response.AsJson(new { Result = true, AuthToken = model.user.authentication_token });
@ -311,7 +311,7 @@ namespace PlexRequests.UI.Modules
private Response GetUsers() private Response GetUsers()
{ {
var settings = AuthService.GetSettings(); var settings = PlexService.GetSettings();
var token = settings?.PlexAuthToken; var token = settings?.PlexAuthToken;
if (token == null) if (token == null)

@ -1,230 +1,227 @@
#region Copyright #region Copyright
// /************************************************************************ // /************************************************************************
// Copyright (c) 2016 Jamie Rees // Copyright (c) 2016 Jamie Rees
// File: ApplicationTesterModule.cs // File: ApplicationTesterModule.cs
// Created By: Jamie Rees // Created By: Jamie Rees
// //
// Permission is hereby granted, free of charge, to any person obtaining // Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the // a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including // "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, // without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to // distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to // permit persons to whom the Software is furnished to do so, subject to
// the following conditions: // the following conditions:
// //
// The above copyright notice and this permission notice shall be // The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. // included in all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using Nancy; using Nancy;
using Nancy.ModelBinding; using Nancy.ModelBinding;
using Nancy.Security; using Nancy.Security;
using Nancy.Validation; using Nancy.Validation;
using NLog; using NLog;
using PlexRequests.Api.Interfaces; using PlexRequests.Api.Interfaces;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.UI.Helpers; using PlexRequests.UI.Helpers;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
public class ApplicationTesterModule : BaseAuthModule public class ApplicationTesterModule : BaseAuthModule
{ {
public ApplicationTesterModule(ICouchPotatoApi cpApi, ISonarrApi sonarrApi, IPlexApi plexApi, public ApplicationTesterModule(ICouchPotatoApi cpApi, ISonarrApi sonarrApi, IPlexApi plexApi,
ISettingsService<AuthenticationSettings> authSettings, ISickRageApi srApi, IHeadphonesApi hpApi, ISettingsService<PlexRequestSettings> pr) : base("test", pr) ISickRageApi srApi, IHeadphonesApi hpApi, ISettingsService<PlexRequestSettings> pr) : base("test", pr)
{ {
this.RequiresAuthentication(); this.RequiresAuthentication();
CpApi = cpApi; CpApi = cpApi;
SonarrApi = sonarrApi; SonarrApi = sonarrApi;
PlexApi = plexApi; PlexApi = plexApi;
AuthSettings = authSettings; SickRageApi = srApi;
SickRageApi = srApi; HeadphonesApi = hpApi;
HeadphonesApi = hpApi;
Post["/cp"] = _ => CouchPotatoTest();
Post["/cp"] = _ => CouchPotatoTest(); Post["/sonarr"] = _ => SonarrTest();
Post["/sonarr"] = _ => SonarrTest(); Post["/plex"] = _ => PlexTest();
Post["/plex"] = _ => PlexTest(); Post["/sickrage"] = _ => SickRageTest();
Post["/sickrage"] = _ => SickRageTest(); Post["/headphones"] = _ => HeadphonesTest();
Post["/headphones"] = _ => HeadphonesTest();
}
}
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private ISonarrApi SonarrApi { get; }
private ISonarrApi SonarrApi { get; } private ICouchPotatoApi CpApi { get; }
private ICouchPotatoApi CpApi { get; } private IPlexApi PlexApi { get; }
private IPlexApi PlexApi { get; } private ISickRageApi SickRageApi { get; }
private ISickRageApi SickRageApi { get; } private IHeadphonesApi HeadphonesApi { get; }
private IHeadphonesApi HeadphonesApi { get; }
private ISettingsService<AuthenticationSettings> AuthSettings { get; } private Response CouchPotatoTest()
{
private Response CouchPotatoTest() var couchPotatoSettings = this.Bind<CouchPotatoSettings>();
{ var valid = this.Validate(couchPotatoSettings);
var couchPotatoSettings = this.Bind<CouchPotatoSettings>(); if (!valid.IsValid)
var valid = this.Validate(couchPotatoSettings); {
if (!valid.IsValid) return Response.AsJson(valid.SendJsonError());
{ }
return Response.AsJson(valid.SendJsonError()); try
} {
try var status = CpApi.GetStatus(couchPotatoSettings.FullUri, couchPotatoSettings.ApiKey);
{ return status.success
var status = CpApi.GetStatus(couchPotatoSettings.FullUri, couchPotatoSettings.ApiKey); ? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to CouchPotato successfully!" })
return status.success : Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to CouchPotato, please check your settings." });
? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to CouchPotato successfully!" })
: Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to CouchPotato, please check your settings." }); }
catch (Exception e) // Exceptions are expected if we cannot connect so we will just log and swallow them.
} {
catch (Exception e) // Exceptions are expected if we cannot connect so we will just log and swallow them. Log.Warn("Exception thrown when attempting to get CP's status: ");
{ Log.Warn(e);
Log.Warn("Exception thrown when attempting to get CP's status: "); var message = $"Could not connect to CouchPotato, please check your settings. <strong>Exception Message:</strong> {e.Message}";
Log.Warn(e); if (e.InnerException != null)
var message = $"Could not connect to CouchPotato, please check your settings. <strong>Exception Message:</strong> {e.Message}"; {
if (e.InnerException != null) message = $"Could not connect to CouchPotato, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}";
{ }
message = $"Could not connect to CouchPotato, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}"; return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
} }
return Response.AsJson(new JsonResponseModel { Result = false, Message = message }); }
}
} private Response SonarrTest()
{
private Response SonarrTest() var sonarrSettings = this.Bind<SonarrSettings>();
{ var valid = this.Validate(sonarrSettings);
var sonarrSettings = this.Bind<SonarrSettings>(); if (!valid.IsValid)
var valid = this.Validate(sonarrSettings); {
if (!valid.IsValid) return Response.AsJson(valid.SendJsonError());
{ }
return Response.AsJson(valid.SendJsonError()); try
} {
try var status = SonarrApi.SystemStatus(sonarrSettings.ApiKey, sonarrSettings.FullUri);
{ return status?.version != null
var status = SonarrApi.SystemStatus(sonarrSettings.ApiKey, sonarrSettings.FullUri); ? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to Sonarr successfully!" })
return status?.version != null : Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Sonarr, please check your settings." });
? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to Sonarr successfully!" })
: Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Sonarr, please check your settings." }); }
catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them.
} {
catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them. Log.Warn("Exception thrown when attempting to get Sonarr's status: ");
{ Log.Warn(e);
Log.Warn("Exception thrown when attempting to get Sonarr's status: "); var message = $"Could not connect to Sonarr, please check your settings. <strong>Exception Message:</strong> {e.Message}";
Log.Warn(e); if (e.InnerException != null)
var message = $"Could not connect to Sonarr, please check your settings. <strong>Exception Message:</strong> {e.Message}"; {
if (e.InnerException != null) message = $"Could not connect to Sonarr, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}";
{ }
message = $"Could not connect to Sonarr, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}"; return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
} }
return Response.AsJson(new JsonResponseModel { Result = false, Message = message }); }
}
} private Response PlexTest()
{
private Response PlexTest() var plexSettings = this.Bind<PlexSettings>();
{ var valid = this.Validate(plexSettings);
var plexSettings = this.Bind<PlexSettings>(); if (!valid.IsValid)
var valid = this.Validate(plexSettings); {
if (!valid.IsValid) return Response.AsJson(valid.SendJsonError());
{ }
return Response.AsJson(valid.SendJsonError()); if (plexSettings?.PlexAuthToken == null)
} {
var settings = AuthSettings.GetSettings(); return Response.AsJson(new JsonResponseModel { Result = false, Message = "Plex is not setup yet, you need to update your Authentication settings" });
if (settings?.PlexAuthToken == null) }
{ try
return Response.AsJson(new JsonResponseModel { Result = false, Message = "Plex is not setup yet, you need to update your Authentication settings" }); {
} var status = PlexApi.GetStatus(plexSettings.PlexAuthToken, plexSettings.FullUri);
try return status != null
{ ? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to Plex successfully!" })
var status = PlexApi.GetStatus(settings.PlexAuthToken, plexSettings.FullUri); : Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Plex, please check your settings." });
return status != null
? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to Plex successfully!" }) }
: Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Plex, please check your settings." }); catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them.
{
} Log.Warn("Exception thrown when attempting to get Plex's status: ");
catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them. Log.Warn(e);
{ var message = $"Could not connect to Plex, please check your settings. <strong>Exception Message:</strong> {e.Message}";
Log.Warn("Exception thrown when attempting to get Plex's status: "); if (e.InnerException != null)
Log.Warn(e); {
var message = $"Could not connect to Plex, please check your settings. <strong>Exception Message:</strong> {e.Message}"; message = $"Could not connect to Plex, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}";
if (e.InnerException != null) }
{ return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
message = $"Could not connect to Plex, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}"; }
} }
return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
} private Response SickRageTest()
} {
var sickRageSettings = this.Bind<SickRageSettings>();
private Response SickRageTest() var valid = this.Validate(sickRageSettings);
{ if (!valid.IsValid)
var sickRageSettings = this.Bind<SickRageSettings>(); {
var valid = this.Validate(sickRageSettings); return Response.AsJson(valid.SendJsonError());
if (!valid.IsValid) }
{ try
return Response.AsJson(valid.SendJsonError()); {
} var status = SickRageApi.Ping(sickRageSettings.ApiKey, sickRageSettings.FullUri);
try return status?.result == "success"
{ ? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to SickRage successfully!" })
var status = SickRageApi.Ping(sickRageSettings.ApiKey, sickRageSettings.FullUri); : Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to SickRage, please check your settings." });
return status?.result == "success"
? Response.AsJson(new JsonResponseModel { Result = true, Message = "Connected to SickRage successfully!" }) }
: Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to SickRage, please check your settings." }); catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them.
{
} Log.Warn("Exception thrown when attempting to get SickRage's status: ");
catch (Exception e) // Exceptions are expected, if we cannot connect so we will just log and swallow them. Log.Warn(e);
{ var message = $"Could not connect to SickRage, please check your settings. <strong>Exception Message:</strong> {e.Message}";
Log.Warn("Exception thrown when attempting to get SickRage's status: "); if (e.InnerException != null)
Log.Warn(e); {
var message = $"Could not connect to SickRage, please check your settings. <strong>Exception Message:</strong> {e.Message}"; message = $"Could not connect to SickRage, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}";
if (e.InnerException != null) }
{ return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
message = $"Could not connect to SickRage, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}"; }
} }
return Response.AsJson(new JsonResponseModel { Result = false, Message = message });
} private Response HeadphonesTest()
} {
var settings = this.Bind<HeadphonesSettings>();
private Response HeadphonesTest() var valid = this.Validate(settings);
{ if (!valid.IsValid)
var settings = this.Bind<HeadphonesSettings>(); {
var valid = this.Validate(settings); return Response.AsJson(valid.SendJsonError());
if (!valid.IsValid) }
{ try
return Response.AsJson(valid.SendJsonError()); {
} var result = HeadphonesApi.GetVersion(settings.ApiKey, settings.FullUri);
try if (!string.IsNullOrEmpty(result.latest_version))
{ {
var result = HeadphonesApi.GetVersion(settings.ApiKey, settings.FullUri); return
if (!string.IsNullOrEmpty(result.latest_version)) Response.AsJson(new JsonResponseModel
{ {
return Result = true,
Response.AsJson(new JsonResponseModel Message = "Connected to Headphones successfully!"
{ });
Result = true, }
Message = "Connected to Headphones successfully!" return Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Headphones, please check your settings." });
}); }
} catch (Exception e)
return Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Headphones, please check your settings." }); {
} Log.Warn("Exception thrown when attempting to get Headphones's status: ");
catch (Exception e) Log.Warn(e);
{ var message = $"Could not connect to Headphones, please check your settings. <strong>Exception Message:</strong> {e.Message}";
Log.Warn("Exception thrown when attempting to get Headphones's status: "); if (e.InnerException != null)
Log.Warn(e); {
var message = $"Could not connect to Headphones, please check your settings. <strong>Exception Message:</strong> {e.Message}"; message = $"Could not connect to Headphones, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}";
if (e.InnerException != null) }
{ return Response.AsJson(new JsonResponseModel { Result = false, Message = message }); ;
message = $"Could not connect to Headphones, please check your settings. <strong>Exception Message:</strong> {e.InnerException.Message}"; }
} }
return Response.AsJson(new JsonResponseModel { Result = false, Message = message }); ; }
}
}
}
} }

@ -29,7 +29,6 @@ using System.Threading.Tasks;
using Nancy; using Nancy;
using Nancy.Linker; using Nancy.Linker;
using Nancy.Responses.Negotiation;
using PlexRequests.Api.Interfaces; using PlexRequests.Api.Interfaces;
using PlexRequests.Core; using PlexRequests.Core;
@ -41,12 +40,11 @@ namespace PlexRequests.UI.Modules
public class LandingPageModule : BaseModule public class LandingPageModule : BaseModule
{ {
public LandingPageModule(ISettingsService<PlexRequestSettings> settingsService, ISettingsService<LandingPageSettings> landing, public LandingPageModule(ISettingsService<PlexRequestSettings> settingsService, ISettingsService<LandingPageSettings> landing,
ISettingsService<PlexSettings> ps, IPlexApi pApi, ISettingsService<AuthenticationSettings> auth, IResourceLinker linker) : base("landing", settingsService) ISettingsService<PlexSettings> ps, IPlexApi pApi, IResourceLinker linker) : base("landing", settingsService)
{ {
LandingSettings = landing; LandingSettings = landing;
PlexSettings = ps; PlexSettings = ps;
PlexApi = pApi; PlexApi = pApi;
AuthSettings = auth;
Linker = linker; Linker = linker;
Get["LandingPageIndex","/", true] = async (x, ct) => Get["LandingPageIndex","/", true] = async (x, ct) =>
@ -77,21 +75,19 @@ namespace PlexRequests.UI.Modules
private ISettingsService<LandingPageSettings> LandingSettings { get; } private ISettingsService<LandingPageSettings> LandingSettings { get; }
private ISettingsService<PlexSettings> PlexSettings { get; } private ISettingsService<PlexSettings> PlexSettings { get; }
private ISettingsService<AuthenticationSettings> AuthSettings { get; }
private IPlexApi PlexApi { get; } private IPlexApi PlexApi { get; }
private IResourceLinker Linker { get; } private IResourceLinker Linker { get; }
private async Task<Response> CheckStatus() private async Task<Response> CheckStatus()
{ {
var auth = await AuthSettings.GetSettingsAsync();
var plexSettings = await PlexSettings.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync();
if (string.IsNullOrEmpty(auth.PlexAuthToken) || string.IsNullOrEmpty(plexSettings.Ip)) if (string.IsNullOrEmpty(plexSettings.PlexAuthToken) || string.IsNullOrEmpty(plexSettings.Ip))
{ {
return Response.AsJson(false); return Response.AsJson(false);
} }
try try
{ {
var status = PlexApi.GetStatus(auth.PlexAuthToken, plexSettings.FullUri); var status = PlexApi.GetStatus(plexSettings.PlexAuthToken, plexSettings.FullUri);
return Response.AsJson(status != null); return Response.AsJson(status != null);
} }
catch (Exception) catch (Exception)

@ -1,98 +0,0 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexUsersModule.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Linq;
using System.Threading.Tasks;
using Nancy;
using Nancy.Responses.Negotiation;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Music;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models;
namespace PlexRequests.UI.Modules
{
public class PlexUsersModule : BaseAuthModule
{
public PlexUsersModule(ISettingsService<PlexRequestSettings> pr, IPlexApi plexApi, ISettingsService<AuthenticationSettings> auth,
IRepository<PlexUsers> repo) : base("plexusers", pr)
{
PlexApi = plexApi;
AuthSettings = auth;
Repo = repo;
Get["/"] = x => Index();
Get["/users", true] = async (x, ct) => await GetPlexUsers();
Post["/alias", true] = async (x, ct) => await Alias();
}
private IPlexApi PlexApi { get; }
private ISettingsService<AuthenticationSettings> AuthSettings { get; }
private IRepository<PlexUsers> Repo { get; }
private Negotiator Index()
{
return View["Index"];
}
private async Task<Response> GetPlexUsers()
{
var authSettings = await AuthSettings.GetSettingsAsync();
var users = PlexApi.GetUsers(authSettings.PlexAuthToken);
return Response.AsJson(users.User);
}
private async Task<Response> Alias()
{
var plexUserId = (int)Request.Form["plexid"];
var alias = (string)Request.Form["alias"];
var allUsers = await Repo.GetAllAsync();
var existingUser = allUsers.FirstOrDefault(x => x.PlexUserId == plexUserId);
if (existingUser == null)
{
// Create a new mapping
existingUser = new PlexUsers { PlexUserId = plexUserId, UserAlias = alias };
}
else
{
// Modify existing alias
existingUser.UserAlias = alias;
}
await Repo.InsertAsync(existingUser);
return Response.AsJson(new JsonResponseModel { Result = true });
}
}
}

@ -49,19 +49,22 @@ namespace PlexRequests.UI.Modules
{ {
public class UserLoginModule : BaseModule public class UserLoginModule : BaseModule
{ {
public UserLoginModule(ISettingsService<AuthenticationSettings> auth, IPlexApi api, ISettingsService<PlexRequestSettings> pr, ISettingsService<LandingPageSettings> lp, IAnalytics a) : base("userlogin", pr) public UserLoginModule(ISettingsService<AuthenticationSettings> auth, IPlexApi api, ISettingsService<PlexSettings> plexSettings, ISettingsService<PlexRequestSettings> pr, ISettingsService<LandingPageSettings> lp, IAnalytics a) : base("userlogin", pr)
{ {
AuthService = auth; AuthService = auth;
LandingPageSettings = lp; LandingPageSettings = lp;
Analytics = a; Analytics = a;
Api = api; Api = api;
PlexSettings = plexSettings;
Get["UserLoginIndex","/", true] = async (x, ct) => await Index(); Get["UserLoginIndex","/", true] = async (x, ct) => await Index();
Post["/"] = x => LoginUser(); Post["/", true] = async (x,ct) => await LoginUser();
Get["/logout"] = x => Logout(); Get["/logout"] = x => Logout();
} }
private ISettingsService<AuthenticationSettings> AuthService { get; } private ISettingsService<AuthenticationSettings> AuthService { get; }
private ISettingsService<LandingPageSettings> LandingPageSettings { get; } private ISettingsService<LandingPageSettings> LandingPageSettings { get; }
private ISettingsService<PlexSettings> PlexSettings { get; }
private IPlexApi Api { get; } private IPlexApi Api { get; }
private IAnalytics Analytics { get; } private IAnalytics Analytics { get; }
@ -74,7 +77,7 @@ namespace PlexRequests.UI.Modules
return View["Index", settings]; return View["Index", settings];
} }
private Response LoginUser() private async Task<Response> LoginUser()
{ {
var dateTimeOffset = Request.Form.DateTimeOffset; var dateTimeOffset = Request.Form.DateTimeOffset;
var username = Request.Form.username.Value; var username = Request.Form.username.Value;
@ -86,7 +89,8 @@ namespace PlexRequests.UI.Modules
var authenticated = false; var authenticated = false;
var settings = AuthService.GetSettings(); var settings = await AuthService.GetSettingsAsync();
var plexSettings = await PlexSettings.GetSettingsAsync();
if (IsUserInDeniedList(username, settings)) if (IsUserInDeniedList(username, settings))
{ {
@ -109,14 +113,14 @@ namespace PlexRequests.UI.Modules
if (signedIn.user?.authentication_token != null) if (signedIn.user?.authentication_token != null)
{ {
Log.Debug("Correct credentials, checking if the user is account owner or in the friends list"); Log.Debug("Correct credentials, checking if the user is account owner or in the friends list");
if (CheckIfUserIsOwner(settings.PlexAuthToken, signedIn.user?.username)) if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, signedIn.user?.username))
{ {
Log.Debug("User is the account owner"); Log.Debug("User is the account owner");
authenticated = true; authenticated = true;
} }
else else
{ {
authenticated = CheckIfUserIsInPlexFriends(username, settings.PlexAuthToken); authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
Log.Debug("Friends list result = {0}", authenticated); Log.Debug("Friends list result = {0}", authenticated);
} }
} }
@ -124,8 +128,8 @@ namespace PlexRequests.UI.Modules
else if (settings.UserAuthentication) // Check against the users in Plex else if (settings.UserAuthentication) // Check against the users in Plex
{ {
Log.Debug("Need to auth"); Log.Debug("Need to auth");
authenticated = CheckIfUserIsInPlexFriends(username, settings.PlexAuthToken); authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
if (CheckIfUserIsOwner(settings.PlexAuthToken, username)) if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, username))
{ {
Log.Debug("User is the account owner"); Log.Debug("User is the account owner");
authenticated = true; authenticated = true;

@ -18,13 +18,13 @@ namespace PlexRequests.UI.Modules
{ {
public class UserManagementModule : BaseModule public class UserManagementModule : BaseModule
{ {
public UserManagementModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IPlexApi plexApi, ISettingsService<AuthenticationSettings> auth) : base("usermanagement", pr) public UserManagementModule(ISettingsService<PlexRequestSettings> pr, ICustomUserMapper m, IPlexApi plexApi, ISettingsService<PlexSettings> plex) : base("usermanagement", pr)
{ {
//this.RequiresClaims(UserClaims.Admin); //this.RequiresClaims(UserClaims.Admin);
UserMapper = m; UserMapper = m;
PlexApi = plexApi; PlexApi = plexApi;
AuthSettings = auth; PlexSettings = plex;
Get["/"] = x => Load(); Get["/"] = x => Load();
@ -36,7 +36,7 @@ namespace PlexRequests.UI.Modules
private ICustomUserMapper UserMapper { get; } private ICustomUserMapper UserMapper { get; }
private IPlexApi PlexApi { get; } private IPlexApi PlexApi { get; }
private ISettingsService<AuthenticationSettings> AuthSettings { get; } private ISettingsService<PlexSettings> PlexSettings { get; }
private Negotiator Load() private Negotiator Load()
{ {
@ -63,11 +63,11 @@ namespace PlexRequests.UI.Modules
}); });
} }
var authSettings = await AuthSettings.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync();
if (!string.IsNullOrEmpty(authSettings.PlexAuthToken)) if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
{ {
//Get Plex Users //Get Plex Users
var plexUsers = PlexApi.GetUsers(authSettings.PlexAuthToken); var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);
foreach (var u in plexUsers.User) foreach (var u in plexUsers.User)
{ {
@ -116,11 +116,11 @@ namespace PlexRequests.UI.Modules
private async Task<Response> PlexDetails(int id) private async Task<Response> PlexDetails(int id)
{ {
var authSettings = await AuthSettings.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync();
if (!string.IsNullOrEmpty(authSettings.PlexAuthToken)) if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
{ {
//Get Plex Users //Get Plex Users
var plexUsers = PlexApi.GetUsers(authSettings.PlexAuthToken); var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);
var selectedUser = plexUsers.User?.FirstOrDefault(x => x.Id == id); var selectedUser = plexUsers.User?.FirstOrDefault(x => x.Id == id);
if (selectedUser != null) if (selectedUser != null)

@ -222,7 +222,6 @@
<Compile Include="Modules\CultureModule.cs" /> <Compile Include="Modules\CultureModule.cs" />
<Compile Include="Modules\IssuesModule.cs" /> <Compile Include="Modules\IssuesModule.cs" />
<Compile Include="Modules\LandingPageModule.cs" /> <Compile Include="Modules\LandingPageModule.cs" />
<Compile Include="Modules\PlexUsersModule.cs" />
<Compile Include="Modules\UpdateCheckerModule.cs" /> <Compile Include="Modules\UpdateCheckerModule.cs" />
<Compile Include="NinjectModules\ApiModule.cs" /> <Compile Include="NinjectModules\ApiModule.cs" />
<Compile Include="NinjectModules\ConfigurationModule.cs" /> <Compile Include="NinjectModules\ConfigurationModule.cs" />

@ -1,184 +1,139 @@
@using PlexRequests.UI.Helpers @using PlexRequests.UI.Helpers
@Html.Partial("_Sidebar") @Html.Partial("_Sidebar")
@{ @{
var baseUrl = Html.GetBaseUrl(); var baseUrl = Html.GetBaseUrl();
var formAction = "/admin/authentication"; var formAction = "/admin/authentication";
if (!string.IsNullOrEmpty(baseUrl.ToHtmlString())) if (!string.IsNullOrEmpty(baseUrl.ToHtmlString()))
{ {
formAction = "/" + baseUrl.ToHtmlString() + formAction; formAction = "/" + baseUrl.ToHtmlString() + formAction;
} }
} }
<div class="col-sm-8 col-sm-push-1"> <div class="col-sm-8 col-sm-push-1">
<form class="form-horizontal" method="POST" action="@formAction" id="mainForm"> <form class="form-horizontal" method="POST" action="@formAction" id="mainForm">
<fieldset> <fieldset>
<legend>Authentication Settings</legend> <legend>Authentication Settings</legend>
<div class="form-group"> <div class="form-group">
<div class="checkbox"> <div class="checkbox">
@if (Model.UserAuthentication) @if (Model.UserAuthentication)
{ {
<input type="checkbox" id="userAuth" name="UserAuthentication" checked="checked"> <input type="checkbox" id="userAuth" name="UserAuthentication" checked="checked">
<label for="userAuth">Enable User Authentication</label> <label for="userAuth">Enable User Authentication</label>
} }
else else
{ {
<input type="checkbox" id="userAuth" name="UserAuthentication"> <input type="checkbox" id="userAuth" name="UserAuthentication">
<label for="userAuth">Enable User Authentication</label> <label for="userAuth">Enable User Authentication</label>
} }
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="checkbox"> <div class="checkbox">
@if (Model.UsePassword) @if (Model.UsePassword)
{ {
<input type="checkbox" id="UsePassword" name="UsePassword" checked="checked"> <input type="checkbox" id="UsePassword" name="UsePassword" checked="checked">
<label for="UsePassword">Require users to login with their passwords</label> <label for="UsePassword">Require users to login with their passwords</label>
} }
else else
{ {
<input type="checkbox" id="UsePassword" name="UsePassword"> <input type="checkbox" id="UsePassword" name="UsePassword">
<label for="UsePassword">Require users to login with their passwords</label> <label for="UsePassword">Require users to login with their passwords</label>
} }
</div> </div>
</div> </div>
<div class="form-group">
<label for="authToken" class="control-label">Plex Authorization Token</label> <br />
<div class=""> <br />
<input type="text" class="form-control-custom form-control" id="authToken" name="PlexAuthToken" placeholder="Plex Auth Token" value="@Model.PlexAuthToken"> <p class="form-group">Current users that are allowed to authenticate: </p>
</div>
</div> <div class="form-group">
<select id="users" multiple="" class="form-control-custom" style="height: 180px;"></select>
<div class="form-group"> </div>
<label for="username" class="control-label">Username and Password</label> <div class="form-group">
<div>
<input type="text" class="form-control form-control-custom" id="username" name="Username" placeholder="username"> <div>
</div> <button id="refreshUsers" class="btn btn-primary-outline">Refresh Users</button>
<br/> </div>
<div> </div>
<input type="password" class="form-control form-control-custom" id="password" name="Password" placeholder="Password">
</div> <p class="form-group">A comma separated list of users that you do not want to login.</p>
</div> <div class="form-group">
<div class="form-group"> <label for="deniedUsers" class="control-label">Denied Users</label>
<div class=""> <div >
<button id="requestToken" class="btn btn-primary-outline">Request Token <i class="fa fa-key"></i></button> <input type="text" class="form-control-custom form-control " id="DeniedUsers" name="DeniedUsers" placeholder="e.g. John, Bobby" value="@Model.DeniedUsers">
</div> </div>
</div> </div>
<br/>
<div>
<br /> </div>
<br /> <div class="form-group">
<p class="form-group">Current users that are allowed to authenticate: </p> <div>
<button type="submit" class="btn btn-primary-outline">Submit</button>
<div class="form-group"> </div>
<select id="users" multiple="" class="form-control-custom" style="height: 180px;"></select> </div>
</div> </fieldset>
<div class="form-group"> </form>
</div>
<div>
<button id="refreshUsers" class="btn btn-primary-outline">Refresh Users</button>
</div> <script>
</div> $(function () {
<p class="form-group">A comma separated list of users that you do not want to login.</p> var base = '@Html.GetBaseUrl()';
<div class="form-group">
<label for="deniedUsers" class="control-label">Denied Users</label> if ($('#PlexAuthToken')) {
<div > loadUserList();
<input type="text" class="form-control-custom form-control " id="DeniedUsers" name="DeniedUsers" placeholder="e.g. John, Bobby" value="@Model.DeniedUsers"> }
</div>
</div> $('#refreshUsers').click(function (e) {
<br/> e.preventDefault();
<div> loadUserList();
</div> });
<div class="form-group">
<div>
<button type="submit" class="btn btn-primary-outline">Submit</button>
</div>
</div>
</fieldset> function loadUserList() {
</form> $('#users').html("");
</div> var url = "getusers";
$.ajax({
type: "Get",
<script> url: url,
$(function () { dataType: "json",
success: function (response) {
var base = '@Html.GetBaseUrl()';
$('#users').html("");
if ($('#PlexAuthToken')) { if(!response.result){
loadUserList(); generateNotify(response.message,"danger");
} $('#users').append("<option>Error!</option>");
return;
$('#refreshUsers').click(function (e) { }
e.preventDefault(); if (response.users.length > 0) {
loadUserList(); $(response.users).each(function () {
}); $('#users').append("<option>" + this + "</option>");
});
$('#requestToken').click(function (e) { } else {
e.preventDefault(); $('#users').append("<option>No Users, Please refresh!</option>");
var $form = $("#mainForm"); }
$.ajax({ },
type: $form.prop("method"), error: function (e) {
url: "requestauth", console.log(e);
data: $form.serialize(), generateNotify("Something went wrong!", "danger");
dataType: "json", $('#users').html("");
success: function (response) { $('#users').append("<option>Error!</option>");
console.log(response); }
if (response.result === true) { });
generateNotify("Success!", "success");
$('#authToken').val(response.authToken); }
} else {
generateNotify(response.message, "warning");
} });
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
function loadUserList() {
$('#users').html("");
var url = "getusers";
$.ajax({
type: "Get",
url: url,
dataType: "json",
success: function (response) {
$('#users').html("");
if(!response.result){
generateNotify(response.message,"danger");
$('#users').append("<option>Error!</option>");
return;
}
if (response.users.length > 0) {
$(response.users).each(function () {
$('#users').append("<option>" + this + "</option>");
});
} else {
$('#users').append("<option>No Users, Please refresh!</option>");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
$('#users').html("");
$('#users').append("<option>Error!</option>");
}
});
}
});
</script> </script>

@ -1,153 +1,201 @@
@using PlexRequests.UI.Helpers @using PlexRequests.UI.Helpers
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<PlexRequests.Core.SettingModels.PlexSettings> @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<PlexRequests.Core.SettingModels.PlexSettings>
@Html.Partial("_Sidebar") @Html.Partial("_Sidebar")
@{ @{
int port; int port;
if (Model.Port == 0) if (Model.Port == 0)
{ {
port = 32400; port = 32400;
} }
else else
{ {
port = Model.Port; port = Model.Port;
} }
} }
<div class="col-sm-8 col-sm-push-1"> <div class="col-sm-8 col-sm-push-1">
<form class="form-horizontal" method="POST" id="mainForm"> <form class="form-horizontal" method="POST" id="mainForm">
<fieldset> <fieldset>
<legend>Plex Settings</legend> <legend>Plex Settings</legend>
<div class="form-group"> <div class="form-group">
<label for="Ip" class="control-label">Plex Hostname or IP</label> <label for="Ip" class="control-label">Plex Hostname or IP</label>
<div> <div>
<input type="text" class="form-control form-control-custom " id="Ip" name="Ip" placeholder="localhost" value="@Model.Ip"> <input type="text" class="form-control form-control-custom " id="Ip" name="Ip" placeholder="localhost" value="@Model.Ip">
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="portNumber" class="control-label">Port</label> <label for="portNumber" class="control-label">Port</label>
<div> <div>
<input type="text" class="form-control form-control-custom " id="portNumber" name="Port" placeholder="Port Number" value="@port"> <input type="text" class="form-control form-control-custom " id="portNumber" name="Port" placeholder="Port Number" value="@port">
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="checkbox"> <div class="checkbox">
@if (Model.Ssl) @if (Model.Ssl)
{ {
<input type="checkbox" id="Ssl" name="Ssl" checked="checked"><label for="Ssl">SSL</label> <input type="checkbox" id="Ssl" name="Ssl" checked="checked"><label for="Ssl">SSL</label>
} }
else else
{ {
<input type="checkbox" id="Ssl" name="Ssl"><label for="Ssl">SSL</label> <input type="checkbox" id="Ssl" name="Ssl"><label for="Ssl">SSL</label>
} }
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="checkbox"> <div class="checkbox">
@if (Model.AdvancedSearch) @if (Model.AdvancedSearch)
{ {
<input type="checkbox" id="AdvancedSearch" name="AdvancedSearch" checked="checked"><label for="AdvancedSearch">Use Advanced Search</label> <input type="checkbox" id="AdvancedSearch" name="AdvancedSearch" checked="checked"><label for="AdvancedSearch">Use Advanced Search</label>
} }
else else
{ {
<input type="checkbox" id="AdvancedSearch" name="AdvancedSearch"><label for="AdvancedSearch">Use Advanced Search</label> <input type="checkbox" id="AdvancedSearch" name="AdvancedSearch"><label for="AdvancedSearch">Use Advanced Search</label>
} }
</div> </div>
<small>If enabled we will be able to have a 100% accurate match, but we will be querying Plex for every single item in your library. So if you have a big library then this could take some time.</small> <small>If enabled we will be able to have a 100% accurate match, but we will be querying Plex for every single item in your library. So if you have a big library then this could take some time.</small>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="SubDir" class="control-label">Plex SubDirectory</label> <label for="SubDir" class="control-label">Plex SubDirectory</label>
<div> <div>
<input type="text" class="form-control form-control-custom " id="SubDir" name="SubDir" value="@Model.SubDir"> <input type="text" class="form-control form-control-custom " id="SubDir" name="SubDir" value="@Model.SubDir">
</div> </div>
</div> </div>
<div class="form-group">
<div> <div class="form-group">
<button id="testPlex" type="submit" class="btn btn-primary-outline">Test Connectivity <div id="spinner"></div></button> <label for="authToken" class="control-label">Plex Authorization Token</label>
</div> <div class="">
</div> <input type="text" class="form-control-custom form-control" id="authToken" name="PlexAuthToken" placeholder="Plex Auth Token" value="@Model.PlexAuthToken">
</div>
<div class="form-group"> </div>
<div>
<button id="save" type="submit" class="btn btn-primary-outline">Submit</button> <div class="form-group">
</div> <label for="username" class="control-label">Username and Password</label>
</div> <div>
</fieldset> <input type="text" class="form-control form-control-custom" id="username" name="Username" placeholder="username">
</form> </div>
</div> <br />
<div>
<input type="password" class="form-control form-control-custom" id="password" name="Password" placeholder="Password">
<script> </div>
$(function () { </div>
var base = '@Html.GetBaseUrl()'; <div class="form-group">
<div class="">
$('#testPlex').click(function (e) { <button id="requestToken" class="btn btn-primary-outline">Request Token <i class="fa fa-key"></i></button>
e.preventDefault(); </div>
var url = createBaseUrl(base, '/test/plex'); </div>
var $form = $("#mainForm");
<div class="form-group">
$('#spinner').attr("class", "fa fa-spinner fa-spin"); <div>
$.ajax({ <button id="testPlex" type="submit" class="btn btn-primary-outline">Test Connectivity <div id="spinner"></div></button>
type: $form.prop("method"), </div>
url: url, </div>
data: $form.serialize(),
dataType: "json", <div class="form-group">
success: function (response) { <div>
$('#spinner').attr("class", ""); <button id="save" type="submit" class="btn btn-primary-outline">Submit</button>
console.log(response); </div>
if (response.result === true) { </div>
generateNotify(response.message, "success"); </fieldset>
</form>
$('#spinner').attr("class", "fa fa-check"); </div>
$('#authToken').val(response.authToken);
} else {
generateNotify(response.message, "warning"); <script>
$('#spinner').attr("class", "fa fa-times"); $(function () {
} var base = '@Html.GetBaseUrl()';
},
error: function (e) { $('#testPlex').click(function (e) {
e.preventDefault();
$('#spinner').attr("class", "fa fa-times"); var url = createBaseUrl(base, '/test/plex');
console.log(e); var $form = $("#mainForm");
generateNotify("Something went wrong!", "danger");
} $('#spinner').attr("class", "fa fa-spinner fa-spin");
}); $.ajax({
}); type: $form.prop("method"),
url: url,
$('#save').click(function (e) { data: $form.serialize(),
e.preventDefault(); dataType: "json",
var port = $('#portNumber').val(); success: function (response) {
if (isNaN(port)) { $('#spinner').attr("class", "");
generateNotify("You must specify a Port.", "warning"); console.log(response);
return; if (response.result === true) {
} generateNotify(response.message, "success");
var $form = $("#mainForm"); $('#spinner').attr("class", "fa fa-check");
$.ajax({ $('#authToken').val(response.authToken);
type: $form.prop("method"), } else {
data: $form.serialize(), generateNotify(response.message, "warning");
url: $form.prop("action"), $('#spinner').attr("class", "fa fa-times");
dataType: "json", }
success: function (response) { },
if (response.result === true) { error: function (e) {
generateNotify(response.message, "success");
} else { $('#spinner').attr("class", "fa fa-times");
generateNotify(response.message, "warning"); console.log(e);
} generateNotify("Something went wrong!", "danger");
}, }
error: function (e) { });
console.log(e); });
generateNotify("Something went wrong!", "danger");
} $('#requestToken').click(function (e) {
}); e.preventDefault();
}); var $form = $("#mainForm");
$.ajax({
}); type: $form.prop("method"),
url: "requestauth",
data: $form.serialize(),
dataType: "json",
success: function (response) {
console.log(response);
if (response.result === true) {
generateNotify("Success!", "success");
$('#authToken').val(response.authToken);
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
$('#save').click(function (e) {
e.preventDefault();
var port = $('#portNumber').val();
if (isNaN(port)) {
generateNotify("You must specify a Port.", "warning");
return;
}
var $form = $("#mainForm");
$.ajax({
type: $form.prop("method"),
data: $form.serialize(),
url: $form.prop("action"),
dataType: "json",
success: function (response) {
if (response.result === true) {
generateNotify(response.message, "success");
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
});
</script> </script>
Loading…
Cancel
Save