namespace GODATA.Controllers { using LoggingHelper; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Security; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using GODATA.Models; using GODATA.Models.Util; using GODATA.AuthenticationServices; using GODATA.RoleServices; using GODATA.Models.UserInventory; using RestSharp; /// /// Class used to manage user authentication and registration. /// public class AccountController : Controller { #region Global Variables /// /// Represent object of LoggingUtility class /// LoggingUtility objLog = new LoggingUtility(); /// /// Represent string object contain log file path /// string path = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PathLog"]); /// /// Represent string object contain log status /// string logtf = (ConfigurationManager.AppSettings["Log"]); /// /// Represent string object contain Error log status /// string errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]); /// /// getting application name from AppSetting in web.config file /// private static string _appName = ConfigurationManager.AppSettings["ApplicationName"].ToString(); /// /// getting email subject name from AppSetting in web.config file /// private static string _emailSubjectTitle = ConfigurationManager.AppSettings["EmailSubjectTitle"].ToString(); /// /// getting web api token from AppSetting in web.config file /// private static string _securityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString(); /// /// get url on which rest api's are hosted /// private static string _RestClientUrl = ConfigurationManager.AppSettings["RestfulApiUrl"].ToString(); #endregion public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*"); base.OnActionExecuting(filterContext); } } /// /// User /// to this action when does not have permission to access particular page. /// /// Redirection URL after authorize user. /// Action Result public ActionResult UnauthorizedAccess(string returnUrl) { return RedirectToAction("Index", new { returnUrl = returnUrl }); } /// /// GET /Acount/Index /// /// Action Result [AllowCrossSiteJson] public ActionResult Index() { return View(); } #region Actions - LogOn/LogOff /// /// GET: /Account/LogOn /// /// Action Result [AllowCrossSiteJson] public ActionResult LogOn() { return PartialView(); } /// /// POST: /Account/LogOn /// /// User LogOnModel with UserName,Password etc. /// Destination Url after successfully login. /// Action Result [AllowCrossSiteJson] [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { objLog.AddLogFile("Account_LogOn", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); if (ModelState.IsValid) { UserClient oUserClient = new UserClient(); string[] roles = null; try { //Getting user details from auth engine var userDetail = oUserClient.validateLoginDetails(model.UserName.Trim(), model.Password, _appName); var userAppId = oUserClient.GetUserById(userDetail.userId); //Get user's application id if (userDetail.userId != Guid.Empty && userDetail.Role.Count() > 0) { roles = userDetail.Role.ToArray(); Session.Add("AuthUserId", userDetail.userId); Session.Add("AuthUserAppId", userAppId.ApplicationId); HttpContext.Application.Add("UserRole", userDetail.Role.FirstOrDefault()); } if (roles != null) { //Getting user and organization details UserDetailsModel oUserDetailsModel = GetUserOrganizationDetails(model.UserName.Trim()); if (oUserDetailsModel.Status == "1") { HttpContext.Response.Cookies["portalroles"].Value = null; FormsAuthentication.SetAuthCookie(model.UserName.Trim(), model.RememberMe); string roleStr = string.Join(";", roles); HttpContext.Application.Add("roles", roles); Session.Add("UtcMinute", oUserDetailsModel.OffsetInMinute); Session.Add("DealerId", oUserDetailsModel.ObjectId); var utcMinute = new System.Web.HttpCookie("UtcMinute");//instantiate an new cookie and give it a name utcMinute.Values.Add("UtcMinute", oUserDetailsModel.OffsetInMinute.ToString());//populate it with //, value pairs Response.Cookies.Add(utcMinute);//add it to the client Session.Add("UserId", oUserDetailsModel.UserId); var userId = new System.Web.HttpCookie("UserId");//instantiate an new cookie and give it a name userId.Values.Add("UserId", oUserDetailsModel.UserId.ToString());//populate it with key, value pairs Response.Cookies.Add(userId);//add it to the client Session.Add("UserName", model.UserName.Trim()); var userName = new System.Web.HttpCookie("UserName");//instantiate an new cookie and give it a name userName.Values.Add("UserName", model.UserName.Trim().ToString());//populate it with key, value pairs Response.Cookies.Add(userName);//add it to the client Session.Add("FirstName", oUserDetailsModel.FirstName == null ? string.Empty : oUserDetailsModel.FirstName); var firstName = new System.Web.HttpCookie("FirstName");//instantiate an new cookie and give it a name firstName.Values.Add("FirstName", oUserDetailsModel.FirstName == null ? string.Empty : oUserDetailsModel.FirstName);//populate it with key, value pairs Response.Cookies.Add(firstName);//add it to the client Session.Add("AuthEngineId", oUserDetailsModel.AuthEngineId); var authEngineId = new System.Web.HttpCookie("AuthEngineId");//instantiate an new cookie and give it a name authEngineId.Values.Add("AuthEngineId", oUserDetailsModel.AuthEngineId);//populate it with key, value pairs Response.Cookies.Add(authEngineId);//add it to the client Session.Add("UserRole", oUserDetailsModel.Designation); var userRole = new System.Web.HttpCookie("UserRole");//instantiate an new cookie and give it a name userRole.Values.Add("UserRole", oUserDetailsModel.Designation);//populate it with key, value pairs //Response.Cookies.Add(userRole);//add it to the client if (!string.IsNullOrEmpty(returnUrl)) { objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); return Json(new { returnUrl = returnUrl }); } else { returnUrl = Url.RouteUrl("DefaultLoginUrl"); //returnUrl = Url.Action("Index", "Home", new { currtime = DateTime.Now.Ticks }); return Json(new { returnUrl = returnUrl + "?currtime=" + DateTime.Now.Ticks }); } } else { //ModelState.AddModelError(string.Empty, "You are not mapped with any organization. Please contact to your administrator."); ModelState.AddModelError(string.Empty, Convert.ToString(ConfigurationManager.AppSettings["Login_user_not_mapped"])); } } else { //ModelState.AddModelError(string.Empty, "The user name or password is incorrect."); ModelState.AddModelError(string.Empty, Convert.ToString(ConfigurationManager.AppSettings["login_name_pwd_incorrect"])); } } catch (Exception ex) { objLog.ErrorLogFile("Account_LogOn", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); //ModelState.AddModelError(string.Empty, "Login was unsuccessful. Please correct the errors and try again."); ModelState.AddModelError(string.Empty, Convert.ToString(ConfigurationManager.AppSettings["login_unsuccessfull"])); } finally { if (oUserClient.InnerChannel.State != System.ServiceModel.CommunicationState.Faulted) { oUserClient.Close(); } } } else { //ModelState.AddModelError(string.Empty, "The user name or password is incorrect."); ModelState.AddModelError(string.Empty, Convert.ToString(ConfigurationManager.AppSettings["login_name_pwd_incorrect"])); } //// If we got this far, something failed, redisplay form return View(model); } /// /// GET: /Account/LogOff /// /// Action Result public ActionResult LogOff() { objLog.AddLogFile("Account_LogOff", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); try { FormsAuthentication.SignOut(); string[] cookies = System.Web.HttpContext.Current.Request.Cookies.AllKeys; foreach (string cookie in cookies) { System.Web.HttpCookie currentUserCookie = System.Web.HttpContext.Current.Request.Cookies[cookie]; currentUserCookie.Value = null; System.Web.HttpContext.Current.Response.SetCookie(currentUserCookie); System.Web.HttpContext.Current.Request.Cookies[cookie].Expires = DateTime.Now.AddDays(-1); } //string returnUrl = Url.RouteUrl("DefaultLoginUrl"); Session.Clear(); Session.Abandon(); bool isAjaxRequest = Request.Headers["X-Requested-With"] == "XMLHttpRequest"; if (isAjaxRequest && !Request.IsAuthenticated) { return JavaScript("window.location = '/Account/Index'"); } return RedirectToAction("Index", "Account"); } catch (Exception ex) { objLog.ErrorLogFile("Account_LogOff", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); throw ex; } } #endregion #region Rest API /// /// Web Api method calling to get login user's details /// /// Login user's name /// Returns list of user details public UserDetailsModel GetUserOrganizationDetails(string UserName) { objLog.AddLogFile("Account_GetUserOrganizationDetails", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); try { UserDetailsModel model = null; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; var client = new RestSharp.RestClient(_RestClientUrl); var request = new RestRequest("Api/User", Method.POST); request.AddParameter("Token", _securityToken); request.AddParameter("UserName", UserName); request.RequestFormat = DataFormat.Json; request.AddHeader("content-type", "application/json"); var response = client.Execute(request); var content = response.Content; model = JsonConvert.DeserializeObject(content); return model; } catch (Exception ex) { objLog.ErrorLogFile("Account_GetUserOrganizationDetails", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); throw ex; } } #endregion #region Actions - Forgot Password /// /// Function used to retrive user password. /// /// Action Result public ActionResult ForgotPassword() { return View(); } /// /// Function used to reset user password. /// /// Forgot password model. /// Action Result [HttpPost] public ActionResult ForgotPassword(ForgotPasswordModel model) { objLog.AddLogFile("Account_ForgotPassword", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); if (ModelState.IsValid) { UserClient oUserClient = new UserClient(); string newPassword =null; try { List listMailId = new List(); listMailId.Add(model.EmailAddress); model.EmailAddress = "priya.joshi@softude.com"; newPassword = oUserClient.ForgotPassword(model.EmailAddress); string filePath = Server.MapPath("~/MailFormat/ForgotPassword.txt"); using (StreamReader reader = System.IO.File.OpenText(filePath)) { string mailFormat = reader.ReadToEnd(); mailFormat = string.Format(mailFormat, newPassword); new EmailServices().SendMail(mailFormat, model.EmailAddress, _emailSubjectTitle + " - Forgot Password"); var objForgotPassword = new ForgotPassword { @object = new List<@object> { new @object {to = listMailId, cc = listMailId, bcc = listMailId, message = mailFormat, subject = _emailSubjectTitle + " - Forgot Password"} } }; ForgotPassword forgotPasswordModel = GetNewPassword(objForgotPassword.@object); if (forgotPasswordModel.valid == true) { return RedirectToAction("Index", "Account"); } } return View(); } catch (Exception ex) { objLog.ErrorLogFile("Account_ForgotPassword", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); //ModelState.AddModelError(string.Empty, "Reset password was unsuccessful. Please correct the errors and try again."); ModelState.AddModelError(string.Empty, Convert.ToString(ConfigurationManager.AppSettings["login_name_pwd_incorrect"])); } finally { if (oUserClient.InnerChannel.State != System.ServiceModel.CommunicationState.Faulted) { oUserClient.Close(); } } } return View(model); } /// /// Web Api method calling to get new password in Forgot Password condition /// /// object json including mail id and subject and message /// return forgot password model public ForgotPassword GetNewPassword(object objectForgotPassword) { objLog.AddLogFile("Account_GetNewPassword", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); try { var client = new RestSharp.RestClient(ConfigurationManager.AppSettings["RestApiUrlForgotpassword"].ToString()); var json = JsonConvert.SerializeObject(objectForgotPassword); json = json.TrimStart('[').TrimEnd(']'); var request = new RestRequest(ConfigurationManager.AppSettings["RestApiForgotpassword"].ToString(), Method.POST); request.AddParameter("text/json", json, ParameterType.RequestBody); var response = client.Execute(request).Data; return response; } catch (Exception ex) { objLog.ErrorLogFile("Account_GetNewPassword", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); throw ex; } } #endregion } }