2016-12-12 04:32:26 +00:00
|
|
|
import 'package:angel_framework/angel_framework.dart';
|
2016-12-13 01:05:20 +00:00
|
|
|
import 'package:ua_parser/ua_parser.dart' as ua;
|
2016-12-12 04:32:26 +00:00
|
|
|
|
2016-12-13 01:05:20 +00:00
|
|
|
/// Injects a [ua.Client] and [ua.UserAgent] into requests.
|
2016-12-12 04:32:26 +00:00
|
|
|
///
|
|
|
|
/// If [strict] is `true`, then an invalid
|
|
|
|
/// `User-Agent` header will throw a `400 Bad Request`.
|
|
|
|
RequestMiddleware parseUserAgent({bool strict: true}) {
|
|
|
|
return (req, res) async {
|
|
|
|
try {
|
2016-12-13 01:05:20 +00:00
|
|
|
final client = ua.parse(req.headers.value('User-Agent'));
|
|
|
|
req
|
|
|
|
..inject(ua.Client, client)
|
|
|
|
..inject(ua.UserAgent, client.userAgent);
|
2016-12-12 04:32:26 +00:00
|
|
|
} catch (e) {
|
2016-12-13 01:05:20 +00:00
|
|
|
throw strict ?
|
|
|
|
new AngelHttpException.BadRequest(message: 'Invalid user agent.') : e;
|
2016-12-12 04:32:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
}
|