Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

DeviceAuth: the phone's own lock, as an app plugin

Duarte Santos143076cd4f9e
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index aea946284..b9483449c 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -104,6 +104,9 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
+ <!-- Delete my account on a paired phone: the phone's own face, fingerprint or screen lock
+ confirms it is the owner first (DeviceAuthPlugin). A normal permission, no prompt. -->
+ <uses-permission android:name="android.permission.USE_BIOMETRIC" />
<!-- Gym check-in: scanning a membership QR/barcode with the camera. -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Health Connect (#200): write-only, asked for only when the user turns it on in Settings.
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/DeviceAuthPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/DeviceAuthPlugin.java
new file mode 100644
index 000000000..a6094fc62
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/DeviceAuthPlugin.java
@@ -0,0 +1,120 @@
+package ch.duartesantos.opengym;
+
+import android.app.Activity;
+import android.app.KeyguardManager;
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Build;
+import android.os.CancellationSignal;
+import androidx.activity.result.ActivityResult;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.ActivityCallback;
+import com.getcapacitor.annotation.CapacitorPlugin;
+
+/**
+ * The phone's own screen lock, asked before the app deletes an account its pairing proves
+ * (components/DeleteAccount.jsx, lib/device-auth.js). Android 10 and later show the system
+ * BiometricPrompt, which takes a face or a fingerprint (strong or weak) and the PIN, pattern or
+ * password; before that, the lock screen's own confirm. The platform's classes only: no
+ * androidx.biometric dependency for one prompt.
+ *
+ * Usage from JS:
+ * const DeviceAuth = registerPlugin('DeviceAuth');
+ * await DeviceAuth.check(); // { secure: true } when there is a lock to ask
+ * await DeviceAuth.verify({ reason: '…' }); // resolves once unlocked; rejects with the code
+ * // 'cancelled', 'not-secure' (no lock) or 'failed'
+ */
+@CapacitorPlugin(name = "DeviceAuth")
+public class DeviceAuthPlugin extends Plugin {
+
+ private KeyguardManager keyguard() {
+ return (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
+ }
+
+ @PluginMethod
+ public void check(PluginCall call) {
+ KeyguardManager km = keyguard();
+ JSObject ret = new JSObject();
+ ret.put("secure", km != null && km.isDeviceSecure());
+ call.resolve(ret);
+ }
+
+ @PluginMethod
+ @SuppressWarnings("deprecation") // createConfirmDeviceCredentialIntent: what Android 7 to 9 have
+ public void verify(PluginCall call) {
+ KeyguardManager km = keyguard();
+ if (km == null || !km.isDeviceSecure()) {
+ call.reject("no screen lock", "not-secure");
+ return;
+ }
+ String reason = call.getString("reason", "Confirm it's you");
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ getActivity().runOnUiThread(() -> prompt(call, reason));
+ return;
+ }
+ // Android 7 to 9: BiometricPrompt cannot fall back to the PIN there, the lock screen can.
+ Intent intent = km.createConfirmDeviceCredentialIntent(reason, null);
+ if (intent == null) {
+ call.reject("no screen lock", "not-secure");
+ return;
+ }
+ startActivityForResult(call, intent, "confirmResult");
+ }
+
+ @ActivityCallback
+ private void confirmResult(PluginCall call, ActivityResult result) {
+ if (call == null) return;
+ if (result.getResultCode() == Activity.RESULT_OK) resolveVerified(call);
+ else call.reject("cancelled", "cancelled");
+ }
+
+ @SuppressWarnings("deprecation") // setDeviceCredentialAllowed: the only way on Android 10
+ private void prompt(PluginCall call, String reason) {
+ BiometricPrompt.Builder builder = new BiometricPrompt.Builder(getContext()).setTitle(reason);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ builder.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG
+ | BiometricManager.Authenticators.BIOMETRIC_WEAK
+ | BiometricManager.Authenticators.DEVICE_CREDENTIAL);
+ } else {
+ builder.setDeviceCredentialAllowed(true);
+ }
+ BiometricPrompt prompt = builder.build();
+ prompt.authenticate(new CancellationSignal(), getContext().getMainExecutor(), new BiometricPrompt.AuthenticationCallback() {
+ @Override
+ public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
+ resolveVerified(call);
+ }
+
+ // A face or finger it did not know: the prompt stays up for another try, so this is
+ // not the end of it. Only an error ends the call.
+ @Override
+ public void onAuthenticationFailed() {}
+
+ @Override
+ public void onAuthenticationError(int code, CharSequence message) {
+ switch (code) {
+ case BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED:
+ case BiometricPrompt.BIOMETRIC_ERROR_CANCELED:
+ call.reject("cancelled", "cancelled");
+ break;
+ case BiometricPrompt.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL:
+ call.reject("no screen lock", "not-secure");
+ break;
+ default:
+ call.reject(message != null ? message.toString() : "failed", "failed");
+ }
+ }
+ });
+ }
+
+ private void resolveVerified(PluginCall call) {
+ JSObject ret = new JSObject();
+ ret.put("verified", true);
+ call.resolve(ret);
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
index babd6403a..dbd348822 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
@@ -27,6 +27,7 @@ public class MainActivity extends BridgeActivity {
registerPlugin(RestAlertPlugin.class);
registerPlugin(BackupFolderPlugin.class);
registerPlugin(BarIconsPlugin.class);
+ registerPlugin(DeviceAuthPlugin.class);
super.onCreate(savedInstanceState);
passSystemBarsToPage();
}
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index 8686f4080..bc36bd173 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -21,6 +21,7 @@
AA0200000000000000000004 /* RestAlertPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000003 /* RestAlertPlugin.swift */; };
AA0200000000000000000006 /* RestTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000005 /* RestTone.swift */; };
AA0200000000000000000008 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = AA0200000000000000000007 /* PrivacyInfo.xcprivacy */; };
+ AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000001 /* DeviceAuthPlugin.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -42,6 +43,7 @@
AA0200000000000000000003 /* RestAlertPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestAlertPlugin.swift; sourceTree = "<group>"; };
AA0200000000000000000005 /* RestTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestTone.swift; sourceTree = "<group>"; };
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
+ AA0300000000000000000001 /* DeviceAuthPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAuthPlugin.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -92,6 +94,7 @@
AA0200000000000000000001 /* MainViewController.swift */,
AA0200000000000000000003 /* RestAlertPlugin.swift */,
AA0200000000000000000005 /* RestTone.swift */,
+ AA0300000000000000000001 /* DeviceAuthPlugin.swift */,
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
@@ -234,6 +237,7 @@
AA0200000000000000000002 /* MainViewController.swift in Sources */,
AA0200000000000000000004 /* RestAlertPlugin.swift in Sources */,
AA0200000000000000000006 /* RestTone.swift in Sources */,
+ AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/frontend/ios/App/App/DeviceAuthPlugin.swift b/frontend/ios/App/App/DeviceAuthPlugin.swift
new file mode 100644
index 000000000..3f715230d
--- /dev/null
+++ b/frontend/ios/App/App/DeviceAuthPlugin.swift
@@ -0,0 +1,57 @@
+import Foundation
+import Capacitor
+import LocalAuthentication
+
+/**
+ * The phone's own screen lock, asked before the app deletes an account its pairing proves
+ * (components/DeleteAccount.jsx, lib/device-auth.js). `.deviceOwnerAuthentication` is Face ID or
+ * Touch ID, falling back to the passcode, so any phone with a lock can answer it.
+ *
+ * Usage from JS:
+ * const DeviceAuth = registerPlugin('DeviceAuth');
+ * await DeviceAuth.check(); // { secure: true } when there is a lock to ask
+ * await DeviceAuth.verify({ reason: '…' }); // resolves once unlocked; rejects with the code
+ * // 'cancelled', 'not-secure' (no lock) or 'failed'
+ */
+@objc(DeviceAuthPlugin)
+public class DeviceAuthPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "DeviceAuthPlugin"
+ public let jsName = "DeviceAuth"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "check", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "verify", returnType: CAPPluginReturnPromise),
+ ]
+
+ @objc func check(_ call: CAPPluginCall) {
+ var error: NSError?
+ let secure = LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)
+ call.resolve(["secure": secure])
+ }
+
+ @objc func verify(_ call: CAPPluginCall) {
+ let context = LAContext()
+ var error: NSError?
+ guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
+ // No passcode at all is the one case the sheet goes ahead without a lock; anything
+ // else that stops the check (a locked-out sensor, say) is a failure.
+ let code = (error as? LAError)?.code == .passcodeNotSet ? "not-secure" : "failed"
+ call.reject(error?.localizedDescription ?? code, code)
+ return
+ }
+ let reason = call.getString("reason") ?? "Confirm it's you"
+ context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { ok, error in
+ if ok {
+ call.resolve(["verified": true])
+ return
+ }
+ switch (error as? LAError)?.code {
+ case .userCancel?, .appCancel?, .systemCancel?:
+ call.reject("cancelled", "cancelled")
+ case .passcodeNotSet?:
+ call.reject("no screen lock", "not-secure")
+ default:
+ call.reject(error?.localizedDescription ?? "failed", "failed")
+ }
+ }
+ }
+}
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index e3a1b1145..2189347e9 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -78,5 +78,7 @@
<string>Used to scan your gym membership QR code, and to take a photo or video of an exercise you add yourself.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Used to record the sound of a video you take of an exercise you add yourself.</string>
+ <key>NSFaceIDUsageDescription</key>
+ <string>Used to make sure it’s really you before your account is deleted.</string>
</dict>
</plist>
diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swift
index 6969c56e4..0f67eafa7 100644
--- a/frontend/ios/App/App/MainViewController.swift
+++ b/frontend/ios/App/App/MainViewController.swift
@@ -10,5 +10,6 @@ class MainViewController: CAPBridgeViewController {
override open func capacitorDidLoad() {
bridge?.registerPluginInstance(PrintPlugin())
bridge?.registerPluginInstance(RestAlertPlugin())
+ bridge?.registerPluginInstance(DeviceAuthPlugin())
}
}