private async Task SendRecoverEmail(string email, string userName)
 {
     var expires     = DateTime.Now.AddHours(2);
     var issuer      = _configuration["Issuer"];
     var securityKey = _awsSecretManagerService.GetSecret(_configuration["SecretName_RecoverEmail"]);
     var claims      = new[]
     {
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, email),
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.UniqueName, email)
     };
     var serializedToken = _securityTokenHandler.WriteToken(email, claims, issuer, securityKey, expires);
     var url             = _configuration["PLAYERS2_URL"] + "newpassword?u17=";
     var template        = ForgotPasswordTemplate.GetForgotPasswordBody(url + serializedToken);
     var emailTopic      = _configuration["EMAIL_TOPIC"];
     var message         = new Message()
     {
         From    = "*****@*****.**",
         Body    = template,
         To      = email,
         Subject = $"{userName}, change your password of PLAYER2 here!"
     };
     await _snsClient.Send(emailTopic, JsonConvert.SerializeObject(new
     {
         Message = message
     })).ConfigureAwait(false);
 }
Exemplo n.º 2
0
 private async Task SendConfirmationEmail(string email, string userName)
 {
     var expires     = DateTime.Now.AddDays(30);
     var issuer      = _configuration["Issuer"];
     var securityKey = _awsSecretManagerService.GetSecret(_configuration["SecretName_ConfirmEmail"]);
     var claims      = new[]
     {
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, email),
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
         new System.Security.Claims.Claim(JwtRegisteredClaimNames.UniqueName, email)
     };
     var serializedToken = _securityTokenHandler.WriteToken(email, claims, issuer, securityKey, expires);
     var url             = _configuration["PLAYERS2_URL"] + "confirm.html?u19=";
     var template        = CreateAccountTemplate.GetAcocuntsBody(url + serializedToken);
     var emailTopic      = _configuration["EMAIL_TOPIC"];
     var message         = new Message()
     {
         From    = "*****@*****.**",
         Body    = template,
         To      = email,
         Subject = $"Welcome to PLAYER2 {userName}! Please confirm your e-mail here"
     };
     await _snsClient.Send(emailTopic, JsonConvert.SerializeObject(new
     {
         Message = message
     })).ConfigureAwait(false);
 }
Exemplo n.º 3
0
        public string GenerateToken(string name, string role, int userId, object validationId, string userPath, out string refreshTokenString, bool refreshTokenAsWell = false)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentOutOfRangeException(nameof(name));
            }

            string tokenString = null;

            refreshTokenString = null;

            if (_handler.CanWriteToken)
            {
                var signingCredentials = new SigningCredentials(_securityKey.SecurityKey, _tokenParameters.EncryptionAlgorithm);
                var now               = _tokenParameters.ValidFrom ?? DateTime.UtcNow;
                var numericNow        = GetNumericDate(now);
                var notBefore         = now;
                var numericNotBefore  = GetNumericDate(notBefore);
                var expiration        = now.AddMinutes(_tokenParameters.AccessLifeTimeInMinutes);
                var numericExpiration = GetNumericDate(expiration);
                var header            = new JwtHeader(signingCredentials);
                var payload           = new JwtPayload
                {
                    { "iss", _tokenParameters.Issuer },
                    { "sub", _tokenParameters.Subject },
                    { "aud", _tokenParameters.Audience },
                    { "exp", numericExpiration },
                    { "iat", numericNow },
                    { "nbf", numericNotBefore },
                    { "name", name },
                    { "jti", Guid.NewGuid().ToString("N") },
                    { "uid", userId },
                    { "uvid", validationId },
                    { "upath", userPath }
                };
                if (!string.IsNullOrWhiteSpace(role))
                {
                    payload.AddClaim(new Claim("role", role));
                }

                var accessToken = new JwtSecurityToken(header, payload);
                tokenString = _handler.WriteToken(accessToken);

                if (refreshTokenAsWell)
                {
                    var refreshExpiration = expiration.AddMinutes(_tokenParameters.RefreshLifeTimeInMinutes);
                    numericExpiration = GetNumericDate(refreshExpiration);
                    notBefore         = expiration;
                    numericNotBefore  = GetNumericDate(notBefore);
                    payload           = new JwtPayload
                    {
                        { "iss", _tokenParameters.Issuer },
                        { "sub", _tokenParameters.Subject },
                        { "aud", _tokenParameters.Audience },
                        { "exp", numericExpiration },
                        { "iat", numericNow },
                        { "nbf", numericNotBefore },
                        { "name", name },
                        { "jti", Guid.NewGuid().ToString("N") },
                        { "uid", userId },
                        { "uvid", validationId },
                        { "upath", userPath }
                    };

                    var refreshToken = new JwtSecurityToken(header, payload);
                    refreshTokenString = _handler.WriteToken(refreshToken);
                }
            }

            return(tokenString);
        }
        internal override HandleResponse HandleIt(AuthenticateUserCommand request, CancellationToken cancellationToken)
        {
            var email = request.Email;

            _logger.Info($"Trying loggin for user {email}");

            var isFacebook = request.FacebookLogin != null &&
                             !string.IsNullOrEmpty(request.FacebookLogin.Email) &&
                             !string.IsNullOrEmpty(request.FacebookLogin.AccessToken);

            if (isFacebook)
            {
                var isValid = InvokeFunction(LAMBDA_FACEBOOK_VALIDATED, new { request.FacebookLogin }).Result;
                if (!isValid)
                {
                    return new HandleResponse()
                           {
                               Error = "Invalid token!"
                           }
                }
                ;
                email = request.FacebookLogin.Email;
            }

            var isGoogle = request.GoogleLogin != null &&
                           !string.IsNullOrEmpty(request.GoogleLogin.AccessToken) &&
                           !string.IsNullOrEmpty(request.GoogleLogin.ProfileObj.Email);

            if (isGoogle)
            {
                var isValid = InvokeFunction(LAMBDA_GOOGLE_VALIDATED, new { request.GoogleLogin }).Result;
                if (!isValid)
                {
                    return new HandleResponse()
                           {
                               Error = "Invalid token!"
                           }
                }
                ;
                email = request.GoogleLogin.ProfileObj.Email;
            }

            var user = _accountRepository.GetAccountByEmail(email).Result;

            if (user == null)
            {
                _logger.Info($"User {email} was not found on database.");
                return(new HandleResponse()
                {
                    Error = $"Invalid credentials, User {email} was not found"
                });
            }

            if (!isFacebook && !isGoogle)
            {
                var isPasswordValid = _passwordHasher.Verify(request.Password, user.PasswordHash);

                if (!isPasswordValid)
                {
                    return new HandleResponse()
                           {
                               Error = $"Invalid credentials invalid password"
                           }
                }
                ;
                if (!user.IsActive)
                {
                    return new HandleResponse()
                           {
                               Error = "You must verificated your e-mai. Please, check your inbox messages."
                           }
                }
                ;
            }

            var roleClaims   = user.Roles.Select(e => e.Role.Claims.Select(c => c.Claim));
            var customClaims = new List <System.Security.Claims.Claim>();

            foreach (var roleClaim in roleClaims)
            {
                foreach (var claim in roleClaim)
                {
                    var customClaim = new System.Security.Claims.Claim(claim.ClaimType, claim.ClaimValue);

                    var existent = customClaims.FirstOrDefault(c => c.Type.Equals(customClaim.Type,
                                                                                  StringComparison.InvariantCultureIgnoreCase) &&
                                                               c.Value.Equals(customClaim.Value, StringComparison.InvariantCultureIgnoreCase));
                    if (existent == null)
                    {
                        customClaims.Add(customClaim);
                    }
                }
            }
            var roleId = user.Roles.FirstOrDefault()?.Role?.Id ?? 0;
            var claims = new[]
            {
                new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, roleId.ToString()),
                new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                new System.Security.Claims.Claim(JwtRegisteredClaimNames.UniqueName, email),
                new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()),
            }.Union(customClaims);
            var expires         = DateTime.Now.AddHours(2);
            var issuer          = _configuration["Issuer"];
            var securityKey     = _awsSecretManagerService.GetSecret(_configuration["SecretName"]);
            var serializedToken = _securityTokenHandler.WriteToken(email, claims, issuer, securityKey, expires);
            var userDto         = _mapper.Map <UserDto>(user);

            return(new HandleResponse()
            {
                Content = new
                {
                    access_token = serializedToken,
                    token_type = "Bearer",
                    user = userDto
                }
            });
        }