예제 #1
0
        /// <summary>
        /// Authenticates user by providing its email and password
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public AuthInfo Authenticate(LoginRequest loginRequest)
        {
            var member = memberRepository.GetByEmail(loginRequest.Email);

            if (member == null)
            {
                throw new AuthenticationException();
            }

            if (!passwordHasher.Verify(loginRequest.Password, member.Password))
            {
                throw new AuthenticationException();
            }

            var now             = DateTime.Now;
            var newAccessToken  = tokenHandler.GenerateAccessToken(member);
            var newRefreshToken = tokenHandler.GenerateRefreshToken();

            tokenRepository.Add(new Token()
            {
                AccessToken  = newAccessToken,
                RefreshToken = newRefreshToken,
                BlackListed  = false,
                ExpiredAt    = now.AddDays(5),
                CreatedAt    = now,
            });

            return(new AuthInfo
            {
                AccessToken = newAccessToken,
                RefreshToken = newRefreshToken
            });
        }
예제 #2
0
        public async Task <TokenModel> Build(CredentialModel creds)
        {
            var client = await _tokenRepository.ClientRepository.GetByIdAsync(creds.Id);

            if (client == null)
            {
                throw new FaultException($"Client by Id {creds.Id} isn't exist");
            }

            if (!_credentialsValidator.IsValid(creds, client))
            {
                throw new FaultException("Wrong password");
            }

            var tokenValue = BuildSecureToken();

            _tokenRepository.Add(tokenValue, client);
            await _tokenRepository.Save();

            var token = new TokenModel
            {
                TimeToLive = _tokenValidator.GetTokenTimeToLive(),
                Value      = tokenValue
            };

            return(token);
        }
        public async Task <bool> SalvarToken(TokenViewModel token)
        {
            try
            {
                var tokenDB = await _tokenRepository.Get(x => x.TelefoneResp == token.TelefoneResp);

                Token newToken = new Token();
                if (tokenDB.Any())
                {
                    newToken        = tokenDB.FirstOrDefault();
                    newToken.UserId = token.UserId;
                    await BeginTransaction();

                    await Task.Run(() => _tokenRepository.Update(newToken));
                    await Commit();

                    return(true);
                }
                else
                {
                    newToken = Mapper.Map <Token>(token);
                    await BeginTransaction();

                    await Task.Run(() => _tokenRepository.Add(newToken));
                    await Commit();

                    return(true);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #4
0
        public TokenViewModel GenerateToken(int userID, string username, string password, string ip, string userAgent, long ticks)
        {
            string hash      = string.Join(":", new string[] { username, ip, userAgent, ticks.ToString() });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMACSHA256.Create(_alg))
            {
                hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = Convert.ToBase64String(hmac.Hash);
                hashRight = string.Join(":", new string[] { username, ticks.ToString() });
            }
            string tokenString = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));
            var    issuedOn    = DateTime.Now;

            var token = new Token
            {
                UserId      = userID,
                TokenString = tokenString,
                IssuedOn    = issuedOn,
                ExpiresIn   = 86400
            };

            _tokenRepository.Add(token);

            _unitOfWork.SaveChanges();
            return(Mapper.Map <Token, TokenViewModel>(token));
        }
예제 #5
0
        public string CreateDefaultOrganizationAndProject(User user)
        {
            string organizationId = user.OrganizationIds.FirstOrDefault();

            if (!String.IsNullOrEmpty(organizationId))
            {
                var defaultProject = _projectRepository.GetByOrganizationId(user.OrganizationIds.First(), useCache: true).FirstOrDefault();
                if (defaultProject != null)
                {
                    return(defaultProject.Id);
                }
            }
            else
            {
                var organization = new Organization {
                    Name = "Default Organization"
                };
                BillingManager.ApplyBillingPlan(organization, Settings.Current.EnableBilling ? BillingManager.FreePlan : BillingManager.UnlimitedPlan, user);
                _organizationRepository.Add(organization);
                organizationId = organization.Id;
            }

            var project = new Project {
                Name = "Default Project", OrganizationId = organizationId
            };

            project.NextSummaryEndOfDayTicks = DateTime.UtcNow.Date.AddDays(1).AddHours(1).Ticks;
            project.AddDefaultOwnerNotificationSettings(user.Id);
            project = _projectRepository.Add(project);

            _tokenRepository.Add(new Token {
                Id             = StringExtensions.GetNewToken(),
                OrganizationId = organizationId,
                ProjectId      = project.Id,
                CreatedUtc     = DateTime.UtcNow,
                ModifiedUtc    = DateTime.UtcNow,
                Type           = TokenType.Access
            });

            if (!user.OrganizationIds.Contains(organizationId))
            {
                user.OrganizationIds.Add(organizationId);
                _userRepository.Save(user, true);
            }

            return(project.Id);
        }
예제 #6
0
        public void CreateSampleOrganizationAndProject(string userId)
        {
            if (_tokenRepository.GetById(SAMPLE_API_KEY) != null)
            {
                return;
            }

            User user         = _userRepository.GetById(userId, true);
            var  organization = new Organization {
                Id = "537650f3b77efe23a47914f3", Name = "Acme"
            };

            _billingManager.ApplyBillingPlan(organization, BillingManager.UnlimitedPlan, user);
            organization = _organizationRepository.Add(organization);

            var project = new Project {
                Id = "537650f3b77efe23a47914f4", Name = "Disintegrating Pistol", OrganizationId = organization.Id
            };

            project.NextSummaryEndOfDayTicks = DateTime.UtcNow.Date.AddDays(1).AddHours(1).Ticks;
            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultOwnerNotificationSettings(userId);
            project = _projectRepository.Add(project);

            _tokenRepository.Add(new Token {
                Id             = SAMPLE_API_KEY,
                OrganizationId = organization.Id,
                ProjectId      = project.Id,
                ExpiresUtc     = DateTime.UtcNow.AddYears(100),
                CreatedUtc     = DateTime.UtcNow,
                ModifiedUtc    = DateTime.UtcNow,
                Type           = TokenType.Access
            });

            _tokenRepository.Add(new Token {
                Id             = SAMPLE_USER_API_KEY,
                OrganizationId = organization.Id,
                UserId         = user.Id,
                ExpiresUtc     = DateTime.UtcNow.AddYears(100),
                CreatedUtc     = DateTime.UtcNow,
                ModifiedUtc    = DateTime.UtcNow,
                Type           = TokenType.Access
            });

            user.OrganizationIds.Add(organization.Id);
            _userRepository.Save(user);
        }
예제 #7
0
        public Token CreateToken(User user)
        {
            Token newToken = new Token();

            newToken.Id             = Guid.NewGuid().ToString();
            newToken.ExpireAt       = DateTime.Now.AddDays(3);
            newToken.UserId         = user.Id;
            newToken.Active         = true;
            newToken.CreatedCompany = user.CompanyId;
            newToken.Ticket         = GetToken();
            _tokenRepository.Add(newToken);
            _tokenRepository.Commit();
            return(newToken);
        }
예제 #8
0
        public void AddNewToken(User user, string accessToken, string refreshTokenSerialNumber, string refreshToken)
        {
            DeleteExpiredTokens();
            Token userToken = new Token();

            userToken.UserId                      = user.Id;
            userToken.RefreshTokenValue           = refreshToken;
            userToken.AccessTokenHash             = accessToken;
            userToken.RefreshTokenIdHash          = refreshTokenSerialNumber;
            userToken.RefreshTokenIdHashSource    = null;
            userToken.RefreshTokenExpiresDateTime = DateTimeOffset.UtcNow.AddMinutes(RefreshTokenExpirationTimeInMinutes);
            userToken.AccessTokenExpiresDateTime  = DateTimeOffset.UtcNow.AddMinutes(AccessTokenExpirationTimeInMinutes);
            TokenRepository.Add(userToken);
        }
예제 #9
0
        public Token Create(User user)
        {
            var token = new Token {
                Id          = Guid.NewGuid().ToString("N"),
                UserId      = user.Id,
                CreatedUtc  = DateTime.UtcNow,
                ModifiedUtc = DateTime.UtcNow,
                CreatedBy   = user.Id,
                Type        = TokenType.Access
            };

            _tokenRepository.Add(token);

            return(token);
        }
예제 #10
0
        public Token Create(User user)
        {
            var token = new Token {
                Id          = StringExtensions.GetNewToken(),
                UserId      = user.Id,
                CreatedUtc  = DateTime.UtcNow,
                ModifiedUtc = DateTime.UtcNow,
                CreatedBy   = user.Id,
                Type        = TokenType.Access
            };

            _tokenRepository.Add(token);

            return(token);
        }
예제 #11
0
        public async Task <IActionResult> Validate([FromBody] User user)
        {
            try
            {
                string token = null;

                var login = await UserRepository.Validate(user);

                if (login != null)
                {
                    var createDate = DateTime.Now;
                    var expireDate = DateTime.Now.AddHours(1);

                    token = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken
                                                                         (new JwtHeader(new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("RmF2aWRldkZhdmlkZXY")), SecurityAlgorithms.HmacSha256)), new JwtPayload
                                                                         (
                                                                             "https://favidev.com/",
                                                                             "https://favidev.com/",
                                                                             new[]
                    {
                        new Claim(ClaimTypes.Name, login.Name),
                        new Claim(ClaimTypes.Role, login.UserTypeId.ToString())
                    },
                                                                             createDate,
                                                                             expireDate
                                                                         )
                                                                         ));

                    TokenRepository.Add(new Token()
                    {
                        UserId     = login.Id,
                        Key        = token,
                        Remove     = false,
                        CreateDate = createDate,
                        ExpireDate = expireDate,
                    });

                    return(Json((token, userTypeId: login.UserTypeId.ToString())));
                }

                return(Json(null));
            }
            catch (Exception exception)
            {
                Logger.LogInformation(exception.Message);
                return(new EmptyResult());
            }
        }
        private string GetTokenByIdentity(ClaimsIdentity identity, Role role, ObjectId id)
        {
            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: _authOptionsConfig.Value.Issuer,
                audience: _authOptionsConfig.Value.Audience,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromSeconds(_authOptionsConfig.Value.LifeTime)),
                signingCredentials: new SigningCredentials(_authOptionsConfig.Value.SymmetricSecurityKey, SecurityAlgorithms.HmacSha256));

            _tokenRepository.Add(role, id, jwt, _authOptionsConfig.Value.LifeTime);

            return(new JwtSecurityTokenHandler().WriteToken(jwt));
        }
예제 #13
0
        public ServerResult <User> Login(Login args)
        {
            try
            {
                if (args == null)
                {
                    throw new Exception("Arguments are empty");
                }

                Entities.User user = userRepository.GetByEmail(args.Email);
                if (user != null)
                {
                    tokenRepository.Add(new Entities.Token
                    {
                        User        = user,
                        UserId      = user.Id,
                        TokenString = Convert.ToBase64String(Guid.NewGuid().ToByteArray()),
                        startTime   = DateTime.Now,
                        endTime     = DateTime.Now.AddHours(3)
                    });
                    return(new ServerResult <User>
                    {
                        Data = user.ToDTO(),
                        Success = true
                    });
                }
                else
                {
                    return new ServerResult <User>
                           {
                               Success = false,
                               Message = "Bad credentials",
                               Data    = null,
                           }
                };
            }
            catch (Exception e)
            {
                return(new ServerResult <User>
                {
                    Success = false,
                    Message = e.Message,
                });
            }
        }
예제 #14
0
        /// <summary>
        ///  Function to generate unique token with expiry against the provided userId.
        ///  Also add a record in database for generated token.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public TokenEntity GenerateToken(int userId)
        {
            string   token     = Guid.NewGuid().ToString();
            DateTime issuedOn  = DateTime.Now;
            DateTime expiredOn = DateTime.Now.AddSeconds(
                Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
            var tokendomain = new Token
            {
                UserId    = userId,
                AuthToken = token,
                IssuedOn  = issuedOn,
                ExpiresOn = expiredOn
            };

            _tokenRepository.Add(tokendomain);

            return(Mapper.Map <TokenEntity>(tokendomain));
        }
예제 #15
0
        /// <summary>
        /// Gerar e cadastrar Token
        /// </summary>
        /// <param name="applicationUser"></param>
        /// <returns></returns>
        private ActionResult GenerateToken(ApplicationUser applicationUser)
        {
            var token = BuildToken(applicationUser);

            var newToken = new Token()
            {
                RefreshToken           = token.RefreshToken,
                ExpirationToken        = token.Expiration,
                ExpirationRefreshToken = token.ExpirationRefreshToken,
                User        = applicationUser,
                DateCreated = DateTime.Now,
                Used        = false
            };

            _tokenRepository.Add(newToken);

            return(Ok(token));
        }
예제 #16
0
        private TokenDTO GetUserToken(ApplicationUser usuario)
        {
            //retorna o Token (JWT)
            var token = BuildToken(usuario);

            //salvar o token na base
            var tokenModel = new Token()
            {
                RefreshToken           = token.RefreshToken,
                ExpirationRefreshToken = token.ExpirationRefreshToken,
                ExpitarionToken        = token.Expiration,
                User      = usuario,
                CreatedAt = DateTime.Now,
                Used      = false
            };

            _tokenRepository.Add(tokenModel);
            return(token);
        }
예제 #17
0
        public IActionResult CreateToken([FromBody] CreationRequest request)
        {
            _logger.LogInformation($"Entered Method to create a Token", "Token Creation");

            var newToken = new Token
            {
                ID      = Token.GenerateID(),
                Expires = DateTimeOffset.Now.AddHours(1),
                Content = request.Content
            };

            _logger.LogInformation($"Created a new Token with ID {newToken.ID}", "Token Creation");

            _repository.Add(newToken.ID, newToken);

            return(Ok(
                       new TokenResponse
            {
                ID = newToken.ID,
                Expires = newToken.Expires
            }
                       ));
        }
예제 #18
0
        public string GenerateToken(string name, string password)
        {
            string tokenValue = tokenRepository.GetTokenByName(name).Value;

            if (!string.IsNullOrEmpty(tokenValue))
            {
                return(tokenValue);
            }

            if (identityRepository.Exist(name, password))
            {
                var token = new Token(
                    identityRepository.Get(name).Id,
                    tokenGenerator.Generate(),
                    TimeProvider.Current.Now,
                    GetExpiredTime());

                tokenRepository.Add(token);

                return(token.Value);
            }

            return(String.Empty);
        }
예제 #19
0
 public void CreateToken(DbToken token)
 {
     _tokenRepository.Add(token);
     _unitOfWork.Commit();
 }
예제 #20
0
 public void InsertToken(Token token)
 {
     _repository.Add(token);
 }
 public Task <bool> AddToken(Token token, CancellationToken cancellationToken)
 {
     return(_tokenRepository.Add(token, cancellationToken));
 }
예제 #22
0
 public void Add(AppUserToken appUserToken)
 {
     using var tran = _unitOfWork.BeginTransaction();
     _tokenRepository.Add(appUserToken);
     tran.Commit();
 }