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

[WIP] Add ability to disconnect external accounts #1014

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions pydatalab/pydatalab/routes/v0_1/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,54 @@
from flask_login import current_user

from pydatalab.config import CONFIG
from pydatalab.logger import logged_route
from pydatalab.models.people import DisplayName, EmailStr
from pydatalab.mongo import flask_mongo

USERS = Blueprint("users", __name__)


@USERS.route("/users/<user_id>/remove-identity", methods=["DELETE"])
@logged_route
def remove_user_identity(user_id):
"""Given a user ID, delete a specified identity from the user,
passed in the request body as a JSON object of the form `{"identity_type": <identifier>}`.
"""
request_json = request.get_json()
identity_to_remove: dict[str, str] | None = None
if request_json is not None:
identity_to_remove = request_json.get("identity", None)

if not current_user.is_authenticated and not CONFIG.TESTING:
return (jsonify({"status": "error", "message": "No user authenticated."}), 401)

if not CONFIG.TESTING and current_user.id != user_id and current_user.role != "admin":
return (
jsonify({"status": "error", "message": "User not allowed to edit this profile."}),
403,
)

if not identity_to_remove:
return jsonify({"status": "error", "message": "No identity provided."}), 400

if len(identity_to_remove) != 1:
return jsonify(
{"status": "error", "message": "Only one identity can be removed at a time."}
), 400

identity_type, identity_value = list(identity_to_remove.items())[0]

pull = {"identities": {"identity_type": identity_type, "identifier": str(identity_value)}}
update_result = flask_mongo.db.users.update_one({"_id": ObjectId(user_id)}, {"$pull": pull})
if update_result.matched_count != 1:
return jsonify({"status": "error", "message": "Unable to update user."}), 400

if update_result.modified_count != 1:
return jsonify({"status": "success", "message": "No update was performed"}), 200

return jsonify({"status": "success"}), 200


@USERS.route("/users/<user_id>", methods=["PATCH"])
def save_user(user_id):
request_json = request.get_json()
Expand Down
13 changes: 13 additions & 0 deletions pydatalab/tests/server/test_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,16 @@ def test_user_update_admin(admin_client, real_mongo_client, user_id):
assert resp.status_code == 200
user = real_mongo_client.get_database().users.find_one({"_id": user_id})
assert user["display_name"] == "Test Person"


def test_user_remove_identity(client, real_mongo_client, user_id):
endpoint = f"/users/{str(user_id)}/remove-identity"

real_mongo_client.get_database().users.update_one(
{"_id": user_id},
{"$set": {"identities": [{"identity_type": "orcid", "identifier": "0000-0000-0000-0000"}]}},
)
user_request = client.delete(endpoint, json={"orcid": "0000-0000-0000-0000"})
assert user_request.status_code == 200
user = real_mongo_client.get_database().users.find_one({"_id": user_id})
assert not user.get("identities", None)
126 changes: 83 additions & 43 deletions webapp/src/components/EditAccountSettingsModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,52 +48,67 @@
<div class="form-row">
<div class="form-group col-md-6">
<label for="connected-accounts" class="col-form-label">Connected accounts:</label>
<a
v-if="user.identities.some((identity) => identity.identity_type === 'github')"
type="button"
class="dropdown-item btn login btn-link btn-default"
:href="
'https://github.com/' +
user.identities.find((identity) => identity.identity_type === 'github').name
"
>
<font-awesome-icon :icon="['fab', 'github']" />
{{ user.identities.find((identity) => identity.identity_type === "github").name }}
</a>

<a
v-else-if="showGitHub"
type="button"
class="dropdown-item btn login btn-link btn-default"
aria-label="Login via GitHub"
:href="apiUrl + '/login/github'"
><font-awesome-icon :icon="['fab', 'github']" /> Connect your GitHub account</a
>
<div v-if="user.identities.some((identity) => identity.identity_type === 'github')">
<div type="button" class="dropdown-item identity-section">
<a
class="identity-link"
:href="
'https://github.com/' +
user.identities.find((identity) => identity.identity_type === 'github').name
"
>
<font-awesome-icon :icon="['fab', 'github']" />
{{ user.identities.find((identity) => identity.identity_type === "github").name }}
</a>
<font-awesome-icon
class="identity-disconnect-btn"
:icon="['fas', 'times']"
@click="disconnectIdentity()"
/>
</div>
</div>
<div v-else-if="showGitHub">
<a
type="button"
class="dropdown-item btn login btn-link btn-default"
aria-label="Login via GitHub"
:href="apiUrl + '/login/github'"
><font-awesome-icon :icon="['fab', 'github']" /> Connect your GitHub account</a
>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<a
v-if="user.identities.some((identity) => identity.identity_type === 'orcid')"
type="button"
class="dropdown-item btn login btn-link btn-default"
:href="
'https://orcid.org/' +
user.identities.find((identity) => identity.identity_type === 'orcid').name
"
>
<font-awesome-icon class="orcid-icon" :icon="['fab', 'orcid']" />
{{ user.identities.find((identity) => identity.identity_type === "orcid").name }}
</a>
<a
v-else-if="showORCID"
type="button"
class="dropdown-item btn login btn-link btn-default"
aria-label="Connect ORCID account"
:href="apiUrl + '/login/orcid'"
><font-awesome-icon class="orcid-icon" :icon="['fab', 'orcid']" /> Connect your
ORCID</a
>
<div v-if="user.identities.some((identity) => identity.identity_type === 'orcid')">
<div type="button" class="dropdown-item btn login btn-link btn-default">
<a
class="identity-link"
:href="
'https://orcid.org/' +
user.identities.find((identity) => identity.identity_type === 'orcid').name
"
>
<font-awesome-icon class="orcid-icon" :icon="['fab', 'orcid']" />
{{ user.identities.find((identity) => identity.identity_type === "orcid").name }}
</a>
<font-awesome-icon
class="identity-disconnect-btn"
:icon="['fas', 'times']"
@click="disconnectIdentity()"
/>
</div>
</div>
<div v-else-if="showORCID">
<a
type="button"
class="dropdown-item btn login btn-link btn-default"
aria-label="Connect ORCID account"
:href="apiUrl + '/login/orcid'"
>
<font-awesome-icon class="orcid-icon" :icon="['fab', 'orcid']" /> Connect your ORCID
</a>
</div>
</div>
</div>
<div class="form-row">
Expand Down Expand Up @@ -128,7 +143,12 @@
import { API_URL } from "@/resources.js";
import Modal from "@/components/Modal.vue";
import UserBubble from "@/components/UserBubble.vue";
import { getUserInfo, saveUser, requestNewAPIKey } from "@/server_fetch_utils.js";
import {
getUserInfo,
saveUser,
requestNewAPIKey,
disconnectIdentityFromUser,
} from "@/server_fetch_utils.js";
import StyledInput from "./StyledInput.vue";

export default {
Expand Down Expand Up @@ -189,6 +209,9 @@ export default {
this.$store.commit("setDisplayName", this.user.display_name);
this.$emit("update:modelValue", false);
},
async disconnectIdentity(identityType, identifier) {
await disconnectIdentityFromUser(this.user.immutable_id, identityType, identifier);
},
async getUser() {
let user = await getUserInfo();
if (user != null) {
Expand Down Expand Up @@ -234,6 +257,23 @@ export default {
color: red;
}

.identity-section:hover {
background-color: inherit;
}

.identity-link {
color: black;
}

.identity-disconnect-btn {
padding-left: 10px;
color: darkgrey;
}

.identity-disconnect-btn:hover {
color: black;
}

:deep(.form-error a) {
color: #820000;
font-weight: 600;
Expand Down
28 changes: 18 additions & 10 deletions webapp/src/server_fetch_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ function fetch_put(url, body) {
}

// eslint-disable-next-line no-unused-vars
function fetch_delete(url) {
function fetch_delete(url, body) {
let headers = construct_headers({ "Content-Type": "application/json" });
const requestOptions = {
method: "DELETE",
headers: headers,
body: JSON.stringify(body),
credentials: "include",
};
return fetch(url, requestOptions).then(handleResponse);
Expand Down Expand Up @@ -404,15 +405,6 @@ export function deleteEquipment(item_id) {
.catch((error) => alert("Item delete failed for " + item_id + ": " + error));
}

export function deletSampleFromCollection(collection_id, collection_summary) {
return fetch_delete(`${API_URL}/collections/${collection_id}`)
.then(function (response_json) {
console.log("delete successful" + response_json);
store.commit("deleteFromCollectionList", collection_summary);
})
.catch((error) => alert("Collection delete failed for " + collection_id + ": " + error));
}

export async function getItemData(item_id) {
return fetch_get(`${API_URL}/get-item-data/${item_id}`)
.then((response_json) => {
Expand Down Expand Up @@ -569,6 +561,22 @@ export function saveUser(user_id, user) {
});
}

export function disconnectIdentityFromUser(userId, identityType, identifier) {
fetch_delete(`${API_URL}/users/${userId}/remove-identity`, {
identity: { identityType: identifier },
})
.then(function (response_json) {
if (response_json.status === "success") {
getUserInfo();
} else {
alert("Identity disconnect unsuccessful", response_json.detail);
}
})
.catch(function (error) {
alert(`Identity disconnect unsuccessful: ${error}`);
});
}

export function saveRole(user_id, role) {
fetch_patch(`${API_URL}/roles/${user_id}`, role)
.then(function (response_json) {
Expand Down