0
Fork 0
mirror of https://github.com/verdaccio/verdaccio.git synced 2024-12-16 21:56:25 -05:00

fix: unit test and better error handling

This commit is contained in:
Juan Picado @jotadeveloper 2018-03-21 21:44:19 +01:00
parent f338ee4101
commit 2022a30419
No known key found for this signature in database
GPG key ID: 18AC54485952D158
9 changed files with 65 additions and 49 deletions

View file

@ -296,11 +296,12 @@ class Auth {
/**
* JWT middleware for WebUI
* @return {Function}
*/
jwtMiddleware() {
return (req: $RequestExtend, res: $Response, _next: NextFunction) => {
if (req.remote_user !== null && req.remote_user.name !== undefined) return _next();
if (req.remote_user !== null && req.remote_user.name !== undefined) {
return _next();
}
req.pause();
const next = function(_err) {
@ -308,18 +309,22 @@ class Auth {
return _next();
};
req.remote_user = buildAnonymousUser();
let token = (req.headers.authorization || '').replace('Bearer ', '');
if (!token) return next();
const token = (req.headers.authorization || '').replace('Bearer ', '');
if (!token) {
return next();
}
let decoded;
try {
decoded = this.decode_token(token);
} catch (err) {/**/}
} catch (err) {
// FIXME: intended behaviour, do we want it?
}
if (decoded) {
req.remote_user = authenticatedUser(decoded.user, decoded.group);
} else {
req.remote_user = buildAnonymousUser();
}
next();

View file

@ -1,7 +1,6 @@
import React from 'react';
import {Button, Dialog, Input, Alert} from 'element-react';
import isString from 'lodash/isString';
import get from 'lodash/get';
import isNumber from 'lodash/isNumber';
import {Link} from 'react-router-dom';
@ -72,7 +71,9 @@ export default class Header extends React.Component {
Accept: 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => response.json());
}).then(function(response) {
return response.json();
});
storage.setItem('token', resp.token);
storage.setItem('username', resp.username);
@ -82,11 +83,7 @@ export default class Header extends React.Component {
title: 'Unable to login',
type: 'error'
};
if (get(e, 'response.status', 0) === 401) {
errorObj.description = e.response.error;
} else {
errorObj.description = e.message;
}
errorObj.description = e.message;
this.setState({loginError: errorObj});
}
}

View file

@ -32,7 +32,9 @@ export default class PackageSidebar extends React.Component {
let packageMeta;
try {
packageMeta = await API.request(`sidebar/${packageName}`, 'GET').then((response) => response.json());
packageMeta = await API.request(`sidebar/${packageName}`, 'GET').then(function(response) {
return response.json();
});
} catch (err) {
this.setState({
failed: true

View file

@ -17,10 +17,17 @@ class API {
url = window.VERDACCIO_API_URL + url;
}
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
return fetch(url, {
method,
...options
});
}).then(handleErrors);
}
}

View file

@ -8,7 +8,7 @@ import PackageSidebar from '../../../../src/webui/src/components/PackageSidebar'
import { packageMeta } from '../store/packageMeta';
jest.mock('../../../../src/webui/utils/api', () => ({
get: require('../__mocks__/api').default.get
request: require('../__mocks__/api').default.request,
}));
console.error = jest.fn();
@ -18,7 +18,7 @@ describe('<PackageSidebar /> component', () => {
const wrapper = mount(<PackageSidebar />);
const { loadPackageData } = wrapper.instance();
expect(console.error).toBeCalled();
loadPackageData().then(response => {
loadPackageData().catch(response => {
expect(response).toBeUndefined();
expect(wrapper.state()).toEqual({ failed: true });
});

View file

@ -10,29 +10,36 @@ import { packageMeta } from '../store/packageMeta';
* @param {string} endpoint
* @returns {Promise}
*/
const register = (method = 'get', endpoint, config = {}) => {
const register = (url, method = 'get', options = {}) => {
if (endpoint === 'login' && method === 'post') {
return login(config);
if (url === 'login' && method.toLocaleLowerCase() === 'post') {
return login(options);
}
if (endpoint === 'logo' && method === 'get') {
if (url === 'logo' && method.toLocaleLowerCase() === 'get') {
return logo();
}
if (endpoint === 'sidebar/verdaccio' && method === 'get') {
return Promise.resolve({ data: packageMeta });
if (url === 'sidebar/verdaccio' && method.toLocaleLowerCase() === 'get') {
return new Promise(function(resolve) {
resolve({
json: function() {
return packageMeta;
}
});
});
}
return Promise.reject({ status: 404, data: 'Not found' });
throw Error('Not found');
};
/**
* Bind API methods
*/
const API = ['get', 'post'].reduce((api, method) => {
api[method] = register.bind(null, method);
return api;
}, {});
class API {
request() {
return register.call(null, ...arguments);
}
}
export default API;
export default new API;

View file

@ -8,8 +8,7 @@ import { BrowserRouter } from 'react-router-dom';
import storage from '../../../src/webui/utils/storage';
jest.mock('../../../src/webui/utils/api', () => ({
get: require('./__mocks__/api').default.get,
post: require('./__mocks__/api').default.post
request: require('./__mocks__/api').default.request,
}));
describe('<Header /> component shallow', () => {
@ -81,15 +80,15 @@ describe('<Header /> component shallow', () => {
it('handleSubmit - login should failed with 401', () => {
const HeaderWrapper = wrapper.find(Header).dive();
const handleSubmit = HeaderWrapper.instance().handleSubmit;
const error = {
const errorObject = {
title: 'Unable to login',
type: 'error',
description: 'Unauthorized'
};
HeaderWrapper.setState({ username: 'sam', password: '12345' });
handleSubmit().then(() => {
expect(HeaderWrapper.state('loginError')).toEqual(error);
handleSubmit().catch((error) => {
expect(HeaderWrapper.state('loginError')).toEqual(errorObject);
});
});

View file

@ -5,21 +5,20 @@
*/
export default function(config) {
return new Promise(function(resolve, reject) {
if (config.data.username === 'sam' && config.data.password === '1234') {
resolve({
status: 200,
data: {
username: 'sam',
token: 'TEST_TOKEN'
}
const body = JSON.parse(config.body);
if (body.username === 'sam' && body.password === '1234') {
return new Promise(function(resolve) {
resolve({
json: function() {
return {
username: 'sam',
token: 'TEST_TOKEN'
}
}
});
});
} else {
reject({
response: {
status: 401,
data: { error: 'Unauthorized' }
}
});
throw Error('Unauthorized');
}
});
}

View file

@ -4,7 +4,7 @@
*/
export default function() {
const response = {
data: 'http://xyz.com/image.jpg'
url: 'http://xyz.com/image.jpg'
};
return Promise.resolve(response);
}