How to replace the authorize method in ember-simple-auth - ember.js

I'm trying to refactor my Ember acceptance tests to not use the deprecated authorize method, as it is throwing a warning:
The `authorize` method should be overridden in your application adapter
I checked the docs, and numberous other sources, but they don't actually explain how to migrate my code. Here's what I've got at the moment:
// 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);
}
}
});
And this must be the part that I'm meant to get rid of:
// 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);
}
},
});
And here is my test:
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');
});
});
REMOVING the authorize method and attempting either of the commented out methods yields:
Error: Assertion Failed: The `authorize` method should be overridden in your application adapter. It should accept a single argument, the request object.
If I use the authenticator block as an arg, then regardless of the presence of the authorize method, I simply get:
actual: >
/login
expected: >
/my/other/page
Which, I assume, is because it did not login.
Leaving the authorize method there, and trying the commented methods yields:
Error: Browser timeout exceeded: 10s

Per the docs you linked above: To replace authorizers in an application, simply get the session data from the session service and inject it where needed.
Since you need the session data in your Authorization header, a possible solution for your use case may look like this:
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;
})
});
This should allow you to dynamically set the Authorization header, without doing so via the authorize method.

Ember Simple Auth, has an excellent community and quickly created a guide on how to upgrade to v3.
The latest version fixes this problem completely - If anyone is having this problem, upgrading to 2.1.1 should allow you to use the new format in your application.js:
headers: computed('session.data.authenticated.session', function() {
let headers = {};
let sessionToken = this.get('session.data.authenticated.session');
if (sessionToken && !isEmpty(sessionToken)) {
headers['Authorization'] = "Token " + sessionToken;
}
return headers;
}),
This problem was only present in 2.1.0.

Related

SvelteKit Pass Data From Server to Browser

I am trying to pass data from the server to the client to load my app faster and prevent multiple calls to the database.
Via Fetch
SvelteKit is made to do this via the fetch function. This is great if you have an endpoint that allows for custom fetch. But what if you don't?
Firebase is a perfect example of not having a custom fetch function.
Cookies
I would think I could use cookies, but when I set the cookie, it just prints 'undefined' and never gets set.
<script lang="ts" context="module">
import Cookies from 'js-cookie';
import { browser } from '$app/env';
import { getResources } from '../modules/resource';
export async function load() {
if (browser) {
// working code would use JSON.parse
const c = Cookies.get('r');
return {
props: {
resources: c
}
};
} else {
// server
const r = await getResources();
// working code would use JSON.stringify
Cookies.set('resources', r);
// no cookies were set?
console.log(Cookies.get());
return {
props: {
resources: r
}
};
}
}
</script>
So my code loads correctly, then dissapears when the browser load function is loaded...
Surely there is a functioning way to do this?
J
So it seems the official answer by Rich Harris is to use and a rest api endpoint AND fetch.
routes/something.ts
import { getFirebaseDoc } from "../modules/posts";
export async function get() {
return {
body: await getFirebaseDoc()
};
}
routes/content.svelte
export async function load({ fetch }) {
const res = await fetch('/resources');
if (res.ok) {
return {
props: { resources: await res.json() }
};
}
return {
status: res.status,
error: new Error()
};
}
This seems extraneous and problematic as I speak of here, but it also seems like the only way.
J
You need to use a handler that injects the cookie into the server response (because load functions do not expose the request or headers to the browser, they are just used for loading props I believe). Example here: https://github.com/sveltejs/kit/blob/59358960ff2c32d714c47957a2350f459b9ccba8/packages/kit/test/apps/basics/src/hooks.js#L42
https://kit.svelte.dev/docs/hooks#handle
export async function handle({ event, resolve }) {
event.locals.user = await getUserInformation(event.request.headers.get('cookie'));
const response = await resolve(event);
response.headers.set('x-custom-header', 'potato');
response.headers.append('set-cookie', 'name=SvelteKit; path=/; HttpOnly');
return response;
}
FYI: This functionality was only added 11 days ago in #sveltejs/kit#1.0.0-next.267: https://github.com/sveltejs/kit/pull/3631
No need to use fetch!
You can get the data however you like!
<script context="module">
import db from '$/firebaseConfig'
export async function load() {
const eventref = db.ref('cats/whiskers');
const snapshot = await eventref.once('value');
const res = snapshot.val();
return { props: { myData: res.data } } // return data under `props` key will be passed to component
}
</script>
<script>
export let myData //data gets injected into your component
</script>
<pre>{JSON.stringify(myData, null, 4)}</pre>
Here's a quick demo on how to fetch data using axios, same principle applies for firebase: https://stackblitz.com/edit/sveltejs-kit-template-default-bpr1uq?file=src/routes/index.svelte
If you want to only load data on the server you should use an "endpoint" (https://kit.svelte.dev/docs/routing#endpoints)
My solution might solve it especially for those who work with (e.g: laravel_session), actually in your case if you want to retain the cookie data when loading on each endpoint.
What you should gonna do is to create an interface to pass the event on every api() call
interface ApiParams {
method: string;
event: RequestEvent<Record<string, string>>;
resource?: string;
data?: Record<string, unknown>;
}
Now we need to modify the default sveltekit api(), provide the whole event.
// localhost:3000/users
export const get: RequestHandler = async (event) => {
const response = await api({method: 'get', resource: 'users', event});
// ...
});
Inside your api() function, set your event.locals but make sure to update your app.d.ts
// app.d.ts
declare namespace App {
interface Locals {
r: string;
}
//...
}
// api.ts
export async function api(params: ApiParams) {
// ...
params.event.locals.r = response.headers.get('r')
});
Lastly, update your hooks.ts
/** #type {import('#sveltejs/kit').Handle} */
export const handle: Handle = async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
const response = await resolve(event);
if (!cookies.whatevercookie && event.locals.r) {
response.headers.set(
'set-cookie',
cookie.serialize('whatevercookie', event.locals.r, {
path: '/',
httpOnly: true
})
);
}
return response;
});
Refer to my project:
hooks.ts
app.d.ts
_api.ts
index.ts

Apollo client & Absinthe - difficulty parsing errors

I'm working with the #apollo/client and #absinthe/socket-apollo-link NPM packages in my React app, but I'm having some trouble parsing query and mutation errors received by onError in my implementation of the useQuery and useMutation hooks.
For example, here is the way I've set up a query in my component:
useQuery(OperationLib.agendaQuery, {
fetchPolicy: "network-only",
onCompleted: ({ myData }) => {
setData(myData)
setLoading(false)
},
onError: (error) => {
console.log(error)
}
})
When that onError handler is called, the error object that is returned is logged as:
Error: request: [object Object]
at new ApolloError (app.js:36358)
at app.js:146876
at app.js:145790
at new Promise (<anonymous>)
at Object.error (app.js:145790)
at notifySubscription (app.js:145130)
at onNotify (app.js:145169)
at SubscriptionObserver.error (app.js:145230)
at app.js:58209
at Array.forEach (<anonymous>)
I can break this response into its parts "graphQLErrors", "networkError", "message", "extraInfo", but I'm finding it difficult to get any useful info there. In particular, I'd like to be able to get something out of the message - but in this case, error.message is the string,
request: [object Object]
typeof error.message logs string so yeah I can't really do anything with this.
Maybe I could find something useful under one of the other attributes? Nope, graphQLErrors is an empty array, networkError yields the same output as I got when I logged the initial error above, and extraInfo is undefined.
I dug into the source code and found the method createRequestError - when I added a debug log here to see what the message was, I good some good data - I could see the message that I would think would be available somewhere in the error response:
var createRequestError = function createRequestError(message) {
return new Error("request: ".concat(message));
}.bind(undefined);
What could be causing this issue? Is there something I need to configure in my Apollo/Absinthe initialization? I've set those up like so:
apollo-client.js
import { ApolloClient, InMemoryCache } from "#apollo/client"
import absintheSocketLink from "./absinthe-socket-apollo-link"
export default new ApolloClient({
link: absintheSocketLink,
cache: new InMemoryCache()
})
absinthe-socket-apollo-link.js
import * as AbsintheSocket from "#absinthe/socket"
import { createAbsintheSocketLink } from "#absinthe/socket-apollo-link"
import { Socket as PhoenixSocket } from "phoenix"
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const getToken = () => JSON.parse(window.localStorage.getItem("token"))
let token = getToken();
const params = {
get jwt() {
if (!token) {
token = getToken();
}
return token;
},
};
export default createAbsintheSocketLink(
AbsintheSocket.create(
new PhoenixSocket(`${protocol}://${WS_API_URL}/graphql`, {
reconnect: true,
params: params
})
)
);
Thanks much for any insight!

Jest with moxios keeps timing out when I use custom axios instance

I have a service that uses a custom axios instance that I am trying to test but I keep getting an error.
Here is the error:
: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
Here is the test:
import moxios from 'moxios';
import NotificationService, { instance } from '../NotificationService';
beforeEach(() => {
moxios.install(instance);
});
afterEach(() => {
moxios.uninstall(instance);
});
const fetchNotifData = {
data: {
bell: false,
rollups: []
}
};
describe('NotificationService.js', () => {
it('returns the bell property', async done => {
const isResolved = true;
const data = await NotificationService.fetchNotifications(isResolved);
moxios.wait(() => {
let request = moxios.requests.mostRecent();
console.log(request);
request
.respondWith({
status: 200,
response: fetchNotifData
})
.then(() => {
console.log(data);
expect(data).toHaveProperty('data.bell');
done();
});
});
});
});
And here is the code that I'm trying to test:
import axios from 'axios';
// hardcoded user guid
const userId = '8c4';
// axios instance with hardcoded url and auth header
export const instance = axios.create({
baseURL: 'hidden',
headers: {
Authorization:
'JWT ey'
});
/**
* Notification Service
* Call these methods from the Notification Vuex Module
*/
export default class NotificationService {
/**
* #GET Gets a list of Notifications for a User
* #returns {AxiosPromise<any>}
* #param query
*/
static async fetchNotifications(query) {
try {
const res = await instance.get(`/rollups/user/${userId}`, {
query: query
});
console.log('NotificationService.fetchNotifications()', res);
return res;
} catch (error) {
console.error(error);
}
}
}
I've tried shortening the jest timeout and that did not work. I think it is moxios not installing the axios instance properly, but I can't find any reason why it wouldn't.
Any help is appreciated, thanks in advance.
have you tried changing the Jest environment settings by adding this to your test file?
/**
* #jest-environment node
*/
import moxios from 'moxios';
...
Jest tends to prevent the requests from going out unless you add that. Either way, I use nock instead of moxios and I recommend it.

Using fetch inside an action within my component

I'm curious about how I could implement this, I'd like to not hit this API every time the page loads on the route, but would rather start the call on an action (I suppose this action could go anywhere, but it's currently in a component). I'm getting a server response, but having trouble getting this data inside my component/template. Any ideas? Ignore my self.set property if I'm on the wrong track there....Code below..Thanks!
import Component from '#ember/component';
export default Component.extend({
res: null,
actions: {
searchFlight(term) {
let self = this;
let url = `https://test.api.amadeus.com/v1/shopping/flight-offers?origin=PAR&destination=LON&departureDate=2018-09-25&returnDate=2018-09-28&adults=1&travelClass=BUSINESS&nonStop=true&max=2`;
return fetch(url, {
headers: {
'Content-Type': 'application/vnd.amadeus+json',
'Authorization':'Bearer JO5Wxxxxxxxxx'
}
}).then(function(response) {
self.set('res', response.json());
return response.json();
});
}
}
});
Solved below...
import Component from '#ember/component';
export default Component.extend({
flightResults: null,
actions: {
searchFlight(term) {
let self = this;
let url = `https://test.api.amadeus.com/v1/shopping/flight-offers?origin=PAR&destination=LON&departureDate=2018-09-25&returnDate=2018-09-28&adults=1&travelClass=BUSINESS&nonStop=true&max=2`;
return fetch(url, {
headers: {
'Content-Type': 'application/vnd.amadeus+json',
'Authorization':'Bearer xxxxxxxxxxxxxx'
}
}).then(function(response) {
return response.json();
}).then(flightResults => {
this.set('flightResults', flightResults);
});
}
}
});
You might find ember-concurrency to be useful in this situation. See the example of "Type-ahead search", modified for your example:
const DEBOUNCE_MS = 250;
export default Controller.extend({
flightResults: null;
actions: {
searchFlight(term) {
this.set('flightResults', this.searchRepo(term));
}
},
searchRepo: task(function * (term) {
if (isBlank(term)) { return []; }
// Pause here for DEBOUNCE_MS milliseconds. Because this
// task is `restartable`, if the user starts typing again,
// the current search will be canceled at this point and
// start over from the beginning. This is the
// ember-concurrency way of debouncing a task.
yield timeout(DEBOUNCE_MS);
let url = `https://test.api.amadeus.com/v1/shopping/flight-offers?origin=PAR&destination=LON&departureDate=2018-09-25&returnDate=2018-09-28&adults=1&travelClass=BUSINESS&nonStop=true&max=2`;
// We yield an AJAX request and wait for it to complete. If the task
// is restarted before this request completes, the XHR request
// is aborted (open the inspector and see for yourself :)
let json = yield this.get('getJSON').perform(url);
return json;
}).restartable(),
getJSON: task(function * (url) {
let xhr;
try {
xhr = $.getJSON(url);
let result = yield xhr.promise();
return result;
// NOTE: could also write this as
// return yield xhr;
//
// either way, the important thing is to yield before returning
// so that the `finally` block doesn't run until after the
// promise resolves (or the task is canceled).
} finally {
xhr.abort();
}
}),
});

How to resolve Don't use Ember's function prototype extensions

I received an error of Don't use Ember's function prototype extensions ember/no-function-prototype-extensions
and my line of code is this
import JSONAPIAdapter from 'ember-data/adapters/json-api';
import $ from 'jquery';
import config from 'appName/config/environment';
export default JSONAPIAdapter.extend({
shouldReloadAll: function() {
return false;
},
shouldBackgroundReloadRecord: function() {
return true;
},
namespace: 'api/v1',
host: window.location.origin,
coalesceFindRequests: true,
headers: function() {
// Reference https://github.com/DavyJonesLocker/ember-appkit-rails/issues/220
// Only set the X-CSRF-TOKEN in staging or production, since API will only look for a CSRF token on those environments
let csrfToken;
if (config.environment === 'staging' || config.environment === 'production') {
csrfToken = $('meta[name="csrf-token"]').attr('content');
}
let authorizationToken = 'Token ' + this.currentSession.get('token');
return {
'X-CSRF-TOKEN': csrfToken,
'Authorization': authorizationToken
};
}.property().volatile(),
handleResponse(status, headers, payload, requestData) {
if (this.isInvalid(status, headers, payload)) {
if (payload && typeof payload === 'object' && payload.errors &&
typeof payload.errors === 'object') {
return payload.errors = [payload.errors];
}
}
return this._super(status, headers, payload, requestData);
}
});
this was the line of code that my terminal is referring to .property().volatile(), I have looked on the google but I couldn’t find a similar examples to my work. Btw, I have updated my ember version from 1.13.13 to 3.1.0 and that is the reason why I received the error.
Please help me
Ember's .property() is deprecated.
Instead of:
headers: function() {
// ...
}.property().volatile(),
...do:
headers: computed(function () {
// ...
}).volatile(),
Also add the computed import at the top:
import { computed } from '#ember/object';
When you see these eslint errors, do a google search for the name of the rule, in this case ember/no-function-prototype-extensions. You'll find the description of the error and how to fix:
https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/no-function-prototype-extensions.md