Get token to use with websocket
Closed this issue · 2 comments
brunowego commented
I miss something, I have only access to the token after login, if I refresh the page, I lost the access. The best practice is store this in a cookie? Thanks.
import Ember from 'ember';
import Route from 'ember-route';
import service from 'ember-service/inject';
import on from 'ember-evented/on';
import config from 'apollo-enterprise/config/environment';
export default Route.extend({
store: service(),
currentUser: service(),
session: service(),
cable: service(),
setupConsumer: on('init', function() {
let token = this.get('session.data.authenticated.jwt');
let consumer = this.get('cable')
.createConsumer(`wss://api.${config.APP.host}/cable?token=${token}`);
let channelMixin = Ember.Mixin.create({
received(data) {
this.get('store').pushPayload(data);
}
});
consumer.subscriptions.create({
channel: 'ChatroomsChannel'
}, channelMixin);
}),
model(params) {
return this.get('store').findRecord('chatroom', params.chatroom_id);
},
setupController(controller) {
this._super(...arguments);
controller.set('message', {});
},
actions: {
sendMessage(params) {
let chatroom = this.controller.get('model');
let message = this.get('store').createRecord('message', params);
message.set('chatroom', chatroom);
message.save().then(() => {
this.controller.set('message', {});
});
}
}
});
alechirsch commented
I think this is more of a question for ember-simple-auth, since that package handles the storage.
You are likely by default using the Base storage?
There are other Storage types, one of which is cookie storage.
brunowego commented
Thanks @alechirsch, yes, sorry for that.
I find this solution:
this.get('session.store').restore().then((data) => {
let token = data.authenticated.jwt;
let consumer = this.get('cable')
.createConsumer(`wss://api.${config.APP.host}/cable?token=${token}`);
let channelMixin = Mixin.create({
received(data) {
this.get('store').pushPayload(data);
}
});
consumer.subscriptions.create({
channel: 'ChatroomsChannel'
}, channelMixin);
});