Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Prompt for credentials when connecting smb #11144

Merged
merged 3 commits into from
Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion src/Files.App/Filesystem/NetworkDrivesAPI.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using Files.App.Shell;
using Files.App.Extensions;
using Files.App.Helpers;
using Files.App.Shell;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vanara.Extensions;
using Vanara.InteropServices;
using static Vanara.PInvoke.AdvApi32;
yaira2 marked this conversation as resolved.
Show resolved Hide resolved
using Vanara.PInvoke;
using static Vanara.PInvoke.Mpr;

namespace Files.App.Filesystem
Expand Down Expand Up @@ -117,6 +122,52 @@ public static Task<bool> OpenMapNetworkDriveDialog(long hwnd)
});
}

public static async Task<bool> AuthenticateNetworkShare(string path)
{
NETRESOURCE nr = new NETRESOURCE
{
dwType = NETRESOURCEType.RESOURCETYPE_DISK,
lpRemoteName = path
};

Win32Error connectionError = WNetAddConnection3(HWND.NULL, nr, null, null, 0); // if creds are saved, this will return NO_ERROR

if (connectionError == Win32Error.ERROR_LOGON_FAILURE)
{
var dialog = DynamicDialogFactory.GetFor_CredentialEntryDialog(path);
await dialog.ShowAsync();
var credentialsReturned = dialog.ViewModel.AdditionalData as string[];

if (credentialsReturned is string[] && credentialsReturned[1] != null)
{
connectionError = WNetAddConnection3(HWND.NULL, nr, credentialsReturned[1], credentialsReturned[0], 0);
if (credentialsReturned[2] == "y" && connectionError == Win32Error.NO_ERROR)
{
CREDENTIAL creds = new CREDENTIAL();
creds.TargetName = new StrPtrAuto(path.Substring(2));
creds.UserName = new StrPtrAuto(credentialsReturned[0]);
creds.Type = CRED_TYPE.CRED_TYPE_DOMAIN_PASSWORD;
creds.AttributeCount = 0;
creds.Persist = CRED_PERSIST.CRED_PERSIST_ENTERPRISE;
byte[] bpassword = Encoding.Unicode.GetBytes(credentialsReturned[1]);
creds.CredentialBlobSize = (UInt32)bpassword.Length;
creds.CredentialBlob = Marshal.StringToCoTaskMemUni(credentialsReturned[1]);
CredWrite(creds, 0);
}
}
else
return false;
}

if (connectionError == Win32Error.NO_ERROR)
return true;
else
{
await DialogDisplayHelper.ShowDialogAsync("NetworkFolderErrorDialogTitle".GetLocalizedResource(), connectionError.ToString().Split(":")[1].Trim());
return false;
}
}

public static bool DisconnectNetworkDrive(string drive)
{
return WNetCancelConnection2(drive.TrimEnd('\\'), CONNECT.CONNECT_UPDATE_PROFILE, true).Succeeded;
Expand Down
80 changes: 80 additions & 0 deletions src/Files.App/Helpers/DynamicDialogFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,85 @@ public static DynamicDialog GetFor_FileInUseDialog(List<Shared.Win32Process> loc
});
return dialog;
}

public static DynamicDialog GetFor_CredentialEntryDialog(string path)
{
string[] userAndPass = new string[3];
DynamicDialog? dialog = null;

TextBox inputUsername = new()
{
Height = 35d,
yaira2 marked this conversation as resolved.
Show resolved Hide resolved
PlaceholderText = "CredentialDialogUserName/PlaceholderText".GetLocalizedResource()
};

PasswordBox inputPassword = new()
{
Height = 35d,
PlaceholderText = "CredentialDialogPassword/PlaceholderText".GetLocalizedResource()
};

CheckBox saveCreds = new()
{
Content = "NetworkAuthenticationSaveCheckbox".GetLocalizedResource()
};

inputUsername.TextChanged += (textBox, args) =>
{
userAndPass[0] = inputUsername.Text;
dialog.ViewModel.AdditionalData = userAndPass;
};

inputPassword.PasswordChanged += (textBox, args) =>
{
userAndPass[1] = inputPassword.Password;
dialog.ViewModel.AdditionalData = userAndPass;
};

saveCreds.Checked += (textBox, args) =>
{
userAndPass[2] = "y";
dialog.ViewModel.AdditionalData = userAndPass;
};

saveCreds.Unchecked += (textBox, args) =>
{
userAndPass[2] = "n";
dialog.ViewModel.AdditionalData = userAndPass;
};

dialog = new DynamicDialog(new DynamicDialogViewModel()
{
TitleText = "NetworkAuthenticationDialogTitle".GetLocalizedResource(),
PrimaryButtonText = "AskCredentialDialog/PrimaryButtonText".GetLocalizedResource(),
CloseButtonText = "Cancel".GetLocalizedResource(),
SubtitleText = string.Format("NetworkAuthenticationDialogMessage".GetLocalizedResource(), path.Substring(2)),
DisplayControl = new Grid()
{
MinWidth = 250d,
Children =
{
new StackPanel()
{
Spacing = 10d,
Children =
{
inputUsername,
inputPassword,
saveCreds
}
}
}
},
CloseButtonAction = (vm, e) =>
{
dialog.ViewModel.AdditionalData = null;
vm.HideDialog();
}

});

return dialog;
}
}
}
22 changes: 22 additions & 0 deletions src/Files.App/Helpers/NavigationHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ private static async Task<FilesystemResult> OpenDirectory(string path, IShellPag
var opened = (FilesystemResult)false;
bool isHiddenItem = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
bool isShortcut = FileExtensionHelpers.IsShortcutOrUrlFile(path);
bool isNetwork = path.StartsWith(@"\\", StringComparison.Ordinal);

if (isShortcut)
{
Expand Down Expand Up @@ -330,6 +331,27 @@ private static async Task<FilesystemResult> OpenDirectory(string path, IShellPag

opened = (FilesystemResult)true;
}
else if (isNetwork)
{
var auth = await NetworkDrivesAPI.AuthenticateNetworkShare(path);
yaira2 marked this conversation as resolved.
Show resolved Hide resolved
if (auth)
{
if (forceOpenInNewTab || userSettingsService.FoldersSettingsService.OpenFoldersInNewTab)
yaira2 marked this conversation as resolved.
Show resolved Hide resolved
{
await OpenPathInNewTab(path);
}
else
{
associatedInstance.ToolbarViewModel.PathControlDisplayText = path;
associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
{
NavPathParam = path,
AssociatedTabInstance = associatedInstance
});
}
opened = (FilesystemResult)true;
}
}
else
{
opened = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(path)
Expand Down
12 changes: 12 additions & 0 deletions src/Files.App/Strings/en-US/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -2900,5 +2900,17 @@
</data>
<data name="DisplayEditTagsMenu" xml:space="preserve">
<value>Display the edit tags flyout</value>
</data>
<data name="NetworkAuthenticationDialogMessage" xml:space="preserve">
<value>Enter your credentials to connect to: {0}</value>
</data>
<data name="NetworkAuthenticationDialogTitle" xml:space="preserve">
<value>Enter Network Credentials</value>
</data>
<data name="NetworkAuthenticationSaveCheckbox" xml:space="preserve">
<value>Remember my credentials</value>
</data>
<data name="NetworkFolderErrorDialogTitle" xml:space="preserve">
<value>Network folder error</value>
</data>
</root>
7 changes: 7 additions & 0 deletions src/Files.App/ViewModels/ToolbarViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,13 @@ public async Task CheckPathInput(string currentInput, string currentSelectedPath
if (currentInput.StartsWith('\\') && !currentInput.StartsWith("\\\\", StringComparison.Ordinal))
currentInput = currentInput.Insert(0, "\\");

if (currentInput.StartsWith('\\'))
{
var auth = await NetworkDrivesAPI.AuthenticateNetworkShare(currentInput);
if (!auth)
return;
}

if (currentSelectedPath == currentInput || string.IsNullOrWhiteSpace(currentInput))
return;

Expand Down