How to resolve Don't use Ember's function prototype extensions - ember.js

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

Related

could not find module 'ember-resources'

am trying to build an web app with ember and in the process of making a request to server and receiving a response and for that i used resources from ember-resource
yet it always popping the error module not found ember-resources
the js code
import { use, resource } from 'ember-resources';
import { tracked } from '#glimmer/tracking';
class RequestState {
#tracked value;
#tracked error;
get isPending() {
return !this.error && !this.value;
}
}
export default class RoomselectController extends Controller {
#service router;
#use request = resource(({ on }) => {
const mobile = '123123123';
const state = new RequestState();
$.ajax({
url: 'My',
method: 'GET',
dataType: 'json',
data: { mobile },
success: (response) => state.value = response;,
error: (xhr, status, error) => state.error = `${status}: ${xhr.statusText}`,
});
return state;
});
get result() {
return this.request.value || [];
}
}
i installed ember-resource using
ember install ember-resources
also done npm install ember-resources
still showing the same module not found errro what to do?

Set Session ID Cookie in Nuxt Auth

I have the following set up in my nuxt.config.js file:
auth: {
redirect: {
login: '/accounts/login',
logout: '/',
callback: '/accounts/login',
home: '/'
},
strategies: {
local: {
endpoints: {
login: { url: 'http://localhost:8000/api/login2/', method: 'post' },
user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },
tokenRequired: false,
tokenType: false
}
}
},
localStorage: false,
cookie: true
},
I am using django sessions for my authentication backend, which means that upon a successful login, i will have received a session-id in my response cookie. When i authenticate with nuxt however, i see the cookie in the response, but the cookie is not saved to be used in further requests. Any idea what else i need to be doing?
This is how I handled this, which came from a forum post that I cannot find since. First get rid of nuxt/auth and roll your own with vuex store. You will want two middleware, one to apply to pages you want auth on, and another for the opposite.
This assumes you have a profile route and a login route that returns a user json on successful login.
I'm also writing the user to a cookie called authUser, but that was just for debugging and can be removed if you don't need it.
store/index
import state from "./state";
import * as actions from "./actions";
import * as mutations from "./mutations";
import * as getters from "./getters";
export default {
state,
getters,
mutations,
actions,
modules: {},
};
store/state
export default () => ({
user: null,
isAuthenticated: false,
});
store/actions
export async function nuxtServerInit({ commit }, { _req, res }) {
await this.$axios
.$get("/api/users/profile")
.then((response) => {
commit("setUser", response);
commit("setAuthenticated", true);
})
.catch((error) => {
commit("setErrors", [error]); // not covered in this demo
commit("setUser", null);
commit("setAuthenticated", false);
res.setHeader("Set-Cookie", [
`session=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
`authUser=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
]);
});
}
store/mutations
export const setUser = (state, payload) => (state.user = payload);
export const setAuthenticated = (state, payload) =>
(state.isAuthenticated = payload);
store/getters
export const getUser = (state) => state.user;
export const isAuthenticated = (state) => state.isAuthenticated;
middleware/redirectIfNoUser
export default function ({ app, redirect, _route, _req }) {
if (!app.store.state.user || !app.store.state.isAuthenticated) {
return redirect("/auth/login");
}
}
middleware/redirectIfUser
export default function ({ app, redirect, _req }) {
if (app.store.state.user) {
if (app.store.state.user.roles.includes("customer")) {
return redirect({
name: "panel",
params: { username: app.store.state.user.username },
});
} else if (app.store.state.user.roles.includes("admin")) {
return redirect("/admin/dashboard");
} else {
return redirect({
name: "panel",
});
}
} else {
return redirect("/");
}
}
pages/login- login method
async userLogin() {
if (this.form.username !== "" && this.form.password !== "") {
await this.$axios
.post("/api/auth/login", this.form)
.then((response) => {
this.$store.commit("setUser", response.data);
this.$store.commit("setAuthenticated", true);
this.$cookies.set("authUser", JSON.stringify(response.data), {
maxAge: 60 * 60 * 24 * 7,
});
if (this.$route.query.redirect) {
this.$router.push(this.$route.query.redirect);
}
this.$router.push("/panel");
})
.catch((e) => {
this.$toast
.error("Error logging in", { icon: "error" })
.goAway(800);
The cookie is sent by the server but the client won't read it, until you set the property withCredentials in your client request (about withCredentials read here)
To fix your problem you have to extend your auth config with withCredentials property.
endpoints: {
login: {
url: 'http://localhost:8000/api/login2/',
method: 'post'
withCredentials: true
}
}
Also don't forget to set CORS policies on your server as well to support cookie exchange
Example from ExpressJS
app.use(cors({ credentials: true, origin: "http://localhost:8000" }))
More information about this issue on auth-module github

How to get a file from the backend withou getting it JSON-parsed

I’m able to get an xlsx file from my rails backend with a GET-Request to “/companies/export_xslx”, now I’m facing the problem of getting the file passed the JSON parser. For every request the console shows “JSON.parse: unexpected character at line 1 column 1 of the JSON data”.
This is my setup:
//company model ...
exportXlsx: function() {
const adapter = this.store.adapterFor('company');
return adapter.exportXlsx();
}
//adapters/company.js
import DS from 'ember-data';
import TokenAuthorizerMixin from 'ember-simple-auth-token/mixins/token-authorizer';
export default DS.JSONAPIAdapter.extend(TokenAuthorizerMixin, {
exportXlsx() {
const url = 'companies/export_xlsx';
return this.ajax(url, 'GET',
{ dataType: 'text',
accepts: { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
} });
}
});
I’ll try to alter the default accept header but the requests gets sent with “Accept: application/vnd.api+json”.
I already tried different approaches with “ember-custom-actions” or “ember-cli-file-saver”, they all failed with the JSON.parse… response.
I've found a solution. I tackle the problem in the component with a download service:
// components/companies-download.js
import Component from '#ember/component';
import { computed } from '#ember/object';
import { inject as service } from '#ember/service';
export default Component.extend({
download: service(),
actions: {
downloadXlsx() {
let url = `/companies/export_xlsx`;
this.get('download').file(url);
}
}
});
// services/download.js
import Service from "#ember/service";
import { inject as service } from '#ember/service';
export default Service.extend({
session: service(),
file(url) {
let xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = () => {
let [, fileName] = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(
xhr.getResponseHeader("Content-Disposition")
);
let file = new File([xhr.response], decodeURIComponent(fileName));
let link = document.createElement('a');
link.style.display = 'none';
link.href = URL.createObjectURL(file);
link.download = file.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
xhr.open('GET', url);
xhr.setRequestHeader(
'Authorization',
'Bearer ' + this.get('session.data.authenticated.token')
);
xhr.send();
}
});

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

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.

Ember simple auth 1.0.1 custom authenticator

I am updating my existing code done in ember-simple-auth: 0.8.0 to ember-simple-auth: 1.0.1
There are two problems
It is not persisting a session
REST Calls needed to be having withCredentials: true, not sure where I can set them.
Here is my code
//config/environment.js
ENV['ember-simple-auth'] = {
store: 'simple-auth-session-store:local-storage',
authorizer: 'authorizer:custom',
routeAfterAuthentication: '/dashboard',
routeIfAlreadyAuthenticated: '/dashboard'
};
My authenticator
//authenticators/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';
export default Base.extend({
restore(data) {
return new Ember.RSVP.Promise(function (resolve, reject) {
if (!Ember.isEmpty(data.token)) {
resolve(data);
}
else {
reject();
}
});
},
authenticate(options) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: "POST",
url: config.serverURL + '/api/users/login',
data: JSON.stringify({
username: options.identification,
password: options.password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
invalidate(data) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: "POST",
url: config.serverURL + '/api/users/logout'
}).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
}
});
My authorizer (you can see that I am trying to update my old code)
//authorizers/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
export default Base.extend({
authorize(sessionData, block) {
if (!Ember.isEmpty(sessionData.token)) {
block('X-CSRF-Token', sessionData.token);
block('Content-Type', 'application/json;charset=utf-8');
block('withCredentials', true);
}
}
//authorize(jqXHR, requestOptions) {
// if (!(requestOptions.data instanceof FormData)){
// requestOptions.contentType = 'application/json;charset=utf-8';
// }
//
// requestOptions.crossDomain = true;
// requestOptions.xhrFields = {
// withCredentials: true
// };
//
//
// var token = this.get('session.token');
// console.error(jqXHR);
// if (this.get('session.isAuthenticated') ) {
// jqXHR.setRequestHeader('X-CSRF-Token', token);
// }
//}
});
My application adapter
import DS from 'ember-data';
import config from '../../config/environment';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.RESTAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:custom',
namespace: 'api',
host: config.serverURL,
});
Dashboard
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
session: Ember.inject.service('session'),
needs: 'application',
setupController: function(controller, model){
this.controllerFor('application').set('pageTitle', 'Dashboard');
this._super(controller, model);
}
});
If I do console.log(this.get('session.isAuthenticated'); it returns me true, but when I use that in template it dont work
{{#if session.isAuthenticated}}
1
{{else}}
0
{{/if}}
On my laravel end, i can see that session is created and user is logged in, on Ember side, it was previously setting the session and then resends the credentials with each request. Now when it send another request. I think it is without credentials: True and laravel returns 401. I also tried sending a garbage header and laravel CORS refused that it is not in allowed headers.
Thank you
The authorizer config setting doesn't exist anymore in 1.0 as auto-authorization has been dropped. See the API docs for info on how to add authorization to outgoing requests:
http://ember-simple-auth.com/api/classes/SessionService.html#method_authorize
http://ember-simple-auth.com/api/classes/DataAdapterMixin.html
Also your authorizer should not call the block several times but only ones, passing all authorization data at once.
Also make sure you inject the session service into all controllers and components for templates you use the session in.