public FunctionResult <LoginToken> UserLogin(string loginKey, string pwd) { var r = new FunctionResult <LoginToken>(); pwd = Encryption(pwd); LoginInfo data = LoginDal.Login(loginKey, pwd); if (data != null) { var token = new LoginToken() { UserId = data.UserId, Token = GetToken() }; if (LoginTokenDal.Add(token) > 0) { r.Data = token; RedisService.Set <LoginToken>(DefineTable.CacheName, String.Format(UserAuthorityCacheKey.AuthorityCacheKey, token.Token), token); } else { r.ErrorMsg = "无法获取标识"; } } else { r.ErrorMsg = "无匹配用户登陆信息"; } return(r); }
public ParticipantDto CheckLogin(LoginDto objLoginDto) { ParticipantDto objCheck = new ParticipantDto(); try { LoginDal objLoginDal = new LoginDal(); User objLogin = new User(); objLogin.Email = Convert.ToString(objLoginDto.Email); objLogin.Password = Convert.ToString(objLoginDto.Password); User objNew = new User(); objNew = objLoginDal.CheckLogin(objLogin); objCheck.Education = objNew.Education; objCheck.Email = objNew.Email; objCheck.FirstName = objNew.FirstName; objCheck.LastName = objNew.LastName; objCheck.Mobile = objNew.Mobile; objCheck.UserID = objNew.UserID; } catch (FormatException ex) { throw ex; } return(objCheck); }
public FunctionResult <JobToken> MobileLogin(string mobile, string code) { var r = new FunctionResult <JobToken>(); LoginInfo data = LoginDal.MobileLogin(mobile, code); if (data != null) { var jobToken = new JobToken() { JobId = GetJobId(data.UserId), UserId = data.UserId, Token = GetToken() }; if (JobTokenDal.Add(jobToken) > 0) { r.Data = jobToken; } else { r.ErrorMsg = "无法获取标识"; } } else { r.ErrorMsg = "无匹配用户登陆信息"; } return(r); }
public ActionResult Index(LoginModel l) { Login log; ActionResult actRes; LoginDal helper = new LoginDal(); try { log = helper.getLogin(l.login.Usuario, l.login.Passwd); if (log == null) { l.ErrorMessage = "Error, nombre de usuario o password no validos."; actRes = View(l); } else { //creamos el objeto de sesion Session["usuario"] = log; actRes = RedirectToAction("Home"); } } catch (SqlException e) { l.ErrorMessage = "Problemas al conectar a la bbdd. " + e.Message; actRes = View(l); } catch (InvalidOperationException e) { l.ErrorMessage = "Problemas al conectar a la bbdd. " + e.Message; actRes = View(l); } return(actRes); }
/// <summary> /// 用户登录 /// </summary> /// <param name="model">传递有用户名和密码的实体,若存在此用户(登录成功),其实体对象将对带回</param> /// <returns>1:登录成功 -1:用户名或密码错误</returns> public int user_Login(VwUserModel model) { LoginDal dal = new LoginDal(); VwUserModel userModel = dal.getByUserCodeAndPwd(model.UserCode, model.Password); int code = -1; if (userModel != null) { // 如果存在此用户,则将其赋值给形参,方便调用者获取此用户详细信息,利用引用类型特点 // 注意,不能直接这样赋值,这样直接改变了一会形参的指针,不再指向实参,而是指向方法内 studentModel //model = studentModel; model.Id = userModel.Id; model.UserName = userModel.UserName; model.Telephone = userModel.Telephone; model.IdCard = userModel.IdCard; model.Gender = userModel.Gender; // 注意,返回的是加密后的密码 model.Password = userModel.Password; model.Dept = userModel.Dept; model.RoleId = userModel.RoleId; // 标记存在此用户,密码 code = 1; } return(code); }
public static Result Login(LoginDto dto) { Result result = new Result() { Code = 0 }; try { if (dto == null) { result.Message = "传参有误"; return(result); } if (string.IsNullOrWhiteSpace(dto.UserName) || string.IsNullOrWhiteSpace(dto.UserPwd)) { result.Message = "用户名或密码不可为空"; return(result); } DataTable dt = LoginDal.GetEmpDT(dto.UserName, ExHelper.MD5Hash(dto.UserPwd).ToLower()); if (dt == null || dt.Rows.Count <= 0) { result.Message = "登录失败"; return(result); } LoginDataDto dataDto = dt.ToDtDto <LoginDataDto>(); //dataDto.UserMenuJson = MenuBll.GetMenuListForZtree(dataDto.UserId); var token = "";//TokenHelper.CreatToken(dataDto); var red = RedisHelper.Get <LoginDataDto>(token); if (red != null) { result.Code = 1; result.Message = "登录成功"; result.Obj = token; return(result); } if (RedisHelper.Set(token, dataDto, 43200)) { result.Code = 1; result.Message = "登录成功"; result.Obj = token; } else { result.Message = "缓存服务器异常"; } return(result); } catch (Exception ex) { result.Message = ex.Message; return(result); } }
public bool CheckLogin(LoginDto objLoginDto) { bool status=false; LoginDal objLoginDal = new LoginDal(); Login objLogin = new Login(); objLogin.UserName = objLoginDto.UserName; objLogin.Password = objLoginDto.Password; status = objLoginDal.CheckLogin(objLogin); return status; }
public JsonResult sele() { JsonResult json = new JsonResult(); LoginDal dal = new LoginDal(); List <employee> list = dal.List(); string obj = JsonConvert.SerializeObject(new { data = list }); json.Data = new { Data = list }; json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(json); }
private void btnIngresar_Click(object sender, RoutedEventArgs e) { if (txtNombreUsuario.Text != "" && txtPassword.Password != "") { try { if (!LoginDal.ExisteUsuario(txtNombreUsuario.Text, txtPassword.Password)) { tbkDetalle.Text = "Intente De Nuevo :)"; cont++; txtNombreUsuario.Clear(); txtPassword.Clear(); txtNombreUsuario.Focus(); if (cont > 3) { MessageBox.Show("Demasiado intentos"); this.Close(); } return; } else { User usuario = UserBrl.ObtenerIdUsuario(txtNombreUsuario.Text); if (usuario.PasswordState == 1) { MessageBox.Show("Es necesario Cambiar password"); } else if (usuario.PasswordState == 0) { User usuarioSession = UserBrl.ObtenerSession(txtNombreUsuario.Text, txtPassword.Password); MenuInicio menuPrincipal = new MenuInicio(usuarioSession); menuPrincipal.Show(); this.Close(); } } } catch (Exception ex) { throw ex; } } else { tbkDetalle.Text = "Es necesario llenar los campos"; cont++; if (cont > 3) { MessageBox.Show("Demasiado intentos"); this.Close(); } } }
private void btnEnter_Click(object sender, RoutedEventArgs e) { string lUser = ""; string lPassword = ""; lUser = txtUser.Text; lPassword = txtPassword.Password; var lLoginDal = new LoginDal(); DataTable lDt = lLoginDal.GetUser(lUser, lPassword); //DESENCRYPTA LA CONTRASEÑA byte[] data = Encoding.UTF8.GetBytes(lPassword); HashAlgorithm hash = new SHA1Managed(); byte[] hashBytes = hash.ComputeHash(data); String hashValue = BitConverter.ToString(hashBytes).Replace("-", ""); if (lDt.Rows.Count >= 1) { if ((string)lDt.Rows[0]["Usuario"] == lUser && lDt.Rows[0]["Password"].ToString().ToUpper() == hashValue) { ControlDePacientes.Entities.GlobalUser.Idusuario = (int)lDt.Rows[0]["IdUsuario"]; // MessageBox.Show("Usuario existe en la base de Datos", "Mensaje"); DockGeneral lDockGeneral = new DockGeneral(); this.Close(); lDockGeneral.mIdTipoUsuario = (int)lDt.Rows[0]["CodTipoUsuario"]; lDockGeneral.mUserName = (string)lDt.Rows[0]["Usuario"]; lDockGeneral.ShowDialog(); } else { ControlOperation.alertWarning("Usuario no existe "); txtUser.Text = ""; txtPassword.Password = ""; txtUser.Focus(); } } else { ControlOperation.alertWarning("Usuario no existe "); txtUser.Text = ""; txtPassword.Password = ""; txtUser.Focus(); } }
public bool acessar(String login, String senha) { //instanciando outra classe LoginDal loginDal = new LoginDal(); // Nessa classe será usada o método verificar login e serão passadas as informações escritas pelo usuário // Nessa variavel tem retornará sim ou não tem = loginDal.verificarLogin(login, senha); if (!loginDal.mensagem.Equals("")) { this.mensagem = loginDal.mensagem; } return(tem); // retorna para o formulário }
public void Test() { //assemble bool b; LoginDal dal = new LoginDal(); User u = new User(); u.Gebruikersnaam = "gehadasdf"; u.Wachtwoord = "Something2132"; //act b = dal.Registreer(u); //assert Assert.AreEqual(true, b); }
public ActionResult ForgetPass(LoginModel m) { LoginDal logindal = new LoginDal(); if (!logindal.EmailExist(m.Email)) { ViewBag.femail = "Email Id not Registered"; return(View()); } Passenger p = new Passenger(); p.Email = m.Email; p.Pwd = m.Pwd; logindal.ChangePassword(p); ViewBag.msg = "Password Changed Successfully!!"; return(View()); }
//public bool signin() //{ // try // { // LumexDBPlayer db = LumexDBPlayer.Start(true); // bool status = userregDal.signin(this, db); // db.Stop(); // return status; // } // catch (Exception) // { // throw; // } //} public bool VerifyPassword() { try { LumexDBPlayer db = LumexDBPlayer.Start(); LoginDal logdal = new LoginDal(); bool status = logdal.VerifyPassword(this, db); db.Stop(); return(status); } catch (Exception) { throw; } }
public ActionResult LoginUser(Passenger p) { LoginDal logindal = new LoginDal(); if (logindal.VerifyData(p) == 0) { ViewBag.errormsg = "No such User Exists!!"; } else if (logindal.VerifyData(p) == -1) { ViewBag.errormsg = "Userid / Password is incorrect"; } else { return(RedirectToAction("Index")); } return(View()); }
public async Task <string> Login(string info) { var userInfo = JsonConvert.DeserializeObject <UserInfo>(info); if (string.IsNullOrWhiteSpace(userInfo.Account)) { return(JsonConvert.SerializeObject(new { status = "fail", message = "账号不能为空", date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })); } if (string.IsNullOrWhiteSpace(userInfo.Password)) { return(JsonConvert.SerializeObject(new { status = "fail", message = "密码不能为空", date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })); } LoginDal dal = new LoginDal(); var result = await dal.Login(userInfo.Account, userInfo.Password); if (result.ResultCode != 0) { return(JsonConvert.SerializeObject(new { status = "fail", message = result.ResultMsg, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })); } return(JsonConvert.SerializeObject(new { status = "success", data = result.Data, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Token = GetToken() })); }
private void LoginButton_Click(object sender, EventArgs e) { //check username and password is empty or not if (string.IsNullOrEmpty(UserNameTextBox.Text) || string.IsNullOrEmpty(PasswordTextBox.Text)) { if (string.IsNullOrEmpty(UserNameTextBox.Text)) { UserNameTextBox.Focus(); errorProvider1.SetError(UserNameTextBox, "Please enter username"); }//end of string.IsNullOrEmpty(UserNameTextBox.Text)) else { PasswordTextBox.Focus(); errorProvider1.SetError(PasswordTextBox, "Please enter password"); }////end of settinng password text box error } else { LoginDal logInDataAccess = new LoginDal(); // created an object to invoke the login data access connection in the DAL. Login _loginDetails = new Login { UserName = UserNameTextBox.Text, PassWord = PasswordTextBox.Text }; int recordsCount = logInDataAccess.GetuserDetails(_loginDetails); //this statement acts multipurpose 1)recordsCount acts as variable for checking number of rows retrived 2) for validating the entered user details if (recordsCount > 0) // when the username and password matches one row will be retrived from the database so count is > 0 { this.Hide(); AdminMenuForm menuFm = new AdminMenuForm(); menuFm.Closed += (s, args) => this.Close(); // if username and password matches by using delegate property the current form will be hidden and admin menu form is shown. menuFm.Show(); } else { ErrorMessagelabel.Visible = true; //MessageBox.Show("Please enter Correct Username and Password"); // errorProvider1.SetError(UserNameTextBox, "User Name is Invaldi"); } } }
public void ingresar() { var usuario = txtUsuario.Text; var password = txtPassword.Text; LoginDal ingreso = new LoginDal(); var logueo = ingreso.login(usuario, password); if (logueo != null) { Session["idUsuario"] = logueo[0].Id; Response.Redirect("~/Default.aspx"); } else { Response.Write("<script language=javascript>alert('Usuario o Password incorrecto');</script>"); Response.Redirect("~/Login.aspx"); } }
public LoginBll GetUserById(string userId) { LumexDBPlayer db = LumexDBPlayer.Start(); try { LoginBll user = LoginDal.GetUserById(userId, db); db.Stop(); return(user); } catch (Exception) { throw; } finally { db.Stop(); } }
public ActionResult Register(LoginModel ld) { LoginDal logindal = new LoginDal(); if (logindal.EmailExist(ld.Email)) { ViewBag.erroremail = "Email Already Registered"; return(View()); } Passenger p = new Passenger(); p.Email = ld.Email; p.FName = ld.FName; p.LName = ld.LName; p.Age = ld.Age; p.PhoneNo = Convert.ToInt64(ld.PhoneNo); p.Pwd = ld.Pwd; logindal.InsetData(p); return(View()); }
public JsonResult LoginIn(string name = "", string pwd = "") { LoginDal dal = new LoginDal(); List <employee> emy = dal.LoginSel(name, pwd); JsonResult jsonResult = new JsonResult(); if (emy != null && emy.Count >= 1) { string json = JsonConvert.SerializeObject(emy.FirstOrDefault()); HttpCookie cookie = new HttpCookie("Login", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(json))); Response.Cookies.Add(cookie); jsonResult.Data = new { data = json, state = "200" }; jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(jsonResult); } else { jsonResult.Data = new { data = "未找到用户!", state = "403" }; return(jsonResult); } }
public ActionResult sumbit() { Login loge = new Login(); if (ModelState.IsValid) { loge.user_name = Request.Form["username"]; loge.password = Request.Form["password"]; LoginDal dal = new LoginDal(); List <Login> logins = dal.log.ToList <Login>(); foreach (Login l in logins) { if (l.user_name.Equals(loge.user_name) && l.password.Equals(loge.password)) { if (l.type == 0) { return(View("sce")); } else if (l.type == 1) { return(View("Lec")); } else { return(View("Fac")); } } } } return(View("Login", loge)); }
public ActionResult LoginAction(LoginModel login) { LoginBal bdata = new LoginBal(); bdata.UserId = login.UserId; bdata.Password = login.Password; LoginDal ddata = new LoginDal(); bool status = ddata.Login(bdata); //session sending login id to every page..... Session["loginid"] = bdata.UserId; if (status) { return(RedirectToAction("SignUp")); } else { return(View()); } }
public ActionResult Submit(Admin admin) { LoginDal dal = new LoginDal(); //Userview user = new Userview(); String id = admin.Id; String firstname = admin.FirstName; String lastname = admin.LastName; String permission = admin.Permmision; String password = admin.Password; String username = admin.UserName; List <Admin> objectus = (from x in dal.Users where x.Id == id select x).ToList <Admin>(); if (ModelState.IsValid) { dal.Users.Add(admin); dal.SaveChanges(); } return(View("Adduser", admin)); }
public ActionResult Submit(Login log) { LoginDal dal = new LoginDal(); LoginDal dal1 = new LoginDal(); Userview user = new Userview(); String username1 = log.Username; String password = log.Password; List <Login> objectus = (from x in dal.Userslogin where x.Username == username1 && x.Password == password select x).ToList <Login>(); if (ModelState.IsValid && objectus.Count == 1) { ViewBag.Current = user; user.Login_Use = objectus.First <Login>(); if (user.Login_Use.Permmision.Equals("Admin")) { Session["User"] = username1; Session["Pass"] = password; Session["Per"] = "Admin"; return(RedirectToRoute("Startpageadmin")); } if (user.Login_Use.Permmision.Equals("Lecturer")) { return(View("Present2", log)); } if (user.Login_Use.Permmision.Equals("Student")) { return(View("Present3", log)); } } dal.SaveChanges(); dal1.SaveChanges(); return(View("LoginPage", log)); }
private void btn_Login_Click(object sender, RoutedEventArgs e) { var Name = tb_UserName.Text.ToString(); IntPtr p = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(this.tb_password.SecurePassword); // 使用.NET内部算法把IntPtr指向处的字符集合转换成字符串 string password = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(p); if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(password)) { var info = new LoginDal().Get(Name, password); // var info = HttpClientHelp.dooGet<ApiRetMsg<APIUserBaseModel>>(ApiUrl.GetLogin); if (info.Status != 1) { var user = new GetUserInfo(info.Data.ID, info.Data.VenueId, info.Data.Token, info.Data.AccountName); this.DialogResult = true; } else { MessageBox.Show(info.ErrorMsg); } } }
public IActionResult Index(Login login, IFormCollection frm, LoginDal loginDal) { //ModelState.IsValid : eu li que o atributo "asp-for" presente nas tags já direcionava os dados automaticamente para o Model. //Porém, isso não funcionou. Logo, tive que injetar manualmente os dados das tags para os atributos do Model. if (ModelState.IsValid) { login.NmEmail = frm["txtEmail"]; login.NmSenha = frm["txtSenha"]; //Verifica se é um Responsável, Professor, Secretária ou Diretor. if (frm["Autorizacao"] == "Professor") { login.CdAutorizacao = 1; } else if (frm["Autorizacao"] == "Responsavel") { login.CdAutorizacao = 2; } else if (frm["Autorizacao"] == "Secretaria") { login.CdAutorizacao = 3; } else { login.CdAutorizacao = 4; } //Aqui eu instancio o método da classe para uma variável para poupar processamento. //Só necessitarei do retorno do método e não de seu processamento. string retornoVerificaLogin = loginDal.VerificaUsuario(login); //Se o Banco retornar "Sim", logo eu armazenarei tudo nas Sessions para utilização posterior. if (retornoVerificaLogin == "Sim") { string SessionEmail = login.NmEmail; string SessionSenha = login.NmSenha; int SessionAutorizacao = login.CdAutorizacao; //Estas sessions deram um trabalho. Primeiro preciso utilizar seus serviços em Startup.cs. //Portanto, todas as configurações como validade e outros estão dentro de Services na classe Startup.cs do projeto. HttpContext.Session.SetString("Email", SessionEmail); HttpContext.Session.SetString("Senha", SessionSenha); HttpContext.Session.SetInt32("Autorizacao", SessionAutorizacao); //Após verificado o Login, posso voltar a minha Pagina Inicial. //O _Layout carregado será definido em _ViewStart.cshtml. return(RedirectToAction("Index", "Home")); } else if (retornoVerificaLogin == "Nao") { //Talvez essa lógica seja deprimente, porém é um bom desencargo de consciência. //Caso dê algum erro, será carregada a mesma View com o Alert Message ViewData["Resultado"] = 2; return(View()); } else { //Caso dê algum erro, será carregada a mesma View com o Alert Message. Neste caso o usuário pesquisado não existe. ViewData["Resultado"] = 3; return(View()); } } //Caso ocorra nada... return(View()); }
/// <summary>验证登录 /// </summary> /// <returns>2 具有访问权限 1 没有权限 0 未登录</returns> public int chekLogin(ref string uid, bool liwai, List <RightEntity> userRights) { int result = 0; string sign = CookieFunc.ReadCookie(CoSignKey); if (sign != null && sign != string.Empty) { uid = string.Empty; string pwd = string.Empty; DateTime dt = DateTime.Now; if (design(sign, ref uid, ref pwd, ref dt)) { if (dt.AddDays(15) > DateTime.Now)//令牌未过期 { int signState = new LoginDal().exsitLoginSign(uid, sign, IsOnlyOne); if (signState == 1) { result = 1; } else if (signState == -1) { if (1 == new UserDal().login(uid, pwd)) { result = 1; } } if (result > 0) { if (!liwai) { #region 获取当前页面的权限 UrlPathEntity urlEntity = null; List <RightEntity> rlist = null; if (HttpContext.Current.Request.RawUrl.StartsWith("/Plugins/")) { urlEntity = HuberPluginHandle.getUrlPathEntity(HttpContext.Current.Request.RawUrl.Substring(8), true); rlist = new RightBll().UserGetRights("/" + urlEntity.pluginname + "/" + urlEntity.controller + "/" + urlEntity.action); } else { urlEntity = HuberPluginHandle.getUrlPathEntity(HttpContext.Current.Request.RawUrl, false); rlist = new RightBll().UserGetRights("/" + urlEntity.controller + "/" + urlEntity.action); } UserEntity CurUer = new UserDal().GetUser(uid); if (CurUer != null) { if (rlist.Count > 0) { List <RightEntity> urights = new List <RightEntity>(); string rightCompara = ",{0},"; if (CurUer.Uid == SuperAdminID)//如果是超级管理员,不需要对权限筛选 { urights = rlist; } else { List <RoleEntity> uRoles = new RoleBll().GetRoles(CurUer.RolesIds); if (uRoles != null && uRoles.Count > 0) { foreach (RightEntity right in rlist) { foreach (RoleEntity role in uRoles) { if (role.RightIds.IndexOf(string.Format(rightCompara, right.Id)) > -1) { urights.Add(right); } } } } } userRights = urights; result = 2; } else { if (CurUer.Uid == SuperAdminID)//如果是超级管理员,不需要对权限筛选 { result = 2; } } } #endregion } else { result = 2; } } } } } return(result); }
/// <summary> /// 删除 /// </summary> /// <param name="model"></param> /// <returns></returns> public static int delete(loginModel model) { return(LoginDal.delete(model)); }
/// <summary> /// 修改 /// </summary> /// <param name="model"></param> /// <returns></returns> public static int Update(loginModel model) { return(LoginDal.Update(model)); }
//public bool signin() //{ // try // { // LumexDBPlayer db = LumexDBPlayer.Start(true); // bool status = userregDal.signin(this, db); // db.Stop(); // return status; // } // catch (Exception) // { // throw; // } //} public bool VerifyPassword() { try { LumexDBPlayer db = LumexDBPlayer.Start(); LoginDal logdal = new LoginDal(); bool status = logdal.VerifyPassword(this, db); db.Stop(); return status; } catch (Exception) { throw; } }