public override void OnAuthorization(AuthorizationContext filterContext) { var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest(); var currentUrl = filterContext.HttpContext.Request.RawUrl; //Check all allowed urls. if (CheckAllowedActions()) { return; } string[] strPermissions = string.IsNullOrEmpty(Permissions) ? new string[] { } : Permissions.Split(','); #region Authentication if (filterContext.HttpContext.Request.CurrentExecutionFilePath != Constants.LoginUrl) { bool removeFormsAuthenticationTicket = true; bool isTimeOut = false; if (filterContext.HttpContext.Request.IsAuthenticated && SessionHelper.UserId == 0) { HttpCookie decryptedCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(decryptedCookie.Value); if (ticket != null) { var identity = new GenericIdentity(ticket.Name); if (identity.IsAuthenticated) { ISecurityDataProvider securityDataProvider = new SecurityDataProvider(); LoginModel loginModel = new LoginModel { Email = ticket.Name }; ServiceResponse response = new ServiceResponse(); response = securityDataProvider.AuthenticateUser(loginModel, true); if (response.IsSuccess) { SessionValueData sessiondata = (SessionValueData)response.Data; SessionHelper.UserId = sessiondata.UserId; SessionHelper.UserRoleId = sessiondata.UserRoleId; SessionHelper.CurrentUser = sessiondata.CurrentUser; removeFormsAuthenticationTicket = false; } else { isTimeOut = true; } } else { isTimeOut = true; } } else { isTimeOut = true; } if (removeFormsAuthenticationTicket) { FormsAuthentication.SignOut(); if (filterContext.HttpContext.Request.CurrentExecutionFilePath != "/" && filterContext.HttpContext.Request.CurrentExecutionFilePath != Constants.LoginUrl) { RedirectToAction(filterContext, _loginUrl + GenerateReturnUrl(isAjaxRequest, filterContext), isAjaxRequest); } else { RedirectToAction(filterContext, _loginUrl, isAjaxRequest); } } } else if (SessionHelper.UserId == 0) { if (filterContext.HttpContext.Request.CurrentExecutionFilePath != "/" && filterContext.HttpContext.Request.CurrentExecutionFilePath != Constants.LoginUrl) { RedirectToAction(filterContext, _loginUrl + GenerateReturnUrl(isAjaxRequest, filterContext), isAjaxRequest); } else { RedirectToAction(filterContext, _loginUrl, isAjaxRequest); } } } #endregion #region Authorization if (SessionHelper.UserId > 0) { bool isAuthoized = strPermissions.Contains(Constants.AuthorizedPermission) || strPermissions.Contains(Constants.RememberMePermission); if (!isAuthoized && !isAjaxRequest) { filterContext.Result = new RedirectResult(_accessDeniedUrl); } else if (!isAuthoized) { RedirectToAction(filterContext, _accessDeniedUrl, isAjaxRequest); } else { } } //else //{ //TODO if some action has been performed for the unauthorized user. //} #endregion }
public void SignIn(UserInfo user, bool createPersistentCookie) { if (PortalController.IsMemberOfPortalGroup(user.PortalID) || createPersistentCookie) { // Create a custom auth cookie // first, create the authentication ticket var authenticationTicket = createPersistentCookie ? new FormsAuthenticationTicket(user.Username, true, Config.GetPersistentCookieTimeout()) : new FormsAuthenticationTicket(user.Username, false, Config.GetAuthCookieTimeout()); // encrypt it var encryptedAuthTicket = FormsAuthentication.Encrypt(authenticationTicket); // Create a new Cookie var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthTicket) { Expires = authenticationTicket.Expiration, Domain = GetCookieDomain(user.PortalID), Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, }; if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) { HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); } HttpContext.Current.Response.Cookies.Set(authCookie); AuthCookieController.Instance.Update(authCookie.Value, authCookie.Expires.ToUniversalTime(), user.UserID); if (PortalController.IsMemberOfPortalGroup(user.PortalID)) { var domain = GetCookieDomain(user.PortalID); var siteGroupCookie = new HttpCookie("SiteGroup", domain) { Expires = authenticationTicket.Expiration, Domain = domain, Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Set(siteGroupCookie); } } else { if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) { HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); } FormsAuthentication.SetAuthCookie(user.Username, false); var authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (!string.IsNullOrEmpty(authCookie?.Value)) { var t = FormsAuthentication.Decrypt(authCookie.Value); if (t != null) { AuthCookieController.Instance.Update(authCookie.Value, t.Expiration.ToUniversalTime(), user.UserID); } } } if (user.IsSuperUser) { // save userinfo object in context to ensure Personalization is saved correctly HttpContext.Current.Items["UserInfo"] = user; } // Identity the Login is processed by system. HttpContext.Current.Items["DNN_UserSignIn"] = true; }
public JsonResult Login(LoginModel model) { if (model.Username == null || string.IsNullOrEmpty(model.Username)) { return(Json(new { Code = 300, Msg = "Username is not allowed to be empty.", })); } if (model.Password == null || string.IsNullOrEmpty(model.Password)) { return(Json(new { Code = 300, Msg = "Password is not allowed to be empty.", })); } // 获取Salt var helper = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("Username", model.Username); var user = helper.FindOne(Constant.UserCollectionName, filter); if (user == null) { return(Json(new { Code = 300, Msg = "The username or password is wrong.", })); } var salt = user["Salt"].ToString(); // 验证账号密码 var password = MD5Helper.Encrypt(model.Password + salt); var filter1 = Builders <BsonDocument> .Filter.Eq("Password", password); filter = Builders <BsonDocument> .Filter.And(filter, filter1); user = helper.FindOne(Constant.UserCollectionName, filter); if (user == null) { return(Json(new { Code = 300, Msg = "The username or password is wrong.", })); } var id = user["ID"].ToString(); // 票据数据 var ticketData = new LoginTicketDataModel { UserID = id, }; // 将用户信息写入cookie var cookie = FormsAuthentication.GetAuthCookie(model.Username, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, JsonConvert.SerializeObject(ticketData)); // 将用户ID写入ticket cookie.Value = FormsAuthentication.Encrypt(newTicket); cookie.Expires = DateTime.Now.AddMinutes(ConfigHelper.Expires); HttpContext.Current.Response.Cookies.Add(cookie); return(Json(new { Code = 200, Msg = "Login successfully!", Data = new { Username = user["Username"].ToString(), Name = user["Name"].ToString() } })); }
private Customer EnsureUser() { var encryptedCookie = _httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (encryptedCookie != null && !string.IsNullOrEmpty(encryptedCookie.Value)) { var ticket = FormsAuthentication.Decrypt(encryptedCookie.Value); var result = GetAuthenticatedCustomerFromTicket(ticket); if (result != null && result.Active && !result.Deleted && result.IsRegistered()) { return(result); } } Customer customer; var identity = _httpContext.User.Identity; if (identity == null) { return(null); } var identityName = identity.Name; using (HostingEnvironment.Impersonate()) { using (var context = new PrincipalContext(ContextType.Domain)) using (var principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, identityName)) { var existing = _customerService.GetCustomerByEmail(principal.EmailAddress); if (existing != null && existing.Active && !existing.Deleted && existing.IsRegistered()) { MapRoles(existing, _httpContext.User); SignIn(existing, true); return(existing); } customer = new Customer { Active = true, Email = principal.EmailAddress, HasShoppingCartItems = false, IsSystemAccount = false, Username = principal.EmailAddress }; MapRoles(customer, _httpContext.User); } } var password = GetRandomString(25); var registeredRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered); if (registeredRole == null) { throw new NopException("'Registered' role could not be loaded"); } customer.CustomerRoles.Add(registeredRole); var guestRole = customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == SystemCustomerRoleNames.Guests); if (guestRole != null) { customer.CustomerRoles.Remove(guestRole); } customer.Password = password; customer.PasswordFormat = PasswordFormat.Clear; customer.CreatedOnUtc = DateTime.UtcNow; customer.LastLoginDateUtc = DateTime.UtcNow; customer.LastActivityDateUtc = DateTime.UtcNow; _customerService.InsertCustomer(customer); return(customer); }
}//end event protected void btnSubmit_Click(object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); Session sessionObject = new Session(); FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMinutes(sessionObject.getSessionTimeLimit()), ticket.IsPersistent, ticket.UserData); string encryptedTicket = FormsAuthentication.Encrypt(newTicket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.Expires = newTicket.Expiration; Response.Cookies.Add(cookie); string username = ticket.Name; string Q1 = TextBox4.InnerText; string Q2 = TextBox1.Text; string Q3 = TextBox2.Text; string Q4 = TextBox3.Text; Validate validationObject = new Validate(); Q1 = validationObject.Truncate(Q1, 900); Q2 = validationObject.Truncate(Q2, 900); Q3 = validationObject.Truncate(Q3, 900); Q4 = validationObject.Truncate(Q4, 900); bool recordExists; string errorMessage; Select selectObject = new Select(); recordExists = Select.Select_Natural_Talents(username); errorMessage = selectObject.getErrorMessage(); if (errorMessage != null) { lblError.Text = errorMessage; lblError.Visible = true; ErrorMessage message = new ErrorMessage(); MsgBox(message.SQLServerErrorMessage); }//end if else { if (recordExists == false) { string errorMessage2; errorMessage2 = Insert.Insert_Natural_Talents(username, Q1, Q2, Q3, Q4); if (errorMessage2 != null) { lblError.Text = errorMessage2; lblError.Visible = true; ErrorMessage message = new ErrorMessage(); MsgBox(message.SQLServerErrorMessage); }//end if else { string errorMessage3; errorMessage3 = Update.Update_Natural_Talents_Status(username); if (errorMessage3 != null) { lblError.Text = errorMessage3; lblError.Visible = true; ErrorMessage message = new ErrorMessage(); MsgBox(message.SQLServerErrorMessage); }//end if else { Response.Redirect("~/PL/FOP/FOP_ProgressMenu.aspx"); }//end else }//end else }//end if }//end else }//end event
/// <summary> /// Login to the campus DistAuth system using CAS /// </summary> public static string Login(Action <string> handleUserId = null) { // get the context from the source var context = HttpContext.Current; // try to load a valid ticket HttpCookie validCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket validTicket = null; // check to make sure cookie is valid by trying to decrypt it if (validCookie != null) { try { validTicket = FormsAuthentication.Decrypt(validCookie.Value); } catch { validTicket = null; } } // if user is unauthorized and no validTicket is defined then authenticate with cas //if (context.Response.StatusCode == 0x191 && (validTicket == null || validTicket.Expired)) if (validTicket == null || validTicket.Expired) { // build query string but strip out ticket if it is defined string query = ""; foreach (string key in context.Request.QueryString.AllKeys) { if (string.Compare(key, StrTicket, true) != 0) { query += "&" + key + "=" + context.Request.QueryString[key]; } } // replace 1st character with ? if query is not empty if (!string.IsNullOrEmpty(query)) { query = "?" + query.Substring(1); } // get ticket & service string ticket = context.Request.QueryString[StrTicket]; string service = context.Server.UrlEncode(context.Request.Url.GetLeftPart(UriPartial.Path) + query); // if ticket is defined then we assume they are coming from CAS if (!string.IsNullOrEmpty(ticket)) { // validate ticket against cas StreamReader sr = new StreamReader(new WebClient().OpenRead(StrCasUrl + "validate?ticket=" + ticket + "&service=" + service)); // parse text file if (sr.ReadLine() == "yes") { // get kerberos id string kerberos = sr.ReadLine(); if (handleUserId != null) { handleUserId(kerberos); } else { // set forms authentication ticket FormsAuthentication.SetAuthCookie(kerberos, false); } string returnUrl = GetReturnUrl(); return(!string.IsNullOrEmpty(returnUrl) ? returnUrl : FormsAuthentication.DefaultUrl); } } // ticket doesn't exist or is invalid so redirect user to CAS login context.Response.Redirect(StrCasUrl + "login?service=" + service); } return(null); }
protected void Page_Load(object sender, EventArgs e) { try { string errorText = Request.QueryString["ErrorText"]; if (!string.IsNullOrEmpty(errorText)) { LabelError.Text = errorText; } else { LabelError.Text = string.Empty; } HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; string isLoggingOut = Request.QueryString["out"]; if (null != cookie && !string.IsNullOrEmpty(cookie.Value)) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); ZXPUserData zxpUD = new ZXPUserData(); zxpUD = ZXPUserData.DeserializeZXPUserData(ticket.UserData); LoginControl.UserName = zxpUD._UserName; if (zxpUD._isValid) { if (zxpUD.hasLoaderOrYMAccessOnly() && string.IsNullOrEmpty(isLoggingOut)) { Response.Redirect("/loaderMobile.aspx", false); Context.ApplicationInstance.CompleteRequest(); // end response } else { Response.Redirect("/default.aspx", false); Context.ApplicationInstance.CompleteRequest(); // end response } LabelError.Text = "Already logged in. Please navigate to the page you would like to see by using the links in the menu above."; } else { if (zxpUD.hasLoaderOrYMAccessOnly()) { Response.Redirect("/loaderMobile.aspx", false); Context.ApplicationInstance.CompleteRequest(); // end response } else { String pageURL = FormsAuthentication.GetRedirectUrl(LoginControl.UserName, LoginControl.RememberMeSet); Response.Redirect(pageURL, false); Context.ApplicationInstance.CompleteRequest(); // end response } } AuditLog aLog = new AuditLog(zxpUD._uid); aLog.createNewAuditLogEntry(aLog); } if (!string.IsNullOrEmpty(isLoggingOut)) { int islogout = 0; bool isValidLogout = int.TryParse(isLoggingOut, out islogout); if (isValidLogout && 1 == islogout) { Session.Abandon(); System.Web.Security.FormsAuthentication.SignOut(); } } } catch (System.Threading.ThreadAbortException ex) { ex.ToString(); //do nothing - caused by response.redirect } catch (SqlException excep) { string strErr = " SQLException Error in Login Page_Load(). Details: " + excep.ToString(); ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error); System.Web.HttpContext.Current.Session["ErrorNum"] = 2; ErrorLogging.sendtoErrorPage(2); } catch (Exception ex) { string strErr = " Exception Error in Login Page_Load(). Details: " + ex.ToString(); ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error); System.Web.HttpContext.Current.Session["ErrorNum"] = 1; ErrorLogging.sendtoErrorPage(1); } }
public async Task <ActionResult> Register(RegisterViewModel model) { /*if (ModelState.IsValid) * { * var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; * var result = await UserManager.CreateAsync(user, model.Password); * if (result.Succeeded) * { * await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); * * // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 * // Send an email with this link * // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); * // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); * // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); * * return RedirectToAction("Index", "Home"); * } * AddErrors(result); * }*/ using (ZavrsniEFentities db = new ZavrsniEFentities()) { var newUser = db.User.Create(); bool userExists = db.User.Any(user => user.Username == model.Username); newUser.Username = model.Username; newUser.Password = model.Password; newUser.Email = model.Email; newUser.FirstName = model.FirstName; newUser.LastName = model.LastName; if (Request["CityDropDownList"].Any()) { var citySel = Request["CityDropDownList"]; newUser.IDcityFrom = Convert.ToInt32(citySel); } if (!userExists) { db.User.Add(newUser); db.SaveChanges(); var userGroup = db.BelongsToGroup.Create(); userGroup.IDgroup = 1; userGroup.IDuser = newUser.IDuser; userGroup.TimeChanged = DateTime.Now; db.BelongsToGroup.Add(userGroup); db.SaveChanges(); FormsAuthentication.SetAuthCookie(model.Username, false); var FormsAuthCookie = Response.Cookies[FormsAuthentication.FormsCookieName]; var ExistingTicket = FormsAuthentication.Decrypt(FormsAuthCookie.Value).Name; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The user with this username already exists, please choose another username!"); model.Username = ""; return(View(model)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpRequest request = context.Request; BLL.CRM_receive cci = new BLL.CRM_receive(); Model.CRM_receive model = new Model.CRM_receive(); var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); string CoockiesID = ticket.UserData; BLL.hr_employee emp = new BLL.hr_employee(); int emp_id = int.Parse(CoockiesID); DataSet dsemp = emp.GetList("id=" + emp_id); string empname = dsemp.Tables[0].Rows[0]["name"].ToString(); string uid = dsemp.Tables[0].Rows[0]["uid"].ToString(); if (request["Action"] == "save") { DataRow dremp = dsemp.Tables[0].Rows[0]; model.Receive_num = PageValidate.InputText(request["T_invoice_num"], 255); string orderid = PageValidate.InputText(request["orderid"], 50); BLL.CRM_order order = new BLL.CRM_order(); DataSet dsorder = order.GetList("id=" + int.Parse(orderid)); model.order_id = int.Parse(orderid); if (dsorder.Tables[0].Rows.Count > 0) { model.Customer_id = int.Parse(dsorder.Tables[0].Rows[0]["Customer_id"].ToString()); model.Customer_name = PageValidate.InputText(dsorder.Tables[0].Rows[0]["Customer_name"].ToString(), 255); } model.C_depid = int.Parse(request["T_dep_val"].ToString()); model.C_depname = PageValidate.InputText(request["T_dep"].ToString(), 255); model.C_empid = int.Parse(request["T_employee_val"].ToString()); model.C_empname = PageValidate.InputText(request["T_employee1"].ToString(), 255); model.receive_real = decimal.Parse(request["T_invoice_amount"]); model.Receive_date = DateTime.Parse(request["T_invoice_date"].ToString()); model.Pay_type_id = int.Parse(request["T_invoice_type_val"].ToString()); model.Pay_type = PageValidate.InputText(request["T_invoice_type"].ToString(), 255); model.remarks = PageValidate.InputText(request["T_content"].ToString(), 12000); model.receive_direction_id = int.Parse(request["T_receive_direction_val"].ToString()); model.receive_direction_name = PageValidate.InputText(request["T_receive_direction"], 255); model.Receive_amount = model.receive_direction_id * model.receive_real; string cid = PageValidate.InputText(request["receiveid"], 50); if (!string.IsNullOrEmpty(cid) && cid != "null") { model.id = int.Parse(PageValidate.IsNumber(cid) ? cid : "-1"); DataSet ds = cci.GetList(" id=" + model.id); DataRow dr = ds.Tables[0].Rows[0]; cci.Update(model); C_Sys_log log = new C_Sys_log(); int UserID = emp_id; string UserName = empname; string IPStreet = request.UserHostAddress; string EventTitle = model.Receive_num; string EventType = "收款修改"; int EventID = model.id; if (dr["Receive_amount"].ToString() != request["T_invoice_amount"].Replace(",", "").Replace(".00", "")) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款金额", dr["Receive_amount"].ToString(), request["T_invoice_amount"].Replace(",", "").Replace(".00", "")); } if (dr["Pay_type"].ToString() != request["T_invoice_type"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "付款方式", dr["Pay_type"].ToString(), request["T_invoice_type"]); } if (dr["receive_direction_name"].ToString() != request["T_receive_direction"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款类别", dr["receive_direction_name"].ToString(), request["T_receive_direction"]); } if (dr["Receive_num"].ToString() != request["T_invoice_num"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "凭证号码", dr["Receive_num"].ToString(), request["T_invoice_num"]); } if (dr["Receive_date"].ToString() != request["T_invoice_date"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款时间", dr["Receive_date"].ToString(), request["T_invoice_date"]); } if (dr["remarks"].ToString() != request["T_content"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款内容", "原内容被修改", "原内容被修改"); } if (dr["C_depname"].ToString() != request["T_dep"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款人部门", dr["C_depname"].ToString(), request["T_dep"]); } if (dr["C_empname"].ToString() != request["T_employee1"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "收款人姓名", dr["C_empname"].ToString(), request["T_employee1"]); } } else { model.isDelete = 0; model.create_id = emp_id; model.create_name = dremp["name"].ToString(); model.create_date = DateTime.Now; cci.Add(model); } //更新订单收款金额 order.UpdateReceive(orderid); } if (request["Action"] == "grid") { int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]); int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]); string sortname = request["sortname"]; string sortorder = request["sortorder"]; if (string.IsNullOrEmpty(sortname)) { sortname = " id"; } if (string.IsNullOrEmpty(sortorder)) { sortorder = " desc"; } string sorttext = " " + sortname + " " + sortorder; string Total; string serchtxt = "1=1"; string order_id = request["orderid"]; if (!string.IsNullOrEmpty(order_id) && order_id != "null") { serchtxt += " and order_id=" + int.Parse(order_id); } string customerid = request["customerid"]; if (!string.IsNullOrEmpty(customerid) && customerid != "null") { serchtxt += " and Customer_id=" + int.Parse(customerid); } if (!string.IsNullOrEmpty(request["company"])) { serchtxt += " and Customer_name like N'%" + PageValidate.InputText(request["company"], 250) + "%'"; } if (!string.IsNullOrEmpty(request["receive_num"])) { serchtxt += " and Receive_num like N'%" + PageValidate.InputText(request["receive_num"], 50) + "%'"; } if (!string.IsNullOrEmpty(request["pay_type"])) { serchtxt += " and Pay_type_id =" + int.Parse(request["pay_type_val"]); } if (!string.IsNullOrEmpty(request["department"])) { serchtxt += " and C_depid =" + int.Parse(request["department_val"]); } if (!string.IsNullOrEmpty(request["employee"])) { serchtxt += " and C_empid =" + int.Parse(request["employee_val"]); } if (!string.IsNullOrEmpty(request["startdate"])) { serchtxt += " and Receive_date >= '" + PageValidate.InputText(request["startdate"], 50) + "'"; } if (!string.IsNullOrEmpty(request["enddate"])) { DateTime enddate = DateTime.Parse(request["enddate"]); serchtxt += " and Receive_date <= '" + enddate + "'"; } if (!string.IsNullOrEmpty(request["startdate_del"])) { serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 50) + "'"; } if (!string.IsNullOrEmpty(request["enddate_del"])) { DateTime enddate = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59); serchtxt += " and Delete_time <= '" + enddate + "'"; } //权限 DataSet ds = cci.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total); string dt = Common.GetGridJSON.DataTableToJSON1(ds.Tables[0], Total); context.Response.Write(dt); } if (request["Action"] == "form") { int invoiceid = int.Parse(request["receiveid"]); DataSet ds = cci.GetList("id=" + invoiceid); string dt = Common.DataToJson.DataToJSON(ds); context.Response.Write(dt); } //del if (request["Action"] == "del") { //参数安全过滤 string c_id = PageValidate.InputText(request["id"], 50); DataSet ds = cci.GetList("id=" + int.Parse(c_id)); bool isdel = cci.Delete(int.Parse(c_id)); //更新订单金额 BLL.CRM_order order = new BLL.CRM_order(); string orderid = ds.Tables[0].Rows[0]["order_id"].ToString(); order.UpdateReceive(orderid); if (isdel) { //日志 string EventType = "收款删除"; int UserID = emp_id; string UserName = empname; string IPStreet = request.UserHostAddress; int EventID = int.Parse(c_id); string EventTitle = ds.Tables[0].Rows[0]["Customer_name"].ToString(); string Original_txt = ds.Tables[0].Rows[0]["Receive_amount"].ToString(); string Current_txt = null; C_Sys_log log = new C_Sys_log(); log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "金额", Original_txt, Current_txt); context.Response.Write("true"); } else { context.Response.Write("false"); } } }
// GET: PageAdmin public ActionResult Index() { ViewBag.NameUser = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; return(View("PageAdmin")); }
public ActionResult ProcesaRespuestaAuth(bool?changePassword, bool?isEmbedded) { var user = SeguridadDelegate.UsuarioTemporal; if (changePassword.HasValue && changePassword.Value) { return(PartialView("_LogInRenew", new ModCambioContrasena { CodUsuario = user.CodUsuario })); } try { if (user.IdEstado == (int)EnumEstadoUsuario.Registrado) { return(RedirectToAction("Index", "Registro")); } //El usuario es valido y puede ingresar user.Ticket = SeguridadDelegate.IniciarSesion(user.CodUsuario, user.Ticket); var cookie = FormsAuthentication.GetAuthCookie(user.Ticket, false); //Decrypt the cookie var ticket = FormsAuthentication.Decrypt(cookie.Value); //Create a new ticket using the details from //the generated cookie, but store the username & //token passed in from the authentication method var newticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, user.CodUsuario); //Encrypt the ticket & store in the cookie cookie.Value = FormsAuthentication.Encrypt(newticket); //Update the outgoing cookies collection. Response.Cookies.Set(cookie); Session.RemoveAll(); var url = string.Format(AppProperties.TRANSACURL, user.Locale, user.Ticket); string lang = string.Empty; var idiomas = GeneralesDelegate.ConsultarIdiomas(); foreach (var i in idiomas) { if (i.IdIdioma == user.IdIdioma) { Response.Cookies.Remove(Config.LANG_COOKIE_NAME); lang = i.Abreviatura; var langCookie = new HttpCookie(Config.LANG_COOKIE_NAME, lang) { HttpOnly = true }; Response.AppendCookie(langCookie); } } if (isEmbedded == true) { return(Redirect(url)); } return(Json(new { redireccionar = url }, JsonRequestBehavior.AllowGet)); } catch { Session.RemoveAll(); throw new ControllerException(RecErrores.Err_LogFallido); } }
public FormsAuthenticationTicket DecryptAuthCookie(HttpCookie authcookie) { ticket = FormsAuthentication.Decrypt(authcookie.Value); return(ticket); }
/// <summary> /// This will be used to check user authorization /// </summary> /// <param name="filter_context"></param> protected override void OnAuthorization(AuthorizationContext filter_context) { HttpCookie auth_cookie = Request.Cookies[Cookies.AuthorizationCookie]; HttpCookie admin_auth_cookie = Request.Cookies[Cookies.AdminAuthorizationCookie]; HttpCookie auth_cookie_ud = Request.Cookies[Cookies.AuthorizationCookieMobile]; var requestString = Convert.ToString(filter_context.HttpContext.Request.QueryString); if (auth_cookie_ud != null) { FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie_ud.Value); LOGGEDIN_USER = new JavaScriptSerializer().Deserialize <UserDetails>(auth_ticket.UserData); return; } #region If auth cookie is present if (auth_cookie != null) { #region If Logged User is null if (LOGGEDIN_USER == null) { try { FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie.Value); LOGGEDIN_USER = new JavaScriptSerializer().Deserialize <UserDetails>(auth_ticket.UserData); System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(auth_ticket), null); } catch (Exception exc) { if (auth_cookie != null) { auth_cookie.Expires = DateTime.Now.AddDays(-30); Response.Cookies.Add(auth_cookie); filter_context.Result = RedirectToAction("index", "home"); base.LogExceptionToDatabase(exc); } } } if ((filter_context.ActionDescriptor.ActionName == "Index" || filter_context.ActionDescriptor.ActionName == "SignUp") && filter_context.ActionDescriptor.ControllerDescriptor.ControllerName == "Home") { filter_context.Result = RedirectToAction("Dashboard", "home", new { area = "user" }); } #endregion ViewBag.LOGGEDIN_USER = LOGGEDIN_USER; } #endregion else if (requestString != null && requestString.Contains("Token")) { var queryString = filter_context.HttpContext.Request.QueryString.ToString(); var splitQuery = queryString.Split('&'); if (splitQuery != null && splitQuery.Count() > 1) { var token = splitQuery[0].ToString().Split('=')[1].ToString(); var userid = _UserManager.GetSessionByToken(token); var user = _UserManager.GetUserById(userid); if (user != null) { var data = new UserDetails { FirstName = user.FirstName, LastName = user.LastName, UserEmail = user.Email, ImageLink = user.ImagePath, UserName = user.Email, IsAuthenticated = true, UserID = user.UserId, // UserImage = user.Image, UserType = UserTypes.User, // LastUpdated = user.LastUpdated }; CreateCustomAuthorisationCookieForMobile(user.FirstName + " " + user.LastName, false, new JavaScriptSerializer().Serialize(data)); HttpCookie auth_cookie_udmob = Request.Cookies[Cookies.AuthorizationCookieMobile]; FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie_udmob.Value); LOGGEDIN_USER = new JavaScriptSerializer().Deserialize <UserDetails>(auth_ticket.UserData); } } } #region if authorization cookie is not present and the action method being called is not marked with the [Public] attribute else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(Public), false).Any()) { if (!Request.IsAjaxRequest()) { filter_context.Result = RedirectToAction("index", "home", new { returnUrl = Server.UrlEncode(Request.RawUrl) }); } else { filter_context.Result = Json(new ActionOutput { Status = ActionStatus.Error, Message = "Authentication Error" }, JsonRequestBehavior.AllowGet); } } #endregion #region if authorization cookie is not present and the action method being called is marked with the [Public] attribute else { LOGGEDIN_USER = new UserDetails { IsAuthenticated = false }; ViewBag.LOGGEDIN_USER = LOGGEDIN_USER; } if (filter_context.ActionDescriptor.GetCustomAttributes(typeof(Public), false).Any()) { } else { if (LOGGEDIN_USER != null && LOGGEDIN_USER.IsAuthenticated == false) { filter_context.Result = RedirectToAction("Index", "Login", new { area = "" }); } #endregion if (LOGGEDIN_USER == null || LOGGEDIN_USER.UserType != UserTypes.User && !Request.IsAjaxRequest()) { if (filter_context.ActionDescriptor.ActionName.ToLower() == "Home") { TempData["returnUrl"] = Server.UrlEncode(Request.RawUrl); filter_context.Result = RedirectToAction("Index", "Home", new { area = "", returnUrl = Request.RawUrl }); } else { filter_context.Result = RedirectToAction("Index", "Home", new { area = "" }); } } } base.SetActionName(filter_context.ActionDescriptor.ActionName, filter_context.ActionDescriptor.ControllerDescriptor.ControllerName); }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { return; } HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { if (!string.IsNullOrEmpty(authCookie.Value)) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); if (ticket == null) { return; } try { Business.DAL.UsuarioRepository usuarioRepo = new Business.DAL.UsuarioRepository(); var authenticationService = AuthenticationFactory.CreateAuthentication(); var user = usuarioRepo.GetUserByUserName(ticket.Name, true); var serializeModel = new CustomPrincipalSerializeModel(); serializeModel.UserID = user.Id; serializeModel.FirstName = user.NombreApellido; serializeModel.UserName = user.UserName; var serializer = new JavaScriptSerializer(); var userData = serializer.Serialize(serializeModel); authenticationService.Login(user.NombreApellido, user.Password, user.Recordarme, userData); user.FechaUltimoAcceso = DateTime.Now; usuarioRepo.Modify(user, user.Id); // AppSession.Init_Session(user.Id); // u = uow.LoginWithTicket(ticket.Name); } catch (Exception) { HttpContext.Current.User = null; return; } // HttpContext.Current.User = new Business.UserPrincipal(u); } } /*else * { * Business.UnitOfWork uow = new Business.UnitOfWork(); * Business.User u = null; * try * { * u = uow.LoginAsAnonymous(); * } * catch (Exception) * { * HttpContext.Current.User = null; * return; * } * * HttpContext.Current.User = new Business.UserPrincipal(u); * }*/ }
public ActionResult ViewDetailsPopup(DateTime fromDate, DateTime toDate, string data_Jr, string empCd, string company = null, string showDt = null) { //if (toDate > usDate) // toDate = usDate.Date; // check for director code. string directorCd = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; var _duser = unitOfwork.User.GetByEmpID(directorCd); string drole = _duser.RIC_User_Role.FirstOrDefault().RIC_Role.RR_Role_Name; if (empCd == null || empCd == "") { empCd = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; ViewBag.showSubmittedBy = "Yes"; } else if (drole == directorRoleName) { ViewBag.showSubmittedBy = "Yes"; } else { ViewBag.showSubmittedBy = "No"; } string headerText = null; var _user = unitOfwork.User.GetByEmpID(empCd);//get the role for user. string role = _user.RIC_User_Role.FirstOrDefault().RIC_Role.RR_Role_Name; List <RIC_Job_Report> details = new List <RIC_Job_Report>(); // toDate = toDate.AddDays(1); // DateTime nextDay = date.AddDays(1); //if submission clicked. if (data_Jr == "Submission") { headerText = "Submissions";// For " + fromDate.ToString("MM-dd-yyyy"); details = unitOfwork.RIC_Job_Report.Get_JobRepoartForUser(empCd, fromDate, toDate, role) .Where(s => s.RJ_Submit_Date >= fromDate && s.RJ_Submit_Date <= toDate).ToList(); } else if (data_Jr == "interview")//if interview clicked. { headerText = "Interviews"; details = unitOfwork.RIC_Job_Report.Get_JobRepoartForUser(empCd, fromDate, toDate, role) .Where(s => s.RJ_Interview_Date >= fromDate && s.RJ_Interview_Date <= toDate).ToList(); } else if (data_Jr == "Hire")//if hire click. { headerText = "Hires"; details = unitOfwork.RIC_Job_Report.Get_JobRepoartForUser(empCd, fromDate, toDate, role) .Where(s => s.RJ_Hire_Date >= fromDate && s.RJ_Hire_Date <= toDate).ToList(); } // if company is not null then filter data by company if (company != null) { details = details.Where(s => s.RJ_Company.ToLower() == company.ToLower()).ToList(); } if (showDt == "Y") { headerText = headerText + " For " + fromDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture); } else { toDate = toDate.AddMinutes(1); headerText = headerText + " For " + fromDate.ToString("hh tt", CultureInfo.InvariantCulture) + " To " + toDate.ToString("hh tt", CultureInfo.InvariantCulture); } //if (fromDate.AddDays(1) != toDate)//add the header text // headerText = headerText + " From " + fromDate.ToString("MM-dd-yyyy") + " To " + toDate.AddDays(-1).ToString("MM-dd-yyyy"); //else // headerText = headerText + " For " + fromDate.ToString("MM-dd-yyyy"); ViewBag.Header = headerText; return(PartialView("ViewDetailsPopup", details.OrderBy(s => s.RJ_Submitted_By).ThenBy(s => s.RJ_DateIssued))); }
public async Task TestWithCookieAsync() { // arrange var obj = new { username = "******", firstName = "Johnny", lastName = "Lingo", email = "*****@*****.**" }; var repository = new Mock <IRepository>(); var settings = new ApplicationSettings(); var validationService = new Mock <ValidationService>(repository.Object, settings); var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object); var mailService = new Mock <MailService>(repository.Object); var httpContext = new Mock <HttpContextBase>(); var httpRequest = new Mock <HttpRequestBase>(); var httpResponse = new Mock <HttpResponseBase>(); var requestCookies = new HttpCookieCollection(); var responseCookies = new HttpCookieCollection(); var user = new User { Username = obj.username, FirstName = obj.firstName, LastName = obj.lastName, Email = obj.email }; var set = TestUtilities.CreateDbSetMock(new List <User> { user }); repository .Setup(x => x.AsQueryable <User>()) .Returns(set.Object); httpContext .SetupGet(x => x.Request) .Returns(httpRequest.Object); httpContext .SetupGet(x => x.Response) .Returns(httpResponse.Object); httpRequest .SetupGet(x => x.Cookies) .Returns(requestCookies); httpResponse .SetupGet(x => x.Cookies) .Returns(responseCookies); var data = JObject.FromObject(new { id = user.Id, firstName = "John", lastName = "Smith", roles = new string[] {} }); var ticket = new FormsAuthenticationTicket(1, user.Username, DateTime.UtcNow, DateTime.UtcNow.Add(FormsAuthentication.Timeout), false, data.ToString(), FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var requestCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.MinValue }; requestCookies.Add(requestCookie); dynamic model = JObject.FromObject(obj); var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object); // act await accountService.UpdatePersonalInformationAsync(httpContext.Object, obj.username, model); // assert var responseCookie = responseCookies[FormsAuthentication.FormsCookieName]; var decryptedTicket = FormsAuthentication.Decrypt(responseCookie.Value); dynamic result = JObject.Parse(decryptedTicket.UserData); Assert.Equal(obj.firstName, (string)result.firstName); Assert.Equal(obj.lastName, (string)result.lastName); }
/// <summary> /// This will be used to chek admin user authorization /// </summary> /// <param name="filter_context"></param> protected override void OnAuthorization(AuthorizationContext filter_context) { HttpCookie auth_cookie = Request.Cookies[Cookies.AdminAuthorizationCookie]; #region If auth cookie is present if (auth_cookie != null) { #region If LoggedInUser is null if (LOGGEDIN_USER == null) { FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie.Value); LOGGEDIN_USER = new JavaScriptSerializer().Deserialize <PermissonAndDetailModel>(auth_ticket.UserData); System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(auth_ticket), null); } #endregion ViewBag.LOGGEDIN_USER = LOGGEDIN_USER.UserDetails; ViewBag.USER_PERMISSONS = LOGGEDIN_USER.ModulesModelList; } #endregion #region if authorization cookie is not present and the action method being called is not marked with the [Public] attribute else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(Public), false).Any()) { if (!Request.IsAjaxRequest()) { filter_context.Result = RedirectToAction("Index", "Home", new { returnUrl = Server.UrlEncode(Request.RawUrl), area = "Admin" }); } else { filter_context.Result = Json(new ActionOutput { Status = ActionStatus.Error, Message = "Authentication Error" }, JsonRequestBehavior.AllowGet); } } #endregion if (auth_cookie != null) { #region If Logged User is null if (LOGGEDIN_USER == null) { FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie.Value); LOGGEDIN_USER = new JavaScriptSerializer().Deserialize <PermissonAndDetailModel>(auth_ticket.UserData); System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(auth_ticket), null); } if (filter_context.ActionDescriptor.ActionName == "Index" && filter_context.ActionDescriptor.ControllerDescriptor.ControllerName == "Home") { filter_context.Result = RedirectToAction("dashboard", "home", new { area = "Admin" }); } #endregion ViewBag.LOGGEDIN_USER = LOGGEDIN_USER.UserDetails; ViewBag.USER_PERMISSONS = LOGGEDIN_USER.ModulesModelList; } #region if authorization cookie is not present and the action method being called is not marked with the [Public] attribute else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(Public), false).Any()) { if (!Request.IsAjaxRequest()) { filter_context.Result = RedirectToAction("index", "home", new { returnUrl = Server.UrlEncode(Request.RawUrl), area = "Admin" }); } else { filter_context.Result = Json(new ActionOutput { Status = ActionStatus.Error, Message = "Authentication Error" }, JsonRequestBehavior.AllowGet); } } #endregion #region if authorization cookie is not present and the action method being called is marked with the [Public] attribute else { //LOGGEDIN_USER.UserDetails = new UserModel { IsApproved = false }; //ViewBag.LOGGEDIN_USER = LOGGEDIN_USER.UserDetails; } #endregion SetActionName(filter_context.ActionDescriptor.ActionName, filter_context.ActionDescriptor.ControllerDescriptor.ControllerName); }
public FormsAuthenticationTicket Decrypt(string encryptedTicket) { return(FormsAuthentication.Decrypt(encryptedTicket)); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpRequest request = context.Request; BLL.CRM_order order = new BLL.CRM_order(); Model.CRM_order model = new Model.CRM_order(); var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); string CoockiesID = ticket.UserData; BLL.hr_employee emp = new BLL.hr_employee(); int emp_id = int.Parse(CoockiesID); DataSet dsemp = emp.GetList("id=" + emp_id); string empname = dsemp.Tables[0].Rows[0]["name"].ToString(); string uid = dsemp.Tables[0].Rows[0]["uid"].ToString(); if (request["Action"] == "save") { DataRow dremp = dsemp.Tables[0].Rows[0]; model.Customer_id = int.Parse(request["T_Customer_val"]); model.Customer_name = PageValidate.InputText(request["T_Customer"], 255); model.Order_date = DateTime.Parse(request["T_date"]); model.pay_type_id = int.Parse(request["T_paytype_val"]); model.pay_type = PageValidate.InputText(request["T_paytype"], 255); model.Order_details = PageValidate.InputText(request["T_details"].ToString(), 4000); model.Order_status_id = int.Parse(request["T_status_val"]); model.Order_status = PageValidate.InputText(request["T_status"], 255); model.Order_amount = decimal.Parse(request["T_amount"]); model.create_id = emp_id; model.create_date = DateTime.Now; model.C_dep_id = int.Parse(request["c_dep_val"]); model.C_dep_name = PageValidate.InputText(request["c_dep"], 255); model.C_emp_id = int.Parse(request["c_emp_val"]); model.C_emp_name = PageValidate.InputText(request["c_emp"], 255); model.F_dep_id = int.Parse(request["f_dep_val"]); model.F_dep_name = PageValidate.InputText(request["f_dep"], 255); model.F_emp_id = int.Parse(request["f_emp_val"]); model.F_emp_name = PageValidate.InputText(request["f_emp"], 255); int orderid; string pid = PageValidate.InputText(request["orderid"], 50); if (!string.IsNullOrEmpty(pid) && pid != "null") { model.id = int.Parse(PageValidate.IsNumber(pid) ? pid : "-1"); DataSet ds = order.GetList("id=" + model.id); DataRow dr = ds.Tables[0].Rows[0]; orderid = model.id; order.Update(model); //context.Response.Write(model.id ); context.Response.Write("{success:success}"); C_Sys_log log = new C_Sys_log(); int UserID = emp_id; string UserName = empname; string IPStreet = request.UserHostAddress; string EventTitle = model.Customer_name; string EventType = "订单修改"; int EventID = model.id; if (dr["Customer_name"].ToString() != request["T_Customer"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "客户", dr["Customer_name"].ToString(), request["T_Customer"]); } if (dr["Order_details"].ToString() != request["T_details"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "订单详情", "原内容被修改", "原内容被修改"); } if (dr["Order_date"].ToString() != request["T_date"].ToString() + " 0:00:00") { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "成交时间", dr["Order_date"].ToString(), request["T_date"].ToString() + " 0:00:00"); } if (dr["Order_amount"].ToString() != request["T_amount"].Replace(",", "").Replace(".00", "")) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "订单总额", dr["Order_amount"].ToString(), request["T_amount"].Replace(",", "").Replace(".00", "")); } if (dr["Order_status"].ToString() != request["T_status"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "订单状态", dr["Order_status"].ToString(), request["T_status"]); } if (dr["F_dep_name"].ToString() != request["f_dep"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "促成人员部门", dr["F_dep_name"].ToString(), request["f_dep"]); } if (dr["F_emp_name"].ToString() != request["f_emp"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "促成人员", dr["F_emp_name"].ToString(), request["f_emp"]); } if (dr["pay_type"].ToString() != request["T_paytype"]) { log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, "支付方式", dr["pay_type"].ToString(), request["T_paytype"]); } } else { model.isDelete = 0; model.Serialnumber = DateTime.Now.AddMilliseconds(3).ToString("yyyyMMddHHmmssfff").Trim(); //model.arrears_invoice = decimal.Parse(request["T_amount"]); orderid = order.Add(model); context.Response.Write("{success:success}"); } //更新订单收款金额 order.UpdateReceive(orderid.ToString()); //更新订单发票金额 order.UpdateInvoice(orderid.ToString()); string json = request["PostData"].ToLower(); JavaScriptSerializer js = new JavaScriptSerializer(); PostData[] postdata; postdata = js.Deserialize <PostData[]>(json); BLL.CRM_order_details cod = new BLL.CRM_order_details(); Model.CRM_order_details modeldel = new Model.CRM_order_details(); modeldel.order_id = orderid; cod.Delete(" order_id=" + modeldel.order_id); for (int i = 0; i < postdata.Length; i++) { modeldel.product_id = postdata[i].Product_id; modeldel.product_name = postdata[i].Product_name; modeldel.quantity = postdata[i].Quantity; modeldel.unit = postdata[i].Unit; modeldel.price = postdata[i].Price; modeldel.amount = postdata[i].Amount; cod.Add(modeldel); } } if (request["Action"] == "grid") { int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]); int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]); string sortname = request["sortname"]; string sortorder = request["sortorder"]; if (string.IsNullOrEmpty(sortname)) { sortname = " id"; } if (string.IsNullOrEmpty(sortorder)) { sortorder = "desc"; } string sorttext = " " + sortname + " " + sortorder; string Total; string serchtxt = "1=1"; string issar = request["issarr"]; if (issar == "1") { serchtxt += " and isnull( arrears_money,0)>0"; } if (!string.IsNullOrEmpty(request["company"])) { serchtxt += " and Customer_name like N'%" + PageValidate.InputText(request["company"], 100) + "%'"; } if (!string.IsNullOrEmpty(request["contact"])) { serchtxt += " and Order_status_id = " + int.Parse(request["contact_val"]); } if (!string.IsNullOrEmpty(request["department"])) { serchtxt += " and F_dep_id = " + int.Parse(request["department_val"]); } if (!string.IsNullOrEmpty(request["employee"])) { serchtxt += " and F_emp_id = " + int.Parse(request["employee_val"]); } if (!string.IsNullOrEmpty(request["startdate"])) { serchtxt += " and Order_date >= '" + PageValidate.InputText(request["startdate"], 255) + "'"; } if (!string.IsNullOrEmpty(request["enddate"])) { DateTime enddate = DateTime.Parse(request["enddate"]); serchtxt += " and Order_date <= '" + DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59) + "'"; } if (!string.IsNullOrEmpty(request["startdate_del"])) { serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 255) + "'"; } if (!string.IsNullOrEmpty(request["enddate_del"])) { DateTime enddate = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59); serchtxt += " and Delete_time <= '" + enddate + "'"; } //权限 serchtxt += DataAuth(emp_id.ToString()); DataSet ds = order.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total); string dt = Common.GetGridJSON.DataTableToJSON1(ds.Tables[0], Total); context.Response.Write(dt); } if (request["Action"] == "gridbycustomerid") { string customerid = PageValidate.InputText(request["customerid"], 50); DataSet ds = order.GetList(0, " Customer_id =" + int.Parse(customerid), " Order_date desc"); context.Response.Write(Common.GetGridJSON.DataTableToJSON(ds.Tables[0])); } if (request["Action"] == "form") { int pid = int.Parse(request["orderid"]); DataSet ds = order.GetList("id=" + pid); string dt = Common.DataToJson.DataToJSON(ds); context.Response.Write(dt); } if (request["Action"] == "del") { //参数安全过滤 string c_id = PageValidate.InputText(request["id"], 50); DataSet ds = order.GetList("id=" + int.Parse(c_id)); BLL.CRM_contract contract = new BLL.CRM_contract(); BLL.CRM_invoice invoice = new BLL.CRM_invoice(); BLL.CRM_receive receive = new BLL.CRM_receive(); if (invoice.GetList("order_id=" + int.Parse(c_id)).Tables[0].Rows.Count > 0) { //invoice context.Response.Write("false:invoice"); } else if (receive.GetList("order_id=" + int.Parse(c_id)).Tables[0].Rows.Count > 0) { //receive context.Response.Write("false:receive"); } else { bool canedel = true; if (uid != "admin") { Data.GetDataAuth dataauth = new Data.GetDataAuth(); string txt = dataauth.GetDataAuthByid("3", "Sys_del", emp_id.ToString()); string[] arr = txt.Split(':'); switch (arr[0]) { case "none": canedel = false; break; case "my": for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i]["C_emp_id"].ToString() == arr[1]) { canedel = true; } else { canedel = false; } } break; case "dep": for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i]["C_dep_id"].ToString() == arr[1]) { canedel = true; } else { canedel = false; } } break; case "all": canedel = true; break; } } if (canedel) { bool isdel = order.Delete(int.Parse(c_id)); BLL.CRM_order_details cod = new BLL.CRM_order_details(); cod.Delete("order_id=" + int.Parse(c_id)); if (isdel) { //日志 string EventType = "订单删除"; int UserID = emp_id; string UserName = empname; string IPStreet = request.UserHostAddress; int EventID = int.Parse(c_id); string EventTitle = ds.Tables[0].Rows[0]["Customer_name"].ToString(); string Original_txt = null; string Current_txt = null; C_Sys_log log = new C_Sys_log(); log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null, Original_txt, Current_txt); context.Response.Write("true"); } else { context.Response.Write("false"); } } else { context.Response.Write("delfalse"); } } } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpRequest request = context.Request; BLL.Personal_Calendar calendar = new BLL.Personal_Calendar(); Model.Personal_Calendar model = new Model.Personal_Calendar(); var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); string CoockiesID = ticket.UserData; BLL.hr_employee emp = new BLL.hr_employee(); int emp_id = int.Parse(CoockiesID); DataSet dsemp = emp.GetList("id=" + emp_id); string empname = dsemp.Tables[0].Rows[0]["name"].ToString(); string uid = dsemp.Tables[0].Rows[0]["uid"].ToString(); if (request["Action"] == "get") { CalendarViewType viewType = (CalendarViewType)Enum.Parse(typeof(CalendarViewType), request["viewtype"]); string strshowday = request["showdate"]; int clientzone = Convert.ToInt32(request["timezone"]); int serverzone = GetTimeZone(); var zonediff = serverzone - clientzone; var format = new CalendarViewFormat(viewType, DateTime.Parse(strshowday), DayOfWeek.Monday); DataSet ds = calendar.GetList("emp_id=" + emp_id + " and StartTime>='" + format.StartDate.ToString("yyyy-MM-dd hh:mm:ss") + "' and EndTime<='" + format.EndDate.ToString("yyyy-MM-dd hh:mm:ss") + "'"); string dt = DataToJSON(ds); var data = new JsonCalendarViewData(calendar.DataTableToList(ds.Tables[0]), format.StartDate, format.EndDate); context.Response.Write("{\"start\":\"\\/Date(" + MilliTimeStamp(format.StartDate) + ")\\/\",\"end\":\"\\/Date(" + MilliTimeStamp(format.EndDate) + ")\\/\",\"error\":null,\"issort\":true,\"events\":[" + dt + "]}"); //context.Response.Write(dt); } if (request["Action"] == "quickadd") { int clientzone = Convert.ToInt32(request["timezone"]); int serverzone = GetTimeZone(); var zonediff = serverzone - clientzone; model.Subject = PageValidate.InputText(request["CalendarTitle"], 4000); model.StartTime = DateTime.Parse(request["CalendarStartTime"]).AddHours(zonediff); model.EndTime = DateTime.Parse(request["CalendarEndTime"]).AddHours(zonediff); model.IsAllDayEvent = PageValidate.InputText(request["IsAllDayEvent"], 255) == "1" ? true : false; model.CalendarType = 1; model.InstanceType = 0; model.UPAccount = emp_id.ToString(); model.UPTime = DateTime.Now; model.MasterId = clientzone; model.emp_id = emp_id; model.Category = emp_id.ToString(); int n = calendar.Add(model); context.Response.Write("{\"IsSuccess\":true,\"Msg\":\"\u64cd\u4f5c\u6210\u529f!\",\"Data\":\"" + n + "\"}"); } if (request["Action"] == "quickupdate") { string Id = request["calendarId"]; int clientzone = Convert.ToInt32(request["timezone"]); int serverzone = GetTimeZone(); var zonediff = serverzone - clientzone; model.StartTime = DateTime.Parse(request["CalendarStartTime"]).AddHours(zonediff); model.EndTime = DateTime.Parse(request["CalendarEndTime"]).AddHours(zonediff); model.UPAccount = emp_id.ToString(); model.UPTime = DateTime.Now; model.MasterId = clientzone; model.Id = int.Parse(Id); calendar.quickUpdate(model); context.Response.Write("{IsSuccess:true}"); } if (request["Action"] == "quickdel") { int id = Convert.ToInt32(request["calendarId"]); calendar.Delete(id); context.Response.Write("{IsSuccess:true}"); } if (request["Action"] == "form") { int id = Convert.ToInt32(request["calendarid"]); DataSet ds = calendar.GetList("Id=" + id); string dt = Common.DataToJson.DataToJSON(ds); context.Response.Write(dt); } if (request["Action"] == "save") { string Id = request["calendarid"]; int clientzone = 8; int serverzone = GetTimeZone(); var zonediff = serverzone - clientzone; model.StartTime = DateTime.Parse(request["T_starttime"]).AddHours(zonediff); model.EndTime = DateTime.Parse(request["T_endtime"]).AddHours(zonediff); model.Subject = Common.PageValidate.InputText(request["T_content"], 4000); model.emp_id = emp_id; model.UPAccount = emp_id.ToString(); model.UPTime = DateTime.Now; model.MasterId = clientzone; model.CalendarType = 1; model.InstanceType = 0; model.IsAllDayEvent = PageValidate.InputText(request["allday"], 255) == "True" ? true : false; model.Id = int.Parse(Id); calendar.Update(model); context.Response.Write("{IsSuccess:true}"); } if (request["Action"] == "Today") { DateTime starttime = DateTime.Parse(DateTime.Now.ToShortDateString() + " 00:00:00"); DateTime endtime = DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 00:00:00"); //DataSet ds = calendar.GetList(0, "datediff(day,[StartTime],getdate())=0 and datediff(day,[EndTime],getdate())=0 and emp_id=" + int.Parse(emp_id), "[StartTime] desc"); DataSet ds = calendar.GetList(0, "'" + DateTime.Now.ToShortDateString() + " 23:59:50' >= StartTime and '" + DateTime.Now.ToShortDateString() + " 0:00:00' <= EndTime and emp_id=" + emp_id, "StartTime desc"); context.Response.Write(GetGridJSON.DataTableToJSON(ds.Tables[0])); } }
//public static string GetMenuUsuario_Old() //{ // string MenuData = string.Empty; // try // { // MenuData = "<ul class=\"v-menu subdown\">"; // //MenuData = "<ul id=\"top-level\">"; // int UltimoNivel = 0; // FormsAuthenticationTicket encTicket = FormsAuthentication.Decrypt(Session["user"].ToString()); // CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(encTicket.UserData); // using (SeguricelEntities db = new SeguricelEntities()) // { // List<Modulo> Data = (from m in db.Modulo_TipoUsuario // where m.IdTipoUsuario == serializeModel.IdTipoUsuario & m.Modulo.Activo // orderby m.IdModulo // select m.Modulo).ToList(); // foreach (Modulo _modulo in Data) // { // switch ((eTipoElementoMenu)_modulo.IdTipoElemento) // { // case eTipoElementoMenu.Nivel2: // switch (UltimoNivel) // { // case 2: // MenuData += "</ul>"; // break; // case 3: // MenuData += "</ul></ul>"; // break; // case 4: // MenuData += "</ul></ul></ul>"; // break; // } // MenuData += string.Format("<li><a href=\"#\">{0}</a><ul class=\"sub-level\">", _modulo.Nombre); // UltimoNivel = 2; // break; // case eTipoElementoMenu.Nivel3: // switch (UltimoNivel) // { // case 3: // MenuData += "</ul>"; // break; // case 4: // MenuData += "</ul></ul>"; // break; // } // MenuData += string.Format("<li><a href=\"#\">{0}</a><ul class=\"sub-level\">", _modulo.Nombre); // UltimoNivel = 3; // break; // case eTipoElementoMenu.Nivel4: // switch (UltimoNivel) // { // case 4: // MenuData += "</ul>"; // break; // } // MenuData += string.Format("<li><a href=\"#\">{0}</a><ul class=\"sub-level\">", _modulo.Nombre); // UltimoNivel = 4; // break; // case eTipoElementoMenu.Elemento: // MenuData += string.Format("<li><a href=\"../{1}/{2}\">{0}</a></li>", _modulo.Nombre, _modulo.Controller, _modulo.Action); // break; // } // } // } // } // catch // { // } // return MenuData; //} public static string GetMenuUsuario() { string MenuData = string.Empty; try { MenuData = "<ul class=\"v-menu\">"; int UltimoNivel = 0; FormsAuthenticationTicket encTicket = FormsAuthentication.Decrypt(Session["user"].ToString()); CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <CustomPrincipalSerializeModel>(encTicket.UserData); using (SeguricelEntities db = new SeguricelEntities()) { List <Modulo> Data = (from m in db.Modulo_TipoUsuario where m.IdTipoUsuario == serializeModel.IdTipoUsuario & m.Modulo.Activo orderby m.IdModulo select m.Modulo).ToList(); foreach (Modulo _modulo in Data) { switch ((eTipoElementoMenu)_modulo.IdTipoElemento) { case eTipoElementoMenu.Nivel2: switch (UltimoNivel) { case 3: MenuData += "</ul></li>"; break; case 4: MenuData += "</ul></li></ul></li>"; break; } MenuData += string.Format("<li class=\"menu-title\">{0}</li>", _modulo.Nombre); UltimoNivel = 2; break; case eTipoElementoMenu.Nivel3: switch (UltimoNivel) { case 3: MenuData += "</ul></li>"; break; case 4: MenuData += "</ul></li></ul></li>"; break; } MenuData += string.Format("<li><a href=\"#\" class=\"dropdown-toggle\">{0}</a><ul class=\"d-menu\" data-role=\"dropdown\"><li class=\"menu-title\">{0}</li>", _modulo.Nombre); //MenuData += string.Format("<li><a href=\"#\" class=\"dropdown-toggle\">{0}</a><ul class=\"d-menu\" data-role=\"dropdown\"><li class=\"menu-title\">{0}</li>", _modulo.Nombre); UltimoNivel = 3; break; case eTipoElementoMenu.Nivel4: switch (UltimoNivel) { case 4: MenuData += "</ul></li>"; break; } MenuData += string.Format("<li><a href=\"#\" class=\"dropdown-toggle\">{0}</a><ul class=\"d-menu\" data-role=\"dropdown\"><li class=\"menu-title\">{0}</li>", _modulo.Nombre); //MenuData += string.Format("<li><a href=\"#\">{0}</a><ul class=\"d-menu\" data-role=\"dropdown\">", _modulo.Nombre); UltimoNivel = 4; break; case eTipoElementoMenu.Elemento: MenuData += string.Format("<li><a href=\"../{1}/{2}\" onclick=\"showDialog('#dialogoRegistro')\">{0}</a></li>", _modulo.Nombre, _modulo.Controller, _modulo.Action); break; } } } } catch (Exception ex) { throw ex; } MenuData += "</ul>"; return(MenuData); }
/// Added null checks /// <summary> /// Core Authorization logic /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { bool authorized = false; if (httpContext == null) { return(authorized); } var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null && !authTicket.Expired) { var roles = authTicket.UserData.Split(','); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles); } authorized = true; } else { authorized = false; } return(authorized); //check roles //if (HttpContext.Current != null && HttpContext.Current.Items.Contains("Roles")) //{ // //Get all application level roles // applicationRoles = HttpContext.Current.Items["Roles"] as string[]; // //if user does not belong to any roles in SharePoint // if (applicationRoles == null || applicationRoles.GetLength(0) <= 0) // { // //httpContext.Items.Add(IS_AUTHORIZED, authorized); // // EspHelpers.LogUnAuthorizedAccess("User does not belong to any role in SharePoint - " + controller + "." + action); // return authorized; // } // else // { // //check if roles exists in web.config // if (ConfigurationManager.AppSettings.AllKeys.Contains(Roles)) // { // //allowable roles will be passed as comma seperated values. convert to string[] // allowableRoles = ConfigurationManager.AppSettings[Roles].ToString().Split(','); // if (applicationRoles != null) // { // //if user belongs to atleast one SharePoint role, check if user is a member of a role that is allowed // foreach (string role in applicationRoles) // { // string trimmedRole = role.Trim(); // // if(trimmedRole contains _ then remove guid before _ and compaire it with allowble roles) // if (trimmedRole.Contains("_")) // { // //Input: e1878836-7950-48d3-b331-16705a822877_Experts or e1878836-7950-48d3-b331-16705a822877_LeadTO // //Output: USA _Experts or _LeadTO // //Remove characters before character “_” // trimmedRole = trimmedRole.Substring(trimmedRole.IndexOf('_')); // } // if (allowableRoles.Contains(trimmedRole)) // { // authorized = true; // //httpContext.Items.Add(IS_AUTHORIZED, authorized); // return authorized; // } // } // } // //if we have reached this point, then user is not a member of allowable roles // //EspHelpers.LogUnAuthorizedAccess("User is not a member of any allowable role - " + controller + "." + action); // return authorized; // } // else // { // // If roles does not exist in web.config, then disallow user // authorized = false; // // EspHelpers.LogUnAuthorizedAccess("Role specified (" + Roles + ") does not exist in web.config - " + controller + "." + action); // return authorized; // } // } //} //else //{ // //not authorized // //httpContext.Items.Add(IS_AUTHORIZED, authorized); // // EspHelpers.LogUnAuthorizedAccess("ApplicationIdentity not initialized correctly with Roles - " + controller + "." + action); // return authorized; //} }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { try { if (Request.IsAuthenticated) { string[] roles; if ((Request.Cookies["bfp_roles"] == null) || (Request.Cookies["bfp_roles"].Value == "")) { user = new clsUsers(); user.iOrgId = _functions.GetUserOrgId(HttpContext.Current.User.Identity.Name, false); user.iId = _functions.GetUserOrgId(HttpContext.Current.User.Identity.Name, true); DataTable dtGroups = user.GetUserGroupsList(); string roleStr = ""; foreach (DataRow dr in dtGroups.Rows) { roleStr += String.Format("{0};", dr["vchDesc"]); } roleStr = roleStr.Remove(roleStr.Length - 1, 1); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, HttpContext.Current.User.Identity.Name, DateTime.Now, DateTime.Now.AddHours(1), false, roleStr ); roles = roleStr.Split(new Char[] { ';' }); String cookieStr = FormsAuthentication.Encrypt(ticket); Response.Cookies["bfp_roles"].Value = cookieStr; Response.Cookies["bfp_roles"].Path = "/"; Response.Cookies["bfp_roles"].Expires = DateTime.Now.AddHours(1); } else { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["bfp_roles"].Value); ArrayList userRoles = new ArrayList(); foreach (String role in ticket.UserData.Split(new char[] { ';' })) { userRoles.Add(role); } roles = (String[])userRoles.ToArray(typeof(String)); } HttpContext.Current.User = new GenericPrincipal(Context.User.Identity, roles); } } catch (Exception ex) { _functions.Log("Application error: \n" + ex.ToString()); } finally { if (user != null) { user.Dispose(); } } }
protected void context_PreRequestHandlerExecute(object sender, EventArgs e) { /************************* * If Request is of type .sauth OR any type as specified in Config, allow and skip. * If Request is of LoginURL, skip * OTHERWISE::::::::::::::::::::: * <<<<IF USER IS NOT LOGGED IN>>> * If AuthenticationOption = SocialAuth * Redirect in Priority - ConfigurationLoginURL, "LoginForm.sauth" * If AuthenticationOption = FormsAuthentication * Don't do anything. Let .NET handle it as per user's setting in Web.Config * If AuthenticationOption = Everything Custom * Don't do anything. User will put checking code on every page himself. * **********************/ AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption(); if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN) { //block any .aspx page. Rest all is allowed. //TODO: Better Implementation of this string requestUrlExtension = VirtualPathUtility.GetExtension(HttpContext.Current.Request.RawUrl); string urlWithoutParameters = (new Uri(HttpContext.Current.Request.Url.ToString()).GetLeftPart(UriPartial.Path)).ToLower(); string host = (new Uri(HttpContext.Current.Request.GetBaseURL())).ToString().ToLower(); if (requestUrlExtension != ".aspx" && !string.IsNullOrEmpty(requestUrlExtension)) { return; } //Check for excludes //Allowed Folders if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Folders)) { string[] foldersToExclude = Utility.GetSocialAuthConfiguration().Allow.Folders.Split(new char[] { '|' }); foreach (string folderName in foldersToExclude) { if (urlWithoutParameters.Contains(host + (host.EndsWith("/") ? "" : "/") + folderName)) { return; } } } //Allowed Files if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Files)) { string[] filesToExclude = Utility.GetSocialAuthConfiguration().Allow.Files.Split(new char[] { '|' }); foreach (string fileName in filesToExclude) { if (Regex.IsMatch(urlWithoutParameters, "/" + fileName.ToLower() + "$")) { return; } } } //If requested page is login URL only, allow it string currentUrl = HttpContext.Current.Request.Url.AbsolutePath; string loginurl = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl; loginurl = string.IsNullOrEmpty(loginurl) ? "socialauth/loginform.sauth" : loginurl; if (currentUrl.ToLower().EndsWith(loginurl.ToLower())) { return; } //If Url is pointing to a .aspx page, authorize it! HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); if (cookie != null) { HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)), null); } else { //User is not logged in SocialAuthUser.RedirectToLoginPage(); } if (HttpContext.Current.Session != null) { if (SocialAuthUser.IsLoggedIn() && HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] == null) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(SessionManager.GetUserSessionGUID().ToString(), false, HttpContext.Current.Session.Timeout); string EncryptedTicket = FormsAuthentication.Encrypt(ticket); cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket); HttpContext.Current.Response.Cookies.Add(cookie); } } } //Often, Forms Cookie persist even where there is no connection. To avoid that!! if (HttpContext.Current.Session != null) { if (SessionManager.ConnectionsCount == 0) { if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null && Utility.GetAuthenticationOption() != AUTHENTICATION_OPTION.FORMS_AUTHENTICATION) { if (SessionManager.GetUserSessionGUID().ToString() != FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name) { SocialAuthUser.Disconnect(); } } } } if (HttpContext.Current.ApplicationInstance.IsSTSaware()) { if (HttpContext.Current.Session != null) { if (SocialAuthUser.IsLoggedIn()) { if (SocialAuthUser.GetCurrentUser().GetProfile() != null) { SocialAuthUser.SetClaims(); } } } } }
protected void Page_Load(object sender, EventArgs e) { HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.Cache.SetNoStore(); Response.Cache.SetExpires(DateTime.Now); Response.Cache.SetValidUntilExpires(true); Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.Cache.SetNoStore(); if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); if (ticket.Expiration <= DateTime.Now) { Response.Redirect("~/PL/Membership/Login.aspx"); }//end if else { Session sessionObject = new Session(); FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMinutes(sessionObject.getSessionTimeLimit()), ticket.IsPersistent, ticket.UserData); string encryptedTicket = FormsAuthentication.Encrypt(newTicket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.Expires = newTicket.Expiration; Response.Cookies.Add(cookie); }//end else }//end if else { Response.Redirect("~/PL/Membership/Login.aspx"); }//end else HttpCookie _authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket _ticket = FormsAuthentication.Decrypt(_authCookie.Value); string username = _ticket.Name; bool recordExists; string errorMessage; Select selectObject = new Select(); recordExists = Select.Select_Natural_Talents(username); errorMessage = selectObject.getErrorMessage(); if (errorMessage != null) { lblError.Text = errorMessage; lblError.Visible = true; ErrorMessage message = new ErrorMessage(); MsgBox(message.SQLServerErrorMessage); }//end if else { if (recordExists == true) { btnSubmit.Visible = false; btnContinue.Visible = true; ArrayList record = new ArrayList(); record = Select.Select_Natural_Talents_Record(username); errorMessage = selectObject.getErrorMessage(); if (errorMessage != null) { lblError.Text = errorMessage; lblError.Visible = true; ErrorMessage message = new ErrorMessage(); MsgBox(message.SQLServerErrorMessage); }//end if else { TextBox4.InnerText = record[0].ToString(); TextBox1.Text = record[1].ToString(); TextBox2.Text = record[2].ToString(); TextBox3.Text = record[3].ToString(); }//end else }//end if }//end else }//end event
/* * FUNCTION : Login_Click * * DESCRIPTION : Validates form against database. If all conform then user is logged in and redirected to corresponding page: * 1. System Admin -> * 2. Institute Admin -> * 3. Basic User -> Mainpage */ protected void Login_Click(object sender, EventArgs e) { checkIfEmpty(password); checkIfEmpty(UserName); if ((checkIfEmpty(password)) && (checkIfEmpty(UserName))) { if (IsValidEmail(UserName.Text)) { CurrentUser.UserName = UserName.Text; string input = password.Text; DataTable dt = new DataTable(); dt = myDAL.returnUserForUsername(CurrentUser.UserName); if (dt.Rows.Count != 0) { foreach (DataRow row in dt.Rows) { int temp; bool retval = Int32.TryParse(row["_user_id"].ToString(), out temp); if (retval) { CurrentUser.UserID = temp; CurrentUser.hashpass = row["_hash"].ToString(); CurrentUser.userSalt = row["_salt"].ToString(); CurrentUser.fname = row["_first_name"].ToString(); CurrentUser.lname = row["_last_name"].ToString(); CurrentUser.userGroupId = row["_user_group_id"].ToString(); CurrentUser.yearOfGraduation = row["_estimated_year_of_graduation"].ToString(); } } } string thishash = CreatePasswordHash(password.Text, CurrentUser.userSalt); if (thishash == CurrentUser.hashpass)//user validated { // ViewState.Add("UserGroup", CurrentUser.userGroupId); string userDataString = string.Concat(CurrentUser.userGroupId, "|", CurrentUser.UserID); // Create the cookie that contains the forms authentication ticket HttpCookie authCookie = FormsAuthentication.GetAuthCookie(UserName.Text, true); // Get the FormsAuthenticationTicket out of the encrypted cookie FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); // Create a new FormsAuthenticationTicket that includes our custom User Data FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString); // Update the authCookie's Value to use the encrypted version of newTicket authCookie.Value = FormsAuthentication.Encrypt(newTicket); // Manually add the authCookie to the Cookies collection Response.Cookies.Add(authCookie); // Determine redirect URL and send user there string redirUrl = FormsAuthentication.GetRedirectUrl(UserName.Text, true); if (CurrentUser.userGroupId == "1") //system admin { Response.Redirect("~/ManageAccounts.aspx", true); } else if (CurrentUser.userGroupId == "2") //institute admin { Response.Redirect("~/AdminSetCourseBooks.aspx"); log.AddEventToLog("System Admin Verified - Redirecting to Manage Accounts", "Audit", "LoginPage"); } else if (CurrentUser.userGroupId == "3") //student user { log.AddEventToLog("Basic User Identity Verified", "Audit", "LoginPage"); //int val = Int32.Parse(ViewState["UserGroup"].ToString()); Response.Redirect("~/MainPage.aspx"); } } else { log.AddEventToLog("Failed Login - Incorrect Password", "Audit", "LoginPage"); failedLogin.Visible = true; failedLogin.ForeColor = System.Drawing.Color.Red; failedLogin.Text = "Failed to Login"; //invalid password } } else { log.AddEventToLog("Failed Login - Incorrect Username", "Audit", "LoginPage"); failedLogin.Visible = true; failedLogin.ForeColor = System.Drawing.Color.Red; failedLogin.Text = "Failed to Login"; //wrong username format } } else { log.AddEventToLog("Failed Login - Empty Field", "Audit", "LoginPage"); failedLogin.Visible = true; failedLogin.ForeColor = System.Drawing.Color.Red; failedLogin.Text = "Failed to Login"; //empty field scenario } }
protected void Page_Load(object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); //Debug.WriteLine(ticket.UserData); if (!ticket.UserData.Contains("Domain Admins")) { MessageBox.Show("No tienes permisos para administrar :("); Response.Redirect("CaseQuestionnaire.aspx"); } else { Table TableCase = (Table)FindControl("TableCase"); int row = 1; string strDSN = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source =|DataDirectory|CaseList.accdb;" + "Persist Security Info = False"; string queryString = "select * from [Case]"; OleDbConnection connection = new OleDbConnection(strDSN); try { connection.Open(); OleDbCommand command = new OleDbCommand(queryString, connection); OleDbDataReader reader = command.ExecuteReader(); while (reader.Read()) { TableRow tRow = new TableRow(); TableCase.Rows.Add(tRow); TableCell tCell = new TableCell(); System.Web.UI.WebControls.CheckBox chk = new System.Web.UI.WebControls.CheckBox(); chk.ID = "row_" + row.ToString(); tCell.Controls.Add(chk); tRow.Cells.Add(tCell); for (int i = 0; i < 12; i++) { tCell = new TableCell(); tCell.Text = reader.GetString(i); tRow.Cells.Add(tCell); } row++; } reader.Close(); } catch (Exception ex) { MessageBox.Show("Failed to connect to data source"); } finally { connection.Close(); } } }
public JsonResult GetGraphforWeek(DateTime RequestedDate) { string empCd = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; DateTime dateToday = RequestedDate; DateTime startDateOFweek = dateToday.Date.AddDays(DayOfWeek.Monday - dateToday.Date.DayOfWeek); DateTime endDateOFweek = startDateOFweek.AddDays(5); RolePrincipal r = (RolePrincipal)User; string role = r.GetRoles().FirstOrDefault(); var jdDataForWeek = unitOfwork.RIC_Job_Report.Get_JobRepoartForUser(empCd, startDateOFweek, endDateOFweek, role). Where(w => w.RJ_Submit_Date >= startDateOFweek && w.RJ_Submit_Date <= endDateOFweek). Select(s => new { SubDate = s.RJ_Submit_Date, empCd = s.RJ_EmpCd }).GroupBy(s => s.SubDate.Date).Select(sg => new { Date = sg.Key, SubList = sg.GroupBy(sl => sl.SubDate.Hour).Select(slg => new { Hour = slg.Key, SubCount = slg.Count() }).ToList() }).OrderBy(o => o.Date).ToList(); // ; List <List <int> > dataForWeek = new List <List <int> >(); // var result =jdDataForWeek for (int day = 0; day <= 4; day++) { DateTime date = startDateOFweek.AddDays(day); List <int> dataforDay = new List <int>(); var subForDay = jdDataForWeek.FirstOrDefault(s => s.Date.Date == date); if (subForDay != null) { for (int j = 5; j <= 24; j++) { var forHour = subForDay.SubList.FirstOrDefault(s => s.Hour == j); dataforDay.Add(forHour != null ? forHour.SubCount : 0); } } dataForWeek.Add(dataforDay); } //foreach (var item in jdDataForWeek) //{ // List<int> dataforDay = new List<int>(); // for (int j = 5; j <= 24; j++) // { // var forHour = item.SubList.FirstOrDefault(s => s.Hour == j); // dataforDay.Add(forHour != null ? forHour.SubCount : 0); // } // dataForWeek.Add(dataforDay); //} //for (int i = 0; i <= 3; i++) //{ // DateTime date = startDateOFweek.AddDays(i); // var details = GetDetails(date, date.AddDays(1), empCd); // List<int> dataforDay=new List<int>(); // for (int j = 5; j <= 24; j++) // { // var forHour= details.FirstOrDefault(s=>s.forHours==j); // dataforDay.Add(forHour != null ? forHour.submissionCount : 0); // } // dataForWeek.Add(dataforDay); //} return(Json(dataForWeek, JsonRequestBehavior.AllowGet)); }
public ActionResult Login(string returnUrl) { HttpCookie existingCookie = Request.Cookies[".ASPXAUTH"]; if (existingCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(existingCookie.Value); if (!ticket.Expired) { LoginModel model = new LoginModel(); model.UserName = ticket.Name; model.RememberMe = true; ViewBag.RememberMeSet = false; Session["userId"] = WebSecurity.GetUserId(model.UserName); var userId = WebSecurity.GetUserId(model.UserName); string[] rolesArray = Roles.GetRolesForUser(); bool isWorking = WebSecurity.CurrentUserId != -1; //Session["subScriptionId"] = _userService.GetUserSubscription(WebSecurity.CurrentUserId)[0].idSubscription; var userInformation = _userService.GetUserInformation(userId); if (userInformation.Acknowledgment == true) { if (userInformation.userLastReportId != null && userInformation.userLastReportId > 0) { var url = ConfigurationManager.AppSettings["SmartSocialWeb"] + "/Home/Main#/MainReport/" + userInformation.userLastReportId; return(Redirect(url)); } else { var userInfo = _userService.GetMainPageInfo(userId, rolesArray, model.UserName); if (userInfo.userSubscriptionsReponse.UserSubscriptionsObjects.Count > 0) { if (userInfo.userSubscriptionsReponse.UserSubscriptionsObjects[0].ServiceSubscription.ServiceDeliveries.Count > 0) { var firstReport = userInfo.userSubscriptionsReponse.UserSubscriptionsObjects[0].ServiceSubscription.ServiceDeliveries.FirstOrDefault().SmartReports.FirstOrDefault().idSmartReport; var url = ConfigurationManager.AppSettings["SmartSocialWeb"] + "/Home/Main#/MainReport/" + firstReport; return(Redirect(url)); } else { var url = ConfigurationManager.AppSettings["SmartSocialWeb"] + "/Home/Main#/NoReport"; return(Redirect(url)); } } else { var url = ConfigurationManager.AppSettings["SmartSocialWeb"] + "/Home/Main#/NoReport"; return(Redirect(url)); } } } } else { return(View()); } } else { ViewBag.RememberMeSet = false; } ViewBag.ReturnUrl = returnUrl; return(View()); }
public void OnAuthentication(AuthenticationContext filterContext) { //var controllerName = filterContext.RouteData.Values["controller"]; //var actionName = filterContext.RouteData.Values["action"]; // if (filterContext.HttpContext.Request.IsAjaxRequest()) // { if ((filterContext.HttpContext.Session == null) || (filterContext.HttpContext.Session["TvmValid"] == null)) { filterContext.Result = new HttpUnauthorizedResult(); return; } var authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { // Unauthorized filterContext.Result = new HttpUnauthorizedResult(); return; } // Get the forms authentication ticket. FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket == null) { filterContext.Result = new HttpUnauthorizedResult(); // mark unauthorized*/ } else { filterContext.HttpContext.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(authTicket.Name, "Forms"), authTicket.UserData.Split(',').Select(t => t.Trim()).ToArray()); UA _ua = (UA)filterContext.HttpContext.Session["TvmValid"]; AppUA appUA = new AppUA(); appUA.RolesCSV = authTicket.UserData; appUA.UserName = _ua.UserName; LoggedUserName = appUA.UserName; SPAccounts.DataAccessObject.DTO.Common common = new SPAccounts.DataAccessObject.DTO.Common(); appUA.DateTime = common.GetCurrentDateTime(); appUA.AppID = _ua.AppID; filterContext.HttpContext.Session.Add("AppUA", appUA); } //} //NON AJAX CALL //else //{ // if ((filterContext.HttpContext.Session == null) || (filterContext.HttpContext.Session["TvmValid"] == null)) // { // filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Index" } }); // return; // } // //// // var authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; // if (authCookie == null) // { // filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Index" } }); // return; // } // // Get the forms authentication ticket. // FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); // // object usercookie = JsonConvert.DeserializeObject(authTicket.UserData); // Up to you to write this Deserialize method -> it should be the reverse of what you did in your Login action // if (authTicket == null) // { // filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Index" } }); // } // else // { // filterContext.HttpContext.User = new System.Security.Principal.GenericPrincipal( // new System.Security.Principal.GenericIdentity(authTicket.Name, "Forms"), authTicket.UserData.Split(',').Select(t => t.Trim()).ToArray()); // } //} }