using DefenseWeb.Helper; using DefenseWeb.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace DefenseWeb.Controllers { [Authorize] public class AccountController : CustomControllerBase { List adUrl = new List() { new adUrl() { name = "台北", url = "192.168.6.128" }, }; // // GET: /Account/Login [OutputCache(Duration = 60)] [AllowAnonymous] public ActionResult Login(string returnUrl) { SelectList selectList = new SelectList(adUrl, "url", "name"); ViewBag.adUrl = selectList; if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Home"); } ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [Obsolete] public ActionResult Login(LoginViewModel model, string returnUrl) { SelectList selectList = new SelectList(adUrl, "url", "name"); string sMsg = null; int iDiffDay = 0; ViewBag.adUrl = selectList; if (!ModelState.IsValid) { return View(model); } #if DEBUG var result = IsValidationForAD(model.Domain, model.Username, model.Password, out sMsg, out iDiffDay); #else var result = IsValidationForAD(model.Domain, model.Username, model.Password ,out sMsg, out iDiffDay); #endif if (sMsg != null) { ModelState.AddModelError("", sMsg); return View(model); } if (result) { string url = new ConfigHelper().GetWebConfig("UserInfoUrl"); var data = CallRemote(url, true); var obj = JObject.Parse(data); if (obj.GetValue("Success").ToObject() == true && obj["UserData"].Type == JTokenType.Null) { ModelState.AddModelError("", "找不到該員工資料/Cannot find this employee profile"); return View(model); } else if (obj.GetValue("Success").ToObject() == false) { ModelState.AddModelError("", "伺服器發生問題,無法登入/Server problem, unable to log in"); return View(model); } //檢查是否已填寫問卷 url = new ConfigHelper().GetWebConfig("DepartureUrl"); var departure_obj = JObject.Parse(CallRemote(url, true)); if (departure_obj.GetValue("desc") != null && !string.IsNullOrEmpty(departure_obj.GetValue("desc").ToString())) { ModelState.AddModelError("", "伺服器發生問題,無法登入/Server problem, unable to log in"); return View(model); } if (!departure_obj.GetValue("Success").ToObject()) { ModelState.AddModelError("", "已離職人員/Terminated staff"); return View(model); } //檢查是否已填寫問卷 url = new ConfigHelper().GetWebConfig("ExistSurveyUrl"); var survey_data = CallRemote(url, true); var survey_obj = JObject.Parse(survey_data); if (survey_obj.GetValue("desc") != null && !string.IsNullOrEmpty(survey_obj.GetValue("desc").ToString())) { ModelState.AddModelError("", "伺服器發生問題,無法登入/Server problem, unable to log in"); return View(model); } if (!survey_obj.GetValue("Success").ToObject()) { ModelState.AddModelError("", "今天已經填過問卷/Have completed the questionnaire today"); return View(model); } obj["UserData"]["password"] = model.Password; obj["UserData"]["domain"] = model.Domain; obj["UserData"]["DiffDay"] = iDiffDay; FormsAuthentication.SetAuthCookie(model.Username, true, FormsAuthentication.FormsCookiePath); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket ( 1, model.Username, DateTime.Now, DateTime.Now.AddMinutes(15), false, obj["UserData"].ToString(), FormsAuthentication.FormsCookiePath); //將 Ticket 加密 var encTicket = FormsAuthentication.Encrypt(authTicket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("", "登入嘗試失試。"); return View(model); } } public static class ADUserProperties { public const String OBJECTCLASS = "objectClass"; public const String CONTAINERNAME = "cn"; public const String LASTNAME = "sn"; public const String COUNTRYNOTATION = "c"; public const String CITY = "l"; public const String STATE = "st"; public const String TITLE = "title"; public const String POSTALCODE = "postalCode"; public const String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; public const String FIRSTNAME = "givenName"; public const String MIDDLENAME = "initials"; public const String DISTINGUISHEDNAME = "distinguishedName"; public const String INSTANCETYPE = "instanceType"; public const String WHENCREATED = "whenCreated"; public const String WHENCHANGED = "whenChanged"; public const String DISPLAYNAME = "displayName"; public const String USNCREATED = "uSNCreated"; public const String MEMBEROF = "memberOf"; public const String USNCHANGED = "uSNChanged"; public const String COUNTRY = "co"; public const String DEPARTMENT = "department"; public const String COMPANY = "company"; public const String PROXYADDRESSES = "proxyAddresses"; public const String STREETADDRESS = "streetAddress"; public const String DIRECTREPORTS = "directReports"; public const String NAME = "name"; public const String OBJECTGUID = "objectGUID"; public const String USERACCOUNTCONTROL = "userAccountControl"; public const String BADPWDCOUNT = "badPwdCount"; public const String CODEPAGE = "codePage"; public const String COUNTRYCODE = "countryCode"; public const String BADPASSWORDTIME = "badPasswordTime"; public const String LASTLOGOFF = "lastLogoff"; public const String LASTLOGON = "lastLogon"; public const String PWDLASTSET = "pwdLastSet"; public const String PRIMARYGROUPID = "primaryGroupID"; public const String OBJECTSID = "objectSid"; public const String ADMINCOUNT = "adminCount"; public const String ACCOUNTEXPIRES = "accountExpires"; public const String LOGONCOUNT = "logonCount"; public const String LOGINNAME = "sAMAccountName"; public const String SAMACCOUNTTYPE = "sAMAccountType"; public const String SHOWINADDRESSBOOK = "showInAddressBook"; public const String LEGACYEXCHANGEDN = "legacyExchangeDN"; public const String USERPRINCIPALNAME = "userPrincipalName"; public const String EXTENSION = "ipPhone"; public const String SERVICEPRINCIPALNAME = "servicePrincipalName"; public const String OBJECTCATEGORY = "objectCategory"; public const String DSCOREPROPAGATIONDATA = "dSCorePropagationData"; public const String LASTLOGONTIMESTAMP = "lastLogonTimestamp"; public const String EMAILADDRESS = "mail"; public const String MANAGER = "manager"; public const String MOBILE = "mobile"; public const String PAGER = "pager"; public const String FAX = "facsimileTelephoneNumber"; public const String HOMEPHONE = "homePhone"; public const String MSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl"; public const String MDBUSEDEFAULTS = "mDBUseDefaults"; public const String MSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor"; public const String HOMEMDB = "homeMDB"; public const String MSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded"; public const String HOMEMTA = "homeMTA"; public const String MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails"; public const String MAILNICKNAME = "mailNickname"; public const String MSEXCHHOMESERVERNAME = "msExchHomeServerName"; public const String MSEXCHVERSION = "msExchVersion"; public const String MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType"; public const String MSEXCHMAILBOXGUID = "msExchMailboxGuid"; public const String NTSECURITYDESCRIPTOR = "nTSecurityDescriptor"; } private bool IsValidationForAD(string url, string Username, string Password, out string o_sMsg, out int i_diffDay) { o_sMsg = null; bool isSuccess = false; i_diffDay = 0; try { string srvr = url; srvr = "LDAP://" + srvr; PrincipalContext ctx = new PrincipalContext(ContextType.Domain, url, Username, Password); var user = UserPrincipal.FindByIdentity(ctx, Username); if (user != null) { DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject(); List lsPropName = (from x in typeof(ADUserProperties).GetFields() select x.GetValue(typeof(string)).ToString()).ToList(); Dictionary dicADInfo = new Dictionary(); foreach (string sPropName in lsPropName) { if (entry.Properties.Contains(sPropName)) { dicADInfo.Add(sPropName, entry.Properties[sPropName].Value); } } var expiresDate = (DateTime)entry.InvokeGet("PasswordExpirationDate"); i_diffDay = new TimeSpan(expiresDate.Ticks - DateTime.Now.Ticks).Days; isSuccess = true;//verify password is succeed! } } catch (DirectoryServicesCOMException ex) { if (ex.ExtendedErrorMessage.IndexOf("data 532,") > -1) { o_sMsg = @"您的AD 密碼已過期,請使用公司電腦設備到 eip.chipmos.com 網站更新密碼。eip.chipmos.com Your AD password has expired. Please go to eip.chipmos.com web site to change your password by using CHIPMOS computer equipment."; } else { o_sMsg = ex.Message; } Logger.Error(string.Format("sMsg={0},para={1} ex.StackTrace={2}, innerException={3} ", ex.Message, JsonConvert.SerializeObject(new { url = url, Username = Username, Password = Password, msg = ex.ExtendedErrorMessage }), ex.StackTrace, ex.InnerException)); } return isSuccess; } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } public ActionResult GetUserData() { //todo return Content(CallRemote("")); } public ActionResult WriteUserData() { //todo // CallRemote(""); return Content(CallRemote("")); } } }