Merge pull request #728 from deltachat/oauth2

implement OAuth2
This commit is contained in:
björn petersen
2019-02-21 22:59:15 +01:00
committed by GitHub
11 changed files with 256 additions and 64 deletions
+12 -1
View File
@@ -173,7 +173,18 @@
<activity android:name=".RegistrationActivity"
android:launchMode="singleTask"
android:windowSoftInputMode="stateUnchanged"
android:configChanges="touchscreen|keyboard|keyboardHidden|orientation|screenLayout|screenSize"/>
android:configChanges="touchscreen|keyboard|keyboardHidden|orientation|screenLayout|screenSize">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- this scheme is used as the redirect_url for getOauth2Url()
and should be whitelisted by the supported oauth2 services -->
<data android:scheme="chat.delta" android:path="/${applicationId}/auth" tools:ignore="AppLinkUrlError"/>
<data android:scheme="chat.delta" android:path="/auth" tools:ignore="AppLinkUrlError"/>
</intent-filter>
</activity>
<activity android:name=".LogViewActivity"
android:label="@string/pref_view_log"
+2
View File
@@ -898,6 +898,7 @@ messenger-backend/src/dc_contact.c \
messenger-backend/src/dc_dehtml.c \
messenger-backend/src/dc_hash.c \
messenger-backend/src/dc_imap.c \
messenger-backend/src/dc_oauth2.c \
messenger-backend/src/dc_job.c \
messenger-backend/src/dc_jobthread.c \
messenger-backend/src/dc_key.c \
@@ -921,6 +922,7 @@ messenger-backend/src/dc_msg.c \
messenger-backend/src/dc_param.c \
messenger-backend/src/dc_pgp.c \
messenger-backend/src/dc_saxparser.c \
messenger-backend/src/dc_jsmn.c \
messenger-backend/src/dc_simplify.c \
messenger-backend/src/dc_smtp.c \
messenger-backend/src/dc_sqlite3.c \
+13
View File
@@ -651,6 +651,19 @@ JNIEXPORT jstring Java_com_b44t_messenger_DcContext_getInfo(JNIEnv *env, jobject
}
JNIEXPORT jstring Java_com_b44t_messenger_DcContext_getOauth2Url(JNIEnv *env, jobject obj, jstring addr, jstring redirectUrl)
{
CHAR_REF(addr);
CHAR_REF(redirectUrl);
char* temp = dc_get_oauth2_url(get_dc_context(env, obj), addrPtr, redirectUrlPtr);
jstring ret = JSTRING_NEW(temp);
free(temp);
CHAR_UNREF(redirectUrl);
CHAR_UNREF(addr);
return ret;
}
JNIEXPORT jstring Java_com_b44t_messenger_DcContext_getContactEncrInfo(JNIEnv *env, jobject obj, jint contact_id)
{
char* temp = dc_get_contact_encrinfo(get_dc_context(env, obj), contact_id);
+21 -1
View File
@@ -114,7 +114,7 @@
android:layout_height="wrap_content"
android:visibility="gone"
app:constraint_referenced_ids="inbox, imap_login, imap_server, imap_port, imap_security_label, imap_security, outbox_view_spacer_top,
outbox, smtp_login, smtp_password, smtp_server, smtp_port, smtp_security_label, smtp_security" />
outbox, smtp_login, smtp_password, smtp_server, smtp_port, smtp_security_label, smtp_security, auth_method_label, auth_method" />
<TextView
android:id="@+id/advanced_text"
@@ -326,6 +326,26 @@
app:layout_constraintStart_toStartOf="@id/guideline_root_start"
app:layout_constraintTop_toBottomOf="@id/smtp_security_label" />
<TextView
android:id="@+id/auth_method_label"
style="@style/TextAppearance.AppCompat.Caption"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/login_auth_method"
android:paddingTop="16dp"
app:layout_constraintEnd_toEndOf="@id/guideline_root_end"
app:layout_constraintStart_toStartOf="@id/guideline_root_start"
app:layout_constraintTop_toBottomOf="@id/smtp_security" />
<Spinner
android:id="@+id/auth_method"
android:layout_width="0dp"
android:layout_height="48dp"
android:entries="@array/auth_methods"
app:layout_constraintEnd_toEndOf="@id/guideline_root_end"
app:layout_constraintStart_toStartOf="@id/guideline_root_start"
app:layout_constraintTop_toBottomOf="@id/auth_method_label" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
+5
View File
@@ -201,4 +201,9 @@
<item>Off</item>
</string-array>
<string-array name="auth_methods">
<item>Automatic</item>
<item>OAuth2</item>
</string-array>
</resources>
+3
View File
@@ -267,6 +267,9 @@
<string name="login_smtp_server">SMTP server</string>
<string name="login_smtp_port">SMTP port</string>
<string name="login_smtp_security">SMTP Security</string>
<string name="login_auth_method">Authorization method</string>
<string name="login_info_oauth2_title">Continue with simplified setup?</string>
<string name="login_info_oauth2_text">The entered e-mail-address supports a simplified setup (OAuth2).\n\nIn the next step, please allow Delta Chat to act as your Chat with E-Mail app.\n\nDelta Chat has no servers, your data stays on your device!</string>
<string name="login_info_gmail_text">For GMail Accounts you need to create an App-Password if you have 2FA enabled. If this setting is not available, you need to enable Less Secure Apps.</string>
<string name="login_error_mail">Please enter a valid email address</string>
<string name="login_error_server">Please enter a valid server / IP address</string>
+4
View File
@@ -31,6 +31,7 @@ public class DcContext {
public final static int DC_EVENT_GET_STRING = 2091;
public final static int DC_EVENT_GET_QUANTITIY_STRING = 2092;
public final static int DC_EVENT_HTTP_GET = 2100;
public final static int DC_EVENT_HTTP_POST = 2110;
public final static int DC_IMEX_EXPORT_SELF_KEYS = 1;
public final static int DC_IMEX_IMPORT_SELF_KEYS = 2;
@@ -55,6 +56,8 @@ public class DcContext {
public final static int DC_QR_URL = 332;
public final static int DC_QR_ERROR = 400;
public final static int DC_LP_AUTH_OAUTH2 = 0x2;
public final static int DC_LP_AUTH_NORMAL = 0x4;
public final static int DC_LP_IMAP_SOCKET_STARTTLS = 0x100;
public final static int DC_LP_IMAP_SOCKET_SSL = 0x200;
public final static int DC_LP_IMAP_SOCKET_PLAIN = 0x400;
@@ -91,6 +94,7 @@ public class DcContext {
public native String getConfig (String key, String def);
public int getConfigInt (String key, int def) { try{return Integer.parseInt(getConfig(key, Integer.toString(def)));} catch(Exception e) {} return 0; }
public native String getInfo ();
public native String getOauth2Url (String addr, String redirectUrl);
public native String initiateKeyTransfer ();
public native boolean continueKeyTransfer (int msg_id, String setup_code);
public native void imex (int what, String dir);
@@ -2,6 +2,7 @@ package org.thoughtcrime.securesms;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
@@ -26,7 +27,13 @@ import com.b44t.messenger.DcEventCenter;
import org.thoughtcrime.securesms.connect.ApplicationDcContext;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.permissions.Permissions;
import org.thoughtcrime.securesms.util.IntentUtils;
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture;
import org.thoughtcrime.securesms.util.concurrent.SettableFuture;
import org.thoughtcrime.securesms.util.views.ProgressDialog;
import org.w3c.dom.Text;
import java.util.concurrent.ExecutionException;
import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_ADDRESS;
import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_MAIL_PASSWORD;
@@ -38,13 +45,6 @@ import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_PORT;
import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_SERVER;
import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_USER;
/**
* The register account activity. Prompts ths user for their registration information
* and begins the account registration process.
*
* @author Moxie Marlinspike
* @author Daniel Böhrs
*/
public class RegistrationActivity extends BaseActionBarActivity implements DcEventCenter.DcEventDelegate {
private enum VerificationType {
@@ -63,52 +63,13 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
MenuItem loginMenuItem;
Spinner imapSecurity;
Spinner smtpSecurity;
Spinner authMethod;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.registration_activity);
initializeResources();
DcHelper.getContext(this).eventCenter.addObserver(this, DcContext.DC_EVENT_CONFIGURE_PROGRESS);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = this.getMenuInflater();
menu.clear();
inflater.inflate(R.menu.registration, menu);
loginMenuItem = menu.findItem(R.id.do_register);
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.do_register) {
onLogin();
return true;
} else if (id == android.R.id.home) {
// handle close button click here
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy() {
super.onDestroy();
DcHelper.getContext(this).eventCenter.removeObservers(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
private void initializeResources() {
emailInput = findViewById(R.id.email_text);
passwordInput = findViewById(R.id.password_text);
advancedGroup = findViewById(R.id.advanced_group);
@@ -121,6 +82,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
imapSecurity = findViewById(R.id.imap_security);
smtpSecurity = findViewById(R.id.smtp_security);
authMethod = findViewById(R.id.auth_method);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
@@ -134,7 +96,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
imapPortInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.PORT));
smtpServerInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.SERVER));
smtpPortInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.PORT));
// loginButton.setOnClickListener(l -> onLogin());
advancedTextView.setOnClickListener(l -> onAdvancedSettings());
advancedIcon.setOnClickListener(l -> onAdvancedSettings());
advancedIcon.setRotation(45);
@@ -166,7 +127,60 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
if((server_flags&DcContext.DC_LP_SMTP_SOCKET_STARTTLS)!=0) sel = 2;
if((server_flags&DcContext.DC_LP_SMTP_SOCKET_PLAIN)!=0) sel = 3;
smtpSecurity.setSelection(sel);
sel = 0;
if((server_flags&DcContext.DC_LP_AUTH_OAUTH2)!=0) sel = 1;
authMethod.setSelection(sel);
}
DcHelper.getContext(this).eventCenter.addObserver(this, DcContext.DC_EVENT_CONFIGURE_PROGRESS);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = this.getMenuInflater();
menu.clear();
inflater.inflate(R.menu.registration, menu);
loginMenuItem = menu.findItem(R.id.do_register);
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.do_register) {
checkOauth2start().addListener(new ListenableFuture.Listener<Boolean>() {
@Override
public void onSuccess(Boolean oauth2started) {
if(!oauth2started) {
onLogin();
}
}
@Override
public void onFailure(ExecutionException e) {
onLogin();
}
});
return true;
} else if (id == android.R.id.home) {
// handle close button click here
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy() {
super.onDestroy();
DcHelper.getContext(this).eventCenter.removeObservers(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
private void focusListener(View view, boolean focused, VerificationType type) {
@@ -175,6 +189,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
switch (type) {
case EMAIL:
verifyEmail(inputEditText);
checkOauth2start();
break;
case SERVER:
verifyServer(inputEditText);
@@ -186,18 +201,70 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
}
}
private void verifyEmail(TextInputEditText view) {
String error = getString(R.string.login_error_mail);
String email = view.getText().toString();
if (!matchesEmailPattern(email)) {
view.setError(error);
private long oauth2Requested = 0;
private ListenableFuture<Boolean> checkOauth2start() {
SettableFuture<Boolean> oauth2started = new SettableFuture<>();
String email = emailInput.getText().toString();
if (!TextUtils.isEmpty(email) ) {
// the redirect-uri is also used as intent-filter in the manifest
// and should be whitelisted by the supported oauth2 services
String redirectUrl = "chat.delta:/"+BuildConfig.APPLICATION_ID+"/auth";
String oauth2url = DcHelper.getContext(this).getOauth2Url(email, redirectUrl);
if (!TextUtils.isEmpty(oauth2url)) {
new AlertDialog.Builder(this)
.setTitle(R.string.login_info_oauth2_title)
.setMessage(R.string.login_info_oauth2_text)
.setNegativeButton(R.string.cancel, (dialog, which)->{
if(isGmail(email)) {
showGmailNoOauth2Hint();
}
oauth2started.set(false);
})
.setPositiveButton(R.string.perm_continue, (dialog, which)-> {
// pass control to browser, we'll be back in business at (**)
oauth2Requested = System.currentTimeMillis();
IntentUtils.showBrowserIntent(this, oauth2url);
oauth2started.set(true);
})
.setCancelable(false)
.show();
} else if (isGmail(email)) {
showGmailNoOauth2Hint();
oauth2started.set(false);
}
else {
oauth2started.set(false);
}
}
if (!TextUtils.isEmpty(email) && isGmail(email) && !gmailDialogShown) {
gmailDialogShown = true;
new AlertDialog.Builder(this)
.setMessage(R.string.login_info_gmail_text)
.setPositiveButton(R.string.ok, null)
.show();
else {
oauth2started.set(false);
}
return oauth2started;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
String path = uri.getPath();
if(!(path.startsWith("/"+BuildConfig.APPLICATION_ID)||path.startsWith("/auth"))
|| System.currentTimeMillis()-oauth2Requested > 3*60*60*1000) {
return; // timeout after some hours or a request belonging to a bad path.
}
// back in business after we passed control to the browser in (**)
String code = uri.getQueryParameter("code");
if(!TextUtils.isEmpty(code)) {
passwordInput.setText(code);
authMethod.setSelection(1/*OAuth2*/);
onLogin();
}
}
}
@@ -209,6 +276,25 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
return email != null && (email.toLowerCase().contains("@gmail.") || email.toLowerCase().contains("@googlemail."));
}
private void showGmailNoOauth2Hint()
{
if(!gmailDialogShown) {
gmailDialogShown = true;
new AlertDialog.Builder(this)
.setMessage(R.string.login_info_gmail_text)
.setPositiveButton(R.string.ok, null)
.show();
}
}
private void verifyEmail(TextInputEditText view) {
String error = getString(R.string.login_error_mail);
String email = view.getText().toString();
if (!matchesEmailPattern(email)) {
view.setError(error);
}
}
private void verifyServer(TextInputEditText view) {
String error = getString(R.string.login_error_server);
String server = view.getText().toString();
@@ -289,6 +375,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
if(smtpSecurity.getSelectedItemPosition()==1) server_flags |= DcContext.DC_LP_SMTP_SOCKET_SSL;
if(smtpSecurity.getSelectedItemPosition()==2) server_flags |= DcContext.DC_LP_SMTP_SOCKET_STARTTLS;
if(smtpSecurity.getSelectedItemPosition()==3) server_flags |= DcContext.DC_LP_SMTP_SOCKET_PLAIN;
if(authMethod.getSelectedItemPosition()==1) server_flags |= DcContext.DC_LP_AUTH_OAUTH2;
DcHelper.getContext(this).setConfigInt("server_flags", server_flags);
// calling configure() results in
@@ -338,6 +425,4 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve
}
}
}
}
@@ -36,9 +36,12 @@ import org.thoughtcrime.securesms.util.Util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
@@ -585,6 +588,7 @@ public class ApplicationDcContext extends DcContext {
break;
case DC_EVENT_HTTP_GET:
// calling this from the main thread may result in NetworkOnMainThreadException error
String httpContent = null;
try {
URL url = new URL(dataToString(data1));
@@ -609,6 +613,50 @@ public class ApplicationDcContext extends DcContext {
}
return stringToData(httpContent);
case DC_EVENT_HTTP_POST:
// calling this from the main thread may result in NetworkOnMainThreadException error
String postContent = null;
try {
String urlStr = dataToString(data1);
String paramStr = "";
if(urlStr.contains("?")) {
paramStr = urlStr.substring(urlStr.indexOf("?")+1);
urlStr = urlStr.substring(0, urlStr.indexOf("?"));
}
byte[] bytes = paramStr.getBytes();
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setConnectTimeout(15 * 1000);
conn.setReadTimeout(15 * 1000);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
conn.getOutputStream().write(bytes);
int responseCode = conn.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
StringBuilder total = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
total.append(line).append('\n');
}
if (responseCode == HttpURLConnection.HTTP_OK) {
postContent = total.toString();
}
else {
Log.i("DeltaChat", String.format("DC_EVENT_HTTP_POST error: %s", total.toString()));
}
} finally {
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
return stringToData(postContent);
case DC_EVENT_GET_STRING:
String s;
switch ((int) data1) {
@@ -155,7 +155,7 @@ public class AdvancedPreferenceFragment extends CorrectedPreferenceFragment
String app = context.getString(R.string.app_name);
String version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
return String.format("%s v%s", app, version);
return String.format("%s %s", app, version);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
return context.getString(R.string.app_name);
+1
View File
@@ -8,6 +8,7 @@ Transport | IMAP v4 ([RFC 3501](https://tools.ietf.org/ht
Embedded media | MIME Document Series ([RFC 2045](https://tools.ietf.org/html/rfc2045), [RFC 2046](https://tools.ietf.org/html/rfc2046)), Content-Disposition Header ([RFC 2183](https://tools.ietf.org/html/rfc2183)), Multipart/Related ([RFC 2387](https://tools.ietf.org/html/rfc2387))
Identify server folders | IMAP LIST Extension ([RFC 6154](https://tools.ietf.org/html/rfc6154))
Push | IMAP IDLE ([RFC 2177](https://tools.ietf.org/html/rfc2177))
Authorization | OAuth2 ([RFC 6749](https://tools.ietf.org/html/rfc6749))
End-to-end encryption | [Autocrypt Level 1](https://autocrypt.org/level1.html), OpenPGP ([RFC 4880](https://tools.ietf.org/html/rfc4880)) and Security Multiparts for MIME ([RFC 1847](https://tools.ietf.org/html/rfc1847))
Configuration assistance | [Autoconfigure](https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Autoconfiguration) and [Autodiscover](https://technet.microsoft.com/library/bb124251(v=exchg.150).aspx)
Messenger functions | [Email-chat](https://github.com/deltachat/spec/blob/master/spec.md#email-chat-specification)