Esempio n. 1
0
        public async Task <ApiResponse <bool> > Verify(Guid tcid, string token)
        {
            Guard.Against.NullOrWhiteSpace(token, nameof(token));
            Guard.Against.NullOrEmpty(tcid, nameof(tcid));

            var tenantContact = await _hostRepository.GetFirstAsync <TenantContact>(tc => tc.Id == tcid,
                                                                                    includeProperties : "Tokens");

            if (tenantContact == null)
            {
                return(ApiResponse <bool> .Error());  //ErrorProvider.GetError("no_tenant_contact")
            }

            var validToken = tenantContact.Tokens.FirstOrDefault(t => t.Value == token);

            if (validToken != null && !validToken.Valid)
            {
                return(ApiResponse <bool> .Error()); //ErrorProvider.GetError("token_issued")
            }

            var validDurationPassed = validToken.CreatedOn.AddHours(24) < DateTime.Now;

            if (validDurationPassed)
            {
                return(ApiResponse <bool> .Error()); // ErrorProvider.GetError("token_expired")
            }
            validToken.Valid             = false;
            tenantContact.EmailConfirmed = true;
            _hostRepository.Update(tenantContact);
            await _hostRepository.SaveAsync();

            await CreateTenantResources(tenantContact.Email, tenantContact.PasswordHash);

            return(ApiResponse <bool> .Success());
        }
        public async Task <AuthResponse> GenerateAuthResponseForUser(ApplicationUser user)
        {
            var tokenHandler   = new JwtSecurityTokenHandler();
            var secretKey      = _configuration.GetSection("JwtSettings")["SecretKey"];
            var tokenLifeTime  = _configuration.GetSection("JwtSettings")["TokenLifeTime"];
            var secretKeyBytes = Encoding.ASCII.GetBytes(secretKey);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtCustomClaimNames.Id, user.Id.ToString()),
            };

            var userClaims = await _userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);

            var userRoles = await _userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));

                var role = await _roleManager.FindByNameAsync(userRole);

                if (role == null)
                {
                    continue;
                }

                var roleClaims = await _roleManager.GetClaimsAsync(role);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.Add(TimeSpan.Parse(tokenLifeTime)),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(secretKeyBytes), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var newToken     = _tokenFactory.GenerateToken();
            var refreshToken = new RefreshToken
            {
                Token             = newToken,
                JwtId             = token.Id,
                ApplicationUserId = user.Id,
                //ExpiresOn = DateTime.Now.AddMonths(1)
                ExpiresOn = DateTime.SpecifyKind(DateTime.Now.AddMonths(1), DateTimeKind.Utc)
            };

            _hostRepository.Create(refreshToken);
            await _hostRepository.SaveAsync();

            return(new AuthResponse {
                AccessToken = new AccessToken(tokenHandler.WriteToken(token),
                                              (int)TimeSpan.Parse(tokenLifeTime).TotalMinutes),
                RefreshToken = refreshToken.Token
            });
        }