Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rebased version of feature/api-v2-auth #142

Merged
merged 57 commits into from Jul 19, 2018
Merged
Changes from 1 commit
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
23e1b35
login and set user_id from cookie
trickpattyFH20 Jun 6, 2018
8ecd35a
store cookie and user login info
trickpattyFH20 Jun 7, 2018
db13668
send login data to view
trickpattyFH20 Jun 7, 2018
1ff2067
- add CSRF cookie
trickpattyFH20 Jun 8, 2018
599e4e3
csrf token fix cookie name
trickpattyFH20 Jun 8, 2018
edf35fd
fix return fetch
trickpattyFH20 Jun 8, 2018
3151da8
err handle for missing cookie
trickpattyFH20 Jun 8, 2018
ce7210b
lint
trickpattyFH20 Jun 8, 2018
ce13c38
pull settings
trickpattyFH20 Jun 12, 2018
497549f
v2 loggout
trickpattyFH20 Jul 6, 2018
775e73f
settings conf and fix hanging promise
trickpattyFH20 Jul 10, 2018
c9750f4
pull user settings
trickpattyFH20 Jul 10, 2018
b1ef9a1
move api js from panel to background
trickpattyFH20 Jul 11, 2018
321591d
lint
trickpattyFH20 Jul 11, 2018
6cb0214
Enable log in init from the website.
jsignanini Jul 12, 2018
1ff0dee
Move auth/account domains to globals.
jsignanini Jul 12, 2018
f9cdde2
pull user settings on login and init
trickpattyFH20 Jul 12, 2018
95267b0
lint
trickpattyFH20 Jul 12, 2018
6f3a1c9
Implement logout.
jsignanini Jul 12, 2018
8925f31
Implement send verify email.
jsignanini Jul 12, 2018
ceab22a
login data success missing
trickpattyFH20 Jul 12, 2018
8bc68d9
pushUserSettings and remove unused
trickpattyFH20 Jul 12, 2018
f9ca859
Implement create account v2.
jsignanini Jul 12, 2018
f9353d8
Fix logout from platform pages not sending message to background.
jsignanini Jul 12, 2018
13cb22f
remove api from panel
trickpattyFH20 Jul 12, 2018
1586b4a
Fix missing function.
jsignanini Jul 12, 2018
20027a2
Add error handling for v2 login.
jsignanini Jul 12, 2018
01bc2f3
move userLogin fetch to background
trickpattyFH20 Jul 12, 2018
d6d1cb8
forgot password email
trickpattyFH20 Jul 13, 2018
2bcb36d
fix lgmogout
trickpattyFH20 Jul 13, 2018
a890e69
fix legacy settings conf
trickpattyFH20 Jul 13, 2018
e014e5a
setup login
trickpattyFH20 Jul 13, 2018
170ff18
setup createAccount
trickpattyFH20 Jul 13, 2018
b00d98b
move createAccount fetch
trickpattyFH20 Jul 13, 2018
dc161b6
Several refactors and fixes.
jsignanini Jul 13, 2018
92bba03
Remove catch from logout.
jsignanini Jul 16, 2018
287fcef
account actions unit tests
trickpattyFH20 Jul 16, 2018
96baf39
lint
trickpattyFH20 Jul 16, 2018
785f318
Further refactor.
jsignanini Jul 16, 2018
954d689
Refactor account.register.
jsignanini Jul 16, 2018
3287c98
Refactor send validate account email.
jsignanini Jul 16, 2018
8ab1b9c
Refactor reset password.
jsignanini Jul 17, 2018
77b62e7
More refactoring.
jsignanini Jul 17, 2018
973cbc2
fix unit test
trickpattyFH20 Jul 17, 2018
ec5b159
Linter fix.
jsignanini Jul 17, 2018
a1cf6eb
fix login_info unit tests
trickpattyFH20 Jul 17, 2018
0551439
Add specific babel-loader for background source files.
jsignanini Jul 18, 2018
f3d91e2
refresh token logout handler - api as class
trickpattyFH20 Jul 18, 2018
b803acc
export _getJSONAPIErrorsObject - move getCsrfCookie to api
trickpattyFH20 Jul 18, 2018
03b6630
lint
trickpattyFH20 Jul 18, 2018
0a24cf2
Refactor account into own component.
jsignanini Jul 18, 2018
4ab01fc
Move logged in check into Account class. Cleanup.
jsignanini Jul 18, 2018
b254b0e
Refactor account in setup page.
jsignanini Jul 19, 2018
c96f307
Refactor setup page header log in.
jsignanini Jul 19, 2018
0bafa11
lint - use logger in ExtMessenger
trickpattyFH20 Jul 19, 2018
736afa7
update tests
trickpattyFH20 Jul 19, 2018
c244fb9
Update to be in sync with develop branch
IAmThePan Jul 19, 2018
File filter
Filter file types
Jump to
Jump to file
Failed to load files.

Always

Just for now

store cookie and user login info
  • Loading branch information
trickpattyFH20 authored and IAmThePan committed Jul 19, 2018
commit 8ecd35ac9968bb8ba5230a9c8e86d425ae404633
@@ -11,6 +11,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/
import 'whatwg-fetch';
import normalize from 'json-api-normalizer';
import build from 'redux-object';
import {
GET_PANEL_DATA, GET_SUMMARY_DATA, GET_BLOCKING_DATA,
TOGGLE_CLIQZ_FEATURE,
@@ -24,11 +26,12 @@ import {
} from '../constants/constants';
import { sendMessageInPromise } from '../utils/msg';
import { doXHR } from '../utils/utils';
import { get } from '../utils/api';
import globals from '../../../src/classes/Globals';
import { decodeJwt, log } from '../../../src/utils/common';

// const API_ROOT_URL = `https://consumerapi.${globals.GHOSTERY_DOMAIN}.com`;
const API_ROOT_URL = `http://localhost:8080`;
const API_ROOT_URL = `http://ghostery.io:8080`;

/**
* Update Cliqz Features.
@@ -114,17 +117,43 @@ export function toggleExpert() {
};
}

/**
* Call accountAPI and get user info. Called from Login
* Component. Picked up by Panel reducer.
* @param {Object} query
* @return {Object} dispatch
*/

export function fetchUser(user_id) {

console.log('fetchUser');
console.log(user_id);

return function (dispatch) {
console.log(user_id);
// TODO make fetch to /api/v2/users/{user_id}
// TODO copy jsonapi from account-web to utils
// utils.jsonapi.get('users', user_id)
// .then(() => {
// // TODO sendMessageInPromise to background to set email (new location somewhere in conf)
// });
}
return get('users', user_id)
.then((data) => {
// normalize user data with jsonapi
const user = build(normalize(data), 'users', user_id);
// store user info in background conf
return sendMessageInPromise('setLoginInfo', user)
.then({

})
.catch(e => {

});
})
.catch((errors) => {
console.log(errors);
dispatch({
type: SHOW_NOTIFICATION,
data: {
text: t('server_error_message'),
classes: 'alert',
},
});
});
};
}

/**
@@ -160,7 +189,9 @@ export function userLogin(email, password) {
});
});
}
sendMessageInPromise('setLoginInfo').then((user_id) => {
return sendMessageInPromise('getLoginCookie')
.then((user_id) => {
console.log('sendMessageInPromise getLoginCookie', user_id);
dispatch({
type: LOGIN_SUCCESS,
data: { user_id }
@@ -172,6 +203,7 @@ export function userLogin(email, password) {
classes: 'success',
},
});
return user_id;
})
.catch((error) => {
// server error
@@ -185,8 +217,8 @@ export function userLogin(email, password) {
},
});
});
return;
}).catch((err) => {
})
.catch((err) => {
log('PanelActions userLogin server error', err);
dispatch({ type: LOGIN_FAILED });
dispatch({
@@ -90,7 +90,9 @@ class Login extends React.Component {

this.props.actions.userLogin(email, password)
.then((user_id) => {
this.props.actions.fetchUser(user_id);
if (user_id) {
this.props.actions.fetchUser(user_id)
}
});
}
/**
@@ -0,0 +1,126 @@
import 'whatwg-fetch';

// TODO make this not global vars
let isRefreshing = false;
const tokenRefreshedEventType = 'tokenRefreshed';
const Config = {
account_server : {
host: 'http://ghostery.io:8081'
},
};

const _getJSONAPIErrorsObject = e => ([{ title: 'Something went wrong.', detail: e.toString() }]);

const _refreshToken = function () {
if (isRefreshing) {
let bindedResolve;
const _processRefreshTokenEvent = (resolve, e) => {
window.removeEventListener(tokenRefreshedEventType, bindedResolve, false);
resolve(e.detail);
};
return new Promise((resolve, reject) => {
bindedResolve = _processRefreshTokenEvent.bind(null, resolve);
window.addEventListener(tokenRefreshedEventType, bindedResolve, false);
});
}

isRefreshing = true;
return fetch(`${Config.auth_server.host}/api/v2/refresh_token`, { // eslint-disable-line no-undef
method: 'POST',
credentials: 'include',
});
};

const _sendReq = (method, path, body) => (
fetch(`${Config.account_server.host}${path}`, { // eslint-disable-line no-undef
method,
headers: {
'Content-Type': 'application/vnd.api+json',
'Content-Length': Buffer.byteLength(JSON.stringify(body)),
'X-CSRF-Token': '' // TODO get cookie from conf,
},
body: JSON.stringify(body),
credentials: 'include',
})
);

const _processResponse = res => (
new Promise((resolve, reject) => {
const { status } = res;
if (status === 204) {
resolve();
return;
}
res.json().then((data) => {
if (status >= 400) {
reject(data);
} else {
resolve(data);
}
});
})
);

const _sendAuthenticatedRequest = (method, path, body) => (
new Promise((resolve, reject) => {
_sendReq(method, path, body)
.then(_processResponse)
.then((data) => {
resolve(data);
})
.catch((data) => {
let shouldRefresh = false;
data.errors.forEach((e) => {
if (e.code === '10021' || e.code === '10022') { // token is expired or missing
shouldRefresh = true;
}
});
if (shouldRefresh) {
_refreshToken()
.then((res) => {
isRefreshing = false;
window.dispatchEvent(new CustomEvent(tokenRefreshedEventType, {
detail: res,
}));
const { status } = res;
if (status >= 400) {
res.json().then((data2) => {
reject(data2.errors);
}).catch((err) => {
reject(_getJSONAPIErrorsObject(err));
});
return;
}
_sendReq(method, path, body)
.then(_processResponse)
.then((data3) => {
resolve(data3);
})
.catch((err) => {
reject(_getJSONAPIErrorsObject(err));
});
});
} else {
reject(_getJSONAPIErrorsObject(data));
}
});
})
);

export const get = function (type, id, include = '') {
if (!id) { return Promise.reject(new Error('id is missing')); }
return _sendAuthenticatedRequest('GET', `/api/v2/${type}/${id}?include=${include}`);
};

export const save = function (type, data) {
return _sendAuthenticatedRequest('POST', `/api/v2/${type}/`, data);
};

export const update = function (type, data) {
// TODO check for data.id and fail
return _sendAuthenticatedRequest('PATCH', `/api/v2/${type}/${data.id}`, { data });
};

export const remove = function (type, id) {
return _sendAuthenticatedRequest('DELETE', `/api/v2/${type}/${id}`);
};
@@ -48,6 +48,7 @@
"d3-scale": "^1.0.6",
"foundation-sites": "^6.4.4-rc1",
"history": "^4.7.2",
"json-api-normalizer": "^0.4.10",
"moment": "^2.19.1",
"react": "^16.0.0",
"react-dom": "^16.0.0",
@@ -56,6 +57,7 @@
"react-router-dom": "^4.2.2",
"react-shadow": "^16.2.0",
"redux": "^3.7.2",
"redux-object": "^0.5.6",
"redux-thunk": "^2.2.0",
"spanan": "^2.0.0",
"ua-parser-js": "^0.7.17",
@@ -723,15 +723,22 @@ function onMessageHandler(request, sender, callback) {
log('GET LOGIN INFO ERROR:', err);
});
return true;
} else if (name === 'setLoginInfo') {
} else if (name === 'getLoginCookie') {
// Note: if you want to trigger a logout, send message as empty {}
accounts.setLoginInfo().then((result) => {
accounts.getLoginCookie().then((result) => {
callback(result);
}).catch((err) => {
callback();
log('SET LOGIN INFO ERROR');
log('GET LOGIN COOKIE ERROR');
});
return true;
} else if (name === 'setLoginInfo') {
accounts.setLoginInfo(message).then((result) => {
callback(result);
}).catch((err) => {
callback();
log('SET LOGIN INFO ERROR');
});
} else if (name === 'update_database') {
checkLibraryVersion().then((result) => {
callback(result);
@@ -841,6 +848,7 @@ function initializeDispatcher() {
utils.flushChromeMemoryCache();
});
dispatcher.on('conf.save.login_info', (loginInfo) => {
console.log('conf.save.login_info', loginInfo);
if (loginInfo.logged_in) {
accounts.pullUserSettings().catch((err) => {
log("dispatcher.on('conf.save.login_info): pullUserSettings error:", err);
@@ -59,25 +59,31 @@ const SYNC_SET = new Set(globals.SYNC_ARRAY);
*
* @return {Promise} login info object
*/
export function setLoginInfo() {
/* @TODO
- get user info from /api/v2/users/{userid}
- email will be in response. store it in conf.login_info
- use extension cookie API to get user_id cookie
*/
export function setLoginInfo(user) {
console.log('inside background setLoginInfo', user);
return new Promise((resolve, reject) => {
const { email, emailValidated, id } = user;
conf.login_info = {
logged_in: true,
user_id: id,
is_validated: emailValidated,
email
};
});
}

export function getLoginCookie() {
return new Promise((resolve, reject) => {
chrome.cookies.get({
url: 'localhost', // ghostery.com || ghosterystage.com
url: 'http://ghostery.io', // ghostery.com || ghosterystage.com
name: 'user_id',
}, cookie => {
conf.login_info = {
logged_in: true,
user_id: cookie.value
// user_token,
// decoded_user_token,
// is_validated // (email validation) get from user endpoint
};
resolve(cookie.value);
}, (cookie) => {
if (cookie) {
resolve(cookie.value);
return;
}
reject('err getting login user_id cookie');
return;
});
});

@@ -5773,6 +5773,12 @@ jsesc@~0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d"

json-api-normalizer@^0.4.10:
version "0.4.10"
resolved "https://registry.yarnpkg.com/json-api-normalizer/-/json-api-normalizer-0.4.10.tgz#5c997a50d45d9ea47ae75cb8c223bffb236ee20a"
dependencies:
lodash "^4.17.2"

json-buffer@3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.0.tgz#5b1f397afc75d677bde8bcfc0e47e1f9a3d9a898"
@@ -8332,6 +8338,10 @@ redux-mock-store@^1.5.1:
dependencies:
lodash.isplainobject "^4.0.6"

redux-object@^0.5.6:
version "0.5.6"
resolved "https://registry.yarnpkg.com/redux-object/-/redux-object-0.5.6.tgz#db573a466ea26d59a98646a748333e00c11702e3"

redux-thunk@^2.2.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.3.0.tgz#51c2c19a185ed5187aaa9a2d08b666d0d6467622"
ProTip! Use n and p to navigate between commits in a pull request.