【问题标题】:How to restrict user-generated content in SQLite database to that user如何将 SQLite 数据库中用户生成的内容限制为该用户
【发布时间】:2022-10-02 10:47:02
【问题描述】:

我有一个通过 Flutter 创建的应用程序。它使用 SQLite 数据库来允许用户存储用户生成的数据。它还需要使用 Firebase 进行身份验证,其中每个用户都必须拥有一个帐户才能登录应用程序。

就在今天,我注意到当我使用与我使用的主帐户不同的测试帐户登录手机上的应用程序时,我可以使用这个新帐户访问使用我的另一个帐户创建的 SQLite 数据库中的所有内容,让我有点意外。

有没有办法将用户生成的内容限制为特定用户?我的意思是,如果一个用户在设备上登录应用程序并创建了一些内容,如果他们在同一设备上使用他们的帐户登录应用程序,其他用户将看不到该内容?

为了处理数据库并向其中添加条目,我构建了这个完美运行的代码:

  static final DatabaseClientCalculations instance =
      DatabaseClientCalculations._init();
  static Database? _database;
  DatabaseClientCalculations._init();

  /// Calling the database
  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB(\'calculationsDatabaseV6.db\');
    return _database!;
  }

  /// Future function to open the database
  Future<Database> _initDB(String filePath) async {
    final path = await getDatabasesPath();
    final dbPath = join(path, filePath);
    return await openDatabase(dbPath,
        version: 11, onCreate: _create, onUpgrade: _update);
  }

要在数据库中创建一个新条目,我使用这个:

  Future<CalcResult> create(CalcResult calcResult) async {
    final db = await instance.database;
    final id = await db.insert(calcResults, calcResult.toJson());
    return calcResult.copy(id: id);
  }

要读取特定的数据库条目,这是我使用的:

  Future<CalcResult> readNote(int id) async {
    final db = await instance.database;
    final maps = await db.query(
      calcResults,
      columns: CalcResultFields.calcValues,
      where: \'${CalcResultFields.id} = ?\',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return CalcResult.fromJson(maps.first);
    } else {
      throw Exception(\'ID $id not found\');
    }
  }

要在 ListView 中显示所有条目,我使用的是:

  Future<List<CalcResult>> readAllNotes() async {
    final db = await instance.database;
    final orderBy =
        \'${CalcResultFields.toDate} DESC, ${CalcResultFields.toTime} DESC\';
    final result = await db.query(calcResults, orderBy: orderBy);
    return result.map((json) => CalcResult.fromJson(json)).toList();
  }

正如我所说,这确实工作得很好,除了似乎任何用户都可以查看任何其他用户的数据。似乎我错误地假设由于身份验证,没有用户会看到其他任何人的内容。

有没有办法限制对数据库条目的访问仅限于创建这些条目的人?我可以做些什么来将用户生成的内容仅限于该用户?

    标签: flutter sqlite authentication firebase-authentication sqflite


    【解决方案1】:

    一种方法是在数据库中创建数据项的每个条目,其中一列具有创建它的用户的 ID。

    然后在查询函数中将传递用户 id 以及搜索条件的重置,以仅获取用户 id 创建并因此被允许访问的记录

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2010-09-17
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      相关资源
      最近更新 更多