Exemplo n.º 1
0
        public async Task <IActionResult> Register(RegisterModel model, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new IdentityUser
            {
                UserName = model.Username ?? model.Email,
                Email    = model.Email
            };
            var result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                result.Errors.ToList().ForEach(error => ModelState.AddModelError(string.Empty, error.Description));

                return(BadRequest(ModelState));
            }

            var userFound = await UserManager.FindByEmailAsync(model.Email);

            await UserService.Create(userFound.Id, cancellationToken);

            Logger.LogInformation("User created a new account with password.");

            var jwtToken = await JwtTokenService.Generate(user.Id);

            return(Ok(jwtToken));
        }
        public async Task <IActionResult> Login([FromBody] LoginInputModel loginInputModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _signInManager.PasswordSignInAsync(
                loginInputModel.Username,
                loginInputModel.Password,
                false, false
                );

            if (!result.Succeeded)
            {
                return(this.BadRequest());
            }

            var user = await _userManager.Users.FirstOrDefaultAsync(u =>
                                                                    u.UserName == loginInputModel.Username);

            var token = _authenticationTokenGenerator.Generate(user);

            var outputModel = new LoginOutputModel()
            {
                Token     = token.Value,
                ExpiresIn = token.ExpiresIn,
                TokenType = token.TokenType
            };

            return(Ok(outputModel));
        }
        private ChannelBase CreateSecureChannel()
        {
            var getEC2TagOption = configuration.GetEC2TagOptionFromEC2TagsSection();
            var environmentTag  = getEC2TagOption.Environment;
            var customerTag     = getEC2TagOption.Customer;

            var jwtBearerTokenSymetricSecurityKey = refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiJwtBearerTokenSymetricSecurityKey;

            var credentials = CallCredentials.FromInterceptor((context, metadata) =>
            {
                var jwtToken = new JwtToken()
                               .SetExpires(DateTime.UtcNow.AddMinutes(2))
                               .SetIssuer(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory)
                               .SetAudience(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory);

                var bearerToken = jwtTokenService.Generate(jwtToken, jwtBearerTokenSymetricSecurityKey);

                metadata.Add("Authorization", $"Bearer {bearerToken}");
                return(Task.CompletedTask);
            });


            var channelCredentials = ChannelCredentials.Create(new SslCredentials(), credentials);
            var grpcChannelOptions = new GrpcChannelOptions
            {
                //HttpClient = httpClient,
                // LoggerFactory = logFactory,
                Credentials = channelCredentials
            };

            var channel = GrpcChannel.ForAddress(refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiAddress, grpcChannelOptions);

            return(channel);
        }
Exemplo n.º 4
0
        public async Task <(Result result, string token)> LoginAsync(string cardId, string pin1)
        {
            // Is the card exist?
            var card = await _context.Cards.Include(c => c.Citizen)
                       .ThenInclude(c => c.HealthInfo)
                       .FirstOrDefaultAsync(c => c.Id == cardId);

            if (card is null)
            {
                return(Result.Failure("محاولة تسجيل دخول غير صحيحة."), null);
            }

            // Is card active?
            if (!card.Active)
            {
                return(Result.Failure("هذه البطاقة معطلة."), null);
            }

            // Is card valid?
            if (card.TerminationDate < _dateTime.Now)
            {
                return(Result.Failure("هذه البطاقة منتهية الصلاحية."), null);
            }

            // Is card locked out
            if (await _userManager.IsLockedOutAsync(card))
            {
                return(Result.Failure("لقد حاولت عدة مرات تم تعطيل الحساب لبضع دقائق حاول في وقت لاحق."), null);
            }

            // Is this a correct PIN?
            var isCorrectPin = card.Pin1Hash == _hashService.Create(pin1, card.Pin1Salt);

            var cardRoles = await _userManager.GetRolesAsync(card);

            if (isCorrectPin)
            {
                var token = _jwtTokenService.Generate(
                    new List <Claim>
                {
                    new Claim("img", Path.Combine(_directoryService.CitizenPhotosRelativePath, card.Citizen.PhotoUrl)),
                    new Claim("firstname", card.Citizen.FullName.FirstName),
                    new Claim("healthId", card.Citizen.HealthInfo.Id)
                }
                    .AddJti()
                    .AddNameIdentifier(card.CitizenId)
                    .AddSub(card.Id)
                    .AddRoles(cardRoles.ToArray())
                    );

                return(Result.Success(), token);
            }

            // try to signin with invalid password to increase lockout on failure counter
            // to enabled lockout account if failed to sign a lot of time
            await _signInManager.PasswordSignInAsync(card, "123", false, true);

            return(Result.Failure("محاولة تسجيل دخول غير صحيحة."), null);
        }
        public async Task <IActionResult> GetToken([FromBody] TokenRequestModel model)
        {
            Guid nonce = model.Nonce;

            if (m_nonceStore.Exists(nonce))
            {
                var deviceModel = model.DeviceModel;


                if (await m_attestationService.IsValidAttestation(model.AttestationCypher, attestSecret, nonce))
                {
                    // Creating the token
                    TokenParams tokenParams = new TokenParams(jwtSecret, JwtIssuer, JwtAudience);
                    var         token       = m_tokenService.Generate(deviceModel, tokenParams);
                    return(Ok(token));
                }
            }

            return(Ok(m_tokenService.GenerateFakeToken()));
        }