mdanics / mdanics/fluttergram

Apple Sign in

Open
#91 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Dart
Stars
2.4k
Forks
614
PR merge metrics
No merged PRs in 30d

Description

I have tried to implement apple sign in as an authentication provider, am having an issues for
1 Not navigating to the next page
2. It seems is not fetching any data am requesting.
Below is the code
using apple_sign_in 0.1.0 from pub.dev

Future<void> _ensureLoggedIn(BuildContext context) async {
  print('[_ensureLoggedIn] START');

  GoogleSignInAccount user = googleSignIn.currentUser;
  if (user == null) {
    print('[_ensureLoggedIn] user == null');
    print('[_ensureLoggedIn] [signInSilently] START');
    user = await googleSignIn.signInSilently();
    print('[_ensureLoggedIn] [signInSilently] DONE');
  }

  if (user == null) {
    print('[_ensureLoggedIn] user == null');
    print('[_ensureLoggedIn] [signIn] START');
    await googleSignIn.signIn().then((_) {
      tryCreateUserRecord(context);
    });
    print('[_ensureLoggedIn] [signIn] DONE');
  }

  if (await auth.currentUser() == null) {

    print('[_ensureLoggedIn] auth.currentUser() == null');
    print('[_ensureLoggedIn] [googleSignIn.currentUser.authentication] START');


    GoogleSignInAuthentication credentials = await googleSignIn.currentUser.authentication;
    final GoogleSignInAccount googleUser = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

print('[_ensureLoggedIn] [googleSignIn.currentUser.authentication] DONE');
    print('[_ensureLoggedIn] [signInWithGoogle] START');
  final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
 return(await auth.signInWithCredential(credential)).user.uid;
  }
print('[_ensureLoggedIn] DONE');
}
Future<void> _silentLogin(BuildContext context) async {
  GoogleSignInAccount user = googleSignIn.currentUser;
if (user == null) {
    user = await googleSignIn.signInSilently();
    await tryCreateUserRecord(context);
  }
 if (await auth.currentUser() == null && user != null) {
    final GoogleSignInAccount googleUser = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await googleUser
        .authentication;
   final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    await auth.signInWithCredential(credential);
  }
}

// APPLE
Future<void> signInWithApple(BuildContext context) async {
  final AuthorizationResult result = await AppleSignIn.performRequests([
    AppleIdRequest(requestedScopes: [Scope.email, Scope.fullName])
  ]);
switch (result.status) {
    case AuthorizationStatus.authorized:
 // Store user ID
      await FlutterSecureStorage()
          .write(key: "userId", value: result.credential.user);
       final AppleIdCredential _auth = result.credential;
      final OAuthProvider oAuthProvider = new OAuthProvider(providerId: "apple.com");
     final AuthCredential credential = oAuthProvider.getCredential(
        idToken: String.fromCharCodes(_auth.identityToken),
        accessToken: String.fromCharCodes(_auth.authorizationCode),
      );
 await auth.signInWithCredential(credential);
// update the user information
      if (_auth.fullName != null) {
        auth.currentUser().then( (value) async {
          UserUpdateInfo user = UserUpdateInfo();
          user.displayName = "${_auth.fullName.givenName} ${_auth.fullName.familyName}";
          await value.updateProfile(user);
        });
      }

      break;
 case AuthorizationStatus.error:
      print("Sign In Failed ${result.error.localizedDescription}");
      break;
case AuthorizationStatus.cancelled:
      print("User Cancelled");
      break;
  }
}
tryCreateUserRecord(BuildContext context) async {
  GoogleSignInAccount user = googleSignIn.currentUser;
  if (user == null) {
    return null;
  }
  DocumentSnapshot userRecord = await ref.document(user.id).get();
  if (userRecord.data == null) {
    // no user record exists, time to create
 String userName = await Navigator.push( context,
      // We'll create the SelectionScreen in the next step!
      MaterialPageRoute(
          builder: (context) => Center(
                child: Scaffold(
                    appBar: AppBar(
                      leading: Container(),
                      title: Text('Fill out missing data',
                          style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold)),
                      backgroundColor: Colors.white,
                    ),
                    body: ListView(
                      children: <Widget>[
                         Container(
                          child: CreateAccount(),
                        ),
                      ],
                    )),
              )),
 );
 if (userName != null || userName.length != 0){
      ref.document(user.id).setData({
        "id": user.id,
        "username": userName,
        "photoUrl": user.photoUrl,
        "email": user.email,
        "displayName": user.displayName,
      });
    }
  }
 currentUserModel = User.fromDocument(userRecord);
}
 and separate container for 
AppleSignInButton(
               type: ButtonType.signIn,
                cornerRadius: 6.0,
                 onPressed: () async {
                await signInWithApple( context );
                Navigator.push (context ,MaterialPageRoute(
                    builder: (_) =>
                        HomePage()));
              },

Please any help or any light something on the codes would be appreciated.
Thanks

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing signInWithApple and the AppleSignInButton callback, then compare their authentication and navigation flow with _ensureLoggedIn and _silentLogin. Check how auth.currentUser, the Apple credential, and the Firestore user record are handled. Done means authorized Apple sign-in completes, reaches HomePage, and retrieves or creates the expected user data.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart, firebase, flutter
Domain
authentication, database, mobile
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.