Beispiel #1
0
        public async Task <IActionResult> Token([FromBody] LoginIM model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = await _context.Users.FirstOrDefaultAsync(d => d.Username == model.Username);

            var salt    = Convert.FromBase64String(user.SecurityStamp);
            var pwdHash = EncryptionHelper.HashPasswordWithSalt(model.Password, salt);

            if (user.PasswordHash != pwdHash)
            {
                return(BadRequest(new ReturnVM {
                    Message = "用户名或密码不正确。"
                }));
            }

            var token = await GetJwtSecurityTokenAsync(user);

            var vm = new UserLoginVM
            {
                Id       = user.Id,
                Username = user.Username,
                RealName = user.RealName,
                Email    = user.Email,
                PhotoUrl = user.PhotoUrl,
                Token    = new JwtSecurityTokenHandler().WriteToken(token)
            };

            return(Ok(vm));
        }
Beispiel #2
0
        //[HttpPost]
        //public IActionResult Register(RegisterIM model)
        //{

        //    if (!ModelState.IsValid)
        //    {
        //        var errorMes = GetModelErrorMessage();
        //        AR.Setfailure(errorMes);
        //        return Json(AR);
        //        // return Json(false);
        //    }


        //    var result = _userServices.CreateUser(model.UserName, model.Email, model.Password, model.DisplayName,model.Mobile);

        //    if (result == 1)
        //    {
        //        AR.Setfailure(Messages.CannotRegisterEmail);
        //        _logger.LogError(Messages.CannotRegisterEmail);
        //        return Json(AR);
        //    }

        //    if (result == 2)
        //    {
        //        AR.Setfailure(Messages.CannotRegisterUserName);
        //        _logger.LogError(Messages.CannotRegisterUserName);
        //        return Json(AR);
        //    }


        //    AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, model.UserName));
        //    _logger.LogError(string.Format(Messages.AlertCreateSuccess, model.UserName));
        //    return Json(AR);
        //}
        public IActionResult Login(string returnUrl)
        {
            var im = new LoginIM
            {
                ReturnUrl = returnUrl
            };

            return(View(im));
        }
        public IActionResult Login(string returnUrl)
        {
            var im = new LoginIM
            {
                Username  = "******",
                Password  = "******",
                ReturnUrl = returnUrl
            };

            return(View(im));
        }
        public ActionResult Login(LoginIM model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(Redirect("/bbi-admin"));
            }

            if (ModelState.IsValid)
            {
                if (Session["SigCaptcha"] != null && Session["SigCaptcha"].ToString().ToLower() != model.CaptchaText.ToLower())
                {
                    ModelState.AddModelError(string.Empty, "验证码不正确!");
                    return(View(model));
                }

                var user = _userServices.SignIn(model.UserName, model.Password);
                if (user != null)
                {
                    if (!user.IsActive)
                    {
                        ModelState.AddModelError(string.Empty, "此帐号已经被停用!");
                        return(View(model));
                    }
                    var roles = user.Roles.Select(m => m.RoleName).ToArray();

                    user.LastActivityDate = DateTime.Now;
                    _userServices.UpdateLastActivityDate(user);

                    //设置cookies
                    _userServices.SetUserCookies(model.RememberMe, user, roles);

                    GlobalContext.Properties["user"] = user.UserName;
                    _logger.Info("登录");

                    if (roles.Contains("系统管理员") || roles.Contains("创始人"))
                    {
                        return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                    }
                    else if (roles.Contains("User"))
                    {
                        return(RedirectToAction("Index", "User"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }

                ModelState.AddModelError(string.Empty, "无效的用户名或密码!");
            }

            return(View(model));
        }
        public async Task <IActionResult> Login(LoginIM im)
        {
            if (im == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            var lookupUser = _userServices.SignIn(im.Username, im.Password);

            if (lookupUser == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            // create claims
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Sid, lookupUser.Id.ToString()),
                new Claim("RealName", lookupUser.RealName ?? "无"),
                new Claim(ClaimTypes.Name, lookupUser.UserName),
                new Claim(ClaimTypes.Email, lookupUser.Email)
            };

            // create identity
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var userRoles = _roleServices.GetRolesByUserId(lookupUser.Id).ToArray();

            //add a list of roles

            if (userRoles.Any())
            {
                var roles = string.Join(",", userRoles.Select(d => d.RoleName));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
            }

            // create principal
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
            {
                IsPersistent = im.RememberMe,
                ExpiresUtc   = DateTimeOffset.Now.Add(TimeSpan.FromDays(180))
            });

            AR.SetSuccess(Messages.Wellcome);
            return(Json(AR));
        }
        public ServiceResult <LoginOM> Login(LoginIM im)
        {
            ServiceResult <LoginOM> result = new ServiceResult <LoginOM>();

            string deviceNumber = this.GetDeviceNumber();

            if (string.IsNullOrEmpty(deviceNumber))
            {
                result.Code = ReasonCode.MISSING_REQUIRED_FIELDS;
                return(result);
            }

            result.Data = new UserAccountComponent().Login(im, deviceNumber, this.GetClientIPAddress());

            return(result);
        }
Beispiel #7
0
        public LoginOM Login(LoginIM im, string deviceNumber, string ip)
        {
            var user = CheckUser(im.CountryId, im.Cellphone, im.Password);
            var isNeedGoogleVerify =
                ValidationFlagComponent.CheckSecurityOpened(user.ValidationFlag, ValidationFlag.GooogleAuthenticator);

            var deviceList = new UserDeviceDAC().GetUserDeviceByAccountId(user.Id);

            var isNewDevice = deviceList.All(item => item.DeviceNumber != deviceNumber);

            if (!deviceList.Any())
            {
                if (!string.IsNullOrEmpty(user.Pin) && !user.IsBindingDevice)
                {
                    new UserDeviceDAC().Insert(new UserDevice()
                    {
                        DeviceNumber = deviceNumber, Name = " ", UserAccountId = user.Id, LastActiveTime = DateTime.UtcNow
                    });

                    new UserAccountDAC().UpdateIsBindingDevice(user.Id);
                    isNewDevice = false;
                }
            }
            if ((isNewDevice && !string.IsNullOrEmpty(user.Pin)) || isNeedGoogleVerify)
            {
                return(new LoginOM()
                {
                    IsNeedGoogleVerify = isNeedGoogleVerify, IsNewDevice = isNewDevice, UserInfo = GetUserVerifyItems(user)
                });
            }

            Task.Factory.StartNew(() =>
            {
                var model = new UserLoginLog
                {
                    UserAccountId = user.Id,
                    IP            = ip,
                    Timestamp     = DateTime.UtcNow,
                };
                new UserLoginLogDAC().Insert(model);
            });

            return(IssueAccessToken(user));
        }
Beispiel #8
0
        public IActionResult Token([FromBody] LoginIM model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = _userServices.SignIn(model.Username, model.Password);;

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


            var token = GetJwtSecurityToken(user);

            return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
        }
        public async Task <LoginVM> Login(LoginIM inputModel)
        {
            try {
                var result = await httpClient.PostJsonAsync <LoginVM>("api/accounts/login", inputModel);

                if (result.Successful)
                {
                    await apiAuthenticationStateProvider.SetAuthenticatedUserAsync(result.Token, inputModel.RememberMe);
                }
                else
                {
                    await apiAuthenticationStateProvider.SignOutAsync();
                }
                return(result);
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
                return(null);
            }
        }
Beispiel #10
0
        public async Task <IActionResult> Login(LoginIM model)
        {
            var result = await signInManager.PasswordSignInAsync(
                model.UserName,
                model.Password,
                isPersistent : false,
                lockoutOnFailure : false);

            if (!result.Succeeded)
            {
                return(Ok(new LoginVM {
                    Successful = false, Error = "Přihlášení se nezdařilo."
                }));                                                                                               // BadRequest()?
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, model.UserName)
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appConfiguration.JwtSecurityKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiration  = DateTime.Now.AddDays(Convert.ToInt32(appConfiguration.JwtExpirationInDays));

            var token = new JwtSecurityToken(
                appConfiguration.JwtIssuer,
                appConfiguration.JwtAudience,
                claims,
                expires: expiration,
                signingCredentials: credentials
                );

            return(Ok(new LoginVM {
                Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
Beispiel #11
0
        public async Task <IActionResult> Login(LoginIM im)
        {
            if (im == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            // var lookupUser = _userServices.SignIn(im.Username, im.Password);

            var user = await _context.Users.FirstOrDefaultAsync(predicate : u => u.UserName == im.Username);

            if (user == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            var salt    = Convert.FromBase64String(user.SecurityStamp);
            var pwdHash = Hash.HashPasswordWithSalt(im.Password, salt);

            if (user.PasswordHash != pwdHash)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }
            ;

            // create claims
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Sid, user.Id.ToString()),
                new Claim("RealName", user.RealName ?? "无"),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email)
            };

            // create identity
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var userRoles = await _context.Roles.Where(d => d.UserRoles.Any(r => r.UserId == user.Id)).ToArrayAsync();

            //add a list of roles

            if (userRoles.Any())
            {
                var roles = string.Join(",", userRoles.Select(d => d.RoleName));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
            }

            // create principal
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
            {
                IsPersistent = im.RememberMe,
                ExpiresUtc   = DateTimeOffset.Now.Add(TimeSpan.FromDays(180))
            });

            AR.SetSuccess(Messages.Wellcome);
            return(Json(AR));
        }