|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:io'; |
| 4 | +import 'package:crypto/crypto.dart'; |
| 5 | +import 'package:dart_appwrite/dart_appwrite.dart'; |
| 6 | +import 'package:dart_appwrite/models.dart'; |
| 7 | +import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; |
| 8 | +import 'package:http/http.dart' as http; |
| 9 | + |
| 10 | +Future<dynamic> main(final context) async { |
| 11 | + final requiredEnvVars = [ |
| 12 | + 'BUNDLE_ID', |
| 13 | + 'TEAM_ID', |
| 14 | + 'KEY_ID', |
| 15 | + 'KEY_CONTENTS_ENCODED' |
| 16 | + ]; |
| 17 | + for (var varName in requiredEnvVars) { |
| 18 | + if (Platform.environment[varName]?.isEmpty ?? true) { |
| 19 | + throw Exception('Environment variable $varName must be set.'); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + final bundleId = Platform.environment['BUNDLE_ID']!; |
| 24 | + final teamId = Platform.environment['TEAM_ID']!; |
| 25 | + final keyId = Platform.environment['KEY_ID']!; |
| 26 | + final keyContentsEncoded = Platform.environment['KEY_CONTENTS_ENCODED']!; |
| 27 | + final keyContents = utf8.decode(base64Decode(keyContentsEncoded)); |
| 28 | + |
| 29 | + final key = ECPrivateKey(keyContents); |
| 30 | + |
| 31 | + final reqBody = context.req.bodyJson as Map<String, dynamic>; |
| 32 | + final code = reqBody['code'] ?? ''; |
| 33 | + final firstName = reqBody['firstName'] ?? ''; |
| 34 | + final lastName = reqBody['lastName'] ?? ''; |
| 35 | + |
| 36 | + // Validate input |
| 37 | + if (code.isEmpty) { |
| 38 | + throw Exception('Code must be provided in the request body.'); |
| 39 | + } |
| 40 | + |
| 41 | + // Create a JWT client secret |
| 42 | + final header = {'alg': 'ES256', 'kid': keyId}; |
| 43 | + final jwt = JWT( |
| 44 | + {}, |
| 45 | + header: header, |
| 46 | + subject: bundleId, |
| 47 | + issuer: teamId, |
| 48 | + audience: Audience.one('https://appleid.apple.com'), |
| 49 | + ); |
| 50 | + final clientSecret = jwt.sign( |
| 51 | + key, |
| 52 | + algorithm: JWTAlgorithm.ES256, |
| 53 | + expiresIn: Duration(minutes: 5), |
| 54 | + ); |
| 55 | + |
| 56 | + final authTokenRequestBody = { |
| 57 | + 'grant_type': 'authorization_code', |
| 58 | + 'code': code, |
| 59 | + 'client_id': bundleId, |
| 60 | + 'client_secret': clientSecret, |
| 61 | + }; |
| 62 | + |
| 63 | + final authTokenResponse = await http.post( |
| 64 | + Uri.parse('https://appleid.apple.com/auth/token'), |
| 65 | + headers: { |
| 66 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 67 | + }, |
| 68 | + body: authTokenRequestBody, |
| 69 | + ); |
| 70 | + |
| 71 | + if (authTokenResponse.statusCode != 200) { |
| 72 | + throw Exception( |
| 73 | + 'Failed to exchange code for token: ${authTokenResponse.body}'); |
| 74 | + } |
| 75 | + |
| 76 | + final body = json.decode(authTokenResponse.body); |
| 77 | + |
| 78 | + // Use access token to fetch any additional information if needed |
| 79 | + // final accessToken = body['access_token'] ?? ''; |
| 80 | + |
| 81 | + // Store refresh token if you want to refresh the access token later |
| 82 | + // final refreshToken = body['refresh_token'] ?? ''; |
| 83 | + |
| 84 | + final idToken = JWT.decode(body['id_token']); |
| 85 | + final sub = idToken.payload['sub'] ?? ''; |
| 86 | + if (sub.isEmpty) { |
| 87 | + throw Exception('ID Token does not contain a valid subject (sub) claim.'); |
| 88 | + } |
| 89 | + // Hash the sub because it is too long and has characters that are not allowed in Appwrite user IDs |
| 90 | + final userId = md5.convert(utf8.encode(sub)).toString(); |
| 91 | + final email = idToken.payload['email'] ?? ''; |
| 92 | + final userName = '$firstName $lastName'.trim(); |
| 93 | + |
| 94 | + // You can use the Appwrite SDK to interact with other services |
| 95 | + // For this example, we're using the Users service |
| 96 | + final client = Client() |
| 97 | + .setEndpoint(Platform.environment['APPWRITE_FUNCTION_API_ENDPOINT']!) |
| 98 | + .setProject(Platform.environment['APPWRITE_FUNCTION_PROJECT_ID']!) |
| 99 | + .setKey(context.req.headers['x-appwrite-key'] ?? ''); |
| 100 | + final users = Users(client); |
| 101 | + |
| 102 | + // Find user by ID |
| 103 | + User? user; |
| 104 | + try { |
| 105 | + user = await users.get(userId: userId); |
| 106 | + } on AppwriteException catch (e) { |
| 107 | + if (e.type != 'user_not_found') { |
| 108 | + rethrow; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // Find user by email |
| 113 | + final userList = await users.list(queries: [Query.equal('email', email)]); |
| 114 | + if (userList.users.isNotEmpty) { |
| 115 | + user = userList.users.first; |
| 116 | + } |
| 117 | + |
| 118 | + // If user does not exist, create a new user |
| 119 | + user ??= await users.create( |
| 120 | + userId: ID.custom(userId), |
| 121 | + email: email, |
| 122 | + name: userName.isEmpty ? null : userName, |
| 123 | + ); |
| 124 | + |
| 125 | + // Mark the user as verified if not already verified |
| 126 | + if (!user.emailVerification) { |
| 127 | + users.updateEmailVerification( |
| 128 | + userId: userId, |
| 129 | + emailVerification: true, |
| 130 | + ); |
| 131 | + } |
| 132 | + |
| 133 | + // Create token |
| 134 | + final token = await users.createToken( |
| 135 | + userId: user.$id, |
| 136 | + expire: 60, |
| 137 | + length: 128, |
| 138 | + ); |
| 139 | + |
| 140 | + return context.res.json({ |
| 141 | + 'secret': token.secret, |
| 142 | + 'userId': user.$id, |
| 143 | + 'expire': token.expire, |
| 144 | + }); |
| 145 | +} |
0 commit comments