platform/lib/middleware/require_auth.dart

33 lines
925 B
Dart
Raw Normal View History

2016-05-03 04:13:19 +00:00
part of angel_auth;
/// Restricts access to a resource via authentication.
Future<bool> requireAuth(RequestContext req, ResponseContext res,
{bool throws: true}) async {
2016-07-06 13:48:28 +00:00
reject() {
if (throws) {
res.status(HttpStatus.UNAUTHORIZED);
throw new AngelHttpException.Forbidden();
} else
return false;
}
2016-05-03 04:13:19 +00:00
if (req.session.containsKey('userId'))
return true;
2016-07-06 13:48:28 +00:00
else if (req.headers.value("Authorization") != null) {
var jwt = req.headers
.value("Authorization")
.replaceAll(new RegExp(r"^Bearer", caseSensitive: false), "")
.trim();
var split = jwt.split(".");
if (split.length != 3) return reject();
Map header = JSON.decode(UTF8.decode(BASE64URL.decode(split[0])));
if (header['typ'] != "JWT" || header['alg'] != "HS256") return reject();
Map payload = JSON.decode(UTF8.decode(BASE64URL.decode(split[1])));
} else
return reject();
}