Esempio n. 1
0
        public IHttpActionResult Login([Required] AccountLoginDto dto)
        {
            logger.InfoFormat("{0:D3}.{1}", ++numberIndex, MethodBase.GetCurrentMethod().Name);
            var result = new CommonResponse();
            var user   = userApplicationService.GetByLoginname(dto.Loginname);

            if (user == null)
            {
                result.Code        = (int)AccountLoginErrorCode.LoginnameNotExist;
                result.Description = AccountLoginErrorCode.LoginnameNotExist.Description();
                return(Ok(result));
            }
            var password = RsaHelper.Decrypt(dto.Password, RsaKeyManager.XmlPrivateKey);

            if (!user.Password.Equals(password))
            {
                result.Code        = (int)AccountLoginErrorCode.LoginnameAndPasswordNotMatch;
                result.Description = AccountLoginErrorCode.LoginnameAndPasswordNotMatch.Description();
                return(Ok(result));
            }
            else if (user.Status == (int)UserStatus.Disabled)
            {
                result.Code        = (int)AccountLoginErrorCode.AccountIsDisabled;
                result.Description = AccountLoginErrorCode.AccountIsDisabled.Description();
                return(Ok(result));
            }
            result.Code        = (int)CommonErrorCode.Success;
            result.Description = CommonErrorCode.Success.Description();
            result.Data        = user;
            return(Ok(result));
        }
Esempio n. 2
0
        public ActionResult Login(AccountLoginDto dto)
        {
            var accountVerifyInfoDto = _accountService.AccountMatch(dto.AccountName, dto.Password);

            if (accountVerifyInfoDto == null)
            {
                ViewData["errorMsg"] = "账号或者密码错误";

                //账号或者密码错误
                return(View());
            }

            //var webAppKey = RequestUtils.GetString("CacheKey");
            //var callBackUrl = RequestUtils.GetString("CallBackUrl");

            var webAppInfo  = _webAppManager.GetWebAppInfoByCacheKey(dto.CacheKey, dto.CallBackUrl);
            var accountInfo = new AccountInfo(accountVerifyInfoDto.AccountId, accountVerifyInfoDto.Code,
                                              accountVerifyInfoDto.AccountName);

            _logger.Info(accountVerifyInfoDto);
            _logger.Info(accountInfo);

            //写入TGC,因为已经登陆成功,所以此时需要写入,至于Ticket的验证,那是后续的事情
            _ticketGrantingManager.SetTicketGranting(accountInfo);
            //验证,跳转
            var ticket = _ticketManager.CreateTicket(accountInfo.AccountId, accountInfo.Code);
            var url    = UrlUtils.GetClientVerifyTicketUrl(webAppInfo, ticket,
                                                           dto.CallBackUrl);

            return(Redirect(url));
        }
Esempio n. 3
0
        public IActionResult Login(AccountLoginDto dto)
        {
            var accountUserGetDto = _app.Login(dto);

            if (accountUserGetDto == null)
            {
                return(BadRequest("Usuário ou senha inválido."));
            }

            return(Accepted(accountUserGetDto));
        }
Esempio n. 4
0
        public async Task <IActionResult> Login([FromBody] AccountLoginDto model)
        {
            if (!ModelState.IsValid)
            {
                var badResult = new OperationResult();
                badResult.Message = string.Join("; ", ModelState.Values
                                                .SelectMany(x => x.Errors)
                                                .Select(x => x.ErrorMessage));
                return(new OkObjectResult(badResult));
            }

            var result = await _accountService.Login(model);

            return(new OkObjectResult(result));
        }
        public async Task <ActionResult> Login(AccountLoginDto model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (await authenticationService.AuthenticateAsync(model.Username, model.Password))
            {
                return(string.IsNullOrEmpty(returnUrl) ? RedirectToAction("Index", "Home") : (ActionResult)Redirect(returnUrl));
            }

            ViewBag.LoginError = "Prijava neuspešna!";
            return(View(model));
        }
Esempio n. 6
0
        public async Task <bool> Login(AccountLoginDto dto, IAuthenticationManager AuthenticationManager)
        {
            try
            {
                using (DHContext db = new DHContext())
                {
                    User user = await db.Users.Include(r => r.Role).Where(u => u.Login == dto.Login).FirstOrDefaultAsync();

                    if (user == null)
                    {
                        return(false);
                    }
                    else
                    {
                        if (await VerifyHashedPassword(user.HashPassword, dto.Password))
                        {
                            ClaimsIdentity claim = new ClaimsIdentity("ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                            claim.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));
                            claim.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login, ClaimValueTypes.String));
                            claim.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                                                     "OWIN Provider", ClaimValueTypes.String));
                            if (user.Role != null)
                            {
                                claim.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role.Name, ClaimValueTypes.String));
                            }

                            AuthenticationManager.SignOut();
                            AuthenticationManager.SignIn(new AuthenticationProperties
                            {
                                IsPersistent = true
                            }, claim);
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                _logger.Error($"Failed Login for {dto.Login} : {exc}");
                return(false);
            }
        }
Esempio n. 7
0
        public async Task <ApiResult> AccountLogin(AccountLoginDto input)
        {
            var account = await accountRepository.FindAccountByAccounId(input.LoginName);

            if (account == null)
            {
                throw new ApplicationServiceException("登录账号不存在!");
            }
            account.CheckAccountCanLogin(Common.GetMD5SaltCode(input.Password, account.Id), input.LoginAdmin);
            await BuildLoginCache(account);

            var loginToken = Common.GetMD5SaltCode(Guid.NewGuid().ToString(), input.LoginAdmin);
            await stateManager.SetState(new AccountLoginAccessToken(loginToken, new AccessTokenItem(account.Id, input.LoginAdmin)));

            await eventBus.SendEvent(EventTopicDictionary.Account.LoginSucc, new LoginAccountSuccessEvent(loginToken));

            return(ApiResult.Ok(new AccountLoginResponse(loginToken)));
        }
Esempio n. 8
0
        public async Task <ActionResult> Login(AccountLoginDto model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var account = await _mediator.Send(new Login.Command()
            {
                Account = model
            });

            if (!account.IsSucceeded)
            {
                Alert(AlertTypes.Error, "Incorrect email or password!");
                return(View(model));
            }

            return(RedirectToAction(nameof(TargetsController.Index), "Targets"));
        }
Esempio n. 9
0
        public AccountUserGetDto Login(AccountLoginDto dto)
        {
            var accountUserGetDto = new AccountUserGetDto();
            var password          = MD5Hash.Generate(dto.Password);
            var user = _uow.UserRepository.Get(dto.Username, password);

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

            var token = TokenService.GenerateToken(user);

            accountUserGetDto.Id       = user.Id;
            accountUserGetDto.Username = user.Username;
            accountUserGetDto.Role     = user.Role;
            accountUserGetDto.Token    = token;

            return(accountUserGetDto);
        }
Esempio n. 10
0
        public async Task <ServiceResult <TokenDto> > AccountLoginAsync(AccountLoginDto loginDto)
        {
            _logger.LogInformation("User Use JwtLogin");

            UserEntity user = await _userRepo.GetUserAsync(r => r.Username == loginDto.Username || r.Email == loginDto.Username);

            if (user == null)
            {
                throw new KnownException("用户不存在", ServiceResultCode.NotFound);
            }

            bool valid = await _userIdentityService.VerifyUserPasswordAsync(user.Id, loginDto.Password);

            if (!valid)
            {
                throw new KnownException("请输入正确密码", ServiceResultCode.ParameterError);
            }

            _logger.LogInformation($"用户{loginDto.Username},登录成功");
            return(ServiceResult <TokenDto> .Successed(await _jwtTokenService.CreateTokenAsync(user)));
        }
Esempio n. 11
0
        public async Task <IActionResult> Login([FromBody] AccountLoginDto loginDto)
        {
            var signInResult =
                await _signInManager.PasswordSignInAsync(loginDto.Email, loginDto.Password, false, false);

            if (!signInResult.Succeeded)
            {
                return(Unauthorized());
            }

            var user = await _userManager.Users.SingleAsync(x => x.Email == loginDto.Email);

            var accessToken  = GenerateJwtToken(user.Id, user.Email);
            var refreshToken = await GenerateRefreshToken(user.Id);

            return(Ok(new AccountTokenDto
            {
                AccessToken = accessToken,
                RefreshToken = refreshToken.Token
            }));
        }
Esempio n. 12
0
        public ResponseData AccountLogin(AccountLoginDto accountLoginDto)
        {
            ResponseData responseData = null;
            AccountModel accountModel = accountRepository.FindEntity(c => c.AccountName == accountLoginDto.AccountName);

            if (accountModel != null)
            {
                accountModel = accountRepository.FindEntity(c => c.AccountName == accountLoginDto.AccountName && c.AccountPasswd == accountLoginDto.AccountPasswd);
                if (accountModel != null)
                {
                    responseData = new ResponseData {
                        MsgCode = 200, Message = "登录成功"
                    };
                }
                return(new ResponseData {
                    MsgCode = 400, Message = "账号密码不正确"
                });
            }
            return(new ResponseData {
                MsgCode = 400, Message = "账号不存在"
            });
        }
Esempio n. 13
0
        public async Task <SingleResult <AccountPublicDto> > Login(AccountLoginDto model)
        {
            var result = new SingleResult <AccountPublicDto>();

            var auth = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, false);

            if (auth.Succeeded)
            {
                var user = await _userManager.Users.Include(x => x.ReservedBooks).FirstOrDefaultAsync(x => x.Email == model.Email);

                var roles = await GetUserRoles(user);

                var token = (string) await GenerateJwtToken(model.Email, user, roles);

                //await _userManager.SetAuthenticationTokenAsync(user, "SmartLibrary", "AuthorizationToken", token);
                _context.UserTokens.Add(new IdentityUserToken <string>()
                {
                    UserId        = user.Id,
                    LoginProvider = "Identity" + Guid.NewGuid().ToString(),
                    Name          = "Authorization token",
                    Value         = token
                });
                _context.SaveChanges();

                result.Data = _mapper.Map <ApplicationUser, AccountPublicDto>(user);
                result.Data.AuthorizationToken = token;
                result.Data.Roles   = roles;
                result.IsSuccessful = true;
            }
            else
            {
                result.Message = "Incorrect username or password";
            }

            return(result);
        }
Esempio n. 14
0
 public ResponseData AccountLogin([FromBody] AccountLoginDto accountLoginDto)
 {
     return(accountService.AccountLogin(accountLoginDto));
 }
        public async Task <JsonResult> Login(AccountLoginDto dto)
        {
            var result = await _accountService.Login(dto, AuthenticationManager);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Esempio n. 16
0
        public IHttpActionResult Login(AccountLoginDto model)
        {
            string OldHASHValue = string.Empty;

            byte[]        SALT   = new byte[64];
            List <string> errors = new List <string>();

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            switch (model.AccountType)
            {
            case "C":
                var customer = _context.Customers.SingleOrDefault(c => c.Email == model.Email);
                if (customer == null)
                {
                    ModelState.AddModelError("", "Given Email is not registered with us.");
                    return(BadRequest(ModelState));
                }

                var login = _context.Logins.SingleOrDefault(l => l.Email == customer.Email);
                if (login == null)
                {
                    ModelState.AddModelError("", "Given Email is not registered with us.");
                    return(BadRequest(ModelState));
                }
                else if (!login.EmailActivated)
                {
                    ModelState.AddModelError("", "Email is not verified, please verify from the email sent.");
                    return(BadRequest(ModelState));
                }
                OldHASHValue = login.Password;
                SALT         = login.PasswordSalt;

                bool isValidLogin = AuthenticationLogic.CompareHashValue(model.Password, model.Email, OldHASHValue, SALT);

                if (!isValidLogin)
                {
                    ModelState.AddModelError("", "Given password is incorrect.");
                    return(BadRequest(ModelState));
                }
                else
                {
                    var customerDto = Mapper.Map <Customer, CustomerDto>(customer);
                    customerDto.AverageRating = BusinessLogic.GetAverageCustomerRating(customerDto.CustomerId);
                    return(Ok(customerDto));
                }

            case "D":
                var truckOwner = _context.TruckOwners.SingleOrDefault(t => t.Email == model.Email);
                if (truckOwner == null)
                {
                    ModelState.AddModelError("", "Given Email is not registered with us.");
                    return(BadRequest(ModelState));
                }

                var truckOwnerLogin = _context.Logins.SingleOrDefault(l => l.Email == truckOwner.Email);
                if (truckOwnerLogin == null)
                {
                    ModelState.AddModelError("", "Given Email is not registered with us.");
                    return(BadRequest(ModelState));
                }
                else if (!truckOwnerLogin.EmailActivated)
                {
                    ModelState.AddModelError("", "Email is not verified, please verify from the email sent.");
                    return(BadRequest(ModelState));
                }

                OldHASHValue = truckOwnerLogin.Password;
                SALT         = truckOwnerLogin.PasswordSalt;

                bool isValid = AuthenticationLogic.CompareHashValue(model.Password, model.Email, OldHASHValue, SALT);

                if (!isValid)
                {
                    ModelState.AddModelError("", "Given password is incorrect.");
                    return(BadRequest(ModelState));
                }
                else
                {
                    var truckOwnerDto = Mapper.Map <TruckOwner, TruckOwnerDto>(truckOwner);
                    truckOwnerDto.AverageRating = BusinessLogic.GetAverageDriverRating(truckOwnerDto.TruckOwnerId);
                    return(Ok(truckOwnerDto));
                }

            default:
                ModelState.AddModelError("", "Invalid Account type");
                return(BadRequest(ModelState));
            }
        }
Esempio n. 17
0
 public async Task <ServiceResult <TokenDto> > Login(AccountLoginDto loginDto)
 {
     return(await _accountService.AccountLoginAsync(loginDto));
 }