using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Ombi.Api.External.MediaServers.Plex; using Ombi.Controllers.V1; using Ombi.Core.Authentication; using Ombi.Core.Settings; using Ombi.Core.Settings.Models.External; using Ombi.Helpers; using Ombi.Store.Entities; using Ombi.Test.Common; namespace Ombi.Tests { [TestFixture] public class PlexOAuthControllerTests { private Mock _oAuthManager; private Mock _plexApi; private Mock> _plexSettings; private Mock _userManager; private PlexOAuthController _subject; [SetUp] public void Setup() { _oAuthManager = new Mock(); _plexApi = new Mock(); _plexSettings = new Mock>(); _userManager = MockHelper.MockUserManager(new List()); _subject = new PlexOAuthController(_oAuthManager.Object, _plexApi.Object, _plexSettings.Object, Mock.Of>(), _userManager.Object); } private void SetAdminExists(bool exists) { var admins = exists ? new List { new OmbiUser { Id = "admin-id", UserName = "admin" } } : new List(); _userManager.Setup(x => x.GetUsersInRoleAsync(OmbiRoles.Admin)).ReturnsAsync(admins); } [Test] public async Task OAuthWizardCallBack_ReturnsUnauthorized_WhenAdminAlreadyExists() { // This callback is only part of the first-run wizard. Once an administrator account exists // the wizard is finished, so it must return without reading or overwriting the Plex config. SetAdminExists(true); var result = await _subject.OAuthWizardCallBack(1234); Assert.That(result, Is.InstanceOf()); _oAuthManager.Verify(x => x.GetAccessTokenFromPin(It.IsAny()), Times.Never); _plexSettings.Verify(x => x.SaveSettingsAsync(It.IsAny()), Times.Never); } [Test] public async Task OAuthWizardCallBack_ProceedsPastGuard_WhenNoAdminExists() { // On a fresh install (no admin yet) the first-run wizard must still be able to use this // endpoint. Returning an empty token makes the action bail out immediately AFTER the admin // guard, proving the request was allowed through. SetAdminExists(false); _oAuthManager.Setup(x => x.GetAccessTokenFromPin(1234)).ReturnsAsync(string.Empty); var result = await _subject.OAuthWizardCallBack(1234); _oAuthManager.Verify(x => x.GetAccessTokenFromPin(1234), Times.Once); Assert.That(result, Is.InstanceOf()); } } }