作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个中间件 Controller ,该 Controller 负责身份验证。 Controller 将链接在资源 Controller 的前面。我认为这是正确的方法?
在handle方法中,我正在执行数据库查询,该查询需要连接信息。但是,当我尝试通过构造函数传递数据时,它告诉我不允许使用setter。
将带有连接信息的Map从channel.dart传递到中间件 Controller 的最佳方法是什么(请参阅dbConnectionDetails)?
channel.dart
@override
Future prepare() async {
logger.onRecord.listen((rec) => print("$rec ${rec.error ?? ""} ${rec.stackTrace ?? ""}"));
dbConnectionDetails = ConnectionSettings (
user: "mydbuser",
password: "mydbpass",
host: "localhost",
port: 3306
);
}
@override
Controller get entryPoint {
final router = Router();
router
.route("/api/user/query/complex")
.link(() => AuthMiddleware())
.link(() => UserComplexQueryController(dbConnectionDetails));
}
ArgumentError (Invalid argument(s): Invalid controller 'AuthMiddleware'. Controllers must not have setters and all fields must be marked as final, or it must implement 'Recyclable'.)
class AuthMiddleware extends Controller {
// This does not work, as setters not allowed
//AuthMiddleware(this.dbConnectionDetails);
//
//ConnectionSettings dbConnectionDetails
@override
Future<RequestOrResponse> handle(Request request) async {
if (await isValid(request)) {
return request;
}
return Response.unauthorized();
}
Future<bool> isValid(Request request) async {
final String token = request.raw.requestedUri.queryParameters["token"];
final int timestamp = (DateTime.now().toUtc().millisecondsSinceEpoch / 1000).round();
ConnectionSettings dbConnectionDetails = ConnectionSettings (
user: "myuser",
password: "mypass",
host: "localhost",
port: 3306
);
AuthTokenDao authTokenDao = new AuthTokenDao(dbConnectionDetails);
if(await authTokenDao.validateToken(token, timestamp)) {
return true;
}
return false;
}
}
最佳答案
由CA编辑:解决方案(由Joe Conway提供):
class AuthMiddleware extends Controller {
// Works by adding "final"
final ConnectionSettings dbConnectionDetails;
// Now dbConnectionDetails can be passed within the constructor.
AuthMiddleware(this.dbConnectionDetails);
@override
Future<RequestOrResponse> handle(Request request) async {
if (await isValid(request)) {
return request;
}
return Response.unauthorized();
}
Future<bool> isValid(Request request) async {
final String token = request.raw.requestedUri.queryParameters["token"];
final int timestamp = (DateTime.now().toUtc().millisecondsSinceEpoch / 1000).round();
/* Removed this
ConnectionSettings dbConnectionDetails = ConnectionSettings (
user: "myuser",
password: "mypass",
host: "localhost",
port: 3306
);
*/
AuthTokenDao authTokenDao = new AuthTokenDao(dbConnectionDetails);
if(await authTokenDao.validateToken(token, timestamp)) {
return true;
}
return false;
}
}
关于dart - 如何将数据从channel.dart传递到中间件句柄方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062590/
我是一名优秀的程序员,十分优秀!