428 lines
19 KiB
C#
428 lines
19 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Class used to manage user authentication and registration.
|
|
/// </summary>
|
|
public class AccountController : Controller
|
|
{
|
|
#region Global Variables
|
|
|
|
/// <summary>
|
|
/// Represent object of LoggingUtility class
|
|
/// </summary>
|
|
LoggingUtility objLog = new LoggingUtility();
|
|
|
|
/// <summary>
|
|
/// Represent string object contain log file path
|
|
/// </summary>
|
|
string path = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PathLog"]);
|
|
|
|
/// <summary>
|
|
/// Represent string object contain log status
|
|
/// </summary>
|
|
string logtf = (ConfigurationManager.AppSettings["Log"]);
|
|
|
|
/// <summary>
|
|
/// Represent string object contain Error log status
|
|
/// </summary>
|
|
string errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]);
|
|
|
|
/// <summary>
|
|
/// getting application name from AppSetting in web.config file
|
|
/// </summary>
|
|
private static string _appName = ConfigurationManager.AppSettings["ApplicationName"].ToString();
|
|
|
|
/// <summary>
|
|
/// getting email subject name from AppSetting in web.config file
|
|
/// </summary>
|
|
private static string _emailSubjectTitle = ConfigurationManager.AppSettings["EmailSubjectTitle"].ToString();
|
|
|
|
/// <summary>
|
|
/// getting web api token from AppSetting in web.config file
|
|
/// </summary>
|
|
private static string _securityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString();
|
|
|
|
/// <summary>
|
|
/// get url on which rest api's are hosted
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// User
|
|
/// to this action when does not have permission to access particular page.
|
|
/// </summary>
|
|
/// <param name="returnUrl">Redirection URL after authorize user.</param>
|
|
/// <returns>Action Result</returns>
|
|
public ActionResult UnauthorizedAccess(string returnUrl)
|
|
{
|
|
return RedirectToAction("Index", new { returnUrl = returnUrl });
|
|
}
|
|
|
|
/// <summary>
|
|
/// GET /Acount/Index
|
|
/// </summary>
|
|
/// <returns>Action Result</returns>
|
|
[AllowCrossSiteJson]
|
|
public ActionResult Index()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
#region Actions - LogOn/LogOff
|
|
|
|
/// <summary>
|
|
/// GET: /Account/LogOn
|
|
/// </summary>
|
|
/// <returns>Action Result</returns>
|
|
[AllowCrossSiteJson]
|
|
public ActionResult LogOn()
|
|
{
|
|
return PartialView();
|
|
}
|
|
|
|
/// <summary>
|
|
/// POST: /Account/LogOn
|
|
/// </summary>
|
|
/// <param name="model">User LogOnModel with UserName,Password etc.</param>
|
|
/// <param name="returnUrl">Destination Url after successfully login.</param>
|
|
/// <returns>Action Result</returns>
|
|
[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);
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// GET: /Account/LogOff
|
|
/// </summary>
|
|
/// <returns>Action Result</returns>
|
|
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
|
|
|
|
/// <summary>
|
|
/// Web Api method calling to get login user's details
|
|
/// </summary>
|
|
/// <param name="UserName">Login user's name</param>
|
|
/// <returns>Returns list of user details</returns>
|
|
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<UserDetailsModel>(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
|
|
|
|
/// <summary>
|
|
/// Function used to retrive user password.
|
|
/// </summary>
|
|
/// <returns>Action Result</returns>
|
|
public ActionResult ForgotPassword()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Function used to reset user password.
|
|
/// </summary>
|
|
/// <param name="model">Forgot password model.</param>
|
|
/// <returns>Action Result</returns>
|
|
[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<string> listMailId = new List<string>();
|
|
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);
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Web Api method calling to get new password in Forgot Password condition
|
|
/// </summary>
|
|
/// <param name="objectForgotPassword">object json including mail id and subject and message</param>
|
|
/// <returns>return forgot password model</returns>
|
|
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<ForgotPassword>(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
|
|
}
|
|
}
|