패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.2.0

local_session_timeout

응용 프로그램이 사용자 상호작용을 받지 않거나 "x" 기간 동안 백그라운드에서 실행되는 경우 사용자를 인증 페이지로 리디렉션합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.6만
좋아요
102
Pub 점수
150

패키지 설치

flutter pub add local_session_timeout

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

local_session_timeout 패키지는 사용자가 지정된 기간 동안 비활성 상태가 되었거나 앱이 너무 오랫동안 백그라운드에서 실행되었을 때 자동으로 사용자를 인증 페이지로 리디렉션합니다. 사용자 상호작용 또는 경과 시간에 따라 세션 만료를 강제함으로써 보안을 강화합니다. 안전한 접근 제어가 필요한 앱에 적합하며 Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼에서 작동합니다. 간단한 구성으로 Flutter 애플리케이션과 원활하게 통합됩니다.

사용 사례

  • 모바일 앱에서 민감한 데이터 보호
  • 비활동 후 자동 로그아웃 강제 적용
  • 웹 및 데스크톱에서 사용자 세션 보호
  • 장시간 백그라운드 사용 중 무단 접근 방지
  • 시간 기반 세션 만료 구현

주요 기능

  • 비활동 시 자동 리디렉션
  • 백그라운드 타임아웃 감지
  • 크로스 플랫폼 지원
  • Flutter와의 간단한 통합
  • 사용자 정의 타임아웃 기간
  • 사용자 정의 가능한 리디렉션 경로

적합한 대상

  • 보안이 강화된 Flutter 애플리케이션
  • 개인 또는 금융 데이터를 처리하는 앱
  • 기업 수준의 인증 필요 조건
  • 일관된 세션 관리를 필요로 하는 다중 플랫폼 앱
  • 사용자 보안을 우선시하는 개발자

고려 사항

  • 네비게이션 상태를 올바르게 처리해야 합니다
  • 복잡한 라우팅을 위해 맞춤 설정이 필요할 수 있습니다
  • 정확한 시스템 시간과 백그라운드 실행에 의존합니다
  • 지속적인 활성 세션을 필요로 하는 실시간 앱에는 적합하지 않습니다
  • 다양한 플랫폼에서 철저히 테스트되어야 합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

  • With local_session_timeout you can redirect user to authentication page, if the application hasn't received any user interaction, or been running in the background for "x" duration.
  • Works locally, does not require internet connection.
  • Useful for apps with confidential information. If the user leaves the app running, or pushes it to the background to use later and forgets to close it.
  • Works on android, ios, web and desktop.

Getting started

import 'package:local_session_timeout/local_session_timeout.dart';
Create SessionConfig object

An object responsible for specifying durations for different types of timeouts.

It exposes a stream which can be listened for timeout events

final sessionConfig = SessionConfig(
    invalidateSessionForAppLostFocus: const Duration(seconds: 15),
    invalidateSessionForUserInactivity: const Duration(seconds: 30));

// If you don't have access to Navigator via context, you can access it like this
final navigatorKey = GlobalKey<NavigatorState>();
NavigatorState get _navigator => navigatorKey.currentState!;

sessionConfig.stream.listen((SessionTimeoutState timeoutEvent) {
    if (timeout == SessionTimeoutState.userInactivityTimeout) {
        // handle user  inactive timeout
        _navigator.pushNamed("/auth");
    } else if (imeout == SessionTimeoutState.appFocusTimeout) {
        // handle user  app lost focus timeout
        _navigator.pushNamed("/auth");
    }
});
Parameters
  • invalidateSessionForAppLostFocus (Duration? duration): appFocusTimeout event will be emitted through the stream, if the app loses focus and running in background for specified duration. If duration passed is null, app will not emit timeout events for losing focus / pushed into background.

  • invalidateSessionForUserInactivity (Duration? duration): userInactivityTimeout event will be emitted through the stream, if the app doesn't recieve any user activity for specified duration. If duration passed is null, app will not emit timeout events for user inactivity.

Create SessionTimeoutManager object
StreamController<SessionState> sessionStateStream:
SessionTimeoutManager(
    sessionConfig: sessionConfig,
    sessionStateStream: sessionStream,
    userActivityDebounceDuration: const Duration(seconds: 10),
    child: MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
        primarySwatch: Colors.blue,
    ),
    home: const MyHomePage(title: 'Flutter Demo Home Page'),
    )
);
Parameters
  • sessionConfig (SessionConfig sessionConfig): sessionConfig object that was created previously.

  • child (Widget widget): child widget in widget tree.

  • userActivityDebounceDuration (Duration duration) (optional): Since creating a timer object for each user interaction can be CPU intensive, a new timer will be started only in the intervals of userActivityDebounceDuration duration, has default value of 10 seconds.

  • sessionStateStream<SessionState> (StreamController<SessionState>) (optional):

    • If the argument is not passed, session timeout manager will always be listening.
    • If the argument is passed, developer can selectively disable the session timeout manager and re-enable it.
    Sometimes you may want to disable the session timeout manager and re-enable it, consider the following scenarios:
    • User might be in a page reading someting which doesn't contribute to any user inactivity, so you may want to disable the session timeout manager when user is in this page.
    • Typing (both soft keyboard and hardware keyboard) isn't recorded by session timeout manager as user activity, because it is not possible to listen to keyboard events from outside the TextField widget in Flutter, so you may want to disable listener when soft keyboard is open.
    • You may want to disable session timeout manager in auth page, as it doesn't makes much sense to redirect to auth page from auth page.
    • To disable session timeout manager, pass SessionState.stopListening to this stream, and to re-enable session timeout manager, pass SessionState.startListening to this stream. (Developer is responsible for handling and disposing of streamController passed). If you don't pass this argument, session timeout manager will always be listening.

    All of the above usecases are covered in example app

Note: Make sure to keep SessionTimeoutManager as top level widget of your widget tree, so that it records user activity in all screens

Sample Usage (refer example app for complete usage)

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final sessionConfig = SessionConfig(
        invalidateSessionForAppLostFocus: const Duration(seconds: 15),
        invalidateSessionForUserInactivity: const Duration(seconds: 30));

    sessionConfig.stream.listen((SessionTimeoutState timeoutEvent) {
    if (timeoutEvent == SessionTimeoutState.userInactivityTimeout) {
        // handle user  inactive timeout
        // Navigator.of(context).pushNamed("/auth");
    } else if (timeoutEvent == SessionTimeoutState.appFocusTimeout) {
        // handle user  app lost focus timeout
        // Navigator.of(context).pushNamed("/auth");
    }
});

    return SessionTimeoutManager(
      sessionConfig: sessionConfig,
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

Support

All OS's will support userInactivityTimeout, but appLostFocusTImeout is supported only on mobile devices (Android and IOS) as Flutter doesn't support widget lifecycle methods on desktop and Web.

Additional information

This package can be used for both online and offline applications. Even if the application has session / token based auth with webserver, invalidating the session may require require communication with web server, which is not possibe if the user turns off internet connection and pushes the app to the background.

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트