Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // auth.test.js
- import mocha from 'mocha';
- import sinon from 'sinon';
- import { expect } from 'chai';
- import client from 'socket.io-client';
- import jwt from 'json-web-token';
- import '../index.js';
- afterEach(() => {
- sinon.restore();
- });
- describe.only('Connection', () => {
- it('should connect to the socket server', (done) => {
- const authStub = sinon.stub(jwt, 'decode').callsFake((secret, payload, callback) => {
- console.log('secret', secret);
- console.log('payload', payload);
- console.log('callback', callback);
- return callback(null, {data: 'someuser'});
- });
- const connection = new client(`http://localhost:${process.env.PORT}`);
- expect(authStub.called).to.be.true();
- expect(connection.connected).to.be.true();
- connection.on('message', (data) => {
- expect(typeof data).to.be.equals('string');
- done();
- });
- });
- });
- // lib/auth.js
- import jwt from 'json-web-token';
- const secret = 'some secret key, prefer .pem files';
- const decode = (payload) => jwt.decode(secret, payload, (err, data) => {
- return !err ? data : err;
- });
- const auth = (headers, socket) => {
- let authorization;
- if (headers.authorization !== undefined) {
- authorization = headers.authorization;
- } else {
- authorization = null;
- }
- if (!(decode(authorization) instanceof Error)) {
- socket.emit('message', 'client connected');
- return true;
- } else {
- socket.emit('message', 'client unauthorized');
- return false;
- }
- };
- export default auth;
Add Comment
Please, Sign In to add comment