freeradius sqlcounter reply-message and coovachilli - freeradius

The freeradius mailing lists and wiki and all my searching I can't find a workable guide on how the counter reply message is set.
On a default freeradius server time and quota control is working perfectly. The suggestions to enhance the reply message is to add to raddb/sites-availible/default an if statement like this;
expiration{
userlock = 1
}
if(userlock){
update reply {
Reply-Message := "Your account - %{User-Name} - has expired, "
}
ok = reject
}
and this works for expired accounts but when I add another counter like this one below it does not take precedence over the expire counter so the reply is not accurate.
noresetBytecounter{
reject = 1
}
if(reject){
update reply {
Reply-Message := "You have reached your bandwidth limit"
}
ok = reject
#}
Is the format wrong? If so where on earth is a workable guide...

hello why have you commented the last line that has a } i guess it should be :
noresetBytecounter{
reject = 1
}
if(reject){
update reply {
Reply-Message := "You have reached your bandwidth limit"
}
ok = reject
}

Related

Can I avoid Twilio Verify 10 minute code validness limitation?

I'm working on implementing MFA in my pet-project. As I understand from Twilio Verify docs (https://www.twilio.com/docs/verify/api/rate-limits-and-timeouts#code-validity-period) it has some limitations: the code is valid for 10 minutes and I can only send 5 messages in this 10 minute time span (https://www.twilio.com/docs/api/errors/60203). Also, I found a way to avoid this restriction by updating verification status to "cancelled". The code in C# looks like this:
static async Task TestingTwilioLimitations()
{
VerificationResource verification = null;
for (int i = 0; i < 3; i++)
{
verification = await VerificationResource.CreateAsync(
to: "phone number",
channel: "sms",
pathServiceSid: serviceSid
);
Thread.Sleep(TimeSpan.FromSeconds(10));
}
await VerificationResource.UpdateAsync(new UpdateVerificationOptions(serviceSid, verification.Sid, VerificationResource.StatusEnum.Canceled));
for (int i = 0; i < 3; i++)
{
verification = await VerificationResource.CreateAsync(
to: "phone number",
channel: "sms",
pathServiceSid: serviceSid
);
Thread.Sleep(TimeSpan.FromSeconds(10));
}
}
This code allows me to receive 6 messages with codes, despite the limitations of 10 minutes and 5 attempts to send the code. So, the question is, can I use this trick? It allows to spam people (I'm not going to do that, just wanted to be able to configure max send attempts and code validation time from my side), and I'm afraid of being banned by Twilio Verify for using this API calls.
This blog may help you.
How to test Twilio Verify without getting rate limited
Otherwise, no way to change the behavior.

Twilio WhatsApp messages are in 'queued' status

Okay so I got approval from WhatsApp and Twilio (after Facebook Business verification) to use the WhatsApp API for sending out appointment reminders to my clients. I configured the message templates and they got approved too. Check the image below:
I have written a code in Python where I pick my data from a PostgreSQL server hosted on cloud (using psycopg2) and then it sends out messages to the phone numbers fetched using a query. Here is the code:
from twilio.rest import Client
import psycopg2
import time
account_sid = 'AC54xxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'f1384yyyyyyyyyyyyyyyyyyyyyyyyyyy'
connection_string = ""
conn = psycopg2.connect(user = "xxxx",
password = "yyyyyy",
host = "zzzzzzzzzzzzzzz.zzzzzzzzzzzz",
port = "ABCD",
database = "some_db")
cur = conn.cursor()
cur.execute("""query to pick data""")
rows = cur.fetchall()
client_phone_list = []
phone_list_not_received = []
session_date_list = []
session_time_list = []
client_first_name_list = []
for row in rows:
session_date_list.append(row[0])
session_time_list.append(row[1])
client_first_name_list.append(row[2])
client_phone_list.append(row[3])
cur.close()
conn.close()
client = Client(account_sid, auth_token)
message_reminder_template = """Hello {},
This is a reminder about your session today at {}. Please be on time to utilize the full length of
the session and avoid distress :)
We look forward to taking care of you!"""
for i in range(len(client_phone_list)):
first_name = client_first_name_list[i]
appointment_time = session_time_list[i]
message_body = message_reminder_template.format(first_name, appointment_time)
print(message_body)
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
time.sleep(10)
text_status = message.status
print(text_status)
Whenever I run this code the message status returned is always 'queued'. I have checked that I am not using the 'Test Credentials' but the 'Live Credentials'.
I have also checked the error_code and error_message which returns as NULL. So there is no error but the messages are not getting sent. How can I change that?
Any help would be hugely appreciated.
Also note that the message body used in the code above is approved as a template from WhatsApp.
Twilio developer evangelist here.
At the point that you make the API request to send the message the status will be returned to code as "queued". That's this point in your code here:
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
What you do next will not work though:
time.sleep(10)
text_status = message.status
print(text_status)
Waiting 10 seconds and then reading the status from the message object that was returned when you created the message will still return "queued".
If you want to fetch the message status after 10 seconds to see if it has been sent then you will need to make a second call to the messages API, like so:
time.sleep(10)
latest_message = client.messages(message.sid).fetch()
print(latest_message.status)
For a more efficient method of keeping track of the status of your messages, check out this tutorial on receiving webhooks for message status updates.
Let me know if that helped at all.

Subscription throttling limit

I tried to make multiple subscriptions to a single user, to test out how many subscription requests i can send until throttling occurs. I used the following code:
for (int i = 0; i < 10000; i++)
{
try
{
var request = graphClient.Subscriptions.Request();
var result = await request.AddAsync(
new Subscription
{
ChangeType = "created,updated,deleted",
NotificationUrl = notificationUrl,
Resource = "/users/" + userId + "/" + resource,
ExpirationDateTime = DateTimeOffset.UtcNow.AddMinutes(4230),
ClientState = "my-subscription-identifier"
}
);
AddOutputMessage((i + 1) + " Created Webhook", Color.Blue);
}
catch (ServiceException serviceException)
{
AddOutputErrorMessage(serviceException);
}
}
The throttling limit per user per app is 10000 in 10 minutes (as described in another stackoverflow post). I already tested this limit by making some requests to a single users calendar and contacts where it seems to work.
I was able to make 220 subscriptions until throttling occured (tested it three times). Even though that seems to be a little low, my end goal is to make multiple subscription requests for multiple users (for example 1000 subscriptions to a 1000 users), so it wouldn't be a problem if this throttling limit is for a single user only.
The throttling (HttpStatusCode 429) service exception for the subscriptions request also contained the error code 'ExtensionError' which i couldn't really find in the doc.
What i want to know is:
What are the throttling limits for the '/subscription endpoint'?
Especially after how many requests does throttling occur? (per user and overall per app) e.g. if i want to make subscriptions to 1000 users will i be throttled after 220?
What is an 'ExtensionError'?
ExtensionError is actually an OAuth error category. Expand the Message string to see if it has more info.
I'm checking with the code owners to see what the subscription limits for REST are.

Twilio check if phone number has been blacklisted

I am currently integrating into the twilio rest api and need to perform a check on a users phone number to determine if that user has blacklisted themselves or not. I have little experience with this api and scouring through the documentation and google has turned up nothing.
In our application we are going to have a notification center and if the user has blacklisted themselves I do not want to give them the ability to turn on their SMS notifications. Potentially a user could have SMS notifications on but twilio would block any messages. I know there is the ability to get a status code back from twilio when an SMS is queued that shows the user is blacklisted (https://www.twilio.com/docs/api/rest/message). However, I will not be sending messages on the notifications screen and need a direct way (if at all possible) to check twilio to determine if a number is blacklisted. Any help is much appreciated. Let me know if anymore information will be of help.
Megan from Twilio.
I'd be curious to see if you ever tried your own workaround. But I wanted to note for others in a similar situation how you could grab the blacklist error and then do whatever you may want with it.
In Ruby it would look something like this:
require 'rubygems'
require 'twilio-ruby'
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
#client = Twilio::REST::Client.new account_sid, auth_token
begin
#message = #client.messages.create(
from: 'TWILIO_NUMBER',
to: 'USER_NUMBER',
body: 'Howdy!'
)
rescue Twilio::REST::RestError => e
if e.code == 21610
# User is blacklisted
# Store info however you choose
puts e.message
end
end
We check for blacklisting specifically using the code '21610'. For more information about errors you can visit the reference page.
Hope this helps!
Twilio recommends developers to store the opt-out/in statuses in their side. I have stored it in DB. There are 2 ways to collect the unsubscribed users list.
1) Use SMS webhooks. You can find how to configure your Twilio number to receive webhook events here
#PostMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_ATOM_XML_VALUE)
public String twilioConsumer(TwilioEventDTO twilioEventDTO) {
// twilioEventDTO.getBody() => returns the body of the SMS user replied.
twilioService.consume(twilioEventDTO);
return new MessagingResponse.Builder().build().toXml();
}
2) Since I implemented webhooks later, I had to collect already unsubscribed users. When you send sms to the number that has been opted-out, Twilio API throws an exception with the status number of 21610. You can catch it and store the number in DB.
try {
Message result = Message.creator(
new PhoneNumber(toPhoneNumber),
new PhoneNumber(fromPhoneNumber),
messageBody)
.create();
response = result.getStatus().name();
} catch (ApiException e) {
if (e.getCode().equals(21610))
updateSubscription(toPhoneNumber, false);
logger.warn("Error on sending SMS: {}", e.getMessage());
}
P.S.: examples written in Java - Spring Boot framework.

Can I add in Thread.sleep() to address the rate limit exceeded error on Twitter?

To address the Rate Limit Exceeding issue in code, I am just wondering, can I do this?
do
{
Log.Info(this, string.Format("Fetching user timeline statuses for {0}", screenName));
var twitterService = new TwitterService(_consumerKey, _consumerSecret);
twitterService.AuthenticateWith(_accessToken, _accessTokenSecret);
ListTweetsOnUserTimelineOptions listTweetsOnUserTimelineOptions =
new ListTweetsOnUserTimelineOptions();
listTweetsOnUserTimelineOptions.ScreenName = screenName;
listTweetsOnUserTimelineOptions.IncludeRts = true;
Thread.sleep(50000);
catch (Exception e)
{
Log.Error(this, string.Format("exception happened whille calling Twitter Service{0}", e.StackTrace));
}
} while (result.Count < count);
According to the API, the time is divided in to 15 minutes window now. So, by putting in a Thread.sleep() would that be OK? because Twitter documentation doesn't really provide any code example.
All help is greatly appreciated.
Yes you can, but I'd look for a more sophisticated task scheduling, like this one: https://stackoverflow.com/a/14945407/253468
Also revisit the Twitter API docs, I think it's not one request you can send every 15 minutes. Divide the number of times you can request over 15 minutes to know how often you can run your scheduled task.

Resources