2016-11-30 21:51:43 -05:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
using Microsoft.WindowsAzure.Storage;
|
|
|
|
|
|
using Microsoft.WindowsAzure.Storage.Queue;
|
|
|
|
|
|
using System;
|
2019-03-11 23:31:45 -04:00
|
|
|
|
using Bit.Core.Utilities;
|
2016-11-30 21:51:43 -05:00
|
|
|
|
|
|
|
|
|
|
namespace Bit.Core.Services
|
|
|
|
|
|
{
|
2016-12-02 23:37:08 -05:00
|
|
|
|
public class AzureQueueBlockIpService : IBlockIpService
|
2016-11-30 21:51:43 -05:00
|
|
|
|
{
|
2016-11-30 21:54:04 -05:00
|
|
|
|
private readonly CloudQueue _blockIpQueue;
|
|
|
|
|
|
private readonly CloudQueue _unblockIpQueue;
|
2017-07-31 16:58:27 -04:00
|
|
|
|
private bool _didInit = false;
|
2019-03-11 23:31:45 -04:00
|
|
|
|
private Tuple<string, bool, DateTime> _lastBlock;
|
2016-11-30 21:51:43 -05:00
|
|
|
|
|
2016-12-02 23:37:08 -05:00
|
|
|
|
public AzureQueueBlockIpService(
|
2016-11-30 21:51:43 -05:00
|
|
|
|
GlobalSettings globalSettings)
|
|
|
|
|
|
{
|
|
|
|
|
|
var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString);
|
|
|
|
|
|
var queueClient = storageAccount.CreateCloudQueueClient();
|
|
|
|
|
|
|
|
|
|
|
|
_blockIpQueue = queueClient.GetQueueReference("blockip");
|
|
|
|
|
|
_unblockIpQueue = queueClient.GetQueueReference("unblockip");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public async Task BlockIpAsync(string ipAddress, bool permanentBlock)
|
|
|
|
|
|
{
|
2017-07-31 16:58:27 -04:00
|
|
|
|
await InitAsync();
|
2019-03-11 23:31:45 -04:00
|
|
|
|
var now = DateTime.UtcNow;
|
|
|
|
|
|
if(_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock &&
|
|
|
|
|
|
(now - _lastBlock.Item3) < TimeSpan.FromMinutes(1))
|
|
|
|
|
|
{
|
|
|
|
|
|
// Already blocked this IP recently.
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
2016-11-30 21:51:43 -05:00
|
|
|
|
|
2019-03-11 23:31:45 -04:00
|
|
|
|
_lastBlock = new Tuple<string, bool, DateTime>(ipAddress, permanentBlock, now);
|
2019-03-13 09:42:04 -04:00
|
|
|
|
var message = new CloudQueueMessage(ipAddress);
|
2019-03-11 23:31:45 -04:00
|
|
|
|
await _blockIpQueue.AddMessageAsync(message);
|
2016-11-30 21:51:43 -05:00
|
|
|
|
if(!permanentBlock)
|
|
|
|
|
|
{
|
2019-03-11 23:31:45 -04:00
|
|
|
|
await _unblockIpQueue.AddMessageAsync(message, null, new TimeSpan(0, 15, 0), null, null);
|
2016-11-30 21:51:43 -05:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2017-07-31 16:58:27 -04:00
|
|
|
|
|
|
|
|
|
|
private async Task InitAsync()
|
|
|
|
|
|
{
|
|
|
|
|
|
if(_didInit)
|
|
|
|
|
|
{
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
await _blockIpQueue.CreateIfNotExistsAsync();
|
|
|
|
|
|
await _unblockIpQueue.CreateIfNotExistsAsync();
|
|
|
|
|
|
_didInit = true;
|
|
|
|
|
|
}
|
2016-11-30 21:51:43 -05:00
|
|
|
|
}
|
|
|
|
|
|
}
|