/// <summary> /// Logs the current user out. /// </summary> public void LogCurrentUserOut() { WebSecurity.Logout(); }
public ActionResult Logout() { WebSecurity.Logout(); return(RedirectToAction("Index", "Home")); }
public ActionResult RemoveExternalLogins() { ICollection <OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name); List <ExternalLogin> externalLogins = new List <ExternalLogin>(); foreach (OAuthAccount account in accounts) { AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider); externalLogins.Add(new ExternalLogin { Provider = account.Provider, ProviderDisplayName = clientData.DisplayName, ProviderUserId = account.ProviderUserId, }); } ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); return(PartialView("_RemoveExternalLoginsPartial", externalLogins)); }
public ActionResult LogOff() { WebSecurity.Logout(); return(RedirectToAction("Index", "Divisions")); }
public ActionResult Index2(int idJogo = 0) { HttpCookie cookie = Request.Cookies["_barragemId"]; var barragemId = 1; var barragemName = "Barragem do Cerrado"; if (cookie != null) { barragemId = Convert.ToInt32(cookie.Value.ToString()); BarragemView barragem = db.BarragemView.Find(barragemId); barragemName = barragem.nome; } ViewBag.NomeBarragem = barragemName; ViewBag.solicitarAtivacao = ""; Jogo jogo = null; var usuario = db.UserProfiles.Find(WebSecurity.GetUserId(User.Identity.Name)); if (idJogo == 0) { try{ jogo = db.Jogo.Where(u => u.desafiado_id == usuario.UserId || u.desafiante_id == usuario.UserId) .OrderByDescending(u => u.Id).Take(1).Single(); } catch (System.InvalidOperationException e) { //ViewBag.MsgAlert = "Não foi possível encontrar jogos em aberto:" + e.Message; } } else { jogo = db.Jogo.Find(idJogo); } if (jogo != null) { //nao permitir edição caso a rodada já esteja fechada e o placar já tenha sido informado string perfil = Roles.GetRolesForUser(User.Identity.Name)[0]; if (!perfil.Equals("admin") && !perfil.Equals("organizador") && (jogo.rodada.isAberta == false) && (jogo.gamesJogados != 0)) { ViewBag.Editar = false; } else { ViewBag.Editar = true; } ViewBag.situacao_Id = new SelectList(db.SituacaoJogo, "Id", "descricao", jogo.situacao_Id); ViewBag.ptDefendidosDesafiado = getPontosDefendidos(jogo.desafiado_id, jogo.rodada_id); ViewBag.ptDefendidosDesafiante = getPontosDefendidos(jogo.desafiante_id, jogo.rodada_id); } if ((usuario.situacao == "desativado") || (usuario.situacao == "pendente")) { ViewBag.solicitarAtivacao = Class.MD5Crypt.Criptografar(usuario.UserName); } // jogos pendentes var dataLimite = DateTime.Now.AddMonths(-10); var jogosPendentes = db.Jogo.Where(u => (u.desafiado_id == usuario.UserId || u.desafiante_id == usuario.UserId) && !u.rodada.isAberta && u.situacao_Id != 4 && u.situacao_Id != 5 && u.rodada.dataInicio > dataLimite).OrderByDescending(u => u.Id).Take(3).ToList(); ViewBag.JogosPendentes = jogosPendentes; // últimos jogos já finalizados var ultimosJogosFinalizados = db.Jogo.Where(u => (u.desafiado_id == usuario.UserId || u.desafiante_id == usuario.UserId) && !u.rodada.isAberta && (u.situacao_Id == 4 || u.situacao_Id == 5)).OrderByDescending(u => u.Id).Take(5).ToList(); ViewBag.JogosFinalizados = ultimosJogosFinalizados; return(View(jogo)); }
public string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false) { return(WebSecurity.CreateUserAndAccount(userName, password, propertyValues)); }
public bool ChangePassword(string userName, string currentPassword, string newPassword) { return(WebSecurity.ChangePassword(userName, currentPassword, newPassword)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.IsChildAction) { Erp.BackOffice.Helpers.Common.TrackRequest(); } //base.OnAuthorization(filterContext); //returns to login url bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); if (skipAuthorization) { return; } base.OnActionExecuting(filterContext); if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("ErpDbContext", "System_User", "Id", "UserName", autoCreateTables: true); } // initialize navigation by user string sControlerName = filterContext.RouteData.Values["Controller"] != null ? filterContext.RouteData.Values["Controller"].ToString().ToLower() : ""; string sActionName = filterContext.RouteData.Values["Action"] != null ? filterContext.RouteData.Values["Action"].ToString().ToLower() : ""; string sAreaName = filterContext.RouteData.DataTokens["area"] != null ? filterContext.RouteData.DataTokens["area"].ToString().ToLower() : ""; //Ngoài những cái login/logoff ... Thì mới init menu if (sActionName != "login".ToLower() && sActionName != "logoff" && sActionName != "forgetpassword") { //Coi thử đăng nhập chưa if (WebSecurity.IsAuthenticated) { if (Helpers.Common.CurrentUser == null) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "User" }, { "action", "logoff" } }); } //Kiểm tra truy cập if (AccessRight(sActionName, sControlerName, sAreaName)) { if (!filterContext.IsChildAction && !filterContext.HttpContext.Request.IsAjaxRequest()) { Dictionary <string, object> userLoggedInfo = new Dictionary <string, object> { { "FullName", Helpers.Common.CurrentUser.FullName }, { "UserName", Helpers.Common.CurrentUser.UserName }, { "UserTypeName", Helpers.Common.CurrentUser.UserTypeName } }; filterContext.Controller.ViewData["UserLogged"] = userLoggedInfo; //Kiểm tra truy cập ok thì init menu initMenu(filterContext, sControlerName, sActionName); } else //nếu request là ajax thì chuyền viewdata page menu rỗng { filterContext.Controller.ViewData["LayoutMenu"] = new List <PageMenuViewModel>(); } } else { if (filterContext.IsChildAction || filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new ContentResult { Content = "" } } ; else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "ErrorPage" }, { "action", "Index" }, { "area", "" } }); } } } else { if (filterContext.IsChildAction || filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new ContentResult { Content = "" } } ; else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "User" }, { "action", "Login" } }); } } } }
public ActionResult EmailToUser(EmailViewModel viewModel) { // Check model state if (!ModelState.IsValid) { ViewBag.Result = false; ViewBag.ResultMessage = "Lütfen belirtilen alanları doldurunuz!"; return(PartialView("_EmailToUser", viewModel)); } try { var fromUserName = WebSecurity.CurrentUserName; var toUser = _context.UserProfiles.FirstOrDefault(p => p.UserId == viewModel.ToUserId); const string view = "EmailTemplate"; var header = string.Format("{0}", viewModel.Subject); var content = viewModel.Body; //... // Check to user email info if (toUser == null) { ViewBag.Result = false; ViewBag.ResultMessage = "Kullanıcı bilgisi bulunamadı!"; return(PartialView("_EmailToUser", viewModel)); } if (string.IsNullOrWhiteSpace(toUser.Email)) { ViewBag.Result = false; ViewBag.ResultMessage = "Kullanıcı email bilgisi bulunamadı!"; return(PartialView("_EmailToUser", viewModel)); } //... // Log sent email var emailLog = new EmailLog { EmailTypeId = 2, FromUserId = WebSecurity.GetUserId(fromUserName), ToUserId = toUser.UserId, Header = header, Content = content, CreateDate = DateTime.Now }; _context.EmailLogs.Add(emailLog); _context.SaveChanges(); //... // Send email header = string.Format("{0} kullanıcısı size bir mesaj gönderdi!", fromUserName); content = string.Format( @"{0} kullanıcısı size {1} başlıklı mesaj gönderdi.<br/> Mesajı okumak için lütfen <a href='http://estudybase.com/Email/EmailBox?EmailId={2}'>tıklayınız.</a>", fromUserName, viewModel.Subject, emailLog.EmailId); MvcMailMessage mvcMailMessage = UserMailer.SendEmail(view, header, content, toUser.Email); mvcMailMessage.Send(); ViewBag.Result = true; ViewBag.ResultMessage = "Email başarıyla gönderildi!"; return(PartialView("_EmailToUser", viewModel)); } catch (Exception exception) { throw new Exception("Error in EmailController.EmailToUser [Post]", exception); } }
private void SeedMembership() { WebSecurity.InitializeDatabaseConnection("MyDatabaseContext", "UserProfile", "UserId", "UserName", autoCreateTables: true); }
protected void ValidateUser(out bool error) { if (EnableRecaptcha) { RecaptchaControl1.Validate(); if (!RecaptchaControl1.IsValid) { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += "The security code you entered is not correct."; error = true; lblError.Visible = true; } } error = false; lblError.Text = ""; var reg = @"^.*(?=.{6,18})(?=.*\d)(?=.*[a-zA-Z]).*$"; var match = Regex.Match(Password.Text, reg, RegexOptions.IgnoreCase); if (!match.Success) { lblError.Text = "Password requirements not met"; error = true; } //if (ddlTitle.SelectedValue == "0") //{ // if (!string.IsNullOrEmpty(lblError.Text)) // lblError.Text += "</br>"; // lblError.Text += "Title is required."; // error = true; // lblError.Visible = true; //} if (ddlState.SelectedValue == "0") { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += "address is required."; lblError.Visible = true; error = true; } if (WebSecurity.UserExists(Username.Text)) { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += SystemConstants.ErrorUsernameTaken; error = true; lblError.Visible = true; } if (new ProviderDAC().ProviderNameExist(txtCompany.Text)) { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += SystemConstants.ErrorOrganisationNameTaken; error = true; lblError.Visible = true; } if (new ProviderDAC().isEmailAddressExist(Email.Text.ToLower())) { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += SystemConstants.ErrorEmailAddressTaken; error = true; lblError.Visible = true; } var emailReg = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; var emailmatch = Regex.Match(Email.Text, emailReg, RegexOptions.IgnoreCase); if (!emailmatch.Success) { if (!string.IsNullOrEmpty(lblError.Text)) { lblError.Text += "</br>"; } lblError.Text += SystemConstants.ErrorInvalidEmail; error = true; lblError.Visible = true; } }
/// <summary> /// Logs the user on. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <param name="rememberMe">if set to <c>true</c> [remember me].</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool LogUserOn(string userName, string password, bool rememberMe) { return(WebSecurity.Login(userName, password, persistCookie: rememberMe)); }
/// <summary> /// Logs the user on. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool LogUserOn(string userName, string password) { return(WebSecurity.Login(userName, password)); }
/// <summary> /// Creates the user and account. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public void CreateUserAndAccount(string userName, string password) { WebSecurity.CreateUserAndAccount(userName, password); }
public bool Login(string userName, string password, bool persistCookie = false) { return(WebSecurity.Login(userName, password, persistCookie)); }
public ActionResult Register(RegisterModel register) { if (ModelState.IsValid) { HttpPostedFileBase fCodeAtt = Request.Files["fCodeAtt"]; HttpPostedFileBase fTaxAtt = Request.Files["fTaxAtt"]; HttpPostedFileBase fCertAtt = Request.Files["fCertAtt"]; HttpPostedFileBase fLicenceAtt = Request.Files["fLicenceAtt"]; HttpPostedFileBase fDelegateBook = Request.Files["fDelegateBook"]; //**************** 委托书 ************** HttpPostedFileBase fPromiseAtt = Request.Files["fPromiseAtt"]; HttpPostedFileBase fSecretAtt = Request.Files["fSecretAtt"]; HttpPostedFileBase fPeopleAtt = Request.Files["fPeopleAtt"]; //**************** 委托书 ************** if (fCodeAtt == null || fTaxAtt == null || fCertAtt == null || fLicenceAtt == null || fDelegateBook == null || fPromiseAtt == null) { return(Content("error file is null")); } if (Path.GetExtension(fCodeAtt.FileName).ToLower().EndsWith("exe") || Path.GetExtension(fTaxAtt.FileName).ToLower().EndsWith("exe") || Path.GetExtension(fCertAtt.FileName).ToLower().EndsWith("exe") || Path.GetExtension(fCertAtt.FileName).ToLower().EndsWith("exe") || //**************** 委托书 ************** Path.GetExtension(fPromiseAtt.FileName).ToLower().EndsWith("exe") || Path.GetExtension(fDelegateBook.FileName).ToLower().EndsWith("exe")) { return(Content("请上传办公文件或压缩文件")); } //using( TransactionScope scope=new TransactionScope()) //{ WebSecurity.CreateUserAndAccount(register.bemplyee.NumberEmp, register.Password); BEmplyee emp = db.BEmplyees.Single(m => m.NumberEmp.Equals(register.bemplyee.NumberEmp)); emp.CopyFrom(register.bemplyee); //**************** 保密协议 ************** emp.SecretAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fSecretAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.SecretAtt.Substring(0, 4) + @"\" + emp.SecretAtt.Substring(4, 4) + @"\"))); fSecretAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.SecretAtt.Substring(0, 4) + @"\" + emp.SecretAtt.Substring(4, 4) + @"\" + emp.SecretAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.SecretAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fSecretAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fSecretAtt.FileName), "DbType.String", null }, { "@Size", fSecretAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } //*******************资格证明*********** //**************** 保密协议 ************** emp.PeopleAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fPeopleAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.PeopleAtt.Substring(0, 4) + @"\" + emp.PeopleAtt.Substring(4, 4) + @"\"))); fPeopleAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.PeopleAtt.Substring(0, 4) + @"\" + emp.PeopleAtt.Substring(4, 4) + @"\" + emp.PeopleAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.PeopleAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fPeopleAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fPeopleAtt.FileName), "DbType.String", null }, { "@Size", fPeopleAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } //**************** 委托书 ************** emp.PromiseAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fPromiseAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.PromiseAtt.Substring(0, 4) + @"\" + emp.PromiseAtt.Substring(4, 4) + @"\"))); fPromiseAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.PromiseAtt.Substring(0, 4) + @"\" + emp.PromiseAtt.Substring(4, 4) + @"\" + emp.PromiseAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.PromiseAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fPromiseAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fPromiseAtt.FileName), "DbType.String", null }, { "@Size", fPromiseAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.CodeAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fCodeAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.CodeAtt.Substring(0, 4) + @"\" + emp.CodeAtt.Substring(4, 4) + @"\"))); fCodeAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.CodeAtt.Substring(0, 4) + @"\" + emp.CodeAtt.Substring(4, 4) + @"\" + emp.CodeAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.CodeAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fCodeAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fCodeAtt.FileName), "DbType.String", null }, { "@Size", fCodeAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.TaxAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fTaxAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.TaxAtt.Substring(0, 4) + @"\" + emp.TaxAtt.Substring(4, 4) + @"\"))); fTaxAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.TaxAtt.Substring(0, 4) + @"\" + emp.TaxAtt.Substring(4, 4) + @"\" + emp.TaxAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.TaxAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fTaxAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fTaxAtt.FileName), "DbType.String", null }, { "@Size", fTaxAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.CertAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fCertAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.CertAtt.Substring(0, 4) + @"\" + emp.CertAtt.Substring(4, 4) + @"\"))); fCertAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.CertAtt.Substring(0, 4) + @"\" + emp.CertAtt.Substring(4, 4) + @"\" + emp.CertAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.CertAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fCertAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fCertAtt.FileName), "DbType.String", null }, { "@Size", fCertAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.LicenceAtt = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fLicenceAtt != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.LicenceAtt.Substring(0, 4) + @"\" + emp.LicenceAtt.Substring(4, 4) + @"\"))); fLicenceAtt.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.LicenceAtt.Substring(0, 4) + @"\" + emp.LicenceAtt.Substring(4, 4) + @"\" + emp.LicenceAtt.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.LicenceAtt, "DbType.String", null }, { "@Name", Path.GetFileName(fLicenceAtt.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fLicenceAtt.FileName), "DbType.String", null }, { "@Size", fLicenceAtt.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.DelegateBook = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N"); if (fDelegateBook != null) { Directory.CreateDirectory(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.DelegateBook.Substring(0, 4) + @"\" + emp.DelegateBook.Substring(4, 4) + @"\"))); fDelegateBook.SaveAs(Path.Combine(System.Web.Configuration.WebConfigurationManager.AppSettings["AttachmentRootPath"], (emp.DelegateBook.Substring(0, 4) + @"\" + emp.DelegateBook.Substring(4, 4) + @"\" + emp.DelegateBook.Substring(8)))); GenericDataAccess.UpdateBySql("Insert into YZAppAttachment(FileID,Name,Ext,Size,OwnerAccount) values(@FileID,@Name,@Ext,@Size,@OwnerAccount)", new string[, ] { { "@FileID", emp.DelegateBook, "DbType.String", null }, { "@Name", Path.GetFileName(fDelegateBook.FileName), "DbType.String", null }, { "@Ext", Path.GetExtension(fDelegateBook.FileName), "DbType.String", null }, { "@Size", fDelegateBook.ContentLength.ToString(), "DbType.Int32", null }, { "@OwnerAccount", "0", "DbType.String", null } }); } emp.RegisterDate = System.DateTime.Now; db.SaveChanges(); //WebSecurity.Login(emp.NumberEmp, register.Password); //System.Web.Routing.RouteValueDictionary routv= new System.Web.Routing.RouteValueDictionary(); //routv.Add("EmpID","6"); //return RedirectToAction("Create", "Tender_CompanyInfo", routv); // scope.Complete(); //} return(Content("注册成功!请登录")); //return RedirectToLocal("/"); } return(View()); }
public void Logout() { WebSecurity.Logout(); }
protected void btnLogOut_Click(object sender, EventArgs e) { WebSecurity.Logout(); Response.Redirect("Login.aspx"); }
public int GetUserId(string userName) { return(WebSecurity.GetUserId(userName)); }
public ActionResult Logout() { WebSecurity.Logout(); return(RedirectToAction("Default", "Gallery")); }
public string CreateAccount(string userName, string password, bool requireConfirmationToken = false) { return(WebSecurity.CreateAccount(userName, password, requireConfirmationToken)); }
public ActionResult Logout() { WebSecurity.Logout(); return(RedirectToAction("Login")); }
public ActionResult LogOff() { WebSecurity.Logout(); return(RedirectToAction("DatosGen", "Postulacion")); }
public ActionResult Register(mdl_Login model) { WebSecurity.CreateUserAndAccount(model.Username, model.Password); Response.Redirect("~/account/login"); return(View()); }
public ActionResult RemoveExternalLogins() { var accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name); var externalLogins = (from account in accounts let clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider) select new ExternalLogin { Provider = account.Provider, ProviderDisplayName = clientData.DisplayName, ProviderUserId = account.ProviderUserId }).ToList(); ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); return(PartialView("_RemoveExternalLoginsPartial", externalLogins)); }
/// <summary> /// Metodo utilizado para inicializar la configuración del /// plugin WebSecurity, y la inicialización de la conexión /// de la base de datos, tomando en cuenta la tabla de la /// base de datos que almacenará los datos de los usuarios /// de la aplicación. También en este método se insertan los /// datos por defecto requeridos para el mínimo funcionamiento /// de la aplicación, tales como roles y un usuario por defecto. /// </summary> public static void RegisterWebSec() { ///inizializar el websecurity, especificando la tabla ///que guardará los datos básicos de usuario. WebSecurity.InitializeDatabaseConnection ( "SIGECContext", "Users", "ID", "username", autoCreateTables: true ); ///creación de la cuenta por defecto de administrador. if (!WebSecurity.UserExists("admin")) { using (SIGECContext db = new SIGECContext()) { Address a = new Address(); a.city = "Ciudad"; a.municipality = "Municipio"; a.sector = "Sector"; a.street = "Calle"; a.number = "Numero"; a.country = "Republica Dominicana"; var passwordHelper = new PasswordHelper(); passwordHelper.HashPassword("123456"); db.Addresses.Add(a); var user = new User(); user.username = "******"; user.password = PWDTK.HashBytesToHexString(passwordHelper.Hash); user.salt = PWDTK.HashBytesToHexString(passwordHelper.Salt); user.bornDate = DateTime.Now; user.createDate = DateTime.Now; user.email = "*****@*****.**"; user.status = true; user.gender = "M"; user.maritalStatus = "S"; user.dni = "00000000000"; user.firstName = "admin"; user.lastName = "istrador"; user.occupation = "Super Admin"; db.Users.Add(user); user.Address = a; db.SaveChanges(); } } var roles = (SimpleRoleProvider)Roles.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (!roles.GetRolesForUser("admin").Contains("Admin")) { roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); } ///insertar datos de menús y acciones en la base de datos ///para el manejo de permisos. //GlobalHelpers.InsertMenusAndActions(); ///asignar permisos sobre todas las acciones al rol Admin using (var db = new SIGECContext()) { var adminRole = db.webpages_Roles.FirstOrDefault(r => r.RoleName == "Admin"); foreach (SIGEC.Models.Action a in db.Actions) { if (!adminRole.Actions.Contains(a)) { adminRole.Actions.Add(a); } } db.Entry(adminRole).State = System.Data.EntityState.Modified; db.SaveChanges(); } }
public ActionResult Create(UserMerchantViewModel userMerchantViewModel, HttpPostedFileBase file) { logger.Info("Create Post Method Start" + " at " + DateTime.UtcNow); EasyPayContext dbContext = new EasyPayContext(); string path = utils.SaveFile(file); Merchant thisMerchant = new Merchant(); RegisterModel registerModel = new RegisterModel(); if (userMerchantViewModel != null) { thisMerchant.Address = registerModel.Address = userMerchantViewModel.Merchant.Address; thisMerchant.CategoryId = userMerchantViewModel.Merchant.CategoryId; thisMerchant.City = registerModel.City = userMerchantViewModel.Merchant.City; thisMerchant.ContactNo = userMerchantViewModel.Merchant.ContactNo; thisMerchant.EmailId = registerModel.Email = userMerchantViewModel.Merchant.EmailId; thisMerchant.LogoImagePath = path; thisMerchant.MerchantName = userMerchantViewModel.Merchant.MerchantName; thisMerchant.PostalCode = registerModel.PostalCode = userMerchantViewModel.Merchant.PostalCode; thisMerchant.State_StateID = Convert.ToInt32(userMerchantViewModel.RegisterModel.StateID); thisMerchant.Terms = userMerchantViewModel.Merchant.Terms; thisMerchant.URL = userMerchantViewModel.Merchant.URL; registerModel.UserName = userMerchantViewModel.RegisterModel.UserName; registerModel.StateID = userMerchantViewModel.RegisterModel.StateID; registerModel.Phone = userMerchantViewModel.Merchant.ContactNo; registerModel.Password = userMerchantViewModel.RegisterModel.Password; registerModel.ConfirmPassword = userMerchantViewModel.RegisterModel.Password; AccountController AccountController = new Controllers.AccountController(); string dbToken = AccountController.RegisterUser(registerModel); var userId = dbContext.UserProfiles.Where(p => p.UserName == registerModel.UserName).Select(u => u.UserProfileId).FirstOrDefault(); thisMerchant.UserProfileId = userId; dbContext.Merchants.Add(thisMerchant); WebSecurity.ConfirmAccount(userMerchantViewModel.RegisterModel.UserName, dbToken); dbContext.SaveChanges(); logger.Info("Create Post Method New Merchant Created " + " at " + DateTime.UtcNow); //EasyPayContext dbContext1 = new EasyPayContext(); //EasyPay.Models.Membership membership = dbContext1.Memberships.Where(m => m.UserId == userId).FirstOrDefault(); ////var confirm = dbContext1.Memberships.Where(m => m.UserId == userId).FirstOrDefault(); //if (membership.IsConfirmed == false) //{ // membership.IsConfirmed = true; // dbContext1.SaveChanges(); //} EasyPayContext dbContext2 = new EasyPayContext(); string newRoleName = "Merchant"; if (!Roles.RoleExists(newRoleName)) { logger.Info("Create new Role Merchant" + " at " + DateTime.UtcNow); Roles.CreateRole(newRoleName); } var checkUserRole = dbContext2.UsersInRoles.ToList().FirstOrDefault(r => r.UserId == userId); if (checkUserRole == null) { logger.Info("Assign role Merchant to User " + userId + " at " + DateTime.UtcNow); dbContext2.UsersInRoles.Add(new UsersInRole() { RoleId = dbContext2.Roles.Where(r => r.RoleName == newRoleName).Select(r => r.RoleId).FirstOrDefault(), UserId = userId //RoleId=Roles. }); dbContext2.SaveChanges(); } logger.Info("Method End" + " at " + DateTime.UtcNow); return RedirectToAction("Index"); } ViewBag.CategoryId = new SelectList(dbContext.Categories, "CategoryId", "CategoryName", userMerchantViewModel.Merchant.CategoryId); logger.Info("Create Method End" + " at " + DateTime.UtcNow); return View(userMerchantViewModel); //return View(); }
protected void Application_Start() { XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/log4net.xml"))); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoMapperConfig.RegisterMaps(); var username = "******"; var roles = Roles.GetAllRoles(); if (!roles.Any(x => x == RoleName.Admin)) { Roles.CreateRole(RoleName.Admin); } if (!roles.Any(x => x == RoleName.Customer)) { Roles.CreateRole(RoleName.Customer); } var admin = Membership.GetUser(username); if (admin == null) { WebSecurity.CreateUserAndAccount(username, "apcurium5200!"); } if (!Roles.IsUserInRole(username, RoleName.Admin)) { Roles.AddUserToRole(username, RoleName.Admin); } if (!Roles.IsUserInRole(username, RoleName.Customer)) { Roles.AddUserToRole(username, RoleName.Customer); } GlobalConfiguration.Configuration.EnsureInitialized(); DeleteTempFiles(); //EnsureEnvironnementsAreInit(); EnsureMenuColorIsSet(); EnsureDefaultDevicesAreInit(); EnsureDefaultSettingsAreInit(); MigrateNetworkVehiclesToMarketRepresentation(); MigrateCompanyRegionToMarketRegion(); Mapper.CreateMap <EmailSender.SmtpConfiguration, SmtpClient>() .ForMember(x => x.Credentials, opt => opt.MapFrom(x => new NetworkCredential(x.Username, x.Password))); var enableWatchDog = (bool)new AppSettingsReader().GetValue("EnableWatchDog", typeof(bool)); if (enableWatchDog) { StartStatusUpdater(TimeSpan.FromMilliseconds(100)); } }
public ActionResult LogOff() { WebSecurity.Logout(); Session.Abandon(); return(RedirectToAction("Index", "Home")); }
//[ValidateAntiForgeryToken] public HttpResponseMessage Logout() { WebSecurity.Logout(); return(Request.CreateResponse(HttpStatusCode.OK)); }