private Response RequestAuthToken()
        {
            var user = this.Bind <PlexAuth>();

            if (string.IsNullOrEmpty(user.username) || string.IsNullOrEmpty(user.password))
            {
                return(Response.AsJson(new { Result = false, Message = "Please provide a valid username and password" }));
            }

            var model = PlexApi.SignIn(user.username, user.password);

            if (model?.user == null)
            {
                return(Response.AsJson(new { Result = false, Message = "Incorrect username or password!" }));
            }

            var oldSettings = AuthService.GetSettings();

            if (oldSettings != null)
            {
                oldSettings.PlexAuthToken = model.user.authentication_token;
                AuthService.SaveSettings(oldSettings);
            }
            else
            {
                var newModel = new AuthenticationSettings
                {
                    PlexAuthToken = model.user.authentication_token
                };
                AuthService.SaveSettings(newModel);
            }

            return(Response.AsJson(new { Result = true, AuthToken = model.user.authentication_token }));
        }
        private Response PlexAuth()
        {
            var user = this.Bind <PlexAuth>();

            if (string.IsNullOrEmpty(user.username) || string.IsNullOrEmpty(user.password))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Please provide a valid username and password"
                }));
            }

            var model = PlexApi.SignIn(user.username, user.password);

            if (model?.user == null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Incorrect username or password!"
                }));
            }

            // Set the auth token in the session so we can use it in the next form
            Session[SessionKeys.UserWizardPlexAuth] = model.user.authentication_token;

            var servers     = PlexApi.GetServer(model.user.authentication_token);
            var firstServer = servers.Server.FirstOrDefault();

            return(Response.AsJson(new { Result = true, firstServer?.Port, Ip = firstServer?.LocalAddresses, firstServer?.Scheme }));
        }
Beispiel #3
0
        public async Task <PlexAuthentication> SignIn([FromBody] UserRequest request)
        {
            try
            {
                // Do we already have settings?
                _log.LogDebug("OK, signing into Plex");
                var settings = await PlexSettings.GetSettingsAsync();

                if (!settings.Servers?.Any() ?? false)
                {
                    return(null);
                }

                _log.LogDebug("This is our first time, good to go!");

                var result = await PlexApi.SignIn(request);

                _log.LogDebug("Attempting to sign in to Plex.Tv");
                if (!string.IsNullOrEmpty(result.user?.authentication_token))
                {
                    _log.LogDebug("Sign in successful");
                    _log.LogDebug("Getting servers");
                    var server = await PlexApi.GetServer(result.user.authentication_token);

                    var servers = server.Server.FirstOrDefault();
                    if (servers == null)
                    {
                        _log.LogWarning("Looks like we can't find any Plex Servers");
                    }
                    _log.LogDebug("Adding first server");

                    settings.Enable  = true;
                    settings.Servers = new List <PlexServers> {
                        new PlexServers
                        {
                            PlexAuthToken     = result.user.authentication_token,
                            Id                = new Random().Next(),
                            Ip                = servers?.LocalAddresses?.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)?.FirstOrDefault() ?? string.Empty,
                            MachineIdentifier = servers?.MachineIdentifier ?? string.Empty,
                            Port              = int.Parse(servers?.Port ?? "0"),
                            Ssl               = (servers?.Scheme ?? "http") != "http",
                            Name              = "Server 1",
                        }
                    };

                    await PlexSettings.SaveSettingsAsync(settings);
                }

                _log.LogDebug("Finished");
                return(result);
            }
            catch (Exception e)
            {
                _log.LogCritical(e, "Error when trying to sign into Plex.tv");
                throw;
            }
        }
Beispiel #4
0
        public async Task <PlexServersViewModel> GetServers([FromBody] UserRequest u)
        {
            try
            {
                var signIn = await PlexApi.SignIn(u);

                var servers = await PlexApi.GetServer(signIn?.user?.authentication_token);

                return(new PlexServersViewModel {
                    Servers = servers, Success = true
                });
            }
            catch (Exception e)
            {
                return(new PlexServersViewModel
                {
                    Success = false,
                    Message = e.Message
                });
            }
        }
Beispiel #5
0
        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()));
        }
Beispiel #6
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() }));
        }