Skip to content

Commit

Permalink
fix eraCommons
Browse files Browse the repository at this point in the history
  • Loading branch information
hams7504 committed Oct 2, 2023
1 parent 22d2213 commit 0a86d81
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 178 deletions.
332 changes: 158 additions & 174 deletions src/components/eRACommons.js
Original file line number Diff line number Diff line change
@@ -1,219 +1,203 @@
import React, { useState, useEffect } from 'react';
import { a, div, button, label, h, h2, h3, h4, span } from 'react-hyperscript-helpers';
import { get, merge } from 'lodash';
import { find, getOr, isNil } from 'lodash/fp';
import * as qs from 'query-string';
import React from 'react';
import { a, button, div, hh, label, span } from 'react-hyperscript-helpers';
import { AuthenticateNIH, User } from '../libs/ajax';
import { AuthenticateNIH, User, Collections } from '../libs/ajax';
import { Config } from '../libs/config';
import eraIcon from '../images/era-commons-logo.png';
import './Animations.css';

export const eRACommons = hh(class eRACommons extends React.Component {

state = {
export default function ERACommons(props) {
const [state, setState] = useState({
isAuthorized: false,
expirationCount: 0,
eraCommonsId: '',
nihError: false,
isHovered: false
};
});

componentDidMount = async () => {
if (this.props.location !== undefined && this.props.location.search !== '') {
await this.saveNIHAuthentication(this.props.location.search);
} else {
await this.getUserInfo();
}
const onMouseEnter = () => {
setState({ ...state, isHovered: true });
};

onMouseEnter = () => {
this.setState({ isHovered: true });
const onMouseLeave = () => {
setState({ ...state, isHovered: false });
};

onMouseLeave = () => {
this.setState({ isHovered: false });
};

saveNIHAuthentication = async (searchArg) => {
const saveNIHAuthentication = async (searchArg) => {
const parsedToken = qs.parse(searchArg);
this.verifyToken(parsedToken).then(
(decodedNihAccount) => {
AuthenticateNIH.saveNihUsr(decodedNihAccount).then(
() => this.getUserInfo(),
() => this.setState({ nihError: true })
);
},
() => this.setState({ nihError: true })
);
try {
const decodedNihAccount = await verifyToken(parsedToken);
await AuthenticateNIH.saveNihUsr(decodedNihAccount);
await getUserInfo();
} catch (error) {
setState({ ...state, nihError: true });
}
};

getUserInfo = async () => {
if (this.props.researcherProfile === undefined) {
const response = await User.getMe();
const props = response.researcherProperties;
const authProp = find({'propertyKey':'eraAuthorized'})(props);
const expProp = find({'propertyKey':'eraExpiration'})(props);
const isAuthorized = isNil(authProp) ? false : getOr(false,'propertyValue')(authProp);
const expirationCount = isNil(expProp) ? 0 : AuthenticateNIH.expirationCount(getOr(0,'propertyValue')(expProp));
const getUserInfo = async () => {
try {
const response = (props.researcherProfile === undefined) ? await User.getMe() : props.researcherProfile;
const propsData = response.researcherProperties;
const authProp = find({ 'propertyKey': 'eraAuthorized' })(propsData);
const expProp = find({ 'propertyKey': 'eraExpiration' })(propsData);
const isAuthorized = isNil(authProp) ? false : getOr(false, 'propertyValue')(authProp);
const expirationCount = isNil(expProp) ? 0 : AuthenticateNIH.expirationCount(getOr(0, 'propertyValue')(expProp));
const nihValid = isAuthorized && expirationCount > 0;
const eraCommonsId = response.eraCommonsId;
this.props.onNihStatusUpdate(nihValid);
this.setState(prev => {
prev.isAuthorized = isAuthorized;
prev.expirationCount = expirationCount;
prev.eraCommonsId = isNil(eraCommonsId) ? '' : eraCommonsId;
return prev;
});
}
else {
const response = this.props.researcherProfile;
const props = response.researcherProperties;
const authProp = find({'propertyKey':'eraAuthorized'})(props);
const expProp = find({'propertyKey':'eraExpiration'})(props);
const isAuthorized = isNil(authProp) ? false : getOr(false,'propertyValue')(authProp);
const expirationCount = isNil(expProp) ? 0 : AuthenticateNIH.expirationCount(getOr(0,'propertyValue')(expProp));
const nihValid = isAuthorized && expirationCount > 0;
const eraCommonsId = response.eraCommonsId;
this.props.onNihStatusUpdate(nihValid);
this.setState(prev => {
prev.isAuthorized = isAuthorized;
prev.expirationCount = expirationCount;
prev.eraCommonsId = isNil(eraCommonsId) ? '' : eraCommonsId;
return prev;

props.onNihStatusUpdate(nihValid);
setState({
...state,
isAuthorized,
expirationCount,
eraCommonsId: isNil(eraCommonsId) ? '' : eraCommonsId
});
} catch (error) {
console.error('Error fetching user info:', error);
}
};

verifyToken = async (parsedToken) => {
return await AuthenticateNIH.verifyNihToken(parsedToken).then(
(decoded) => decoded,
() => {
this.setState({ nihError: true });
return null;
}
);
const verifyToken = async (parsedToken) => {
try {
const decoded = await AuthenticateNIH.verifyNihToken(parsedToken);
return decoded;
} catch (error) {
setState({ ...state, nihError: true });
return null;
}
};

redirectToNihLogin = async () => {
const destination = window.location.origin + '/' + this.props.destination + '?nih-username-token=<token>';
const nihUrl = `${ await Config.getNihUrl() }?${qs.stringify({ 'return-url': destination })}`;
const redirectToNihLogin = async () => {
const destination = `${window.location.origin}/${props.destination}?nih-username-token=<token>`;
const nihUrl = `${await Config.getNihUrl()}?${qs.stringify({ 'return-url': destination })}`;
window.location.href = nihUrl;
};

deleteNihAccount = async () => {
AuthenticateNIH.eliminateAccount().then(
() => this.getUserInfo(),
() => this.setState({ nihError: true })
);
const deleteNihAccount = async () => {
try {
await AuthenticateNIH.eliminateAccount();
await getUserInfo();
} catch (error) {
setState({ ...state, nihError: true });
}
};

render() {
const logoStyle = {
height: 27,
width: 38,
backgroundRepeat: 'no-repeat',
backgroundSize: 'contain',
backgroundImage: `url(${eraIcon})`,
display: 'inline-block'
};
const buttonHoverState = {
boxShadow: '1px 1px 3px #00609f'
};
const buttonNormalState = {
height: 34,
width: 210,
display: 'block',
border: '1px solid #d3d3d3',
padding: 3,
textAlign: 'center',
marginTop: 3,
backgroundColor: '#fff',
borderRadius: 2,
boxShadow: '1px 1px 3px #999999',
cursor: 'pointer',
color: '#999',
fontWeight: 500,
fontSize: '.8em',
transition: 'all .2s ease'
};
const validationErrorState = get(this.props, 'validationError', false) ? {
color: '#D13B07'
} : {};
const buttonStyle =
merge(this.state.isHovered ? merge(buttonNormalState, buttonHoverState) : buttonNormalState, validationErrorState);
const nihErrorMessage = 'Something went wrong. Please try again.';
useEffect(() => {
if (props.location !== undefined && props.location.search !== '') {
saveNIHAuthentication(props.location.search);
} else {
getUserInfo();
console.log('here')
}
}, [props.location, props.researcherProfile]);

return (
const logoStyle = {
height: 27,
width: 38,
backgroundRepeat: 'no-repeat',
backgroundSize: 'contain',
backgroundImage: `url(${eraIcon})`,
display: 'inline-block'
};
const buttonHoverState = {
boxShadow: '1px 1px 3px #00609f'
};
const buttonNormalState = {
height: 34,
width: 210,
display: 'block',
border: '1px solid #d3d3d3',
padding: 3,
textAlign: 'center',
marginTop: 3,
backgroundColor: '#fff',
borderRadius: 2,
boxShadow: '1px 1px 3px #999999',
cursor: 'pointer',
color: '#999',
fontWeight: 500,
fontSize: '.8em',
transition: 'all .2s ease'
};
const validationErrorState = get(props, 'validationError', false) ? {
color: '#D13B07'
} : {};
const buttonStyle =
merge(state.isHovered ? merge(buttonNormalState, buttonHoverState) : buttonNormalState, validationErrorState);
const nihErrorMessage = 'Something went wrong. Please try again.';

return (
div({
className: props.className,
style: { minHeight: 65, ...props.style }
}, [
label(
{ className: 'control-label', isRendered: props.header },
[
span({}, [
'NIH eRA Commons ID',
isNil(props.required) || props.required === true ? '*' : ''
])
]),
div({
className: this.props.className,
style: { minHeight: 65, ...this.props.style }
isRendered: (!state.isAuthorized || state.expirationCount < 0)
}, [
label(
{ className: 'control-label', isRendered: this.props.header },
[
span({}, [
'NIH eRA Commons ID',
isNil(this.props.required) || this.props.required === true ? '*' : ''
])
]),
a({
style: buttonStyle,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onClick: redirectToNihLogin,
disabled: props.readOnly,
target: '_blank'
}, [
div({ style: logoStyle }),
span({ style: { verticalAlign: '50%' } }, ['Authenticate your account'])
])
]),
span({
className: 'cancel-color required-field-error-span',
isRendered: state.nihError
}, [nihErrorMessage]),
div({ isRendered: (state.isAuthorized) }, [
div({
isRendered: (!this.state.isAuthorized || this.state.expirationCount < 0)
isRendered: state.expirationCount >= 0,
className: 'col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding'
}, [
a({
style: buttonStyle,
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave,
onClick: this.redirectToNihLogin,
disabled: this.props.readOnly,
target: '_blank'
}, [
div({ style: logoStyle }),
span({ style: { verticalAlign: '50%' } }, ['Authenticate your account'])
])
]),
span({
className: 'cancel-color required-field-error-span',
isRendered: this.state.nihError
}, [nihErrorMessage]),
div({ isRendered: (this.state.isAuthorized) }, [
div({
isRendered: this.state.expirationCount >= 0,
className: 'col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding'
}, [
div({
style: {
float: 'left',
fontWeight: 500,
display: 'inline',
paddingTop: 5
}
}, [this.state.eraCommonsId]),
button({
style: {
float: 'left',
margin: '2px 0 0 10px'
},
type: 'button',
disabled: this.props.readOnly,
onClick: this.deleteNihAccount,
className: 'close'
}, [
span({ className: 'glyphicon glyphicon-remove-circle', 'data-tip': 'Clear account', 'data-for': 'tip_clearNihAccount' })
])
]),
div({
style: {
marginTop: 8,
fontStyle: 'italic',
display: 'block'
float: 'left',
fontWeight: 500,
display: 'inline',
paddingTop: 5
}
}, [state.eraCommonsId]),
button({
style: {
float: 'left',
margin: '2px 0 0 10px'
},
className: 'col-lg-12 col-md-12 col-sm-6 col-xs-12 no-padding'
type: 'button',
disabled: props.readOnly,
onClick: deleteNihAccount,
className: 'close'
}, [
div({ isRendered: this.state.expirationCount >= 0, className: 'fadein' }, ['Your NIH authentication will expire in ' + this.state.expirationCount + ' days']),
div({ isRendered: this.state.expirationCount < 0, className: 'fadein' }, [(this.props.researcherProfile === undefined) ? 'Your NIH authentication has expired' : `This user's NIH authentication has expired`])
span({ className: 'glyphicon glyphicon-remove-circle', 'data-tip': 'Clear account', 'data-for': 'tip_clearNihAccount' })
])
]),
div({
style: {
marginTop: 8,
fontStyle: 'italic',
display: 'block'
},
className: 'col-lg-12 col-md-12 col-sm-6 col-xs-12 no-padding'
}, [
div({ isRendered: state.expirationCount >= 0, className: 'fadein' }, ['Your NIH authentication will expire in ' + state.expirationCount + ' days']),
div({ isRendered: state.expirationCount < 0, className: 'fadein' }, [(props.researcherProfile === undefined) ? 'Your NIH authentication has expired' : `This user's NIH authentication has expired`])
])
])
);
}
});
])
);
}
4 changes: 2 additions & 2 deletions src/pages/dar_application/ResearcherInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useState, useEffect} from 'react';
import { Alert } from '../../components/Alert';
import { Link } from 'react-router-dom';
import { a, div, fieldset, h, h2, h3, h4, span } from 'react-hyperscript-helpers';
import { eRACommons } from '../../components/eRACommons';
import ERACommons from '../../components/ERACommons';
import CollaboratorList from './collaborator/CollaboratorList';
import { isEmpty, isNil, get } from 'lodash/fp';
import { FormField, FormValidators, FormFieldTypes } from '../../components/forms/forms';
Expand Down Expand Up @@ -92,7 +92,7 @@ export default function ResearcherInfo(props) {
]),
div({ className: 'flex-row', style: { justifyContent: 'flex-start', alignItems: 'flex-start' } }, [
h4({ style: { marginRight: 30, marginTop: 30 } }, '1.2.1'),
eRACommons({
ERACommons({
destination: eRACommonsDestination,
onNihStatusUpdate: onNihStatusUpdate,
location: location,
Expand Down
Loading

0 comments on commit 0a86d81

Please sign in to comment.