using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
namespace HRM.BO
{
public class FileAccessWithImpersonation : IDisposable
{
#region OLD
//#region Declaration
//string userName = string.Empty;// "chapal" ;
//string domain = string.Empty;// "CEL";
//string password = string.Empty;// "cpl!@#45";
// //string target = string.Empty;// @"\\CEL02\d$\Images\";
/////
///// This is 9 if There is No Domain Defined and 2 otherwise
/////
//public const int LOGON32_LOGON_INTERACTIVE = 9; //2;
/////
///// This is 3 if There is No Domain Defined and 0 otherwise
/////
//public const int LOGON32_PROVIDER_DEFAULT = 3;//0;
//WindowsImpersonationContext impersonationContext;
//#endregion
//#region Functions
//[DllImport("advapi32.dll")]
//public static extern int LogonUserA(String lpszUserName,
// String lpszDomain,
// String lpszPassword,
// int dwLogonType,
// int dwLogonProvider,
// ref IntPtr phToken);
//[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
//public static extern int DuplicateToken(IntPtr hToken,
// int impersonationLevel,
// ref IntPtr hNewToken);
//[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
//public static extern bool RevertToSelf();
//[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
//public static extern bool CloseHandle(IntPtr handle);
//private bool impersonateValidUser()
//{
// WindowsIdentity tempWindowsIdentity;
// IntPtr token = IntPtr.Zero;
// IntPtr tokenDuplicate = IntPtr.Zero;
// domain = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("ADDomain");
// userName = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("ADUser");
// password = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("ADPassword");
// password = Ease.CoreV35.Utility.Global.CipherFunctions.Decrypt("Cel.Admin", password);
// if (RevertToSelf())
// {
// if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
// LOGON32_PROVIDER_DEFAULT, ref token) != 0)
// {
// if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
// {
// tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
// impersonationContext = tempWindowsIdentity.Impersonate();
// if (impersonationContext != null)
// {
// CloseHandle(token);
// CloseHandle(tokenDuplicate);
// return true;
// }
// }
// }
// }
// if (token != IntPtr.Zero)
// CloseHandle(token);
// if (tokenDuplicate != IntPtr.Zero)
// CloseHandle(tokenDuplicate);
// return false;
//}
//private void undoImpersonation()
//{
// if (impersonationContext != null)
// impersonationContext.Undo();
//}
//public void UploadFile(string TargetFolder, string FullFilePath, string NewFileName)
//{
// //System.IO.FileStream fs = null;
// //fs = System.IO.File.Open(FullFilePath , System.IO.FileMode.Open);
// //byte[] bytes = new byte[fs.Length];
// //fs.Read(bytes , 0 , Convert.ToInt32(fs.Length));
// byte[] bytes = File.ReadAllBytes(FullFilePath);
// try
// {
// if (impersonateValidUser())
// {
// //string[] Files = Directory.GetFiles(TargetFolder);
// string fullTargetPath = TargetFolder + "\\" + NewFileName;
// File.WriteAllBytes(fullTargetPath, bytes);
// }
// }
// finally
// {
// undoImpersonation();
// }
//}
//public byte[] GetFileInBytes(string SourceFolder, string FileName)
//{
// byte[] bytes = null;
// try
// {
// if (impersonateValidUser())
// {
// string fullSourcePath = SourceFolder + "\\" + FileName;
// if (File.Exists(fullSourcePath))
// {
// bytes = File.ReadAllBytes(fullSourcePath);
// }
// }
// }
// finally
// {
// undoImpersonation();
// }
// return bytes;
//}
//#endregion
#endregion
//[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
//private static extern bool LogonUser(
//string lpszUsername,
//string lpszDomain,
//string lpszPassword,
//int dwLogonType,
//int dwLogonProvider,
//out SafeAccessTokenHandle phToken);
//private SafeAccessTokenHandle _safeAccessTokenHandle;
//public void ImpersonateUser(string domain, string username, string password)
//{
// const int LOGON32_LOGON_INTERACTIVE = 9;//2;
// const int LOGON32_PROVIDER_DEFAULT = 3;// 0;
// // Call LogonUser to get a token for the user
// bool success = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _safeAccessTokenHandle);
// if (!success)
// {
// throw new Win32Exception(Marshal.GetLastWin32Error());
// }
//}
//public void RunAsImpersonated(Action action)
//{
// if (_safeAccessTokenHandle == null)
// throw new InvalidOperationException("User must be impersonated before running this.");
// WindowsIdentity.RunImpersonated(_safeAccessTokenHandle, action);
//}
//public void Dispose()
//{
// _safeAccessTokenHandle?.Dispose();
//}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);
SafeAccessTokenHandle _safeAccessTokenHandle;
public void ImpersonateUser(string domain, string username, string password)
{
const int LOGON32_PROVIDER_DEFAULT = 0; //3;//0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;//9;//2;
// Call LogonUser to get a token for the user
bool success = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _safeAccessTokenHandle);
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
public void RunAsImpersonated(Action action)
{
if (_safeAccessTokenHandle == null)
throw new InvalidOperationException("User must be impersonated before running this.");
WindowsIdentity.RunImpersonated(_safeAccessTokenHandle, action);
}
public void Dispose()
{
_safeAccessTokenHandle?.Dispose();
}
}
}