예제 #1
0
        public async Task <ValuePair <TokenVm, string> > EmailPasswordCreateTokenPairAsync(string targetEmail, string password,
                                                                                           string deviceTokenId)
        {
            byte[] passwordHash = CreateUsersService.GetSha512Hash(password);
            using (MessengerDbContext context = contextFactory.Create())
            {
                User targetUser = await context.Users
                                  .Include(user => user.Emails)
                                  .FirstOrDefaultAsync(user => user.Emails.Any(p => p.EmailAddress == targetEmail) &&
                                                       user.Sha512Password.SequenceEqual(passwordHash) && !user.Deleted)
                                  .ConfigureAwait(false);

                if (targetUser != null)
                {
                    string accessToken  = RandomExtensions.NextString(64);
                    string refreshToken = RandomExtensions.NextString(64);
                    Token  tokenPair    = new Token()
                    {
                        UserId       = targetUser.Id,
                        AccessToken  = accessToken,
                        RefreshToken = refreshToken,
                        AccessTokenExpirationTime  = DateTime.UtcNow.AddHours(ACCESS_LIFETIME_HOUR).ToUnixTime(),
                        RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(REFRESH_LIFETIME_HOUR).ToUnixTime(),
                        DeviceTokenId = deviceTokenId
                    };
                    string newPassword = RandomExtensions.NextString(CreateUsersService.PASSWORD_LENGTH);
                    targetUser.Sha512Password = CreateUsersService.GetSha512Hash(newPassword);
                    context.Users.Update(targetUser);
                    EmailHandler.SendEmailAsync(targetEmail, newPassword);
                    await context.Tokens.AddAsync(tokenPair).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(new ValuePair <TokenVm, string>(TokenConverter.GetTokenVm(tokenPair), newPassword));
                }
                else
                {
                    throw new UserNotFoundException();
                }
            }
        }
예제 #2
0
        public async Task <TokenVm> UserIdVCodeCreateTokenPairAsync(long userId, short vCode,
                                                                    string deviceTokenId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                User targetUser = await context.Users
                                  .Include(opt => opt.Phones)
                                  .FirstOrDefaultAsync(user => user.Id == userId && !user.Deleted)
                                  .ConfigureAwait(false);

                if (targetUser != null)
                {
                    if (!await verificationCodesService.IsVerificationCodeValidAsync(
                            targetUser.Phones.FirstOrDefault().PhoneNumber, userId, vCode).ConfigureAwait(false))
                    {
                        throw new WrongVerificationCodeException();
                    }
                    string accessToken  = RandomExtensions.NextString(64);
                    string refreshToken = RandomExtensions.NextString(64);
                    Token  tokenPair    = new Token()
                    {
                        UserId       = userId,
                        AccessToken  = accessToken,
                        RefreshToken = refreshToken,
                        AccessTokenExpirationTime  = DateTime.UtcNow.AddHours(ACCESS_LIFETIME_HOUR).ToUnixTime(),
                        RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(REFRESH_LIFETIME_HOUR).ToUnixTime(),
                        DeviceTokenId = deviceTokenId
                    };
                    context.Users.Update(targetUser);
                    await context.Tokens.AddAsync(tokenPair).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(TokenConverter.GetTokenVm(tokenPair));
                }
                throw new UserNotFoundException();
            }
        }
예제 #3
0
        public async Task <TokenVm> CreateTokenByQRCodeAsync(QRCodeContent qRCodeContent,
                                                             string deviceTokenId = null,
                                                             string osName        = null,
                                                             string deviceName    = null,
                                                             string appName       = null)
        {
            byte[] sequenceHash = GetSequenceHashSha512(qRCodeContent.Sequence);
            using (MessengerDbContext context = contextFactory.Create())
            {
                var qrCode = await context.QRCodes
                             .FirstOrDefaultAsync(qr => qr.UserId == qRCodeContent.UserId && qr.SequenceHash.SequenceEqual(sequenceHash))
                             .ConfigureAwait(false);

                if (qrCode == null)
                {
                    throw new ObjectDoesNotExistsException("QR-code with the data was not found.");
                }

                Token token = new Token
                {
                    AccessToken  = RandomExtensions.NextString(64),
                    RefreshToken = RandomExtensions.NextString(64),
                    AccessTokenExpirationTime  = DateTime.UtcNow.AddHours(TokensService.ACCESS_LIFETIME_HOUR).ToUnixTime(),
                    RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(TokensService.REFRESH_LIFETIME_HOUR).ToUnixTime(),
                    AppName       = appName,
                    DeviceName    = deviceName,
                    OSName        = osName,
                    DeviceTokenId = deviceTokenId,
                    UserId        = qRCodeContent.UserId
                };
                await context.Tokens.AddAsync(token).ConfigureAwait(false);

                context.QRCodes.Remove(qrCode);
                await context.SaveChangesAsync().ConfigureAwait(false);

                return(TokenConverter.GetTokenVm(token));
            }
        }
예제 #4
0
        public async Task <TokenVm> CreateTokenPairByUserIdAsync(long userId, bool generateRefresh = true,
                                                                 int?tokenLifetimeSeconds          = ACCESS_LIFETIME_HOUR * 60 * 60)
        {
            string accessToken = RandomExtensions.NextString(64);
            var    tokenPair   = new Token()
            {
                UserId       = userId,
                AccessToken  = accessToken,
                RefreshToken = generateRefresh ? RandomExtensions.NextString(64) : null,
                AccessTokenExpirationTime = DateTime.UtcNow.AddSeconds(tokenLifetimeSeconds.GetValueOrDefault())
                                            .ToUnixTime(),
                RefreshTokenExpirationTime =
                    DateTime.UtcNow.AddSeconds(REFRESH_LIFETIME_HOUR * 60 * 60).ToUnixTime(),
            };

            using (MessengerDbContext context = contextFactory.Create())
            {
                await context.Tokens.AddAsync(tokenPair).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);
            }
            return(TokenConverter.GetTokenVm(tokenPair));
        }
예제 #5
0
        public async Task <List <TokenVm> > RemoveTokensAsync(long userId, string accessToken, List <long> tokensIds)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                var query = context.Tokens.Where(token => token.UserId == userId);
                if (tokensIds != null && tokensIds.Any())
                {
                    var tokensCondition = PredicateBuilder.New <Token>();
                    tokensCondition = tokensIds.Aggregate(tokensCondition,
                                                          (current, value) => current.Or(opt => opt.Id == value).Expand());
                    query = query.Where(tokensCondition);
                }
                else
                {
                    query = query.Where(token => token.AccessToken == accessToken);
                }
                var tokens = await query.ToListAsync().ConfigureAwait(false);

                context.Tokens.RemoveRange(tokens);
                await context.SaveChangesAsync().ConfigureAwait(false);

                return(TokenConverter.GetTokensVm(tokens));
            }
        }
예제 #6
0
        public async Task <TokenVm> EmailVCodeCreateTokenPairAsync(string email, short vCode,
                                                                   string deviceTokenId)
        {
            string accessToken  = RandomExtensions.NextString(64);
            string refreshToken = RandomExtensions.NextString(64);

            using (MessengerDbContext context = contextFactory.Create())
            {
                var targetUser =
                    await context.Users.FirstOrDefaultAsync(user => user.Emails.Any(p => p.EmailAddress == email) && !user.Deleted)
                    .ConfigureAwait(false);

                if (targetUser == null)
                {
                    throw new UserNotFoundException();
                }
                if (!await verificationCodesService.IsVerificationCodeValidAsync(email, targetUser.Id, vCode).ConfigureAwait(false))
                {
                    throw new WrongVerificationCodeException();
                }
                var tokenPair = new Token
                {
                    UserId       = targetUser.Id,
                    AccessToken  = accessToken,
                    RefreshToken = refreshToken,
                    AccessTokenExpirationTime  = DateTime.UtcNow.AddHours(ACCESS_LIFETIME_HOUR).ToUnixTime(),
                    RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(REFRESH_LIFETIME_HOUR).ToUnixTime(),
                    DeviceTokenId = deviceTokenId
                };
                await context.Tokens.AddAsync(tokenPair).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(TokenConverter.GetTokenVm(tokenPair));
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            AlgorithmData  algData        = new AlgorithmData();
            AntlrConverter antlrConverter = new AntlrConverter();
            TokenConverter tc             = new TokenConverter();

            try
            {
                ObjectCache      cache        = MemoryCache.Default;
                var              cachedObject = cache["algoList"];
                List <BlockData> l_algoList   = null;
                if (cachedObject == null)
                {
                    l_algoList = algData.GetBlocks();

                    CacheItemPolicy policy = new CacheItemPolicy();
                    cachedObject = l_algoList;
                    cache.Set("algoList", cachedObject, policy);
                }
                else
                {
                    l_algoList = (List <BlockData>)cache.Get("algoList");
                }
                int count = 0;
                List <planFormulaInfo> l_planList = new List <planFormulaInfo>();
                foreach (var item in l_algoList)
                {
                    planFormulaInfo l_plan = null;
                    Console.WriteLine("Totlal count:" + l_algoList.Count());
                    BlockInfo l_blck = null;
                    if (item.planInfo != null)
                    {
                        foreach (var blck in item.planInfo.PlanFormula.ExpContent)
                        {
                            l_blck = antlrConverter.GetBlockInfo(blck.AntlrContent);
                            string l_err = tc.SetAntlr(l_blck);
                            l_plan = SetBlockStatements(l_blck, blck.AntlrContent, item.ruleId);
                            Console.WriteLine(blck.BlockName);
                            if (l_plan != null)
                            {
                                l_planList.Add(l_plan);
                            }
                        }
                    }
                    if (item.pricer != null)
                    {
                        foreach (var blck in item.pricer.PricerAlgorithm.ExpContent)
                        {
                            l_blck          = antlrConverter.GetBlockInfo(blck.AntlrContent);
                            l_blck.IsPricer = true;
                            string l_err = tc.SetAntlr(l_blck);
                            l_plan = SetBlockStatements(l_blck, blck.AntlrContent, item.ruleId);
                            if (l_plan != null)
                            {
                                l_planList.Add(l_plan);
                            }
                            Console.WriteLine(item.pricer.Name + " " + blck.BlockName);
                        }
                    }
                    if (item.formRules != null)
                    {
                        foreach (var blck in item.formRules.blockExponents)
                        {
                            l_blck = antlrConverter.GetBlockInfo(blck.AntlrContent);
                            string l_err = tc.SetAntlr(l_blck);
                            l_plan = SetBlockStatements(l_blck, blck.AntlrContent, item.ruleId);
                            Console.WriteLine(item.formRules.formulaeName + " - " + blck.BlockName);
                            if (l_plan != null)
                            {
                                l_planList.Add(l_plan);
                            }
                        }
                    }
                    count++;

                    Console.WriteLine(count);
                }
                algData.SaveBlock(l_planList);
                Console.WriteLine("Block validation finished");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Block validation failed");
            }
        }
예제 #8
0
 public void SetUp()
 {
     markdown  = new Markdown();
     conventer = new HtmlConverter();
 }