user_view.dart 16.8 KB
Newer Older
1
2
3
4
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

Leon Tappe's avatar
Leon Tappe committed
5
import 'package:digital_3g_common/backend_switcher.dart';
Leon Tappe's avatar
Leon Tappe committed
6
import 'package:digital_3g_common/theme.dart';
Leon Tappe's avatar
Leon Tappe committed
7
import 'package:digital_3g_common/ui.dart';
8
9
10
import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'package:flutter/material.dart';
Leon Tappe's avatar
Leon Tappe committed
11
import 'package:flutter_bloc/flutter_bloc.dart';
12
import 'package:http/http.dart' as http;
13
import 'package:intl/date_symbol_data_local.dart';
14
15
16
17
18
19
20
21
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../api/auth_api.dart';
import '../api/user_api.dart';
22
import '../models/runtime_setting.dart';
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

class FormData {
  DateTime? certificationDate;
  TimeOfDay? certificationTime;
  bool isTested;
  bool isRecovered;
  bool isVaccinated;

  FormData({
    this.certificationDate,
    this.certificationTime,
    this.isTested = false,
    this.isRecovered = false,
    this.isVaccinated = false,
  });

  void resetBools() {
    isTested = false;
    isRecovered = false;
    isVaccinated = false;
  }
}

class UserView extends StatefulWidget {
  const UserView({key}) : super(key: key);

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

class _UserViewState extends State<UserView> {
Leon Tappe's avatar
Leon Tappe committed
54
  FormData _formData = FormData(
55
56
57
58
59
60
61
62
63
64
65
66
67
    certificationDate: DateTime.now(),
    certificationTime: TimeOfDay.now(),
  );

  final DateFormat _dateFormat = DateFormat.yMd();
  final DateFormat _timeFormat = DateFormat.Hm();

  String _expiryText = '';

  http.Client? _client;

  UserApi? _userApi;

68
69
70
71
72
  String _motd = '';
  // ticket runtime defaults showcasing all different modes
  RuntimeSetting _testedRuntime =
      RuntimeSetting(RuntimeType.duration, duration: const Duration(hours: 24));
  RuntimeSetting _recoveredRuntime = RuntimeSetting(RuntimeType.months, months: 3);
73
  int _recoveredMinAge = 31;
74
75
  RuntimeSetting _vaccinatedRuntime = RuntimeSetting(RuntimeType.nextSemester);

76
77
  @override
  Widget build(BuildContext context) {
Leon Tappe's avatar
Leon Tappe committed
78
79
80
81
82
    return Center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 512.0),
        child: ListView(
          children: [
83
84
85
86
87
88
89
90
91
            if (_motd.isNotEmpty)
              PaddedCard(
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(
                  'Systemnachricht',
                  style: Theme.of(context).textTheme.headline6,
                ),
                Text(_motd),
              ])),
Leon Tappe's avatar
Leon Tappe committed
92
93
94
95
96
97
98
99
100
            PaddedCard(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text('Datenaufnahme', style: Theme.of(context).textTheme.headline5),
                  CheckboxListTile(
                    title: const Text('Getestet'),
                    value: _formData.isTested,
                    onChanged: (bool? input) {
101
                      ScaffoldMessenger.of(context).clearSnackBars();
Leon Tappe's avatar
Leon Tappe committed
102
103
104
105
106
107
108
109
110
111
112
                      setState(() {
                        _formData.resetBools();
                        _formData.isTested = input ?? false;
                        _expiryText = _makeExpiryString();
                      });
                    },
                  ),
                  CheckboxListTile(
                    title: const Text('Genesen'),
                    value: _formData.isRecovered,
                    onChanged: (bool? input) {
113
                      ScaffoldMessenger.of(context).clearSnackBars();
Leon Tappe's avatar
Leon Tappe committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
                      setState(() {
                        _formData.resetBools();
                        _formData.isRecovered = input ?? false;
                        _expiryText = _makeExpiryString();
                      });
                    },
                  ),
                  CheckboxListTile(
                    title: const Text('Geimpft'),
                    value: _formData.isVaccinated,
                    onChanged: (bool? input) {
                      ScaffoldMessenger.of(context).clearSnackBars();
                      setState(() {
                        _formData.resetBools();
                        _formData.isVaccinated = input ?? false;
                        _expiryText = _makeExpiryString();
                      });
                    },
                  ),
133
134
                  if (_formData.isTested || _formData.isRecovered) const Divider(),
                  if (_formData.isTested || _formData.isRecovered)
Leon Tappe's avatar
Leon Tappe committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
                    ListTile(
                        title: const Text('Nachweisdatum'),
                        trailing:
                            Text(_dateFormat.format(_formData.certificationDate ?? DateTime.now())),
                        onTap: () async {
                          ScaffoldMessenger.of(context).clearSnackBars();
                          final date = await showDatePicker(
                            context: context,
                            cancelText: 'Abbrechen',
                            confirmText: 'Bestätigen',
                            fieldLabelText: 'Datum',
                            fieldHintText: 'z.B. 01/04/2021',
                            helpText: 'Nachweisdatum einstellen',
                            initialDate: _formData.certificationDate ?? DateTime.now(),
                            firstDate: DateTime.now().subtract(const Duration(days: 1000)),
                            lastDate: DateTime.now(),
                          );
                          if (date != null) {
                            setState(() {
                              _formData.certificationDate = date;
                              _expiryText = _makeExpiryString();
                            });
                          }
                        }),
                  if (_formData.isTested)
                    ListTile(
                        title: const Text('Nachweiszeit'),
                        trailing: Text(_formData.certificationTime?.format(context) ??
                            _timeFormat.format(DateTime.now())),
                        onTap: () async {
                          ScaffoldMessenger.of(context).clearSnackBars();
                          final time = await showTimePicker(
                            cancelText: 'Abbrechen',
                            confirmText: 'Bestätigen',
                            minuteLabelText: 'Minuten',
                            hourLabelText: 'Stunden',
                            helpText: 'Nachweiszeit auswählen',
                            initialEntryMode: TimePickerEntryMode.dial,
                            context: context,
                            initialTime: _formData.certificationTime ?? TimeOfDay.now(),
                          );
                          if (time != null) {
                            final now = DateTime.now();
                            if (_formData.certificationDate?.year == now.year &&
                                _formData.certificationDate?.month == now.month &&
                                _formData.certificationDate?.day == now.day &&
                                (time.hour > now.hour ||
                                    (time.hour == now.hour && time.minute > now.minute))) {
                              ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                                  content: Text(
                                      'Der gewählte Testzeitpunkt kann nicht benutzt werden, da er in der Zukunft liegt.')));
                            } else {
                              setState(() {
                                _formData.certificationTime = time;
                                _expiryText = _makeExpiryString();
                              });
                            }
                          }
                        }),
                  const Divider(),
                  const Text('Gültig bis:'),
                  Text(_expiryText, style: Theme.of(context).textTheme.headline6),
                ],
              ),
            ),
            const Divider(),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _formData.isRecovered || _formData.isVaccinated || _formData.isTested
                    ? _onShowCode
                    : null,
                child: const Text('QR-Code zeigen', textScaleFactor: 1.2),
              ),
            ),
          ],
211
        ),
Leon Tappe's avatar
Leon Tappe committed
212
      ),
213
214
215
216
217
218
    );
  }

  @override
  void initState() {
    super.initState();
219
220
221
    initializeDateFormatting('de', null);
    _client = Provider.of<AuthApi>(context, listen: false).client;
    _userApi = UserApi(_client!, BlocProvider.of<BackendSwitcher>(context).state);
222
    _initKey();
223
    _initSettings().then((_) => _expiryText = _makeExpiryString());
224
225
226
227
  }

  DateTime? _calculateExpiryDate(FormData form) {
    if (form.isTested) {
228
      return _calculateForType(form, _testedRuntime);
229
    } else if (form.isRecovered) {
230
      if (DateTime.now().difference(form.certificationDate!) < Duration(days: _recoveredMinAge)) {
Leon Tappe's avatar
Leon Tappe committed
231
        throw Exception('test');
232
      }
233
      return _calculateForType(form, _recoveredRuntime);
234
    } else if (form.isVaccinated) {
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
      return _calculateForType(form, _vaccinatedRuntime);
    }
  }

  DateTime? _calculateForType(FormData form, RuntimeSetting runtime) {
    var date = form.certificationDate;
    var time = form.certificationTime;
    switch (runtime.type) {
      case RuntimeType.duration:
        date = DateTime(date!.year, date.month, date.day).add(runtime.duration!);
        date = date.add(Duration(hours: time!.hour, minutes: time.minute));
        return date;
      case RuntimeType.months:
        date = DateTime(date!.year, date.month + runtime.months!, date.day - 1, 23, 59);
        return date;
      case RuntimeType.nextSemester:
        final now = DateTime.now();
        final thisSs = DateTime(now.year, 4);
        final thisWs = DateTime(now.year, 10);
        if (now.isAfter(thisSs) && now.isBefore(thisWs)) {
          date = thisWs;
        } else if (now.isAfter(thisWs) && now.isAfter(thisSs)) {
          date = DateTime(now.year + 1, 4);
        } else if (now.isBefore(thisWs) && now.isBefore(thisSs)) {
          date = thisSs;
        }
        return date;
      default:
        return null;
264
265
266
267
    }
  }

  Future<Uint8List?> _getPublicKey() async {
Leon Tappe's avatar
Leon Tappe committed
268
269
    final response =
        await _client!.get(Uri.parse('${BlocProvider.of<BackendSwitcher>(context).state}/pubkey'));
270
271
272
273
274
275
276
277
278
279
280
281
282
283

    if (response.statusCode == 200) {
      return response.bodyBytes;
    } else {
      return null;
    }
  }

  Future<void> _initKey() async {
    if (Provider.of<AuthApi>(context, listen: false).user?.credentials == null) return;

    final basePath = (await getApplicationDocumentsDirectory()).path;
    final keyFile = File('$basePath/public_key.pem');

284
285
286
287
288
289
290
291
    if (await keyFile.exists()) {
      await keyFile.delete();
    }
    await keyFile.create(recursive: true);
    try {
      keyFile.writeAsBytes((await _getPublicKey())!);
    } catch (e) {
      await keyFile.delete();
292
293
294
295
296
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text(
            'Der lokale Schlüssel konnte nicht heruntergeladen werden. Bitte überprüfe die Internetverbindung und starte die App neu.'),
        duration: Duration(seconds: 5),
      ));
297
298
299
    }
  }

300
301
302
303
304
305
306
  Future<void> _initSettings() async {
    final settings = await _userApi!.getSettings();

    _testedRuntime = settings['runtime_tested'] as RuntimeSetting;
    _recoveredRuntime = settings['runtime_recovered'] as RuntimeSetting;
    _vaccinatedRuntime = settings['runtime_vaccinated'] as RuntimeSetting;

Leon Tappe's avatar
Leon Tappe committed
307
    _recoveredMinAge = int.tryParse(settings['min_age_recovered']) ?? _recoveredMinAge;
308

309
310
311
312
313
    _motd = settings['motd_internal'] ?? '';

    if (mounted) setState(() => true);
  }

314
  String _makeExpiryString() {
Leon Tappe's avatar
Leon Tappe committed
315
316
317
318
319
    DateTime? expiry;
    try {
      expiry = _calculateExpiryDate(_formData);
    } catch (e) {
      if (e.toString().contains('test')) {
320
        return 'Das angegebene Datum erfüllt nicht die Anforderungen für einen Nachweis';
Leon Tappe's avatar
Leon Tappe committed
321
322
323
324
325
      }
    }

    return expiry != null
        ? '${_dateFormat.format(expiry)} ${_timeFormat.format(expiry)}'
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        : 'Bitte zuerst die Nachweisart wählen';
  }

  Future<String> _onEncrypt() async {
    final basePath = (await getApplicationDocumentsDirectory()).path;

    RSAPublicKey publicKey;
    try {
      publicKey = await parseKeyFromFile<RSAPublicKey>('$basePath/public_key.pem');
    } catch (e) {
      final keyFile = File('$basePath/public_key.pem');
      if (keyFile.existsSync()) {
        await File('$basePath/public_key.pem').delete();
      }
340
341
342
343
344
345
346
347
348
349
350

      try {
        await keyFile.writeAsBytes((await _getPublicKey())!);
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text(
              'Der lokale Schlüssel konnte nicht heruntergeladen werden. Bitte überprüfe die Internetverbindung und starte die App neu.'),
          duration: Duration(seconds: 5),
        ));
      }

351
352
353
354
355
      publicKey = await parseKeyFromFile<RSAPublicKey>('$basePath/public_key.pem');
    }

    final encrypter = Encrypter(RSA(publicKey: publicKey, encoding: RSAEncoding.OAEP));

Leon Tappe's avatar
Leon Tappe committed
356
357
358
359
360
361
362
363
364
    DateTime? expiry;
    try {
      expiry = _calculateExpiryDate(_formData);
    } on Exception catch (e) {
      if (e.toString().contains('test')) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('Das Nachweisdatum vom PCR Test muss mindestens 28 Tage zurück liegen')));
      }
    }
365
366
367
368
369
370
371
372
373
374
375
376
377

    if (expiry != null) {
      final encrypted =
          encrypter.encrypt(_calculateExpiryDate(_formData)!.toUtc().toIso8601String());
      return base64.encode(encrypted.bytes);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Endzeitpunkt konnte nicht errechnet werden')));
      return '';
    }
  }

  Future<void> _onShowCode() async {
378
379
    ScaffoldMessenger.of(context).clearSnackBars();

380
381
    final encrypted = await _onEncrypt();

Leon Tappe's avatar
Leon Tappe committed
382
383
    if (encrypted.isEmpty) return;

384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    final response = await _userApi!.makeSeed(encrypted);

    if (response.seed == null || response.hasError) {
      switch (response.error) {
        case UserErrorType.expired:
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text(
                'Der Nachweis konnte nicht signiert werden. Bitte prüfe die Eingaben auf Korrekt- und Sinnhaftigkeit.'),
            duration: Duration(seconds: 5),
          ));
          break;
        case UserErrorType.encryption:
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text(
                'Der Server konnte den Code nicht entschlüsseln. Bitte melde dich ab und starte die App neu um den lokalen Schlüssel zu aktualisieren.'),
            duration: Duration(seconds: 5),
          ));
          break;
        case UserErrorType.server:
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text(
                'Es ist ein Serverfehler aufgetreten. Bitte versuche es erneut. Wenn der Fehler weiter auftritt bitte an den technischen Support wenden.'),
            duration: Duration(seconds: 5),
          ));
          break;
        default:
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text(
                'Ein unbekannter Fehler ist aufgetreten. Bitte die App neu installieren. Wenn der Fehler weiter auftritt bitte an den technischen Support wenden.'),
            duration: Duration(seconds: 5),
          ));
      }
Leon Tappe's avatar
Leon Tappe committed
416
417
      return;
    }
418

Leon Tappe's avatar
Leon Tappe committed
419
420
    _resetForm();

421
422
423
424
    await showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        insetPadding: const EdgeInsets.all(8.0),
Leon Tappe's avatar
Leon Tappe committed
425
        clipBehavior: Clip.antiAlias,
Leon Tappe's avatar
Leon Tappe committed
426
        child: AspectRatio(
Leon Tappe's avatar
Leon Tappe committed
427
          aspectRatio: 0.8,
Leon Tappe's avatar
Leon Tappe committed
428
429
430
431
432
433
434
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
435
                child: QrImage(data: response.seed!.combinedString),
Leon Tappe's avatar
Leon Tappe committed
436
              ),
Leon Tappe's avatar
Leon Tappe committed
437
438
439
440
441
442
443
444
445
446
447
448
449
              MaterialButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Icon(
                  Icons.close_rounded,
                  size: 48.0,
                  color: Colors.white,
                ),
                minWidth: MediaQuery.of(context).size.width - 16.0,
                padding: const EdgeInsets.all(16.0),
                color: primary,
              ),
            ],
          ),
450
451
452
453
        ),
      ),
    );
  }
Leon Tappe's avatar
Leon Tappe committed
454
455
456
457
458
459
460

  void _resetForm() {
    setState(() {
      _formData = FormData(
        certificationDate: DateTime.now(),
        certificationTime: TimeOfDay.now(),
      );
461
      _expiryText = _makeExpiryString();
Leon Tappe's avatar
Leon Tappe committed
462
463
    });
  }
464
}