I am using ember-django-adapter with ember-simple-auth and have written the custom authorizer for token authentication. I am able to obtain the token from server but not able to inject it into the api requests using the adapter.
app/authorizers/application.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
const { service } = Ember.inject;
export default Base.extend({
session: service('session'),
init: function () {
console.log('Intialize authorizer');
},
authorize(data, block) {
const accessToken = data['access_token'];
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
block('Authorization', `Token ${accessToken}`);
console.log("authorizer called with token: " + accessToken);
}
}
});
app/adapters/application.js
import Ember from 'ember';
import DRFAdapter from 'ember-django-adapter/adapter/drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
const { service } = Ember.inject;
export default DRFAdapter.extend(DataAdapterMixin, {
session: service('session'),
authorizer: 'authorizer:application'
});
app/authenticators/token.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
serverTokenEndpoint: 'http://localhost:8000/ember-auth/',
authenticate: function(email, password) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.serverTokenEndpoint,
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
console.log('Got token: ' + response.token);
Ember.run(function() {
resolve({
token: response.token
});
});
}, function(xhr) {
var response = xhr.responseText;
Ember.run(function() {
reject(response);
});
});
});
},
invalidate: function() {
console.log('invalidate...');
return Ember.RSVP.resolve();
}
});
Ember tries to transition to protected route but due to non injection of Authorization header the request fails with 403 error.
Any help is appreciated.
Related
Im new at Vue and im trying to make a Request HTTP to my backend,
When i inspect in my browser, i get the access token from /login but in the api/users i get "Token is Invalid". How do i get my api/users data?
import axios from "axios";
export default {
name: "login",
async created() {
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
data() {
return {
showError: false,
email: "",
password: "",
};
},
methods: {
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
console.log(response);
this.$router.push("intermediorotas");
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 3000);
}
},
},
You can create a service to make call to backend, i guess the problem is the url http://localhots:3000/api, you missed this part http://localhots:3000
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhots:3000/api',
headers: {
'Content-Type': 'application/json',
},
})
export default client
then import the service
import myService from './myService'
await myService.get(`/auth/login`, {})
Im new to VueJS and trying to build authorization functions for my website.
First I attempt to use library name Vue-auth to handle authorization. It works fine, here is my code:
Login.vue
login () {
var redirect = this.$auth.redirect()
this.$auth.login({
headers: {
'Content-Type': 'application/json'
},
data: this.data.body,
rememberMe: this.data.rememberMe,
redirect: {name: redirect ? redirect.from.name : 'Home'},
success (res) {
console.log('Auth Success')
},
error (err) {
console.log(err)
}
navbar ():
<div class="nav-right is-flex">
<router-link v-if="!$auth.check()" to="/login" class="nav-item">Login</router-link>
<a v-if="$auth.check()" #click="logout" class="nav-item">Logout</a>
</div>
In router, to restrict access, I use auth property. Something like:
{
path: '/users',
name: 'users',
component: require('./components/pages/Users.vue'),
meta: {auth: ['admin']}
},
{
path: '/users',
name: 'users',
component: require('./components/pages/Users.vue'),
meta: true
}
And in app.js:
Vue.use(VueAuth, {
auth: {
request: function (req, token) {
this.options.http._setHeaders.call(this, req, {Authorization: 'Bearer ' + token})
},
response: function (res) {
// Get Token from response body
return res.data
}
},
http: require('#websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x.js'),
loginData: { url: 'http://localhost:6789/login', fetchUser: false },
refreshData: { enabled: false }
})
But now I want to write a service to call axios to API Url myself, not using $auth.login function anymore. I changed my
login () {
var self = this;
_AuthenticationService
.login(this.data.body)
.then(response => {
self.info = response;
console.log(response);
})
.catch(err => {
self.info = err;
});
My service:
import axiosconfigurator from '../axiosconfigurator'
class AuthenticationService {
login (request) {
var self = this
return new Promise((resolve, reject) => {
axios.post('https://reqres.in/api/login', {
username: 'Fred',
password: '123'
})
.then(function (response) {
// get token from this response
var token = response.data.token
self._setAuthToken(token, true)
console.log(token)
// var data = core.Parsers.UserParser.parse(response);
// history.update(data);
// deferred.resolve(history);
})
.catch(function (error) {
console.log(error)
reject(error)
});
})
}
So my question is: I dont want to use the vue-auth library login function anymore, but I still want use its advantages like $auth.ready function, or auth property in router and $auth.user. How can I achieve it?
Based on the date of your question and the fact that the library was changed lately
You can call the login method on the vue-auth object passing the following option
makeRequest:false
You have a solution described there
https://github.com/websanova/vue-auth/issues/256
this.$auth.watch.authenticated = true
this.$auth.watch.loaded = true
this.$user(response.user)
this.$router.push('/dashboard')
I tested it and it was not working so I open a ticket
https://github.com/websanova/vue-auth/issues/563
I'm trying to add an subscriber to my Mailchimp list when the following meteor method runs.
I'm getting an error: Parameter "url" must be a string, not object.
import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";
import { Logger } from "/server/api";
import request from "request";
import fetch from "isomorphic-fetch";
const methods = {
"myproject/addToMailchimp": (email) => {
check(email, String);
Logger.info(`contact person at ${email}`);
const request2 = request("https://us16.api.mailchimp.com/3.0/lists/<LISTID>/members", {
method: "POST",
headers: {
"content-type": "application/json"
},
mode: "no-cors",
json: {
email_address: email,
status: "subscribed"
},
redirect: "follow",
auth: {
user: "<USERNAME>",
pass: "<APIKEY>"
}
});
fetch(request2).then((data) => {
console.log(data);
});
}
};
Meteor.methods(methods);
I would really appreciate any help on this. I've never used fetch or request before, so I reckon I'm not using these correctly.
Thanks!
Will
I am trying set a value into userSessionStorage, when i am accessing it from the authenticate() function it seems to work correctly.
However, it is not working in the .then() promise.
app/controllers/show.js
import Ember from 'ember';
import { storageFor } from 'ember-local-storage';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
userSessionStorage: storageFor('user'),
authenticator: 'authenticator:custom',
actions: {
authenticate: function() {
var credentials = this.getProperties('identification', 'password');
// ok
this.set('userSessionStorage.username', credentials.identification);
this.get('session').authenticate('authenticator:custom', credentials)
.then(function(){
// error: TypeError: Cannot read property 'set' of undefined
this.set('userSessionStorage.username', credentials.identification);
})
.catch((message) => {
console.log("message: " + message);
this.controller.set('loginFailed', true);
});
}
}
});
all you need to do is changing the following line:
this.get('session').authenticate('authenticator:custom', credentials)
.then(function(){....}
to using fat arrow notation as follows:
this.get('session').authenticate('authenticator:custom', credentials)
.then(()=>{....}
so that this context within the promise context will be your controller. See following for more about ES6 arrow functions.
It's based on my own code, so you might need to adapt it. But in your authenticator, your authenticate function may look like this :
# authenticator
authenticate(credentials) {
const { identification, password } = credentials;
const data = JSON.stringify({
auth: {
email: identification,
password
}
});
const requestOptions = {
url: this.tokenEndpoint,
type: 'POST',
data,
contentType: 'application/json',
dataType: 'json'
};
return new Promise((resolve, reject) => {
ajax(requestOptions).then((response) => {
// Set your session here
}, (error) => {
run(() => {
reject(error);
});
});
});
},
I am new to ember .I designed an ember app and integrate the fb login in it and have to send facebook accesstoken to app backend (post request) and fetch the token generated by backend(rails).
My Post request response is:
{
"token":"71fcb8c39dc6449e2ac8e88d21e4d008cf746e16a774aa8755f6be0dbc43849265f9010111986a912fde60de4f76eb5a600ec286b26ea0a865cc7f5cab49330a",
"user":{"role":"unverified"}
}
and the component is
import Ember from 'ember';
export default Ember.Component.extend({
fb: Ember.inject.service(),
session: Ember.inject.service(),
authenticate: function(accessToken) {
console.log("accesstoken: "+accessToken);
Ember.$.ajax({
url: "http://localhost:3000/v1/sessions/fb_login",
accepts: 'application/json',
data: { token: accessToken},
crossDomain: true,
headers: {
'Client-Key': '403cb982d0c48473bee32b41b6765e15a26c595c689c620cece5fc15370c33c9c9f6d071f84bf6b88baf466f653f44b4524634bde6fbe68f065f06268f7ed7e2',
},
type: 'post',
success:function(data){
console.log('data is '+data);
}
});
},
actions: {
fb_login() {
this.get('fb').login().then((response) => {
if (response.status === 'connected') {
let fbToken = response.authResponse.accessToken;
this.authenticate(fbToken);
} else if( response.status === 'not_authorized') {
// code for not authrized
// this.transitionTo('/');
} else {
// code for facebook login
// this.transitionTo('/');
}
}).catch(() => {
// this.sendAction('check','/');
});
},
}
});
But after ajax call success is never get called to I am unable to get the the response and browser always responds with:
pretender.js:132 XHR finished loading: POST "http://localhost:3000/v1/sessions/fb_login".
Somebody please explain me how the ajax work in ember for api calls.