오늘하루도 우힣ㅎ

flutter)Firebase를 통한 Google login 연결하기 본문

카테고리 없음

flutter)Firebase를 통한 Google login 연결하기

우힣 2020. 2. 16. 23:29

 flutter에서는 firebase를 통해서 구글 로그인을 쉽게 연결할수 있도록 패키지로 제공을 하여 주고 있다. 처음의 경우 파이어베이스의 프로젝트를 만들고 이것저것 등록해야 하는 과정이 번거롭다고 느껴질수 있지만 한번 해보고 나면 계속 쉽게 해나갈수 있을것이라고 생각이 된다. 요즘은 google id가 없는 사람을 찾는게 더 힘들 정도이기 때문에 google login기능은 사용자에게나 개발자에게나 고마운 기능이라고 생각이 된다.

 

1. 가장 먼저 필요한것은 firebase의 프로젝트를 생성하는 것이다. firebase는 https://console.firebase.google.com/u/0/의 사이트에서 찾아 생성할수가 있다. 프로젝트 추가하기를 누르고 자신이 만들고자 하는 프로젝트의 이름을 지어주기만 하면 프로젝트는 쉽게 만들어진다.(그 뒤의 두단계의 경우 그냥 동의하기를 누르고 계속 버튼을 누르면 되기에 넘어가겠습니답.)

2. 나의 경우 IOS를 기준으로 등록하는걸 보여 줄려 한다. 밑의 옵션중 자신이 원하는 것을 선택하여 진행하면 된다.

  • 앱 등록의 단계에서는 ios 번들 ID은 프로젝트의 가장 처음 부분에서 open ios/Runner.xcworkspace를 사용하여 알수 있다. 해당 명령어를 치게 되면 xcode가 열리게 되는데 번들 ID의 경우 아래사진이 Bundle identifier에 있는것을 복붙을 해주면 된다.

  • 구성파일 다운로드 단계에서는 GoogleService-Info.plist를 다운하여 주기만 하면 된다.
  • 그후에 2번째에서 다운 받은 파일을 Runner folder에 또 Runner라는 폴더가 존재하는데 글로 넣어주면 된다.

  • 그리고 남은 단계들은 그냥 넘어가주면 될것이다.

  • 그리고 해당 프로젝트의 Authentication부분에서 google과 익명부분을 사용설정으로 체크를 해주어야 한다.

3. 이제 yaml파일에 필요한 package를 추가하여 주면 된다. 이 두개의 패키지를 통해서 구글 로그인할수가 있다.

4. 또한 GoolgeServide-Info.plist에서 REVERSED_CLIENT_ID의 key값을 복사하여 Info.plist에 적어야하는데 CFBundleURLTypes부분을 추가해야 한다. 해당 복사한 키값은 여기다 붙여넣어야합니다 에다가 넣어야 합니다.  이 과정은 구글 웹페이지에서 로그인에 성공하면 브라우저 레벨에서 iOS 앱으로 자동 연결되게 하기 위하여 수행하는 것이다.

<key>CFBundleURLTypes</key>
	<array>
	    <dict>
	        <key>CFBundleTypeRole</key>
	        <string>Editor</string>
	        <key>CFBundleURLSchemes</key>
	        <array>
	        <string>여기다가 붙여 넣어야 합니다.</string>
	        </array>
	    </dict>
	</array>

 

5. 다음은 구글 로그인과, 익명 로그인을 위한 버튼을 만들어야 한다.

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
          //해당 부분은 email의 유무에 따라 로그인이 됐는지 안됐는지를 판단하고 해당 로그인이 제대로 됐다면
          //구글의 프로필 이미지, 닉네임, 이메일을 가져와 출력을 시켜줄것이다.
            email == ""
                ? Container()
                : Column(
                    children: <Widget>[
                      Image.network(url),
                      Text(name),
                      Text(email),
                    ],
                  ),
            RaisedButton(
              onPressed: () {
              //여기또한 이메일의 존재 여부를 통해 해당 버튼의 기능을 바꾸게 된다.
                if (email == "") {
                  googleSingIn();
                } else {
                  googleSignOut();
                }
              },
              //여기또한 이메일의 존재 여부를 통해 해당 버튼의 텍스트를 바꾸어 준다.
              child: Container(
                  width: 150,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Icon(Icons.subdirectory_arrow_right),
                      Text(email == "" ? 'Google Login' : "Google Logout")
                    ],
                  )),
            ),
          ],
        ),
      ),
    );
  }

6. google login을 위한 메서드를 생성해준다.

  
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();
  FirebaseUser currentUser;
  String name = "";
  String email = "";
  String url = "";

//구글 로그인을 통해 로그인을 하는 코드이다.
  Future<String> googleSingIn() async {
    final GoogleSignInAccount account = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await account.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final AuthResult authResult = await _auth.signInWithCredential(credential);
    final FirebaseUser user = authResult.user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);

//해당 부분을 통해 현재 로그인된 유저의 이메일, 사진, 닉네임을 설정해준다.
    setState(() {
      email = user.email;
      url = user.photoUrl;
      name = user.displayName;
    });

    return '구글 로그인 성공: $user';
  }

//구글 로그인에서 로그아웃 할때 설정해주었던 모든 것들을 다시 초기화 시켜주는 작업도 함께 해준다.
  void googleSignOut() async {
    await _auth.signOut();
    await googleSignIn.signOut();

    setState(() {
      email = "";
      url = "";
      name = "";
    });

    print("User Sign Out");
  }

##전체코드##

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();
  FirebaseUser currentUser;
  String name = "";
  String email = "";
  String url = "";

  Future<String> googleSingIn() async {
    final GoogleSignInAccount account = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await account.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final AuthResult authResult = await _auth.signInWithCredential(credential);
    final FirebaseUser user = authResult.user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);

    setState(() {
      email = user.email;
      url = user.photoUrl;
      name = user.displayName;
    });

    return '구글 로그인 성공: $user';
  }

  void googleSignOut() async {
    await _auth.signOut();
    await googleSignIn.signOut();

    setState(() {
      email = "";
      url = "";
      name = "";
    });

    print("User Sign Out");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            email == ""
                ? Container()
                : Column(
                    children: <Widget>[
                      Image.network(url),
                      Text(name),
                      Text(email),
                    ],
                  ),
            RaisedButton(
              onPressed: () {
                if (email == "") {
                  googleSingIn();
                } else {
                  googleSignOut();
                }
              },
              child: Container(
                  width: 150,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Icon(Icons.subdirectory_arrow_right),
                      Text(email == "" ? 'Google Login' : "Google Logout")
                    ],
                  )),
            ),
          ],
        ),
      ),
    );
  }
}
Comments