ember.js - 如何在 ember-simple-auth 中替换授权方法
问题描述
我正在尝试重构我的 Ember 验收测试以不使用已弃用 authorize
的方法,因为它会引发警告:
The `authorize` method should be overridden in your application adapter
我检查了docs和许多其他来源,但它们实际上并没有解释如何迁移我的代码。这是我目前所拥有的:
// projectname/app/pods/login/controller.js (excerpt)
export default Controller.extend({
session: service(),
sessionToken: null,
onSuccess: function(res) {
res = res.response;
this.set('sessionToken', res.session);
if (res.state === "authenticated") {
document.cookie = "token="+res.session+";path=/;";
var authOptions = {
success: true,
data : {
session : res.session,
}
};
this.get('session').authenticate("authenticator:company", authOptions);
}
}
});
这一定是我要摆脱的部分:
// project/app/adapters/application.js (excerpt)
export default DS.RESTAdapter.extend(DataAdapterMixin, {
authorize(xhr) { // This is deprecated! I should remove it
let sessionToken = this.get('session.data.authenticated.session');
if (sessionToken && !isEmpty(sessionToken)) {
xhr.setRequestHeader('Authorization', "Token " + sessionToken);
}
},
});
这是我的测试:
import { test, module } from 'qunit';
import { visit, currentURL, find, click, fillIn } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { authenticateSession} from 'ember-simple-auth/test-support';
module('moduleName', function(hooks) {
setupApplicationTest(hooks);
test('moduleName', async function(assert) {
// await authenticateSession(this.application); // Never works
// await authenticateSession(); // Never works
await authenticateSession({
authenticator: "authenticator:company"
}); // Works slightly more?
await visit('/my/other/page');
await assert.equal(currentURL(), '/my/other/page');
});
});
删除该authorize
方法并尝试任一注释掉的方法会产生:
Error: Assertion Failed: The `authorize` method should be overridden in your application adapter. It should accept a single argument, the request object.
如果我将authenticator
块用作 arg,那么无论该authorize
方法是否存在,我都会得到:
actual: >
/login
expected: >
/my/other/page
我认为,这是因为它没有登录。
将authorize
方法留在那里,并尝试注释的方法会产生:
Error: Browser timeout exceeded: 10s
解决方案
根据您在上面链接的文档:要替换应用程序中的授权者,只需从会话服务中获取会话数据并将其注入到需要的地方。
由于您需要Authorization
标题中的会话数据,因此您的用例的可能解决方案可能如下所示:
export default DS.RESTAdapter.extend(DataAdapterMixin, {
headers: computed('session.data.authenticated.session', function() {
const headers = {};
let sessionToken = this.get('session.data.authenticated.session');
if (sessionToken && !isEmpty(sessionToken)) {
headers['Authorization'] = "Token " + sessionToken;
}
return headers;
})
});
这应该允许您动态设置Authorization
标题,而无需通过该authorize
方法进行。
推荐阅读
- python - 熊猫中的简单数据透视图
- java - 如何在springboot jar的相同相对位置包含其他属性文件
- python - 我希望能够从 python 中找到 excel 中的值并在下一列中打印该值
- abap - 使用 CDS 视图和 BOPF 更新多个表中的 BO
- xcode - Xcode - 未启用强化运行时
- android - 无法解决:livedata-core
- javascript - xdescribe,xit 分别表示'未知标识符'xdescribe'/'xit'
- node.js - 如何使提交的表单在出现在索引页面之前经过批准
- java - 为 RecyclerView 和 GridLayoutManager 设置 onclick 时如何添加 Toast 位置?
- javascript - 试图了解用于 react 的 formik 包是如何构建的