I wrote a Telegram Bot in groovy and it was a piece of cake.
Now in order to register propper webhooks I need to get a hold of user's id.
I read, that I should call auth.sendCode method to start that process.
Are there any simpler alternatives to that?
If not, how can I invoke the sendCode with the smallest effort and possibly w/o any additional dependencies? Any examples or pointers using plain java or curl would be good.
After some research I ended up with a simple solution.
Instead of authenticating against the Telegram API over MTProto, I reversed the process. I implemented a new bot-command:
/login {my-user-id}
so that the user sends his id (can be some generated token later) in Telegram bot chat and the bot sends this message - along with Telegram user id! - over webhook to my server, where I do the matching and saving.
The implementation looks like this:
switch( json.message.text ){
case ~/\/login \w+/:
String userId
text.toLowerCase().eachMatch( /\/login (\w+)/ ){ userId = it[ 1 ] }
String telegramUserId = json.message.from.id
saveJoin userId, telegramUserId
break
}
Related
I am trying to call this twitter v2 endpoint to hide a tweet using OAuth1 and ScribeJava
Here is what I have tried
val service = ServiceBuilder(apiKey)
.apiSecret(apiSecret)
.build(TwitterApi.instance())
val url = "https://api.twitter.com/2/tweets/${tweetId}/hidden"
val oauth1 = OAuth1AccessToken(token,secret)
val request = OAuthRequest(Verb.PUT, url)
request.setPayload("{ \"hidden\": true }")
service.signRequest(oauth1, request)
val response = service.execute(request)
When I try that I get a 400 Bad Request back, what is the proper way to do this?
The reason of your problem probably has to do with the fact that you are trying to hide a tweet that you do not have the ability to do so. Please, note the restrictions that a tweet must adhere to in order to be hidden. It is stated in the section Step three: Find a Tweet ID to hide in the Twitter developer documentation:
The hide replies endpoint can hide or unhide replies on behalf of an authorized user. Because we are using the Access Tokens related to your user profile in this example, you will be able to hide replies from users who participate in a conversation started by you. Similarly, if you were using Access Tokens that belong to another user that authorized your app, you would be able to moderate replies to any conversations started by that account.
Ask a friend to reply to a Tweet (let them know you're testing hide replies) or reply to any of your Tweets from a test account. Click on that reply, then copy the numeric part of its URL. That will be the Tweet ID we will hide.
I am new to android development .I have developed an android app from where one can insert some record via the app to the mysql database using php as server side programming.
No need to perform any kind of login operation for inserting the record via the app.
So now the problem is that if a user clicks on sumbit button multiple times(say x times) within a fraction of seconds, then same record will be inserted into the database multiple times(x times) ..obviously with different primary key id in each row.
So i need to prevent it by generating a unique token in oncreate() and pass the token along with the body post request and validate it at the server end using php.
The token must be unique for each post request via app to the server and also it has to be destroyed once it is used for a particular request.
So how to go for it? Please help..i need a reference code if anyone can provide..
A lightweight approach is to generate a token that can self-validate using an HMAC. On the server, you'd generate a token using say generate_token($secret) and send this to the client. The client has to include the token in it's response. Validate the token on the server with valid_token($secret, $token).
To prevent re-use of tokens, you have to store the spent tokens. For example, you could store used tokens in a db-record with a unique constraint before proceeding with the request. If inserting fails on the constraint, you know the token was re-used.
Example of token generation and validation:
function generate_token($secret) {
return build_token($secret, bin2hex(random_bytes(5)));
}
function build_token($secret, $id) {
return $id . '-' . hash_hmac('ripemd160', $id, $secret);
}
function valid_token($secret, $token) {
$parts = explode('-', $token);
return $token === build_token($secret, $parts[0]);
}
There are other ways. You could generate random ID and store them. Then delete them from the store once they're used. Then you don't need a secret. I prefer storing spent tokens because it's stateless up until the last step.
Edit: Note that to protect against CSRF the token has to include a user-specific ID. In PHP, session_id() can often be used for this. A very simplistic approach would concat session_id() to $secret as in generate_token($secret . session_id()) and valid_token($secret . session_id(), $token). I hope you get the idea.
I have programmed a telegram bot. This works fine when sending to groups or to users. However I do a special requirement. I need to be able to send to another bot. When adding both bots to a group as administrators. I still cannot receive the message with my second bot. I only see it with my real user account, that is added to this group.
What am I missing?
I used OKHttp to send the message
Request request = new Request.Builder()
.url("https://api.telegram.org/bot"+telSetup.getToken()+"/sendMessage?chat_id="+lAdr+"&parse_mode=HTML&text="+strMessage)
.build();
client.newCall(request).enqueue(new MyIPProcessing(request.toString()));
and
if (response.message().equals("OK")){
List <String> lStr=response.request().url().encodedPathSegments();
...
to receive messages ... which basically works for communication with "real users".
Any ideas welcome ....
According to Bots FAQ
Bots talking to each other could potentially get stuck in unwelcome loops.
To avoid this, we decided that bots will not be able to see messages from other bots regardless of mode.
You can connect 2 (or more) bots with a private channel!
Just prompt the bots as admin in the channel.
Then when a bot send a post to the channel, other admin bots can see the message/file/...
Bot wouldn't be able to send message to other bots. in most platform APIs it return an error. kindly go through the documentation for the client(bot) and see its functionalities
As the title states it, I want to access the bitbucket API from a native Java Desktop Application. Bitbucket requires Applications to use OAuth2, and for that I found that Oltu should do the job.
However, my knowledge of OAuth is very limited and so I am stuck at a very early point. Here is what I did so far:
Step 1: I registered an OAuth Consumer with my Bitbucket Account with the following details:
Name: jerseytestapp
Description:
CallbackURL: http://localhost:8080/
URL:
Question 1: Could I automate this step?
Step 2: I ran the following Java code:
package jerseytest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
public class BitbucketJersey {
public static void main(String[] args) {
OAuthClientRequest request;
try {
request = OAuthClientRequest
.authorizationLocation("https://bitbucket.org/site/oauth2/authorize")
.setClientId("jerseytestapp")
.setRedirectURI("http://localhost:8080")
.buildQueryMessage();
System.out.println(request.getLocationUri());
} catch (OAuthSystemException e) {
e.printStackTrace();
}
}
}
Step 3: I received the following locationURI and opened in Firefox
https://bitbucket.org/site/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=jerseytestapp
Question 2: Do I need to use the browser or can I do this from the java application?
I receive the following answer message in Firefox:
Invalid client_id
This integration is misconfigured. Contact the vendor for assistance.
Question 3: What would be the correct next steps, and what is wrong with my approach?
Answer 1: You can automate the creation of OAuth Consumers, but you probably don’t want to.
Bitbucket provides documentation on how to create a consumer through their APIs, although the documentation is lacking many pertinent fields. Even so, you could still craft an HTTP request programmatically which mimics whatever Bitbucket's web interface is doing to create consumers. So yes, it could be automated.
Here's why you probably don't want to. In your case, you have three things that need to work together: your application, the end user, and Bitbucket. (Or in terms of OAuth jargon for this flow, those would be the client, resource owner, and authorization server, respectively.) The normal way of doing things is that your application is uniquely identified by the OAuth Consumer that you’ve created in your account, and all usages of Bitbucket by your application will use that single OAuth Consumer to identify your application. So unless you’re doing something like developing a Bitbucket application that generates other Bitbucket applications, you have no need to automate the creation of other OAuth Consumers.
Answer 2: You can authorize directly from your Java application.
Bitbucket states that it supports all four grant flows/types defined in RFC-6749. Your code is currently trying to use the Authorization Code Grant type. Using this grant type WILL force you to use a browser. But that’s not the only problem with this grant type for a desktop application. Without a public webserver to point at, you will have to use localhost in your callback URL, as you are already doing. That is a big security hole because malicious software could intercept traffic to your callback URL to gain access to tokens that the end user is granting to your application only. (See the comments on this stackoverflow question for more discussion on that topic.) Instead, you should be using the Resource Owner Password Credentials Grant type which will allow you to authenticate a Bitbucket’s username and password directly in your application, without the need of an external browser or a callback URL. Bitbucket provides a sample curl command on how to use that grant type here.
Answer 3: The correct next steps would be to model your code after the following sample. What is wrong with your approach is that you are trying to use a grant type that is ill-suited to your needs, and you are attempting to use your OAuth Consumer's name to identify your application instead of your Consumer's key and secret.
The following code sample successfully retrieved an access token with my own username/password/key/secret combination, whose values have been substituted out. Code was tested using JDK 1.8.0_45 and org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0.
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://bitbucket.org/site/oauth2/access_token")
.setGrantType(GrantType.PASSWORD)
.setUsername("someUsernameEnteredByEndUser")
.setPassword("somePasswordEnteredByEndUser")
.buildBodyMessage();
String key = "yourConsumerKey";
String secret = "yourConsumerSecret";
byte[] unencodedConsumerAuth = (key + ":" + secret).getBytes(StandardCharsets.UTF_8);
byte[] encodedConsumerAuth = Base64.getEncoder().encode(unencodedConsumerAuth);
request.setHeader("Authorization", "Basic " + new String(encodedConsumerAuth, StandardCharsets.UTF_8));
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
System.out.println("response body: " + response.getBody());
Your main problem was that you were giving the customer name instead of the client id:
.setClientId("jerseytestapp")
The only way to get the client id that I know of is to query:
https://bitbucket.org/api/1.0/users/your_account_name/consumers
However, even then it was still not working so I contacted bitbucket support. It turned out that the documentation is misleading. You actually need to use the client key instead.
.setClientId("ydrqABCD123QWER4567") // or whatever your case might be
https://bitbucket.org/site/oauth2/authorize?client_id=client_key&response_type=token
I am developing an app for Android which allow users making comments. The problem is: if someone discovered the PHP file of my server which receive a comment and save it in a database this person would have a total control to save unlimited comments. So... How could I avoid this?
I don't know so much of security but... Could it be possible solve it with hash, keys or anything? How?
You could use Oauth and send a token with each request here a example link Oauth2 or you can use a more simple method like:
User log in you app then you create in a table a record with is id and random string
Return this string to the user
When user do request add this string
On PHP verify thata string exists and the id is correct then insert the comment else nothing