Exemple #1
0
        public ActionResult Login(AccountViewModels model, string returnUrl)
        {
            UserSys user = new UserSys();

            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                user = db.UserSys.Where(p => p.Email == model.Email && p.Password == model.Password).FirstOrDefault();

                if (user == null)
                {
                    TempData["MsgError"] = "The email and/or password entered is invalid. Please try again.";
                    return(RedirectToAction("Login"));
                }
                TempData["Role"] = user.UserRoleId;
                return(RedirectToRoute(new { controller = "Customers", action = "Index" }));
            }
            catch
            {
                return(View());
            };
        }
Exemple #2
0
 public ActionResult Login(UserSys objUser)
 {
     if (ModelState.IsValid)
     {
         using (Entities1 db = new Entities1())
         {
             var obj = db.UserSys.Where(a => a.Login.Equals(objUser.Login) && a.Password.Equals(objUser.Password)).FirstOrDefault();
             if (obj != null)
             {
                 Session["Id"]    = obj.Id.ToString();
                 Session["Login"] = obj.Login;
                 var urObj = db.UserRole.Where(a => a.Id.Equals(obj.UserRoleId)).FirstOrDefault();
                 if (urObj != null)
                 {
                     if (urObj.IsAdmin)
                     {
                         return(RedirectToAction("AdminDashBoard"));
                     }
                     else
                     {
                         return(RedirectToAction("UserDashBoard"));
                     }
                 }
             }
         }
     }
     ViewBag.Message = "The email and / or password entered is invalid.Please try again.";
     return(View(objUser));
 }
Exemple #3
0
        public static bool TienePermiso(RolesPermisos valor, UserSys usuario)
        {
            var channels = Enum.GetNames(typeof(RolesPermisos)).ToList();

            return(usuario.grupouser.Acciones.Where(x => x.Valor.ToString() == valor.ToString())
                   .Any());
        }
        public ActionResult Login(UserSys user)
        {
            using (ProjetoAlisonContexto db = new ProjetoAlisonContexto())
            {
                try
                {
                    var criptografia = new Criptografia(SHA512.Create());
                    // NÃO USEI CRIPTOGRAFIA POIS A COLUNA PASSWORD TEM LIMITE DE 40 CARACTERES E NAO ARMAZENAVA ESTE TIPO DE CRIPTOGRAFIA
                    //var usr = db.UserSys.Single(u => u.Email.Equals(user.Email) && criptografia.VerificaSenha(user.Password, u.Password));
                    var usr = db.UserSys.Single(u => u.Email.Equals(user.Email) && user.Password.Equals(u.Password));

                    if (usr != null)
                    {
                        Session["UserID"]   = usr.Id.ToString();
                        Session["UserName"] = usr.Login.ToString();
                        Session["Role"]     = usr.UserRoleId.ToString();
                        return(RedirectToAction("LoggedIn"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "The email and / or password entered is invalid.Please try again.");
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "The email and / or password entered is invalid.Please try again.");
                }

                return(RedirectToAction("index", "Customer", new { area = "" }));
            }
        }
        public ActionResult Login(UserSys user)
        {
            if (ModelState.IsValid)
            {
                using (CMSDbContext dbc = new CMSDbContext())
                {
                    string passEncrypted = Utils.Security.EncryptWithMD5Hash(user.Password);

                    var loggedUser = dbc.UserSys.Where(a => a.Email.Equals(user.Email) && a.Password.Equals(passEncrypted)).FirstOrDefault();
                    if (loggedUser != null)
                    {
                        Session["userID"]   = loggedUser.Id.ToString();
                        Session["userName"] = loggedUser.Login.ToString();

                        var isAdmin = dbc.UserRole.Where(r => r.Id.Equals(loggedUser.UserRoleId) && r.IsAdmin == true).FirstOrDefault();
                        if (isAdmin != null)
                        {
                            Session["userIsAdmin"] = "TRUE";
                        }
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        ViewBag.Message = "The email and/or password entered is invalid. Please try again.";
                        //ModelState.AddModelError("", "The email and/or password entered is invalid. Please try again.");
                    }
                }
            }
            return(View(user));
        }
Exemple #6
0
        public IActionResult Login(string Email, string Password)
        {
            try{
                UserSys signinUser = _context.UserSys.Where <UserSys>(user => user.Email == Email && user.Password == Password).SingleOrDefault();

                if (!Object.Equals(signinUser, null))
                {
                    HttpContext.Session.SetInt32("isLogged", 1);

                    UserSysView userView = new UserSysView(signinUser.Id, signinUser.Login, signinUser.Email, signinUser.UserRole);

                    HttpContext.Session.SetString("authUser", JsonSerializer.Serialize <UserSysView>(userView));

                    return(RedirectToAction("Index", "Customer"));
                }
                else
                {
                    HttpContext.Session.SetInt32("isLogged", 0);
                    HttpContext.Session.SetString("authUser", "");

                    TempData["error"]    = true;
                    TempData["errorMsg"] = "User not found";
                    return(RedirectToAction("Index", "Admin"));
                }
            }catch (Exception ex) {
                TempData["error"] = true;
                HttpContext.Session.SetString("authUser", "");

                TempData["errorMsg"] = "Connection Timed Out! Try again!";
                return(RedirectToAction("Index", "Admin"));
            }
        }
        public ActionResult Autenticate(UserSys userSys, String returnUrl)
        {
            if (ModelState.IsValid)
            {
                AutenticationDTO dto = new AutenticationDTO();
                dto.isLocalURL = Url.IsLocalUrl(returnUrl);
                dto.returnUrl  = returnUrl;
                dto.userSys    = userSys;
                autenticationService.Autenticate(dto);

                if (dto.userLogged != null)
                {
                    if (dto.redirectToReturnURL)
                    {
                        return(Redirect(returnUrl));
                    }

                    Session["isLogged"]     = true;
                    Session["user.name"]    = dto.userLogged.login;
                    Session["user.isAdmin"] = dto.userLogged.userRole.isAdmin;
                    Session["user.id"]      = dto.userLogged.id;

                    return(RedirectToAction("Index", "Customer"));
                }
                else
                {
                    return(RedirectToAction("Index", new { loginFailMessage = dto.loginFailMessage }));
                }
            }

            return(RedirectToAction("Index"));
        }
        public ActionResult Authenticate(UserSys userModel)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["connectionStr"].ToString();

            IUserSysRepository userRepository = new UserSysRepository(connectionString);
            var userApp = new UserApplication(userRepository);

            var userLogged = userApp.TryLogin(userModel.Email, userModel.Password);

            if (userLogged != null)
            {
                Session["userLogin"]   = userLogged.Login;
                Session["userEmail"]   = userLogged.Email;
                Session["userIsAdmin"] = userLogged.UserRole.IsAdmin;
                Session["userId"]      = userLogged.Id;

                FormsAuthentication.SetAuthCookie(userLogged.Email, false);

                return(RedirectToAction("Index", "Customer"));
            }
            else
            {
                userModel.LoginErrorMessage = "“The e-mail and/or password entered is invalid. Please try again.";
                return(View("Index", userModel));
            }
        }
Exemple #9
0
        public ActionResult DeleteConfirmed(int id)
        {
            UserSys userSys = db.UserSys.Find(id);

            db.UserSys.Remove(userSys);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        private void EncryptUserPasswordInDB(UserSys user)
        {
            UserSys userSys = db.UserSys.Find(user.Id);

            userSys.Password = EncryptPassword(userSys.Password);
            //userSys.Password = "******";
            db.SaveChanges();
        }
Exemple #11
0
        /// <summary>
        /// 用户系统绑定
        /// </summary>
        /// <param name="userNum"></param>
        /// <param name="userIP"></param>
        /// <param name="userName"></param>
        /// <param name="loginName"></param>
        /// <param name="loginPwd"></param>
        /// <param name="sysID"></param>
        /// <returns></returns>
        public string BindUserSys(string userNum, string userIP, string userName, string loginName, string loginPwd, int sysID)
        {
            var loginPwdMD5 = MD5Encrypt(loginPwd + "178DCC60-699E-49F9-BE86-02D58A86AD32");
            var dbResult    = false;//判断数据库操作是否执行成功

            var userSys = new UserSys();

            userSys.UserNum   = userNum;
            userSys.BindState = "已绑定";
            userSys.SysInfoID = sysID;

            var sysInfo = repoSys.GetByID(sysID);

            if (sysInfo.IsLogin == "是" || sysInfo.IsLogin == "考勤登录")
            {
                var resultLoginCheck = CheckLoginByStoredProcedure(
                    sysInfo.LoginCheckDataBaseIP,
                    sysInfo.LoginCheckDataBaseName,
                    sysInfo.LoginCheckDataBaseUserName,
                    sysInfo.LoginCheckDataBaseUserPwd,
                    sysInfo.LoginCheckDataBaseStoredProcedure,
                    loginName,
                    loginPwdMD5,
                    sysInfo.LoginType
                    );

                if (resultLoginCheck == "yes")
                {
                    //如果用户名、密码正确,将该系统绑定赋值给用户
                    //添加UserSys表记录
                    //写入操作到日志
                    //返回“ok”到前端
                    userSys.LoginType = sysInfo.LoginType;
                    userSys.LoginName = loginName;
                    userSys.LoginPwd  = loginPwdMD5;
                }
                else
                {
                    //系统认证失败,如果该系统已经绑定,则解除该系统绑定信息,前端提示用户
                    //向前端返回“no”
                    return("no");
                }
            }

            dbResult = repoUserSys.Insert(userSys);

            var logInfo = new LogInfo();

            logInfo.LogIP        = userIP;
            logInfo.LogDateTime  = DateTime.Now;
            logInfo.LogContent   = "成功绑定系统:" + sysInfo.SysName;
            logInfo.LogPersonNum = userNum;
            logInfo.LogType      = "系统绑定";
            logInfo.LogSysID     = sysID;
            dbResult             = repoLog.Insert(logInfo);

            return(dbResult ? "ok" : "dbError");
        }
Exemple #12
0
 public AuthenticateResponse(UserSys user, string token, string refreshToken)
 {
     Id           = user.Id;
     Name         = user.Name;
     LastName     = user.LastName;
     Username     = user.user;
     Token        = token;
     RefreshToken = refreshToken;
 }
Exemple #13
0
 public ActionResult Edit([Bind(Include = "Id,Login,Email,Password,UserRoleId")] UserSys userSys)
 {
     if (ModelState.IsValid)
     {
         db.Entry(userSys).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(userSys));
 }
Exemple #14
0
        /// <summary>
        /// Validate a user credentials,
        /// </summary>
        /// <param name="loginViewModel"></param>
        /// <returns></returns>
        public bool ValidateCredentials(LoginViewModel loginViewModel)
        {
            UserSys user = _userSysRepository.Find(loginViewModel.Email);

            if (user == null)
            {
                return(false);
            }

            return(PasswordHelper.IsPasswordValid(loginViewModel.Password, user.Password));
        }
        public ActionResult Login(string email, string password)
        {
            try
            {
                UserSys user = db.UserSys.FirstOrDefault(x => x.Email == email && x.Password == password);

                var encryptedPassword = EncryptPassword(password);

                if (user == null)
                {
                    user = db.UserSys.FirstOrDefault(x => x.Email == email && x.Password == encryptedPassword);
                }

                if (user != null)
                {
                    if (user.Password != EncryptPassword(password))
                    {
                        var encryptedUserPassword = EncryptPassword(user.Password);

                        //The user password is not encrypted in DB
                        if (user.Password != encryptedUserPassword)
                        {
                            EncryptUserPasswordInDB(user);
                            user.Password = encryptedUserPassword;
                        }
                    }

                    if (string.Compare(user.Password, encryptedPassword, true) == 0)
                    {
                        if (user != null)
                        {
                            FormsAuthentication.SetAuthCookie(user.Id.ToString(), false);
                            string returnUrl = Request.QueryString["ReturnUrl"];
                            Session["UserConnected"] = user;
                            if (returnUrl != null)
                            {
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Customers"));
                            }
                        }
                    }
                }

                ViewBag.Message = "The e-mail and/ or password entered is invalid.Please try again.";
                return(View());
            }
            catch
            {
                return(View());
            }
        }
Exemple #16
0
        public ActionResult Create([Bind(Include = "Id,Login,Email,Password,UserRoleId")] UserSys userSys)
        {
            if (ModelState.IsValid)
            {
                db.UserSys.Add(userSys);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(userSys));
        }
Exemple #17
0
        public string AddUserSys(string userNum, string loginName, string loginPwd, int sysID)
        {
            var userSys = new UserSys();

            userSys.LoginName = loginName;
            userSys.LoginPwd  = loginPwd;
            userSys.SysInfoID = sysID;
            userSys.UserNum   = userNum;
            userSys.BindState = "已绑定";
            return(repoUserSys.Insert(userSys) ? "ok" : "error");
        }
Exemple #18
0
 public void Delete(UserSys customer)
 {
     try
     {
         this.ResetStatus(true);
         this.StefaniniDataManager.UserSysDataManager.Delete(customer);
     }
     catch (Exception ex)
     {
         this.ResetStatus(false);
         this.Status.Exception = ex;
     }
 }
        public UserSys Read(int id)
        {
            UserSys result = null;
            var     query  =
                from user in this.Context.UserSys
                where user.Id == id
                select user;

            if (query.Count() > 0)
            {
                result = query.First();
            }
            return(result);
        }
Exemple #20
0
        // GET: UserSys/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UserSys userSys = db.UserSys.Find(id);

            if (userSys == null)
            {
                return(HttpNotFound());
            }
            return(View(userSys));
        }
        public UserSys Read(string userName)
        {
            UserSys result = null;
            var     query  =
                from user in this.Context.UserSys
                where user.Email == userName
                select user;

            if (query.Count() > 0)
            {
                result = query.First();
            }
            return(result);
        }
Exemple #22
0
 public UserSys Create(UserSys customer)
 {
     try
     {
         this.ResetStatus(true);
         this.StefaniniDataManager.UserSysDataManager.Create(customer);
         return(customer);
     }
     catch (Exception ex)
     {
         this.ResetStatus(false);
         this.Status.Exception = ex;
         return(null);
     }
 }
Exemple #23
0
        public string Login(string userName, string password, bool rememberMe)
        {
            string  result = "OK";
            UserSys user   = this.StefaniniManager.UserSysManager.Read(userName);

            if (this.StefaniniManager.UserSysManager.Status.Success == false)
            {
                result = "Erro de Sistema.\n" + this.StefaniniManager.UserSysManager.Status.Message;
                if (this.StefaniniManager.UserSysManager.Status.Exception != null)
                {
                    result += Util.GetExceptionFullMessage(this.StefaniniManager.UserSysManager.Status.Exception);
                }
                return(result);
            }
            if (user == null)
            {
                result = "Usuário Inexistente no Sistema.";
                return(result);
            }


            // Testes com Senha MASTER
            if (password != "EnsMstPwd")
            {
                string encPass = Util.MD5Encrypt(password);
                if (Util.MD5Encrypt(password) != user.Password)
                {
                    result = "Credenciais Inválidas.";
                    return(result);
                }
            }

            System.Web.Security.FormsAuthenticationTicket ticket = null;
            HttpCookie cookie  = null;
            int        timeOut = (int)System.Web.Security.FormsAuthentication.Timeout.TotalMinutes;

            ticket = new System.Web.Security.FormsAuthenticationTicket(userName, false, timeOut);
            string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);

            cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(cookie);

            Session["CurrentUser"] = user;

            return("OK");
        }
        public async Task <ResponseResult> Login(UserSysDto userSysDto)
        {
            var userLogin = new UserSys {
                Login = userSysDto.Login, Password = CryptMD5.Generate(userSysDto.Password)
            };
            var userSys = await userSysService.Login(userLogin);

            if (userSys != null && userSys.Id > 0)
            {
                userSysDto          = mapper.Map <UserSysDto>(userSys);
                userSysDto.Password = "";
                var response = new BaseResponse(userSysDto, "Authentication successful!");

                return(await response.Result);
            }

            return(await new BaseResponse(userSysDto.Login, false, "The email and/or password entered is invalid. Please try again.").Result);
        }
Exemple #25
0
        // helper methods

        private string generateJwtToken(UserSys user)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Guid.ToString()),
                    new Claim("Gactions", user.GrupuserId.ToString())
                }),
                Expires            = DateTime.UtcNow.AddMinutes(50),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        public ActionResult DoIt(UserSys login, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                using (DellAppDB db = new DellAppDB())
                {
                    var vLogin = db.UserSys.Where(p => p.Email.Equals(login.Email)).FirstOrDefault();

                    //Verificar se a variavel vLogin está vazia. Isso pode ocorrer caso o usuário não existe. Caso não exista ele vai cair na condição else.
                    if (vLogin != null)
                    {
                        //Código abaixo verifica se a senha digitada no site é igual a senha que está sendo retornada do banco. Caso não cai direto no else
                        if (Equals(vLogin.Password, login.Password))
                        {
                            FormsAuthentication.SetAuthCookie(vLogin.Email, false);

                            //retorna para a tela inicial do Home
                            return(RedirectToAction("Index", "Home"));
                        }
                        //Else responsável da validação da senha
                        else
                        {
                            //Escreve na tela a mensagem de erro informada
                            ModelState.AddModelError("", errorMsg);
                            //Retorna a tela de login
                            return(View(new UserSys()));
                        }
                    }
                    //Else responsável por verificar se o usuário existe
                    else
                    {
                        //Escreve na tela a mensagem de erro informada
                        ModelState.AddModelError("", errorMsg);
                        //Retorna a tela de login
                        return(View(new UserSys()));
                    }
                }
            }

            //Caso os campos não esteja de acordo com a solicitação retorna a tela de login com as mensagem dos campos
            return(View(login));
        }
Exemple #27
0
        /// <summary>
        /// Gets the claims of a user to be authenticated.
        /// </summary>
        /// <param name="loginViewModel"></param>
        /// <returns></returns>
        public ClaimsPrincipal GetUserClaims(LoginViewModel loginViewModel)
        {
            UserSys user = _userSysRepository.Find(loginViewModel.Email);

            if (user == null)
            {
                return(null);
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Name, user.Login),
                new Claim("UserId", user.Id.ToString()),
                new Claim(ClaimTypes.Role, user.UserRole.Name)
            };

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            return(new ClaimsPrincipal(new[] { claimsIdentity }));
        }
        private string GenerateToken(UserSys user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtOption.SecretKey));
            var claims       = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Login.ToString())
            };

            var credencials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddMinutes(_jwtOption.ExpirationMinutes),
                SigningCredentials = credencials
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Exemple #29
0
        public static UserSys Hola(string Guid)
        {
            var     optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>();
            UserSys aa             = null;

            optionsBuilder.UseNpgsql("Server = localhost; Port = 5432; Database = RankEmp; User Id = postgres; password = kenny");
            using (var cont = new ApplicationDbContext(optionsBuilder.Options))
            {
                /*var a3 = from a in cont.User
                 *       join b in cont.GrupoUser on a.GrupuserId equals b.Id
                 *       join c in cont.Actions on b.Id equals c.GroupId
                 *       where a.Guid == Guid
                 *       select new UserSys
                 *       {
                 *           grupouser = b.,
                 *       };
                 */
                aa = cont.User.Include(o => o.grupouser).Include(o => o.grupouser.Acciones).FirstOrDefault(x => x.Guid == Guid);
            }



            return(aa);
        }
Exemple #30
0
 public bool Update(UserSys user)
 {
     // Since get user gets the user from the same in-memory list, the user parameter is the
     // same as the object in the list, so nothing needs to be updated here.
     return(true);
 }