-
Notifications
You must be signed in to change notification settings - Fork 125
feat(dart): Add Google Sign-In template #343
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ahmtydn
wants to merge
11
commits into
appwrite:main
Choose a base branch
from
ahmtydn:feat-dart-sign-in-with-google
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a63c60e
feat: add Google Sign-In function with token verification and user ma…
ahmtydn 34e6ff1
fix: update dependencies and ensure email verification is awaited
ahmtydn bf3d3ed
fix: correct markdown formatting in README and ensure email verificat…
ahmtydn 4127d80
feat: enhance Google ID token verification process and update depende…
ahmtydn cdfdae0
Update dart/sign_in_with_google/README.md
ahmtydn b172b11
feat: implement timeout handling for fetching Google public keys and …
ahmtydn 8627223
feat: update Dart SDK version requirement to >=3.5.0 <4.0.0
ahmtydn d2657c3
feat: add additional required environment variables for Appwrite inte…
ahmtydn 683223f
feat: enhance ID token issuer verification with detailed error message
ahmtydn ff31c0f
feat: refactor Google OAuth implementation and update dependencies
ahmtydn ab22688
feat: update dart_jsonwebtoken dependency to version 3.3.1
ahmtydn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| .dart_tool/ | ||
| .packages | ||
| pubspec.lock |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| ````markdown | ||
| # sign-in-with-google | ||
|
|
||
| This function: | ||
|
|
||
| 1. Verifies a Google ID token obtained from the client application. | ||
| 1. If a user with matching id or email doesn't exist, a new user will be created. | ||
| 1. The user's email will be verified if Google has verified it and it hasn't been already in Appwrite. | ||
| 1. A token will be returned allowing the user to exchange the token for a session via `account.createSession()`. | ||
|
|
||
| > Note: This function verifies the Google ID token using Google's tokeninfo endpoint as described in the [official documentation](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token). | ||
ahmtydn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## 🧰 Usage | ||
|
|
||
| ### POST / | ||
|
|
||
| **Headers** | ||
|
|
||
| The Content-Type header must be set to `application/json` so that the request body can be properly parsed as JSON. | ||
|
|
||
| * `Content-Type`: `application/json` | ||
|
|
||
| **Request** | ||
|
|
||
| This function accepts: | ||
|
|
||
| * `idToken` (required) - Google ID token obtained from the client-side Google Sign-In flow | ||
|
|
||
| Sample request body: | ||
|
|
||
| ```json | ||
| { | ||
| "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdlMzA3..." | ||
| } | ||
| ``` | ||
|
|
||
| **Response** | ||
|
|
||
| This function returns: | ||
|
|
||
| * `secret` - `secret` to be passed to `account.createSession()` to create a session | ||
| * `userId` - `userId` to be passed to `account.createSession()` to create a session | ||
| * `expire` - ISO formatted timestamp for when the secret expires | ||
|
|
||
| Sample `200` Response: | ||
|
|
||
| ```json | ||
| { | ||
| "secret": "0cbdd4fd7638e0f3f55871adf2256f8f42f6faa01c9300e482c9a585b76611343dee8562ce4421b1cf9e9de6f8341fb2286499cb7992d02accd2dc699211008c", | ||
| "userId": "112345678901234567890", | ||
| "expire": "2025-07-15T00:10:21.345+00:00" | ||
| } | ||
| ``` | ||
|
|
||
| ## ⚙️ Configuration | ||
|
|
||
| | Setting | Value | | ||
| | ----------------- | --------------- | | ||
| | Runtime | Dart (3.5 ) | | ||
ahmtydn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| | Entrypoint | `lib/main.dart` | | ||
| | Build Commands | `dart pub get` | | ||
| | Permissions | `any` | | ||
| | Timeout (Seconds) | 15 | | ||
| | Scopes | `users.read`, `users.write` | | ||
|
|
||
| ## 🔒 Environment Variables | ||
|
|
||
| The following environment variables are required: | ||
|
|
||
| * `GOOGLE_CLIENT_ID` - Your Google OAuth 2.0 Client ID from the Google Cloud Console | ||
|
|
||
| ## 📱 Client-Side Integration | ||
|
|
||
| To obtain the Google ID token from your client application, use the [google_sign_in](https://pub.dev/packages/google_sign_in) package: | ||
|
|
||
| ```dart | ||
| import 'package:google_sign_in/google_sign_in.dart'; | ||
|
|
||
| final GoogleSignIn _googleSignIn = GoogleSignIn( | ||
| clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', | ||
| ); | ||
|
|
||
| Future<void> signInWithGoogle() async { | ||
| try { | ||
| final GoogleSignInAccount? account = await _googleSignIn.signIn(); | ||
| if (account == null) return; | ||
|
|
||
| final GoogleSignInAuthentication auth = await account.authentication; | ||
| final String? idToken = auth.idToken; | ||
|
|
||
| if (idToken != null) { | ||
| // Send the idToken to your Appwrite function | ||
| final response = await http.post( | ||
| Uri.parse('YOUR_FUNCTION_URL'), | ||
| headers: {'Content-Type': 'application/json'}, | ||
| body: jsonEncode({'idToken': idToken}), | ||
| ); | ||
| // Handle the response | ||
| } | ||
| } catch (error) { | ||
| print('Error signing in with Google: $error'); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ## 🔐 Security Notes | ||
|
|
||
| * The Google ID token is verified using Google's official tokeninfo endpoint | ||
| * The token's audience (client ID) is verified to match your application | ||
| * The token's issuer is verified to be Google | ||
| * The token's expiration time is checked | ||
| * Email verification status from Google is honored in Appwrite | ||
|
|
||
| ```` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| include: package:lints/recommended.yaml |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import 'dart:async'; | ||
| import 'dart:convert'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:dart_appwrite/dart_appwrite.dart'; | ||
| import 'package:dart_appwrite/models.dart'; | ||
| import 'package:http/http.dart' as http; | ||
|
|
||
| Future<dynamic> main(final context) async { | ||
| final requiredEnvVars = ['GOOGLE_CLIENT_ID']; | ||
| for (var varName in requiredEnvVars) { | ||
| if (Platform.environment[varName]?.isEmpty ?? true) { | ||
| throw Exception('Environment variable $varName must be set.'); | ||
| } | ||
| } | ||
ahmtydn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| final googleClientId = Platform.environment['GOOGLE_CLIENT_ID']!; | ||
|
|
||
| final reqBody = context.req.bodyJson as Map<String, dynamic>; | ||
| final idToken = reqBody['idToken'] ?? ''; | ||
|
|
||
| // Validate input | ||
| if (idToken.isEmpty) { | ||
| throw Exception('idToken must be provided in the request body.'); | ||
| } | ||
|
|
||
| // Verify the Google ID token | ||
| final tokenInfoResponse = await http.get( | ||
| Uri.parse('https://oauth2.googleapis.com/tokeninfo?id_token=$idToken'), | ||
| ); | ||
|
|
||
| if (tokenInfoResponse.statusCode != 200) { | ||
| throw Exception( | ||
| 'Failed to verify Google ID token: ${tokenInfoResponse.body}', | ||
| ); | ||
| } | ||
|
|
||
| final tokenInfo = json.decode(tokenInfoResponse.body); | ||
|
|
||
| // Verify the token's audience matches our client ID | ||
| final aud = tokenInfo['aud'] ?? ''; | ||
| if (aud != googleClientId) { | ||
| throw Exception('ID Token audience does not match the expected client ID.'); | ||
| } | ||
|
|
||
| // Verify the token is issued by Google | ||
| final iss = tokenInfo['iss'] ?? ''; | ||
| if (iss != 'https://accounts.google.com' && iss != 'accounts.google.com') { | ||
| throw Exception('ID Token is not issued by Google.'); | ||
| } | ||
|
|
||
| // Verify the token has not expired | ||
| final exp = int.tryParse(tokenInfo['exp']?.toString() ?? '0') ?? 0; | ||
| final currentTime = DateTime.now().millisecondsSinceEpoch ~/ 1000; | ||
| if (exp <= currentTime) { | ||
| throw Exception('ID Token has expired.'); | ||
| } | ||
|
|
||
ahmtydn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Extract user information | ||
| final userId = tokenInfo['sub'] ?? ''; | ||
| if (userId.isEmpty) { | ||
| throw Exception('ID Token does not contain a valid subject (sub) claim.'); | ||
| } | ||
|
|
||
| final email = tokenInfo['email'] ?? ''; | ||
| final emailVerified = tokenInfo['email_verified'] == 'true'; | ||
| final name = tokenInfo['name'] ?? ''; | ||
| final picture = tokenInfo['picture'] ?? ''; | ||
|
|
||
| // You can use the Appwrite SDK to interact with other services | ||
| // For this example, we're using the Users service | ||
| final client = Client() | ||
| .setEndpoint(Platform.environment['APPWRITE_FUNCTION_API_ENDPOINT']!) | ||
| .setProject(Platform.environment['APPWRITE_FUNCTION_PROJECT_ID']!) | ||
| .setKey(context.req.headers['x-appwrite-key'] ?? ''); | ||
| final users = Users(client); | ||
ahmtydn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Find user by ID | ||
| User? user; | ||
| try { | ||
| user = await users.get(userId: userId); | ||
| } on AppwriteException catch (e) { | ||
| if (e.type != 'user_not_found') { | ||
| rethrow; | ||
| } | ||
| } | ||
|
|
||
| // Find user by email | ||
| if (user == null && email.isNotEmpty) { | ||
| final userList = await users.list(queries: [Query.equal('email', email)]); | ||
| if (userList.users.isNotEmpty) { | ||
| user = userList.users.first; | ||
| } | ||
| } | ||
|
|
||
| // If user does not exist, create a new user | ||
| user ??= await users.create( | ||
| userId: ID.custom(userId), | ||
| email: email.isEmpty ? null : email, | ||
| name: name.isEmpty ? null : name, | ||
| ); | ||
|
|
||
| // Mark the user as verified if the email is verified by Google and not already verified | ||
| if (emailVerified && !user.emailVerification) { | ||
| users.updateEmailVerification(userId: userId, emailVerification: true); | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Create token | ||
| final token = await users.createToken( | ||
| userId: user.$id, | ||
| expire: 60, | ||
| length: 128, | ||
| ); | ||
|
|
||
| return context.res.json({ | ||
| 'secret': token.secret, | ||
| 'userId': user.$id, | ||
| 'expire': token.expire, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| name: sign_in_with_google | ||
| version: 1.0.0 | ||
|
|
||
| environment: | ||
| sdk: ^2.17.0 | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| dependencies: | ||
| dart_appwrite: ^16.0.0 | ||
| http: ^1.4.0 | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| dev_dependencies: | ||
| lints: ^2.0.0 | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.