public void Start() { JobRecord.SetRunning(true, JobNames.EmbyUserChecker); try { var settings = EmbySettings.GetSettings(); if (string.IsNullOrEmpty(settings.ApiKey) || !settings.Enable) { return; } var embyUsers = EmbyApi.GetUsers(settings.FullUri, settings.ApiKey); var userManagementSettings = UserManagementSettings.GetSettings(); var dbUsers = Repo.GetAll().ToList(); // Regular users foreach (var user in embyUsers) { var dbUser = dbUsers.FirstOrDefault(x => x.EmbyUserId == user.Id); if (dbUser != null) { // we already have a user continue; } // Looks like it's a new user! var m = new EmbyUsers { EmbyUserId = user.Id, Permissions = UserManagementHelper.GetPermissions(userManagementSettings), Features = UserManagementHelper.GetFeatures(userManagementSettings), UserAlias = string.Empty, Username = user.Name, LoginId = Guid.NewGuid().ToString() }; // If it's the admin, give them the admin permission if (user.Policy.IsAdministrator) { if (!((Permissions)m.Permissions).HasFlag(Permissions.Administrator)) { m.Permissions += (int)Permissions.Administrator; } } Repo.Insert(m); } } catch (Exception e) { Log.Error(e); } finally { JobRecord.SetRunning(false, JobNames.EmbyUserChecker); JobRecord.Record(JobNames.EmbyUserChecker); } }
public static int GetFeatures(UserManagementSettings settings) { var features = 0; if (settings.RecentlyAddedNewsletter) { features += (int)Features.Newsletter; } if (settings.RecentlyAddedNotification) { features += (int)Features.RequestAddedNotification; } return(features); }
public static int GetPermissions(UserManagementSettings settings) { var permission = 0; if (settings.AutoApproveMovies) { permission += (int)Permissions.AutoApproveMovie; } if (settings.AutoApproveMusic) { permission += (int)Permissions.AutoApproveAlbum; } if (settings.AutoApproveTvShows) { permission += (int)Permissions.AutoApproveTv; } if (settings.RequestMovies) { permission += (int)Permissions.RequestMovie; } if (settings.RequestMusic) { permission += (int)Permissions.RequestMusic; } if (settings.RequestTvShows) { permission += (int)Permissions.RequestTvShow; } if (settings.ReportIssues) { permission += (int)Permissions.ReportIssue; } if (settings.UsersCanViewOnlyOwnRequests) { permission += (int)Permissions.UsersCanViewOnlyOwnRequests; } if (settings.UsersCanViewOnlyOwnIssues) { permission += (int)Permissions.UsersCanViewOnlyOwnIssues; } if (settings.BypassRequestLimit) { permission += (int)Permissions.BypassRequestLimit; } return(permission); }
public async Task GetUserManagementSettings_InstanceAdmin_ReturnsUserManagementSettings() { // Arrange const int userId = 1; var user = new LoginUser { InstanceAdminRoleId = 1 }; var settings = new UserManagementSettings { IsPasswordExpirationEnabled = false, IsFederatedAuthenticationEnabled = true }; var settingsRepositoryMock = new Mock <ISqlSettingsRepository>(); settingsRepositoryMock .Setup(m => m.GetUserManagementSettingsAsync()) .ReturnsAsync(settings); var userRepositoryMock = new Mock <IUserRepository>(); userRepositoryMock .Setup(m => m.GetLoginUserByIdAsync(userId)) .ReturnsAsync(user); var controller = new ConfigController ( null, settingsRepositoryMock.Object, userRepositoryMock.Object, null, null, null) { Request = new HttpRequestMessage() }; controller.Request.Properties[ServiceConstants.SessionProperty] = new Session { UserId = userId }; // Act var result = await controller.GetUserManagementSettings() as OkNegotiatedContentResult <UserManagementSettings>; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.Content, settings); }
private async Task ImportAdmin(UserManagementSettings settings, PlexServers server, List <OmbiUser> allUsers) { if (!settings.ImportPlexAdmin) { return; } var plexAdmin = (await _api.GetAccount(server.PlexAuthToken)).user; // Check if the admin is already in the DB var adminUserFromDb = allUsers.FirstOrDefault(x => x.ProviderUserId.Equals(plexAdmin.id, StringComparison.CurrentCultureIgnoreCase)); if (adminUserFromDb != null) { // Let's update the user adminUserFromDb.Email = plexAdmin.email; adminUserFromDb.UserName = plexAdmin.username; adminUserFromDb.ProviderUserId = plexAdmin.id; await _userManager.UpdateAsync(adminUserFromDb); return; } var newUser = new OmbiUser { UserType = UserType.PlexUser, UserName = plexAdmin.username ?? plexAdmin.id, ProviderUserId = plexAdmin.id, Email = plexAdmin.email ?? string.Empty, Alias = string.Empty, StreamingCountry = settings.DefaultStreamingCountry }; var result = await _userManager.CreateAsync(newUser); if (!LogResult(result)) { return; } var roleResult = await _userManager.AddToRoleAsync(newUser, OmbiRoles.Admin); LogResult(roleResult); }
private void CreateDefaultSettingsPage(string baseUrl) { var defaultUserSettings = new UserManagementSettings { RequestMovies = true, RequestTvShows = true, ReportIssues = true, }; var defaultSettings = new PlexRequestSettings { SearchForMovies = true, SearchForTvShows = true, SearchForActors = true, BaseUrl = baseUrl ?? string.Empty, CollectAnalyticData = true, }; var ctor = new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()); var s = new SettingsServiceV2 <PlexRequestSettings>(ctor); s.SaveSettings(defaultSettings); var userSettings = new SettingsServiceV2 <UserManagementSettings>(ctor); userSettings.SaveSettings(defaultUserSettings); var cron = (Quartz.Impl.Triggers.CronTriggerImpl)CronScheduleBuilder.WeeklyOnDayAndHourAndMinute(DayOfWeek.Friday, 7, 0).Build(); var scheduled = new ScheduledJobsSettings { PlexAvailabilityChecker = 60, SickRageCacher = 60, SonarrCacher = 60, CouchPotatoCacher = 60, StoreBackup = 24, StoreCleanup = 24, UserRequestLimitResetter = 12, PlexEpisodeCacher = 12, RecentlyAddedCron = cron.CronExpressionString, // Weekly CRON at 7 am on Mondays }; var scheduledSettings = new SettingsServiceV2 <ScheduledJobsSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider())); scheduledSettings.SaveSettings(scheduled); }
public async Task GetUserManagementSettings_NonInstanceAdmin_ThrowsAuthorizationException() { // Arrange const int userId = 1; var user = new LoginUser { InstanceAdminRoleId = null }; var settings = new UserManagementSettings { IsPasswordExpirationEnabled = false, IsFederatedAuthenticationEnabled = true }; var settingsRepositoryMock = new Mock <ISqlSettingsRepository>(); settingsRepositoryMock .Setup(m => m.GetUserManagementSettingsAsync()) .ReturnsAsync(settings); var userRepositoryMock = new Mock <IUserRepository>(); userRepositoryMock .Setup(m => m.GetLoginUserByIdAsync(userId)) .ReturnsAsync(user); var controller = new ConfigController ( null, settingsRepositoryMock.Object, userRepositoryMock.Object, null, null, null) { Request = new HttpRequestMessage() }; controller.Request.Properties[ServiceConstants.SessionProperty] = new Session { UserId = userId }; // Act await controller.GetUserManagementSettings(); }
private void PopulateDefaultUserManagementSettings() { try { var plexRequestSettings = PlexRequestSettings.GetSettings(); UserManagementSettings.SaveSettings(new UserManagementSettings { AutoApproveMovies = !plexRequestSettings.RequireMovieApproval, RequestTvShows = plexRequestSettings.SearchForTvShows, RequestMusic = plexRequestSettings.SearchForMusic, RequestMovies = plexRequestSettings.SearchForMovies, AutoApproveMusic = !plexRequestSettings.RequireMusicApproval, AutoApproveTvShows = !plexRequestSettings.RequireTvShowApproval }); } catch (Exception e) { Logger.Fatal("Exception when migrating Version 1.10.0 (PopulateDefaultUserMngmentSettings)"); Logger.Fatal(e); } }
public async Task <bool> UserManagementSettings([FromBody] UserManagementSettings settings) { return(await Save(settings)); }
public void Execute(IJobExecutionContext context) { JobRecord.SetRunning(true, JobNames.PlexUserChecker); try { var settings = PlexSettings.GetSettings(); if (string.IsNullOrEmpty(settings.PlexAuthToken)) { return; } var plexUsers = PlexApi.GetUsers(settings.PlexAuthToken); var userManagementSettings = UserManagementSettings.GetSettings(); var mainPlexAccount = PlexApi.GetAccount(settings.PlexAuthToken); var requests = RequestService.GetAll().ToList(); var dbUsers = Repo.GetAll().ToList(); var localUsers = LocalUserRepository.GetAll().ToList(); // Regular users foreach (var user in plexUsers.User) { var dbUser = dbUsers.FirstOrDefault(x => x.PlexUserId == user.Id); if (dbUser != null) { // We already have the user, let's check if they have updated any of their info. var needToUpdate = false; var usernameChanged = false; if (!string.IsNullOrEmpty(user.Username)) // If true then this is a managed user, we do not want to update the email since Managed Users do not have email addresses { // Do we need up update any info? if (!dbUser.EmailAddress.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase)) { dbUser.EmailAddress = user.Email; needToUpdate = true; } } if (!dbUser.Username.Equals(user.Title, StringComparison.CurrentCultureIgnoreCase)) { needToUpdate = true; usernameChanged = true; } if (needToUpdate) { if (usernameChanged) { // The username has changed, let's check if the username matches any local users var localUser = localUsers.FirstOrDefault(x => x.UserName.Equals(user.Title, StringComparison.CurrentCultureIgnoreCase)); dbUser.Username = user.Title; if (localUser != null) { // looks like we have a local user with the same name... // We should delete the local user and the Plex user will become the master, // I am not going to update the Plex Users permissions as that could end up leading to a security vulnerability // Where anyone could change their Plex Username to the PR.Net server admins name and get all the admin permissions. LocalUserRepository.Delete(localUser); } // Since the username has changed, we need to update all requests with that username (unless we are using the alias! Since the alias won't change) if (string.IsNullOrEmpty(dbUser.UserAlias)) { // Update all requests var requestsWithThisUser = requests.Where(x => x.RequestedUsers.Contains(user.Username)).ToList(); foreach (var r in requestsWithThisUser) { r.RequestedUsers.Remove(user.Title); // Remove old r.RequestedUsers.Add(dbUser.Username); // Add new } if (requestsWithThisUser.Any()) { RequestService.BatchUpdate(requestsWithThisUser); } } } Repo.Update(dbUser); } continue; } // Looks like it's a new user! var m = new PlexUsers { PlexUserId = user.Id, Permissions = UserManagementHelper.GetPermissions(userManagementSettings), Features = UserManagementHelper.GetFeatures(userManagementSettings), UserAlias = string.Empty, EmailAddress = user.Email, Username = user.Title, LoginId = Guid.NewGuid().ToString() }; Repo.Insert(m); } // Main Plex user var dbMainAcc = dbUsers.FirstOrDefault(x => x.Username.Equals(mainPlexAccount.Username, StringComparison.CurrentCulture)); var localMainAcc = localUsers.FirstOrDefault(x => x.UserName.Equals(mainPlexAccount.Username, StringComparison.CurrentCulture)); // TODO if admin acc does exist, check if we need to update it // Create the local admin account if it doesn't already exist if (dbMainAcc == null && localMainAcc == null) { var a = new PlexUsers { PlexUserId = mainPlexAccount.Id, Permissions = UserManagementHelper.GetPermissions(userManagementSettings), Features = UserManagementHelper.GetFeatures(userManagementSettings), UserAlias = string.Empty, EmailAddress = mainPlexAccount.Email, Username = mainPlexAccount.Username, LoginId = Guid.NewGuid().ToString() }; a.Permissions += (int)Permissions.Administrator; // Make admin Repo.Insert(a); } } catch (Exception e) { Log.Error(e); } finally { JobRecord.SetRunning(false, JobNames.PlexUserChecker); JobRecord.Record(JobNames.PlexUserChecker); } }
private async Task <LoginModel> AuthenticationSetup(string userId, string username, int dateTimeOffset, Guid loginGuid, bool isOwner, bool plex, bool emby) { var m = new LoginModel(); var settings = await AuthService.GetSettingsAsync(); var localUsers = await CustomUserMapper.GetUsersAsync(); var plexLocalUsers = await PlexUserRepository.GetAllAsync(); var embyLocalUsers = await EmbyUserRepository.GetAllAsync(); var localUser = false; Log.Debug("We are authenticated! Setting session."); // Add to the session (Used in the BaseModules) Session[SessionKeys.UsernameKey] = username; Session[SessionKeys.ClientDateTimeOffsetKey] = dateTimeOffset; if (plex) { var plexLocal = plexLocalUsers.FirstOrDefault(x => x.Username == username); if (plexLocal != null) { loginGuid = Guid.Parse(plexLocal.LoginId); } } if (emby) { var embyLocal = embyLocalUsers.FirstOrDefault(x => x.Username == username); if (embyLocal != null) { loginGuid = Guid.Parse(embyLocal.LoginId); } } var dbUser = localUsers.FirstOrDefault(x => x.UserName == username); if (dbUser != null) { loginGuid = Guid.Parse(dbUser.UserGuid); localUser = true; } if (loginGuid == Guid.Empty && settings.UserAuthentication) { var defaultSettings = UserManagementSettings.GetSettings(); loginGuid = Guid.NewGuid(); var defaultPermissions = (Permissions)UserManagementHelper.GetPermissions(defaultSettings); if (isOwner) { // If we are the owner, add the admin permission. if (!defaultPermissions.HasFlag(Permissions.Administrator)) { defaultPermissions += (int)Permissions.Administrator; } } if (plex) { // Looks like we still don't have an entry, so this user does not exist await PlexUserRepository.InsertAsync(new PlexUsers { PlexUserId = userId, UserAlias = string.Empty, Permissions = (int)defaultPermissions, Features = UserManagementHelper.GetPermissions(defaultSettings), Username = username, EmailAddress = string.Empty, // We don't have it, we will get it on the next scheduled job run (in 30 mins) LoginId = loginGuid.ToString() }); } if (emby) { await EmbyUserRepository.InsertAsync(new EmbyUsers { EmbyUserId = userId, UserAlias = string.Empty, Permissions = (int)defaultPermissions, Features = UserManagementHelper.GetPermissions(defaultSettings), Username = username, EmailAddress = string.Empty, LoginId = loginGuid.ToString() }); } } m.LoginGuid = loginGuid; m.UserId = userId; var type = UserType.LocalUser; if (localUser) { type = UserType.LocalUser; } else if (plex) { type = UserType.PlexUser; } else if (emby) { type = UserType.EmbyUser;; } if (string.IsNullOrEmpty(userId)) { // It's possible we have no auth enabled meaning the userId is empty // Let's find that user! var user = UserHelper.GetUser(username); userId = user?.UserId ?? string.Empty; } UserLogins.Insert(new UserLogins { UserId = userId, Type = type, LastLoggedIn = DateTime.UtcNow }); return(m); }
private async Task <Response> LoginUser() { var userId = string.Empty; var loginGuid = Guid.Empty; var dateTimeOffset = Request.Form.DateTimeOffset; var username = Request.Form.username.Value; Log.Debug("Username \"{0}\" attempting to login", username); if (string.IsNullOrWhiteSpace(username)) { Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass; var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex"); return(Response.AsRedirect(uri.ToString())); } var authenticated = false; var isOwner = false; var settings = await AuthService.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync(); if (IsUserInDeniedList(username, settings)) { Log.Debug("User is in denied list, not allowing them to authenticate"); Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass; var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex"); return(Response.AsRedirect(uri.ToString())); } var password = string.Empty; if (settings.UsePassword) { Log.Debug("Using password"); password = Request.Form.password.Value; } var localUsers = await CustomUserMapper.GetUsersAsync(); var plexLocalUsers = await PlexUserRepository.GetAllAsync(); if (settings.UserAuthentication && settings.UsePassword) // 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 (settings.UserAuthentication) // Check against the users in Plex { 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); } else if (!settings.UserAuthentication) // No auth, let them pass! { Log.Debug("No need to auth"); authenticated = true; } if (authenticated) { UserLogins.Insert(new UserLogins { UserId = userId, Type = UserType.PlexUser, LastLoggedIn = DateTime.UtcNow }); Log.Debug("We are authenticated! Setting session."); // Add to the session (Used in the BaseModules) Session[SessionKeys.UsernameKey] = (string)username; Session[SessionKeys.ClientDateTimeOffsetKey] = (int)dateTimeOffset; var plexLocal = plexLocalUsers.FirstOrDefault(x => x.Username == username); if (plexLocal != null) { loginGuid = Guid.Parse(plexLocal.LoginId); } var dbUser = localUsers.FirstOrDefault(x => x.UserName == username); if (dbUser != null) { loginGuid = Guid.Parse(dbUser.UserGuid); } if (loginGuid != Guid.Empty) { if (!settings.UserAuthentication)// Do not need to auth make admin use login screen for now TODO remove this { if (dbUser != null) { var perms = (Permissions)dbUser.Permissions; if (perms.HasFlag(Permissions.Administrator)) { var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex"); Session["TempMessage"] = Resources.UI.UserLogin_AdminUsePassword; return(Response.AsRedirect(uri.ToString())); } } if (plexLocal != null) { var perms = (Permissions)plexLocal.Permissions; if (perms.HasFlag(Permissions.Administrator)) { var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex"); Session["TempMessage"] = Resources.UI.UserLogin_AdminUsePassword; return(Response.AsRedirect(uri.ToString())); } } } } if (loginGuid == Guid.Empty && settings.UserAuthentication) { var defaultSettings = UserManagementSettings.GetSettings(); loginGuid = Guid.NewGuid(); var defaultPermissions = (Permissions)UserManagementHelper.GetPermissions(defaultSettings); if (isOwner) { // If we are the owner, add the admin permission. if (!defaultPermissions.HasFlag(Permissions.Administrator)) { defaultPermissions += (int)Permissions.Administrator; } } // Looks like we still don't have an entry, so this user does not exist await PlexUserRepository.InsertAsync(new PlexUsers { PlexUserId = userId, UserAlias = string.Empty, Permissions = (int)defaultPermissions, Features = UserManagementHelper.GetPermissions(defaultSettings), Username = username, EmailAddress = string.Empty, // We don't have it, we will get it on the next scheduled job run (in 30 mins) LoginId = loginGuid.ToString() }); } } if (!authenticated) { var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex"); Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass; return(Response.AsRedirect(uri.ToString())); } var landingSettings = await LandingPageSettings.GetSettingsAsync(); if (landingSettings.Enabled) { if (!landingSettings.BeforeLogin) { var uri = Linker.BuildRelativeUri(Context, "LandingPageIndex"); if (loginGuid != Guid.Empty) { return(CustomModuleExtensions.LoginAndRedirect(this, loginGuid, null, uri.ToString())); } return(Response.AsRedirect(uri.ToString())); } } var retVal = Linker.BuildRelativeUri(Context, "SearchIndex"); if (loginGuid != Guid.Empty) { return(CustomModuleExtensions.LoginAndRedirect(this, loginGuid, null, retVal.ToString())); } return(Response.AsRedirect(retVal.ToString())); }