Exemple #1
0
        public void GetUserById_Should_Return_Correct_User()
        {
            RunTest(() =>
            {
                var embyUserOne = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "reggi"
                };
                var embyUserTwo = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "tom"
                };
                var embyUserThee = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "yol"
                };
                using (var database = _context.LiteDatabase)
                {
                    var collection = database.GetCollection <EmbyUser>();
                    collection.InsertBulk(new[] { embyUserOne, embyUserTwo, embyUserThee });
                }

                var user = _mediaServerRepository.GetUserById(embyUserTwo.Id);

                user.Should().NotBeNull();
                user.Id.Should().Be(embyUserTwo.Id);
                user.Name.Should().Be(embyUserTwo.Name);
            });
        }
Exemple #2
0
        public void UpsertUsers_Should_Insert_New_Users()
        {
            RunTest(() =>
            {
                var embyUserOne = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "reggi"
                };
                var embyUserTwo = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "tom"
                };
                _mediaServerRepository.UpsertUsers(new[] { embyUserOne, embyUserTwo });

                using (var database = _context.LiteDatabase)
                {
                    var collection = database.GetCollection <EmbyUser>();
                    var users      = collection.FindAll().OrderBy(x => x.Name).ToList();

                    users.Should().NotContainNulls();
                    users.Count.Should().Be(2);

                    users[0].Id.Should().Be(embyUserOne.Id);
                    users[0].Name.Should().Be(embyUserOne.Name);

                    users[1].Id.Should().Be(embyUserTwo.Id);
                    users[1].Name.Should().Be(embyUserTwo.Name);
                }
            });
        }
Exemple #3
0
        public void GetAllUsers_Should_Return_All_Users()
        {
            RunTest(() =>
            {
                var embyUserOne = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "reggi", IsAdministrator = false
                };
                var embyUserTwo = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "tom", IsAdministrator = true
                };
                using (var database = _context.LiteDatabase)
                {
                    var collection = database.GetCollection <EmbyUser>();
                    collection.InsertBulk(new[] { embyUserOne, embyUserTwo });
                }

                var users = _mediaServerRepository.GetAllUsers().ToList();
                users.Should().NotContainNulls();
                users.Count.Should().Be(2);

                users[0].Id.Should().Be(embyUserOne.Id);
                users[0].Name.Should().Be(embyUserOne.Name);

                users[1].Id.Should().Be(embyUserTwo.Id);
                users[1].Name.Should().Be(embyUserTwo.Name);
            });
        }
        private UserManagementUsersViewModel MapEmbyUser(EmbyUser embyInfo, EmbyUsers dbUser, DateTime lastLoggedIn)
        {
            var newUser = false;

            if (dbUser == null)
            {
                newUser = true;
                dbUser  = new EmbyUsers();
            }
            var features    = (Features)dbUser?.Features;
            var permissions = (Permissions)dbUser?.Permissions;

            var m = new UserManagementUsersViewModel
            {
                Id = embyInfo.Id,
                PermissionsFormattedString = newUser ? "Processing..." : (permissions == 0 ? "None" : permissions.ToString()),
                FeaturesFormattedString    = newUser ? "Processing..." : features.ToString(),
                Username     = embyInfo.Name,
                Type         = UserType.EmbyUser,
                EmailAddress = dbUser.EmailAddress,
                Alias        = dbUser?.UserAlias ?? string.Empty,
                LastLoggedIn = lastLoggedIn,
                ManagedUser  = false
            };

            m.Permissions.AddRange(GetPermissions(permissions));
            m.Features.AddRange(GetFeatures(features));

            return(m);
        }
Exemple #5
0
        public void RemoveAllMediaServerData_Should_Remove_All_Data()
        {
            RunTest(() =>
            {
                using (var database = _context.LiteDatabase)
                {
                    var pluginOne = new PluginInfo {
                        Id = Guid.NewGuid().ToString(), Name = "statistics"
                    };
                    var pluginCollection = database.GetCollection <PluginInfo>();
                    pluginCollection.Insert(pluginOne);

                    var serverInfo = new ServerInfo {
                        Id = Guid.NewGuid().ToString()
                    };
                    var serverInfoCollection = database.GetCollection <ServerInfo>();
                    serverInfoCollection.Insert(serverInfo);

                    var embyUserOne = new EmbyUser {
                        Id = Guid.NewGuid().ToString(), Name = "reggi"
                    };
                    var userCollection = database.GetCollection <EmbyUser>();
                    userCollection.Insert(embyUserOne);

                    var serverOne = new Device {
                        Id = Guid.NewGuid().ToString(), Name = "server1"
                    };
                    var deviceCollection = database.GetCollection <Device>();
                    deviceCollection.Insert(serverOne);
                }

                _mediaServerRepository.RemoveAllMediaServerData();

                using (var database = _context.LiteDatabase)
                {
                    var pluginCollection = database.GetCollection <PluginInfo>();
                    var plugins          = pluginCollection.FindAll();
                    plugins.Count().Should().Be(0);

                    var serverInfoCollection = database.GetCollection <ServerInfo>();
                    var serverInfo           = serverInfoCollection.FindAll();
                    serverInfo.Count().Should().Be(0);

                    var userCollection = database.GetCollection <EmbyUser>();
                    var users          = userCollection.FindAll();
                    users.Count().Should().Be(0);

                    var deviceCollection = database.GetCollection <Device>();
                    var device           = deviceCollection.FindAll();
                    device.Count().Should().Be(0);
                }
            });
        }
Exemple #6
0
        public void MarkUsersAsDeleted_Should_Mark_Users_As_Deleted()
        {
            RunTest(() =>
            {
                var embyUserOne = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "reggi"
                };
                var embyUserTwo = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "tom"
                };
                var embyUserThee = new EmbyUser {
                    Id = Guid.NewGuid().ToString(), Name = "yol"
                };
                using (var database = _context.LiteDatabase)
                {
                    var collection = database.GetCollection <EmbyUser>();
                    collection.InsertBulk(new[] { embyUserOne, embyUserTwo, embyUserThee });
                }

                _mediaServerRepository.MarkUsersAsDeleted(new[] { embyUserOne, embyUserTwo });

                using (var database = _context.LiteDatabase)
                {
                    var collection = database.GetCollection <EmbyUser>();
                    var users      = collection.FindAll().OrderBy(x => x.Name).ToList();

                    users.Should().NotContainNulls();
                    users.Count.Should().Be(3);

                    users[0].Id.Should().Be(embyUserOne.Id);
                    users[0].Name.Should().Be(embyUserOne.Name);
                    users[0].Deleted.Should().BeTrue();

                    users[1].Id.Should().Be(embyUserTwo.Id);
                    users[1].Name.Should().Be(embyUserTwo.Name);
                    users[1].Deleted.Should().BeTrue();

                    users[2].Id.Should().Be(embyUserThee.Id);
                    users[2].Name.Should().Be(embyUserThee.Name);
                    users[2].Deleted.Should().BeFalse();
                }
            });
        }
 public static List <EmbyUser> ConvertToUserList(this JArray model)
 {
     return(model.Children().Select(user =>
     {
         var embyUser = new EmbyUser();
         embyUser.DisablePremiumFeatures = user["Policy"]["DisablePremiumFeatures"]?.Value <bool>() ?? false;
         embyUser.EnableLocalPassword = user["Configuration"]["EnableLocalPassword"].Value <bool>();
         embyUser.HasConfiguredEasyPassword = user["HasConfiguredEasyPassword"].Value <bool>();
         embyUser.HasConfiguredPassword = user["HasConfiguredPassword"].Value <bool>();
         embyUser.HasPassword = user["HasPassword"].Value <bool>();
         embyUser.IsAdministrator = user["Policy"]["IsAdministrator"].Value <bool>();
         embyUser.IsDisabled = user["Policy"]["IsDisabled"].Value <bool>();
         embyUser.IsHidden = user["Policy"]["IsHidden"].Value <bool>();
         embyUser.PlayDefaultAudioTrack = user["Configuration"]["PlayDefaultAudioTrack"].Value <bool>();
         embyUser.InvalidLoginAttemptCount = user["Policy"]["InvalidLoginAttemptCount"].Value <long>();
         embyUser.MaxParentalRating = user["Policy"]["MaxParentalRating"]?.Value <long?>() ?? null;
         embyUser.RemoteClientBitRateLimit = user["Policy"]["RemoteClientBitrateLimit"].Value <long>();
         embyUser.Id = user["Id"].Value <string>();
         embyUser.PrimaryImageTag = user["PrimaryImageTag"]?.Value <string>() ?? string.Empty;
         embyUser.Name = user["Name"].Value <string>();
         embyUser.ServerId = user["ServerId"].Value <string>();
         embyUser.SubtitleMode = user["Configuration"]["SubtitleMode"].Value <string>();
         embyUser.LastActivityDate = user["LastActivityDate"] != null
             ? new DateTimeOffset(user["LastActivityDate"].Value <DateTime>())
             : (DateTimeOffset?)null;
         embyUser.LastLoginDate = user["LastLoginDate"] != null
             ? new DateTimeOffset(user["LastLoginDate"].Value <DateTime>())
             : (DateTimeOffset?)null;
         embyUser.BlockUnratedItems = user["Policy"]["BlockUnratedItems"]?.Values <string>().ToList() ??
                                      new List <string>();
         embyUser.BlockedTags =
             user["Policy"]["BlockedTags"]?.Values <string>().ToList() ?? new List <string>();
         embyUser.AccessSchedules = user["Policy"]["AccessSchedules"]?.Select(x => new UserAccessSchedule
         {
             DayOfWeek = x["DayOfWeek"].Value <string>(),
             StartHour = x["StartHour"].Value <long>(),
             EndHour = x["EndHour"].Value <long>()
         }).ToList() ?? new List <UserAccessSchedule>();
         embyUser.Deleted = false;
         return embyUser;
     }).ToList());
 }
Exemple #8
0
        private async Task <Response> PasswordLogin()
        {
            var password = Request.Form.password.Value;

            if (string.IsNullOrEmpty(password))
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }

            var dateTimeOffset = Request.Form.DateTimeOffset;
            var loginGuid      = Guid.Empty;
            var settings       = await AuthService.GetSettingsAsync();

            var username      = Session[SessionKeys.UserLoginName].ToString();
            var authenticated = false;
            var isOwner       = false;
            var userId        = string.Empty;

            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            // attempt local login first as it has the least amount of overhead
            userId = CustomUserMapper.ValidateUser(username, password)?.ToString();
            if (userId != null)
            {
                authenticated = true;
            }
            else if (userId == null && plexSettings.Enable)
            {
                if (settings.UserAuthentication) // Authenticate with Plex
                {
                    Log.Debug("Need to auth and also provide pass");
                    var signedIn = (PlexAuthentication)PlexApi.SignIn(username, password);
                    if (signedIn.user?.authentication_token != null)
                    {
                        Log.Debug("Correct credentials, checking if the user is account owner or in the friends list");
                        if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, signedIn.user?.username))
                        {
                            Log.Debug("User is the account owner");
                            authenticated = true;
                            isOwner       = true;
                        }
                        else
                        {
                            authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
                            Log.Debug("Friends list result = {0}", authenticated);
                        }
                        userId = signedIn.user.uuid;
                    }
                }
            }
            else if (userId == null && embySettings.Enable)
            {
                if (settings.UserAuthentication) // Authenticate with Emby
                {
                    Log.Debug("Need to auth and also provide pass");
                    EmbyUser signedIn = null;
                    try
                    {
                        signedIn = (EmbyUser)EmbyApi.LogIn(username, password, embySettings.ApiKey, embySettings.FullUri);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                    if (signedIn != null)
                    {
                        Log.Debug("Correct credentials, checking if the user is account owner or in the friends list");
                        if (signedIn?.Policy?.IsAdministrator ?? false)
                        {
                            Log.Debug("User is the account owner");
                            authenticated = true;
                            isOwner       = true;
                        }
                        else
                        {
                            authenticated = CheckIfEmbyUser(username, embySettings);
                            Log.Debug("Friends list result = {0}", authenticated);
                        }
                        userId = signedIn?.Id;
                    }
                }
            }

            if (!authenticated)
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }

            var m = await AuthenticationSetup(userId, username, dateTimeOffset, loginGuid, isOwner, plexSettings.Enable, embySettings.Enable);

            var landingSettings = await LandingPageSettings.GetSettingsAsync();

            if (landingSettings.Enabled)
            {
                if (!landingSettings.BeforeLogin) // After Login
                {
                    var uri = Linker.BuildRelativeUri(Context, "LandingPageIndex");
                    if (m.LoginGuid != Guid.Empty)
                    {
                        return(CustomModuleExtensions.LoginAndRedirect(this, m.LoginGuid, null, uri.ToString()));
                    }
                    return(Response.AsRedirect(uri.ToString()));
                }
            }

            var retVal = Linker.BuildRelativeUri(Context, "SearchIndex");

            if (m.LoginGuid != Guid.Empty)
            {
                return(CustomModuleExtensions.LoginAndRedirect(this, m.LoginGuid, null, retVal.ToString()));
            }
            return(Response.AsJson(new { result = true, url = retVal.ToString() }));
        }
Exemple #9
0
        private async Task <Response> UsernameLogin()
        {
            var username       = Request.Form.username.Value;
            var dateTimeOffset = Request.Form.DateTimeOffset;
            var loginGuid      = Guid.Empty;
            var settings       = await AuthService.GetSettingsAsync();

            if (string.IsNullOrWhiteSpace(username) || IsUserInDeniedList(username, settings))
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            var      authenticated = false;
            var      isOwner       = false;
            var      userId        = string.Empty;
            EmbyUser embyUser      = null;

            if (plexSettings.Enable)
            {
                if (settings.UserAuthentication) // Check against the users in Plex
                {
                    try
                    {
                        Log.Debug("Need to auth");
                        authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
                        if (authenticated)
                        {
                            userId = GetUserIdIsInPlexFriends(username, plexSettings.PlexAuthToken);
                        }
                        if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, username))
                        {
                            Log.Debug("User is the account owner");
                            authenticated = true;
                            isOwner       = true;
                            userId        = GetOwnerId(plexSettings.PlexAuthToken, username);
                        }
                        Log.Debug("Friends list result = {0}", authenticated);
                    }
                    catch (Exception)
                    {
                        return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
                    }
                }
                else if (!settings.UserAuthentication) // No auth, let them pass!
                {
                    authenticated = true;
                }
            }
            if (embySettings.Enable)
            {
                if (settings.UserAuthentication) // Check against the users in Plex
                {
                    Log.Debug("Need to auth");
                    authenticated = CheckIfEmbyUser(username, embySettings);
                    if (authenticated)
                    {
                        embyUser = GetEmbyUser(username, embySettings);
                        userId   = embyUser?.Id;
                    }
                    if (embyUser?.Policy?.IsAdministrator ?? false)
                    {
                        Log.Debug("User is the account owner");
                        authenticated = true;
                        isOwner       = true;
                    }
                    Log.Debug("Friends list result = {0}", authenticated);
                }
                else if (!settings.UserAuthentication) // No auth, let them pass!
                {
                    authenticated = true;
                }
            }

            UsersModel dbUser = await IsDbuser(username);

            if (dbUser != null) // in the db?
            {
                var perms = (Permissions)dbUser.Permissions;
                authenticated = true;
                isOwner       = perms.HasFlag(Permissions.Administrator);
                userId        = dbUser.UserGuid;
            }

            if (settings.UsePassword || isOwner || Security.HasPermissions(username, Permissions.Administrator))
            {
                Session[SessionKeys.UserLoginName] = username;

                var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Views", "UserLogin");
                var file = System.IO.Directory.GetFiles(path).FirstOrDefault(x => x.Contains("Password.cshtml"));
                var html = File.ReadAllText(file);

                return(Response.AsJson(new { result = true, usePassword = true, html }));
            }

            if (!authenticated)
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }
            var result = await AuthenticationSetup(userId, username, dateTimeOffset, loginGuid, isOwner, plexSettings.Enable, embySettings.Enable);


            var landingSettings = await LandingPageSettings.GetSettingsAsync();

            if (landingSettings.Enabled)
            {
                if (!landingSettings.BeforeLogin) // After Login
                {
                    var uri = Linker.BuildRelativeUri(Context, "LandingPageIndex");
                    if (loginGuid != Guid.Empty)
                    {
                        return(CustomModuleExtensions.LoginAndRedirect(this, result.LoginGuid, null, uri.ToString()));
                    }
                    return(Response.AsRedirect(uri.ToString()));
                }
            }


            var retVal = Linker.BuildRelativeUri(Context, "SearchIndex");

            if (result.LoginGuid != Guid.Empty)
            {
                return(CustomModuleExtensions.LoginAndRedirect(this, result.LoginGuid, null, retVal.ToString()));
            }
            return(Response.AsJson(new { result = true, url = retVal.ToString() }));
        }