コード例 #1
0
        public Token UseToken(Guid accountId, Guid tokenId, TokenPurpose purpose)
        {
            var accountContext  = Context.GetAccountDbContext(accountId);
            var tokenRepository = accountContext.GetTokenRepository();
            var token           = tokenRepository.GetOneOrNullById(tokenId);

            // проверим токен
            if (token == null)
            {
                throw new TokenNotValidException("Токен не найден");
            }

            if (token.IsUsed)
            {
                throw new TokenNotValidException("Токен уже использован");
            }

            if (token.Purpose != purpose)
            {
                throw new TokenNotValidException("Неверный тип токена");
            }

            if (token.EndDate < DateTime.Now)
            {
                throw new TokenNotValidException("Истекло время жизни токена");
            }

            // проверим пользователя
            var userRepository = accountContext.GetUserRepository();
            var user           = userRepository.GetById(token.UserId);

            if (token.SecurityStamp != user.SecurityStamp)
            {
                // происходит когда пользователь меняет пароль
                throw new TokenNotValidException("Токен устарел");
            }

            if (user.InArchive)
            {
                throw new TokenNotValidException("Пользователь удален");
            }

            // сделаем отметку, что токен уже использован
            token.IsUsed = true;
            accountContext.SaveChanges();

            return(token);
        }
コード例 #2
0
        public Token GenerateToken(Guid accountId, Guid userId, TokenPurpose purpose, TimeSpan actualInterval)
        {
            var accountContext = Context.GetAccountDbContext(accountId);
            var userRepository = accountContext.GetUserRepository();
            var user           = userRepository.GetById(userId);

            var token = new Token()
            {
                Purpose       = purpose,
                UserId        = user.Id,
                SecurityStamp = user.SecurityStamp,
                EndDate       = DateTime.Now.Add(actualInterval)
            };

            var userTokenRepository = accountContext.GetTokenRepository();

            token = userTokenRepository.Add(token);

            return(token);
        }
コード例 #3
0
        //change this and add a otp send msms
        public string GetOtp(User user, TokenPurpose tokenPurpose)
        {
            string[]          saAllowedCharacters = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
            string            otp   = "";
            VerificationToken token = null;

            do
            {
                otp   = Util.GenerateRandomOTP(6, saAllowedCharacters);
                token = _tokenRepository.GetLatestUserToken(otp);
            } while (token != null);
            var verificationToken = new VerificationToken()
            {
                IsActive     = true,
                UserId       = user.UserId,
                Token        = otp,
                CreatedOn    = DateTime.Now,
                ExpiresOn    = DateTime.Now.AddMinutes(5),
                TokenPurpose = tokenPurpose
            };

            _tokenRepository.Add(verificationToken);
            return(otp);
        }
コード例 #4
0
 public static bool IsSatisfied(this TokenPurpose requirement, TokenPurpose enforcement)
 {
     return((requirement & enforcement) == requirement);
 }
コード例 #5
0
 public static string GenerateTokenPurpose(TokenPurpose tokenPurpose, string credentials)
 {
     return(string.Format("{0}:{1}", tokenPurpose, credentials));
 }
コード例 #6
0
        public void EnsureToken(TokenPayload token, TokenPurpose usage, int operation, int karma, out AccountData account)
        {
            account = null;

            if (token == null)
            {
                throw new InvalidOperationException("Token Not Found");
            }

            if (token.ValidTo < _time.UtcNow)
            {
                throw new InvalidOperationException("Token Outdated");
            }

            if (!usage.IsSatisfied(token.Purpose))
            {
                throw new InvalidOperationException("Token Insufficient Privilege");
            }

            if (_context.TokenRevocationList.Any(x => x.TokenSerial == token.TokenId))
            {
                throw new InvalidOperationException("Token Revoked");
            }

            account = _context.AccountData.Include(x => x.PrivilegeLevelNavigation).Single(x => x.AccountId == token.AccountId);

            if (account == null)
            {
                throw new InvalidOperationException("Token Account Not Found");
            }

            if (account.PrivilegeLevel == GlobalConfig.ACCOUNT_BLOCKED_LEVEL)
            {
                throw new InvalidOperationException("Token Account Blacklisted");
            }

            if (account.SuspendUntil != null && account.SuspendUntil >= _time.UtcNow)
            {
                throw new InvalidOperationException("Token Account Suspended");
            }

            if (!account.PrivilegeLevelNavigation.IgnoreKarma && karma != 0)
            {
                var before = account.Karma;
                var after  = account.Karma + karma;

                if (after < 0 && GlobalConfig.USER_ENABLE_KARMA)
                {
                    throw new InvalidOperationException("Token Insufficient Karma");
                }

                account.Karma = after;

                _context.AccountData.Update(account);

                _context.KarmaLog.Add(new KarmaLog
                {
                    ReportTime = _time.UtcNow,
                    AccountId  = account.AccountId,
                    Reason     = operation,
                    Before     = before,
                    After      = after
                });
            }

            _context.SaveChanges();
        }