Skip to content

Instantly share code, notes, and snippets.

@rithvikvibhu
Created January 15, 2017 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rithvikvibhu/2cd8e79dcfbd9dc72836560f20c13d13 to your computer and use it in GitHub Desktop.
Save rithvikvibhu/2cd8e79dcfbd9dc72836560f20c13d13 to your computer and use it in GitHub Desktop.
Feathers socket auth
import React, { Component, AsyncStorage } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Router, Scene } from 'react-native-router-flux';
import hooks from 'feathers-hooks';
import feathers from 'feathers/client';
import socketio from 'feathers-socketio/client';
import localstorage from 'feathers-localstorage';
import authentication from 'feathers-authentication-client';
if (window.navigator && Object.keys(window.navigator).length == 0) {
window = Object.assign(window, {navigator: {userAgent: 'ReactNative'}});
}
var io = require('socket.io-client');
class HomeChef extends Component {
constructor(props) {
super(props);
const options = {transports: ['websocket'], forceNew: true};
this.socket = io('http://192.168.2.30:3030', options);
this.state = {connected: false};
this.app = feathers()
.configure(socketio(this.socket))
.configure(hooks())
.configure(authentication({ storage: AsyncStorage }));
this.doAuthentication = function () {
this.app.authenticate()
.then( (result) => {
console.log('result:', result);
return this.app.passport.verifyJWT(result.accessToken);
}).then( (payload) => {
console.log('payload:', payload);
return this.app.service('users').get(payload.userId); // My jwtoken contains the user's id
}).then ( (user) => {
this.app.set('user', user);
renderApp(user); // Start up the application proper
}).catch(function(error){
console.log("jwt Auth failed", error);
// renderLogin(); // Show the login form
});
}
}
componentDidMount() {
this.doAuthentication();
this.app.authenticate({
strategy: 'local',
email: 'a@a.aa',
password: 'a'
}).then( (response) => {
// Local authentication (username/password) succeeded.
// We now have a JWToken, which has been stashed in
// localstorage
console.log('response from local auth:', response);
this.doAuthentication(); // The function from the previous post
}).catch( (error) => {
console.error('Error authenticating local auth!', error);
// re-render form
});
this.socket.on('connect', () => {
console.log('connect');
});
this.socket.on('connection_failed', () => {
console.log('connection_failed');
});
this.socket.on('test', (data) => {
console.log('Received data:', data);
});
}
render() {
return (
<Router>
// ... snip ...
</Router>
);
}
}
export default HomeChef;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment