Skip to content
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

M3-161 자동로그인 구현 #24

Merged
merged 11 commits into from
Jul 10, 2024
Merged

M3-161 자동로그인 구현 #24

merged 11 commits into from
Jul 10, 2024

Conversation

koomin1227
Copy link
Member

작업 내용*

  • 앱 실행시 로그인 유무를 판단하여 화면 라우팅 선택
  • dio 요청에 jwt 값을 넣도록 구현

고민한 내용*

자동 로그인

앱이 처음 실행될 때 로그인 여부를 판단하여 로그인 화면과 메인 화면으로 이동시키는 로직이 필요했다.

첫번째 방법

처음에는

GetMaterialApp(
      title: 'Ground Flip',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      initialRoute: '/login',
      getPages: [
        GetPage(name: '/main', page: () => const MainScreen()),
        GetPage(name: '/login', page: () => const LoginScreen()),
      ],
    );

위와 같이 로그인 페이지로 최초 진입시키고 로그인 페이지에서 로그인이 되었는지 검증하고 되었으면 main 페이지로 이동시키는 방법으로 구현했다. 이렇게 하니 로그인이 되었음에도 로그인 페이지가 1초 정도 켜지고 main 화면으로 넘어가는 문제가 있었다. 때문에 방법을 바꾸었다.

두번째 방법

처음 MyApp 위젯이 빌드 될때 initialRoute 를 설정하는 방식으로 수정했다.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load(fileName: ".env");
  await GetStorage.init();
  KakaoSdk.init(
    nativeAppKey: dotenv.env['NATIVE_APP_KEY']!,
  );

  String initialRoute = await AuthService().isLogin() ? '/main' : '/login';
  runApp(
    MyApp(
      initialRoute: initialRoute,
    ),
  );
}

main 문 에서 로그인 여부를 검색하고 첫 라우트 페이지를 설정한다.

현재 로그인 한 유저의 정보를 참조하기

UserManager 라는 싱글톤 클래스를 만들어서 이 클래스에서 현재 로그인된 유저의 id 를 관리한다.

따로 클래스로 분리한 이유는 추후에 유저의 개인 정보들을 캐시해두어 성능을 개선할 수도 있을 것 같았다. 유저 정보 같은 것을 매번 api 호출하기 보다 메모리에 들고 있으면 속도가 개선될 것 같았다.

요청에 access token 붙이기

dio 의 인터셉터를 사용하였다.

onRequest: (options, handler) async {
          final accessToken = await secureStorage.readAccessToken();
          options.headers.addAll({
            'Authorization': 'Bearer $accessToken',
          });
          logRequest(options);
          return handler.next(options);
        },

secureStorage 에서 access token 을 가져와서 헤더에 추가한다.

의문점

secureStorage 는 스토리지인거 같은데 스토리지는 메모리보다 읽기속도가 느린데 매 요청마다 스토리지에서 읽어도 성능에 문제는 생기지 않을까?

리뷰 요구사항

  • secureStorage 는 스토리지인거 같은데 스토리지는 메모리보다 읽기속도가 느린데 매 요청마다 스토리지에서 읽어도 성능에 문제는 생기지 않을까요?

스크린샷

@@ -22,6 +28,10 @@ class DioService {
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) async {
final accessToken = await secureStorage.readAccessToken();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

최적화 관련 걱정하신 부분 제 생각에는 매 요청마다 읽어오니 내부적으로 caching이 될 것 같지만, 정 걱정이 되신다면 GetStorage를 같이 사용하는 방법도 좋을 것 같습니다!

Copy link
Contributor

@tkdals802 tkdals802 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은 코드인것 같습니다

@koomin1227 koomin1227 merged commit f0ebcd4 into develop Jul 10, 2024
1 check passed
@koomin1227 koomin1227 self-assigned this Jul 10, 2024
@koomin1227 koomin1227 deleted the feature/M3-161-autoLogin branch July 10, 2024 08:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants