Example #1
0
        public ActionResult Login(LoginModelView loginInfo)
        {
            if (ModelState.IsValid)
            {
                var model = userBll.Get(c => c.LoginName == loginInfo.LoginName && c.PassWord == loginInfo.Password);
                if (model != null)
                {
                    var extends = model.toEntity <UsersExtend>();
                    if (model.OrganId != null)
                    {
                        var organ = _organBll.Get(c => c.OrganId == model.OrganId);
                        extends.OrganName = organ.OrganName;
                    }
                    if (model.DepartmentId != null)
                    {
                        var dep = _departmentBll.Get(c => c.DepartmentId == model.DepartmentId);
                        extends.DepartmentName = dep.DepartmentName;
                    }

                    WebHelper.FormPrincipal.MyFormsPrincipal <UserInfo> .SignIn(model.LoginName, new UserInfo()
                    {
                        Id = model.UserId
                    }, 40);

                    //将用户信息存入缓存
                    DepositHelper.Set(RedisKeyManager.LoginUserInfo(model.UserId.ToString()), extends);
                    return(Success("登陆成功"));
                }
                else
                {
                    return(Fail("登陆失败"));
                }
            }
            return(View(loginInfo));
        }
Example #2
0
        public IActionResult Login(LoginModelView model)
        {
            // ID, 비밀번호 - 필수
            if (ModelState.IsValid)
            {
                using (var db = new AspnetNoteDbContext())
                {
                    // Linq - 메서드 체이닝
                    // => : A Go to B
                    //var user = db.Users.FirstOrDefault(u => u.UserID == model.UserID && u.UserPassword == model.UserPassword);
                    var user = db.Users.FirstOrDefault(u => u.UserID.Equals(model.UserID) &&
                                                       u.UserPassword.Equals(model.UserPassword));

                    if (user != null)
                    {
                        // 로그인 성공
                        //HttpContext.Session.SetInt32(key, value);
                        HttpContext.Session.SetInt32("LOGIN_KEY", user.UserNo);
                        return(RedirectToAction("LoginSuccess", "Home"));    //로그인 성공 페이지로 이동
                    }
                }
                // 로그인 실패
                ModelState.AddModelError(string.Empty, "사용자 ID 혹인 비밀번호가 올바르지 않습니다.");
            }
            return(View(model));
        }
        public ActionResult AuthorizeProvider(LoginModelView userModel)
        {
            bdFacturacionElectronicaEntities entities = new bdFacturacionElectronicaEntities();
            int?   userId  = entities.Validate_User(userModel.providerModel.UsuarioNit, userModel.providerModel.Password).FirstOrDefault();
            string message = string.Empty;

            switch (userId.Value)
            {
            case -1:
                message = "Usuario o clave incorrecta";
                break;

            case -2:
                message = "La cuenta no ha sido activada";
                break;

            default:
                FormsAuthentication.SetAuthCookie(userModel.providerModel.UsuarioNit, true);
                if (!string.IsNullOrEmpty(Request.Form["ReturnUrl"]))
                {
                    return(RedirectToAction(Request.Form["ReturnUrl"].Split('/')[2]));
                }
                else
                {
                    return(RedirectToAction("MenuProveedor", "Menu"));
                }
            }

            ViewBag.Message = message;
            userModel.providerModel.FEErrorMessage = message;
            return(View("Index", userModel));
        }
Example #4
0
        public async Task <ActionResult> Login(LoginModelView model)
        {
            if (ModelState.IsValid)
            {
                UserDTO userDto = new UserDTO {
                    Login = model.Login, Password = model.Password
                };
                ClaimsIdentity claim = await userService.Authenticate(userDto);

                if (claim == null)
                {
                    ModelState.AddModelError("", "Неверный логин или пароль.");
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);
                    return(RedirectToAction("List", "Post"));
                }
            }
            return(View(model));
        }
 public ActionResult Login(LoginModelView u)
 {
     try
     {
         // esta action trata o post (login)
         if (ModelState.IsValid) //verifica se é válido
         {
             var usuario = _usuarioService.LoginUsuario(u.Email, u.Password);
             if (usuario != null && !usuario.Removido)
             {
                 Session["UsuarioLogado"] = usuario;
                 if (Session["UsuarioLogado"] == null)
                 {
                     return(View(u));
                 }
                 return(RedirectToAction("Index"));
             }
             throw new Exception("Está conta não existe ou não está ativa, por favor contate seu Gerente ou Adminstrador da Rede.");
         }
         return(View(u));
     }
     catch (Exception e)
     {
         ViewBag.Erro = e.Message;
         return(View(u));
     }
 }
        /// <summary>
        /// Clear the session cache, and list all clients to choose.
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            Session.Clear();
            LoginModelView loginView = new LoginModelView();

            loginView.allClients = dbContext.Clients.ToList();
            return(View(loginView));
        }
        public async Task LoginAsyncIsLoginCodeOk()
        {
            LoginModelView loginModelView = new LoginModelView()
            {
                Email    = "*****@*****.**",
                Password = "******",
            };

            var result = await HttpRestClient.LoginAsync(loginModelView);

            Assert.AreEqual(result.Code, HttpStatusCode.OK);
        }
 public ActionResult Login(LoginModelView model)
 {
     try
     {
         var result = this.customerService.Login(model.Email, model.Password, true);
         return(JsonSuccess <Boolean>(result));
     }
     catch (System.Exception ex)
     {
         return(JsonError(ex.Message));
     }
 }
Example #9
0
        public static void InsertLogin(LoginModelView model)
        {
            Login objretorno = new Login();

            //faz o de para: objModelView para objEntity
            Mapper.CreateMap <LoginModelView, Login>();
            var objtpprod = Mapper.Map <Login>(model);

            LoginRepository tpprod = new LoginRepository();

            tpprod.Add(objtpprod);
            tpprod.Save();
        }
Example #10
0
        static async Task Main(string[] args)
        {
            try
            {
                LoginModelView loginModelView = new LoginModelView()
                {
                    Email    = args[0],
                    Password = "******"
                };

                var authorizationResult = await HttpRestClient.LoginAsync(loginModelView);

                Connection connection = await ConnectionBuilder.Create(authorizationResult);

                await connection.Session.Initialization(connection.User);

                connection.IncomingCall += async(sender, delegateArgs) =>
                {
                    Console.WriteLine("Połączenie przychodzące od {0}", delegateArgs.User);
                    Console.WriteLine("Czy zgadzasz sie na połączenie T/N");
                    var answer = Console.ReadLine();
                    if (answer == "T")
                    {
                        await connection.CallAcceptedIncoming(delegateArgs.User);
                    }
                    else if (answer == "N")
                    {
                        await connection.CallDeclinedIncoming(delegateArgs.User);
                    }
                };

                foreach (var friend in connection.Friends)
                {
                    Console.WriteLine(friend.Key + ": " + friend.Value);
                }

                if (args[0] == "*****@*****.**")
                {
                    await connection.Call("*****@*****.**");
                }


                Console.ReadKey();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #11
0
        public static void UpdateLogin(LoginModelView model)
        {
            Login objretorno = new Login();

            //faz o de para: objModelView para objEntity
            Mapper.CreateMap <LoginModelView, Login>();
            var objtpprod = Mapper.Map <Login>(model);

            //objtpprod.dataincl = DateTime.Now;
            LoginRepository tpprod = new LoginRepository();

            tpprod.Edit(objtpprod);
            tpprod.Save();
        }
        public IActionResult Login([FromBody] LoginModelView user)
        {
            if (user.username == null || user.password == null)
            {
                return(BadRequest("Invalid Client request"));
            }

            var dbUser = _context.Users.FirstOrDefault(u => u.username == user.username);


            if (user.username == dbUser.username && user.password == dbUser.password)
            {
                var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SOME_RANDOM_KEY_DO_NOT_SHARE"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var claimsList = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, dbUser.UserId.ToString()),
                    new Claim(ClaimTypes.Name, dbUser.username.ToString()),
                    new Claim(ClaimTypes.Name, dbUser.Role.ToString()),
                };

                var takeOptions = new SecurityTokenDescriptor {
                    Issuer             = "http://localhost:5001",
                    Subject            = new ClaimsIdentity(claimsList),
                    Audience           = "http://localhost:4200",
                    Expires            = DateTime.Now.AddMinutes(15),
                    SigningCredentials = signinCredentials
                };

                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                SecurityToken           token        = tokenHandler.CreateToken(takeOptions);

                var tokenString = tokenHandler.WriteToken(token);

                return(Ok(new
                {
                    succuess = true,
                    Token = tokenString,
                    userId = claimsList[0].Value,
                    username = claimsList[1].Value,
                    role = claimsList[2].Value
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }
        public ActionResult Login(LoginModelView model)
        {
            if (ModelState.IsValid)
            {
                using (RSMEntities db = new RSMEntities())
                {
                    //Tim user active trong database
                    User user = AccBO.CheckLogin(model.Username, model.Password);
                    if (user != null)
                    {
                        //Thuc hien dang nhap
                        FormsAuthentication.SetAuthCookie(model.Username, false);
                        String Role   = user.Role.RoleName;
                        String Action = "";
                        switch (Role)
                        {
                        case "Instructor":
                            Action = "Index_Home";
                            break;

                        case "Staff":
                            Action = "Index";
                            Role   = "RollCall";
                            break;

                        case "Admin":
                            Action = "StudentList";
                            break;

                        case "Student":
                            Action = "CourseList";
                            break;

                        default:
                            Action = "Index";
                            break;
                        }
                        return(RedirectToAction(Action, Role));
                    }
                    else
                    {
                        ModelState.AddModelError("Error", "Invalid username or password.");
                    }
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> Logon(LoginModelView model, string ReturnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ViewBag.ReturnUrl = ReturnUrl;

            //Esta condição criei apenas pra facilitar o login "admin" sem necessitar da base de dados
            if (model.Login.Equals("admin") && model.Password.Equals("admin"))
            {
                SignIn("admin", "Administrator");
                if (string.IsNullOrEmpty(ReturnUrl))
                {
                    return(RedirectToAction("Books", "Book"));
                }
                return(Redirect(ReturnUrl));
            }
            //Fim - Pode ser comentado até aqui, não efeta o funcionamento

            //Esse método do serviço ele faz uma verificãção de usuário e senha no banco de dados
            //O usuário pode ser o e-mail ou nickName cadastrado, ambos irão ser autenticados normalmente
            var acessGranted = await _serviceAccount.LogonIsValid(new UserDTO(model.Login, model.Password));

            if (!acessGranted)
            {
                ModelState.AddModelError("Password", "Usuário ou senha incorretos");
                return(View(model));
            }

            //Esse método é apenas pra capturar qual Profile(Role) que o usuário tem
            //Em condições normais de desenvolvimento, eu criaria uma classe contendo os dados de acesso e que irá conter um enum com o
            //tipo acessGranted ou algo pra identiticar que o o acesso foi permitido, caso nao use utilizasse framework como o Identity
            var roleProfile = await _serviceAccount.GetRoleProfile(model.Login);

            //Eu criei uma classe Abstrata herdado por essa classe que contém esse método, isso facilita bastante, quando é preciso utilizar mais de uma vez
            //o método, fora que deixa o código mais limpo
            SignIn(model.Login, roleProfile);

            if (string.IsNullOrEmpty(ReturnUrl))
            {
                return(RedirectToAction("Books", "Book"));
            }
            return(Redirect(ReturnUrl));
        }
        public IActionResult Login([FromQuery] LoginModelView model)
        {
            logger.LogInfo("Someone is trying to Login");
            if (ModelState.IsValid)
            {
                var login = mapper.Map <BL.ModelsDTO.ApplicationModels.LoginModelDTO>(model);

                var message = service.Login(login);

                logger.LogInfo($"User logged in ");
                return(Ok(message));
            }
            else
            {
                logger.LogError("Authorization failed");
                return(NotFound());
            }
        }
        public async Task <IActionResult> Login(LoginModelView login)
        {
            try
            {
                var result = await _identityService.LoginAsync(login);

                if (result.Code == HttpStatusCode.Unauthorized)
                {
                    return(Unauthorized(result));
                }

                return(Ok(result));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public void Login(LoginModelView loginModelView, Action <bool> onResponse)
        {
            if (IsLoggedIn)
            {
                onResponse(true);
                return;
            }

            if (_isBusy)
            {
                _workingThreads.Enqueue(() => Login(loginModelView, onResponse));
                return;
            }

            _isBusy = true;
            _http.PostAsync <UserModelView, LoginModelView>("auth/signIn", loginModelView,
                                                            (res) => OnLoginResult(res, onResponse))
            .ContinueWith(CallError);
        }
Example #18
0
        private async void LoginButton_Click(object sender, System.EventArgs e)
        {
            LoginModelView login = new LoginModelView()
            {
                Email    = LogincomboBox.Text,
                Password = PasswordcomboBox.Text,
            };

            AuthorizationResult = await HttpRestClient.LoginAsync(login);

            if (AuthorizationResult.Code == HttpStatusCode.OK)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("Błędny login lub hasło");
            }
        }
Example #19
0
        public async Task <JsonResult> SignIn([FromBody] LoginModelView model)
        {
            if (ModelState.IsValid)
            {
                var result =
                    await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.IsPersistent, false);

                if (result.Succeeded)
                {
                    return(Json(model));
                }

                HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;

                if (result.IsLockedOut)
                {
                    return(Json(new ErrorMessage("IsLockedOut")));
                }

                if (result.IsNotAllowed)
                {
                    return(Json(new ErrorMessage("IsNotAllowed")));
                }

                if (result.RequiresTwoFactor)
                {
                    return(Json(new ErrorMessage("RequiresTwoFactor")));
                }

                return(Json(new ErrorMessage("Invalid User or Password")));
            }

            HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;

            return(Json(new ErrorMessage(ViewData.ModelState.Values.Select(x => x.Errors)
                                         .Select(x => x.Select(y => y.ErrorMessage).Aggregate((i, j) => i + "; " + j)))));
        }
Example #20
0
        public IActionResult LoginValidate(LoginModelView loginModel)
        {
            string token   = string.Empty;
            bool   success = false;

            if (loginModel != null)
            {
                if (loginModel.UserName == "admin" && loginModel.Password == "123456")
                {
                    token = JwtHellper.IssueJwt(new Token
                    {
                        Uid  = loginModel.UserName,
                        Role = loginModel.Role
                    });
                    success = true;
                }
            }

            return(Ok(new
            {
                token,
                success
            }));
        }
 public ActionResult Login(LoginModelView objClient)
 {
     if (ModelState.IsValid)
     {
         using (dbContext)
         {
             var obj = dbContext.Clients.Where(a => a.Username.Equals(objClient.client.Username)).FirstOrDefault();
             if (obj != null)
             {
                 Session["UserID"]   = obj.ClientID.ToString();
                 Session["UserName"] = obj.Username.ToString();
                 Session["FullName"] = obj.FirstName + " " + obj.LastName;
                 string photourl = "/Images/avatar-default-icon.png";
                 if (obj.PhotoURL != null && obj.PhotoURL != "")
                 {
                     photourl = "/Images/Users/" + obj.ClientID + "/" + obj.PhotoURL;
                 }
                 Session["img"] = photourl;
                 return(RedirectToAction("index"));
             }
         }
     }
     return(View(objClient));
 }
Example #22
0
        public async Task <HttpAuthorizationResult> LoginAsync(LoginModelView loginModelView)
        {
            var result = await _signInManager.PasswordSignInAsync(loginModelView.Email, loginModelView.Password, loginModelView.RememberMe, false);

            if (!result.Succeeded)
            {
                return(new HttpAuthorizationResult()
                {
                    Code = HttpStatusCode.Unauthorized,
                    Errors = new[] { "Login lub hasło są nie poprawne" },
                });
            }

            var user = await _userManager.FindByEmailAsync(loginModelView.Email);

            return(new HttpAuthorizationResult()
            {
                Id = user.Id,
                User = user.Email,
                DateIssue = DateTime.Now,
                Code = HttpStatusCode.OK,
                Token = _tokenService.Generate(user),
            });
        }
        public async Task <IActionResult> Login(LoginModelView model, string ReturnUrl)
        {
            try
            {
                model.UserName = model.UserName.Trim();
                model.Password = model.Password.Trim();
                if (ModelState.IsValid)
                {
                    if (_db.Database.GetService <IRelationalDatabaseCreator>().Exists())
                    {
                        if (_db.UserLogin.Where(m => m.UserName == model.UserName && m.Password == model.Password).Any())
                        {
                            var login = _db.UserLogin.FirstOrDefault(x => x.UserName == model.UserName && x.Password == model.Password);
                            if (login.IsConfirmed == true)
                            {
                                var user = _db.UserInformation.FirstOrDefault(x => x.Id == login.UserId);
                                if (user.Role > 0)
                                {
                                    await UserSignIn(login, user, ReturnUrl, model.RememberMe);

                                    //var Roles = _db.RoleList.Where(x => x.Id == user.Role).FirstOrDefault();
                                    //var identity = new ClaimsIdentity(new[] {
                                    //   new Claim(ClaimTypes.Name, $"{user?.Name}"),
                                    //   new Claim(ClaimTypes.NameIdentifier, login?.UserName),
                                    //   new Claim(ClaimTypes.Sid, login?.UserId.ToString()),
                                    //   new Claim(ClaimTypes.Role, Roles?.RoleName),
                                    //   new Claim(ClaimTypes.OtherPhone, Roles?.Id.ToString())
                                    //   }, CookieAuthenticationDefaults.AuthenticationScheme);

                                    //var principal = new ClaimsPrincipal(identity);

                                    //await HttpContext.SignInAsync(
                                    //    CookieAuthenticationDefaults.AuthenticationScheme,
                                    //    principal, new AuthenticationProperties { IsPersistent = model.RememberMe });



                                    //return RedirectToLocal(ReturnUrl);
                                    return(RedirectToAction("OAuth", "Account"));

                                    if (login.IsLoginBefore == false || login.IsOtpenable == true)
                                    {
                                        return(RedirectToAction("ConfirmOTP", "Account", new
                                        {
                                            q = _protector.Protect(login.UserName.ToString()),
                                            p = _protector.Protect(login.Password.ToString()),
                                            IsLoginBefore = login.IsLoginBefore ? "true" : "false",
                                            RememberMe = model.RememberMe ? "true" : "false",
                                            ReturnUrl
                                        }));
                                    }
                                    else
                                    {
                                        /*var Roles = _db.RoleList.Where(x => x.Id == user.Role).FirstOrDefault();
                                         * var identity = new ClaimsIdentity(new[] {
                                         * new Claim(ClaimTypes.Name, $"{user?.Name}"),
                                         * new Claim(ClaimTypes.NameIdentifier, login?.UserName),
                                         * new Claim(ClaimTypes.Sid, login?.UserId.ToString()),
                                         * new Claim(ClaimTypes.Role, Roles?.RoleName),
                                         * new Claim(ClaimTypes.OtherPhone, Roles?.Id.ToString())
                                         * }, CookieAuthenticationDefaults.AuthenticationScheme);
                                         *
                                         * var principal = new ClaimsPrincipal(identity);
                                         *
                                         * await HttpContext.SignInAsync(
                                         *  CookieAuthenticationDefaults.AuthenticationScheme,
                                         *  principal, new AuthenticationProperties { IsPersistent = model.RememberMe });*/

                                        await UserSignIn(login, user, ReturnUrl, model.RememberMe);

                                        //return RedirectToLocal(ReturnUrl);
                                        return(RedirectToAction("OAuth", "Account"));
                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError(string.Empty, "Role not set! Please contact your administrator.");
                                    return(View(model));
                                }
                            }
                            else
                            {
                                ModelState.AddModelError(string.Empty, "Email has not been confirmed yet!");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Invalid Email/UserName or Password.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Could not connect to the Database!");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid Email/UserName or Password Format.");
                }
                return(View(model));
            }
            catch (Exception)
            {
                ModelState.AddModelError(string.Empty, "Something wrong while connecting!");
            }
            return(View(model));
        }
 public Login()
 {
     InitializeComponent();
     z = new LoginModelView(this);
     BindingContext = z; //Questa pagina utilizza l'MWWM ed effettua il binding con la classe LoginModelView
 }
 public ActionResult AuthorizeFunctionary(LoginModelView userModel)
 {
     return(View());
 }
Example #26
0
 public static async Task <HttpAuthorizationResult> LoginAsync(LoginModelView model)
 {
     return(await HttpHelper.Post <HttpAuthorizationResult, LoginModelView>(Routes.Identity.Login, model));
 }
 public Login()
 {
     InitializeComponent();
     z = new LoginModelView();
     BindingContext = z;
 }