@nikitasalnikov
Новичок

Как разлогинить приложение пользователя которому дали временные права админа?

Добрый день. Кто может подкинуть идею?
Есть код на сервере на Node.js, по которому админ, дает временные права, другому пользователю
app.put('/temporary-update-role/:userId', verifyToken, verifyRole('admin'), (req, res) => {
    const userId = req.params.userId;
    const { role, duration } = req.body; // duration in minutes

    console.log('Temporarily updating role for userId:', userId, 'to role:', role, 'for duration:', duration, 'minutes');

    // Get current role of the user
    const getCurrentRoleQuery = 'SELECT role FROM registered_users WHERE id = ?';
    db.query(getCurrentRoleQuery, [userId], (err, results) => {
        if (err) {
            console.error('Error fetching current role:', err);
            return res.status(500).json({ error: 'Failed to fetch current role' });
        }

        if (results.length === 0) {
            return res.status(404).json({ error: 'User not found' });
        }

        const currentRole = results[0].role;

        // Update to new role
        const updateRoleQuery = 'UPDATE registered_users SET role = ? WHERE id = ?';
        db.query(updateRoleQuery, [role, userId], (err, result) => {
            if (err) {
                console.error('Error updating user role:', err);
                return res.status(500).json({ error: 'Failed to update user role' });
            }

            console.log('Role updated to:', role);

            // Set timeout to revert the role after the duration
            const expirationTime = Date.now() + duration * 60000;
            setTimeout(() => {
                const revertRoleQuery = 'UPDATE registered_users SET role = ? WHERE id = ?';
                db.query(revertRoleQuery, [currentRole, userId], (err, revertResult) => {
                    if (err) {
                        console.error('Error reverting user role:', err);
                    } else {
                        console.log('Role reverted to:', currentRole);
                    }
                });
            }, duration * 60000); // duration in milliseconds

            res.json({ message: 'User role temporarily updated successfully', expirationTime });
        });
    });
});


Есть код клиента, то есть админа где он дает вводит какое на какое время нужно дать права
import 'package:flutter/material.dart';
import 'package:flutter_application_1/domain/api/api.dart';
import 'package:flutter_application_1/domain/contollers/app_controllers.dart';
import 'package:flutter_application_1/domain/model/registered_users.dart';
import 'package:flutter_application_1/ui/style/app_colors.dart';
import 'package:flutter_application_1/ui/style/app_style.dart';

class UserManagementPage extends StatefulWidget {
  const UserManagementPage({super.key});

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

class _UserManagementPageState extends State<UserManagementPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.mainColor,
        title: Text(
          'Управление правом доступа',
          style: AppStyle.fontStyle.copyWith(
            fontSize: 20,
            color: AppColors.white,
          ),
        ),
      ),
      body: FutureBuilder<List<RegisteredUsers>>(
        future: Api.fetchregisteredUsers(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else {
            final users = snapshot.data!;

            return ListView.separated(
              itemCount: users.length,
              separatorBuilder: (context, index) => const SizedBox(height: 16),
              itemBuilder: (context, index) {
                final user = users[index];
                return Card(
                  child: ListTile(
                    title: Text('${user.username} (${user.role})'),
                    trailing: DropdownButton<String>(
                      value: user.role,
                      items: ['user', 'admin']
                          .map((role) => DropdownMenuItem(
                                value: role,
                                child: Text(role),
                              ))
                          .toList(),
                      onChanged: (newRole) {
                        if (newRole != null) {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                title: const Text('Выберите продолжительность'),
                                content: TextField(
                                  controller:
                                      AppControllers.roleDurationController,
                                  keyboardType: TextInputType.number,
                                  decoration: const InputDecoration(
                                    labelText: 'Длительность (в минутах)',
                                  ),
                            
                                ),
                                actions: [
                                  ElevatedButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                      child: const Text('Отмена')),
                                  ElevatedButton(
                                    onPressed: () {
                                      final duration = int.tryParse(
                                          AppControllers
                                              .roleDurationController.text);

                                      if (duration != null) {
                                        Api.temporaryUpdateRole(
                                                user.id!, newRole, duration)
                                            .then((success) {
                                          Navigator.of(context).pop();
                                          if (success) {
                                            ScaffoldMessenger.of(context)
                                                .showSnackBar(
                                              const SnackBar(
                                                content: Text(
                                                    'Role updated successfully'),
                                              ),
                                            );
                                          } else {
                                            ScaffoldMessenger.of(context)
                                                .showSnackBar(
                                              const SnackBar(
                                                content: Text(
                                                    'Failed to update role'),
                                              ),
                                            );
                                          }
                                        }).catchError((error) {
                                          Navigator.of(context).pop();
                                          ScaffoldMessenger.of(context)
                                              .showSnackBar(
                                            const SnackBar(
                                              content:
                                                  Text('Failed to update role'),
                                            ),
                                          );
                                        });
                                      }
                                    },
                                    child: const Text('Ok'),
                                  ),
                                ],
                              );
                            },
                          );
                        }
                      },
                    ),
                  ),
                );
              },
            );
          }
        },
      ),
    );
  }
}

Права даются, все замечательно работает, юзер который получает права, заходит и может работать с некоторыми функциями,
в консоли сервера появляются сообщения
Role updated to: admin - когда получили права админа
Role reverted to: user - когда закончилось время
НО СУТЬ ВОПРОСА ТАКОВА
Как мне на стороне юзера, КОТОРОМУ дали права админа, по окончании времени сделать выход из приложения? Именно на стороне того юзера, кому дали на время, а не у всех кто пользуется и тем более у админа делать выход?
  • Вопрос задан
  • 60 просмотров
Решения вопроса 1
dima9595
@dima9595
Junior PHP
Например, при запросе данных от пользователя к серверу проверять статус доступа. Если доступ закончился - выбивать из сессии на клиенте (разлогинить, выдавать ошибку или типо того), иначе продолжать работу.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Neonoviiwolf
Flutter developer
В зарпосах есть хёдер, туда передать токен и любой запрос будет с этим токеном, если юзера нужно выкинуть, выкидываем соответствующую ошибку с сервера, а приложение, получив, выкидывают юзера - самое стандартное решение
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы