Skip to content

Commit

Permalink
Separated login and login_info routes
Browse files Browse the repository at this point in the history
  • Loading branch information
marcus-oscarsson committed Nov 22, 2023
1 parent cd79fb9 commit cccdd30
Show file tree
Hide file tree
Showing 17 changed files with 260 additions and 263 deletions.
23 changes: 4 additions & 19 deletions mxcubeweb/core/components/user/usermanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,6 @@ def login(self, login_id: str, password: str):
msg = "User %s signed in" % user.username
logging.getLogger("MX3.HWR").info(msg)

return login_res["status"]

# Abstract method to be implemented by concrete implementation
def _signout(self):
pass
Expand Down Expand Up @@ -212,6 +210,7 @@ def signout(self):

self.app.server.user_datastore.deactivate_user(user)
flask_security.logout_user()

self.emit_observers_changed()

def is_authenticated(self):
Expand All @@ -227,22 +226,6 @@ def force_signout_user(self, username):
self.app.server.emit("forceSignout", room=socketio_sid, namespace="/hwr")

def login_info(self):
res = {
"synchrotronName": HWR.beamline.session.synchrotron_name,
"beamlineName": HWR.beamline.session.beamline_name,
"loggedIn": False,
"loginType": HWR.beamline.lims.loginType.title(),
"proposalList": [],
"user": {
"username": "",
"email": "",
"isstaff": False,
"nickname": "",
"inControl": False,
"ip": "",
},
}

if not current_user.is_anonymous:
login_info = convert_to_dict(json.loads(current_user.limsdata))

Expand Down Expand Up @@ -275,8 +258,10 @@ def login_info(self):
)

res["selectedProposalID"] = HWR.beamline.session.proposal_id
else:
raise Exception("Not logged in")

return current_user, res
return res

def update_user(self, user):
self.app.server.user_datastore.put(user)
Expand Down
25 changes: 10 additions & 15 deletions mxcubeweb/routes/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@
request,
jsonify,
make_response,
redirect,
session,
)
from mxcubeweb.core.util import networkutils
from flask_login import current_user


def deny_access(msg):
resp = jsonify({"msg": msg})
resp.code = 409
resp.code = 401
return resp


Expand Down Expand Up @@ -45,7 +43,7 @@ def login():
password = params.get("password", "")

try:
res = jsonify(app.usermanager.login(login_id, password))
app.usermanager.login(login_id, password)
except Exception as ex:
msg = "[LOGIN] User %s could not login (%s)" % (
login_id,
Expand All @@ -54,8 +52,8 @@ def login():
logging.getLogger("MX3.HWR").exception("")
logging.getLogger("MX3.HWR").info(msg)
res = deny_access("Could not authenticate")

session.permanent = True
else:
res = make_response(jsonify(""), 200)

return res

Expand All @@ -66,8 +64,7 @@ def signout():
Signout from MXCuBE Web and reset the session
"""
app.usermanager.signout()

return redirect("/login", code=302)
return make_response(jsonify(""), 200)

@bp.route("/login_info", methods=["GET"])
def login_info():
Expand All @@ -88,16 +85,14 @@ def login_info():
Status code set to:
200: On success
409: Error, could not log in
401: Error, could not log in
"""
user, res = app.usermanager.login_info()

# Redirect the user to login page if for some reason logged out
# i.e. server restart
if not user:
response = redirect("/login", code=302)
else:
try:
res = app.usermanager.login_info()
response = jsonify(res)
except Exception:
response = make_response(jsonify(""), 401)

return response

Expand Down
2 changes: 1 addition & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"react-redux": "7.2.6",
"react-router": "^6.2.1",
"react-router-bootstrap": "^0.26.1",
"react-router-dom": "^6.2.2",
"react-router-dom": "^6.19.0",
"react-slick": "^0.29.0",
"react-sticky": "^6.0.3",
"redux": "4.1.2",
Expand Down
35 changes: 25 additions & 10 deletions ui/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions ui/src/actions/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,12 @@ function notify(error) {
console.error('REQUEST FAILED', error); // eslint-disable-line no-console
}

export function getInitialState(userInControl) {
return (dispatch) => {
export function getInitialState() {
return (dispatch, getState) => {
const state = {};
const { login } = getState();

dispatch(applicationFetched(false));

const sampleVideoInfo = fetch('mxcube/api/v0.1/sampleview/camera', {
method: 'GET',
Expand Down Expand Up @@ -232,7 +235,7 @@ export function getInitialState(userInControl) {
});

/* don't unselect shapes when in observer mode */
if (userInControl) {
if (login.user.userInControl) {
prom = prom.then(() => {
dispatch(unselectShapes({ shapes: state.shapes }));
});
Expand Down
72 changes: 28 additions & 44 deletions ui/src/actions/login.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable promise/catch-or-return */
/* eslint-disable promise/no-nesting */

/* eslint-disable promise/prefer-await-to-then */

import fetch from 'isomorphic-fetch';
Expand Down Expand Up @@ -67,50 +67,39 @@ export function startSession(userInControl) {
}

export function getLoginInfo() {
return (dispatch) =>
fetchLoginInfo().then(
(loginInfo) => {
dispatch(setLoginInfo(loginInfo));
return loginInfo;
},
() => {
dispatch(showErrorPanel(true));
dispatch(setLoading(false));
},
);
return async (dispatch) => {
try {
const loginInfo = await fetchLoginInfo();
dispatch(setLoginInfo(loginInfo));
} catch (error) {
dispatch(
setLoginInfo({
beamlineName: '',
synchrotronName: '',
loginType: '',
user: '',
proposalList: [],
selectedProposal: '',
selectedProposalID: '',
loggedIn: false,
rootPath: '',
}),
);
dispatch(setLoading(false));
throw error;
}
};
}

export function logIn(proposal, password, navigate) {
// eslint-disable-next-line sonarjs/cognitive-complexity
return (dispatch) => {
const previousUser = localStorage.getItem('currentUser');
if (serverIO.hwrSocket !== null && serverIO.hwrSocket.connected) {
console.log(serverIO.hwrSocket.connected); // eslint-disable-line no-console
} else {
serverIO.connect();
}

sendLogIn(proposal, password, previousUser).then(
sendLogIn(proposal, password).then(
(res) => {
if (res.code === 'ok') {
if (res === '') {
dispatch(showErrorPanel(false));
dispatch(getLoginInfo())
.then((response) => response)
.then((resp) => {
if (resp.loginType === 'User') {
if (resp.user.inControl) {
dispatch(showProposalsForm());
} else {
navigate('/');
}
} else {
dispatch(selectProposal(proposal));
navigate('/');
}
});
navigate('/');
} else {
const { msg } = res;
dispatch(showErrorPanel(true, msg));
dispatch(showErrorPanel(true, res));
dispatch(setLoading(false));
}
},
Expand All @@ -125,23 +114,18 @@ export function logIn(proposal, password, navigate) {
export function forcedSignout() {
return (dispatch) => {
serverIO.disconnect();
localStorage.setItem('currentUser', '');

dispatch({ type: 'SIGNOUT' });
};
}

export function signOut(navigate) {
return (dispatch) => {
serverIO.disconnect();
localStorage.setItem('currentUser', '');

return sendSignOut().then(() => {
dispatch({ type: 'SIGNOUT' });
dispatch(getLoginInfo());

if (navigate) {
navigate('/login');
navigate('/');
}
});
};
Expand Down
7 changes: 6 additions & 1 deletion ui/src/api/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ export function sendSignOut() {
}

export function fetchLoginInfo() {
return endpoint.get('/login_info').json();
return endpoint
.get('/login_info') // eslint-disable-next-line promise/prefer-await-to-callbacks
.unauthorized((err) => {
throw err;
})
.json();
}

export function sendFeedback(sender, content) {
Expand Down
Loading

0 comments on commit cccdd30

Please sign in to comment.