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

Show Users 2fa Status on Admin Page #994

Merged
merged 3 commits into from
Sep 14, 2023
Merged
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
6 changes: 6 additions & 0 deletions migrations/20230913185156-adding-totp-field.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Db } from "mongodb";

export async function up(db: Db) {
await db.collection("users").updateMany({}, { $set: { totp: false } });
}
export async function down(db: Db, client) {}
6 changes: 6 additions & 0 deletions migrations/20230913192154-adding-state-field.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Db } from "mongodb";

export async function up(db: Db) {
await db.collection("users").updateMany({}, { $set: { state: "active" } });
}
export async function down(db: Db, client) {}
4 changes: 4 additions & 0 deletions public/locales/en/checkAal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"informationUpdated": "Your Information has been successfully updated.",
"goBack": "Go back to home page."
}
3 changes: 3 additions & 0 deletions public/locales/pt/admin.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
"columnRole": "Papel",
"columnEdit": "Editar",
"columnStatus": "Status",
"columnTotp": "Totp",
"columnBadges": "Insígnias",
"role-admin": "Admin",
"role-regular": "Regular",
"role-fact-checker": "Checador",
"user-status-true": "Ativo",
"user-status-false": "Inativo",
"user-status-active": "Ativo",
"user-status-inactive": "Inativo",
"user-status-active-button": "Desativar",
Expand Down
4 changes: 4 additions & 0 deletions public/locales/pt/checkAal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"informationUpdated": "Suas Informações foram atualizadas com sucesso.",
"goBack": "Voltar para pagina inicial."
}
7 changes: 6 additions & 1 deletion server/users/dto/update-user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Roles, Status } from "../../auth/ability/ability.factory";
import { IsArray, IsOptional, IsString } from "class-validator";
import { IsArray, IsBoolean, IsOptional, IsString } from "class-validator";
import { Badge } from "../../badge/schemas/badge.schema";
import { ApiProperty } from "@nestjs/swagger";

Expand All @@ -18,4 +18,9 @@ export class UpdateUserDTO {
@IsOptional()
@ApiProperty()
state: Status;

@IsBoolean()
@IsOptional()
@ApiProperty()
totp: boolean;
}
3 changes: 3 additions & 0 deletions server/users/schemas/user.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ export class User {
@Prop({ required: true, default: Roles.Regular })
role: Roles;

@Prop({ required: true, default: false })
totp: boolean;

@Prop({
type: [
{
Expand Down
1 change: 1 addition & 0 deletions server/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export class UsersController {
role: 1,
badges: 1,
state: 1,
totp: 1,
},
});
await this.viewService
Expand Down
15 changes: 15 additions & 0 deletions server/view/view.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,21 @@ export class ViewController {
.render(req, res, "/404-page", Object.assign(parsedUrl.query));
}

@Get("totp")
@Header("Cache-Control", "max-age=86400")
public async showTotpCheck(@Req() req: Request, @Res() res: Response) {
const parsedUrl = parse(req.url, true);

await this.viewService
.getNextServer()
.render(
req,
res,
"/totp-check-page",
Object.assign(parsedUrl.query)
);
}

@IsPublic()
@ApiTags("pages")
@Get("unauthorized")
Expand Down
17 changes: 17 additions & 0 deletions src/api/userApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,22 @@ const register = (params, t) => {
});
};

const updateTotp = (
userId,
params: {
totp: boolean;
}
) => {
return request
.put(`/${userId}`, params)
.then((response) => {
return response?.data;
})
.catch((e) => {
return e?.response?.data;
});
};

const update = (
userId,
params: {
Expand All @@ -93,6 +109,7 @@ const update = (

const userApi = {
updatePassword,
updateTotp,
getById,
getUsers,
register,
Expand Down
8 changes: 7 additions & 1 deletion src/atoms/currentUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,11 @@ import { Roles } from "../types/enums";
const isUserLoggedIn = atom(false);
const currentUserRole = atom(Roles.Regular);
const currentUserId = atom("");
const currentAuthentication = atom("");

export { isUserLoggedIn, currentUserRole, currentUserId };
export {
isUserLoggedIn,
currentUserRole,
currentUserId,
currentAuthentication,
};
5 changes: 4 additions & 1 deletion src/components/MainApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Layout } from "antd";
import { useSetAtom } from "jotai";
import React from "react";
import {
currentAuthentication,
currentUserId,
currentUserRole,
isUserLoggedIn,
Expand All @@ -27,10 +28,12 @@ const MainApp = ({ children }) => {
const setCurrentRole = useSetAtom(currentUserRole);
const setCurrentLoginStatus = useSetAtom(isUserLoggedIn);
const setCurrentUserId = useSetAtom(currentUserId);
GetUserRole().then(({ role, isLoggedIn, id }) => {
const setCurrentLevelAuthentication = useSetAtom(currentAuthentication);
GetUserRole().then(({ role, isLoggedIn, id, aal }) => {
setCurrentRole(role);
setCurrentLoginStatus(isLoggedIn);
setCurrentUserId(id);
setCurrentLevelAuthentication(aal);
});

// Setup to provide breakpoints object on redux
Expand Down
32 changes: 25 additions & 7 deletions src/components/Profile/Totp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getUiNode } from "../../lib/orysdk/utils";
import { useRouter } from "next/router";
import AletheiaButton, { ButtonType } from "../Button";
import colors from "../../styles/colors";
import userApi from "../../api/userApi";

export const Totp = ({ flow, setFlow }) => {
const [imgSource, setImgSource] = useState("");
Expand Down Expand Up @@ -59,29 +60,46 @@ export const Totp = ({ flow, setFlow }) => {

const onSubmitLink = (values: ValuesType) => {
orySubmitTotp({ router, flow, setFlow, t, values })
.then(() => {
return userApi.updateTotp(flow.identity.traits.user_id, {
totp: true,
});
})
.then(() => setIsLoading(false))
.catch(() => {
message.error(t("profile:totpIncorectCodeMessage"));
setIsLoading(false);
});
};

const onSubmitUnLink = () => {
const onSubmitUnLink = (values: ValuesType) => {
initializeCsrf();
setIsLoading(true);
const values = {
csrf_token: flowValues.csrf_token,
totp_unlink: true,
method: "totp",
};
orySubmitTotp({ router, flow, setFlow, t, values })
.then(() => {
return userApi.updateTotp(flow.identity.traits.user_id, {
totp: false,
});
})
.then(() => setIsLoading(false))
.catch(() => {
message.error(t("prifile:totpUnLinkErrorMessage"));
setIsLoading(false);
});
};

const onFinishUnlink = () => {
initializeCsrf();
setIsLoading(true);
flowValues = {
...flowValues,
csrf_token: flowValues.csrf_token,
totp_unlink: true,
method: "totp",
};
onSubmitUnLink(flowValues);
};

const onFinish = (values) => {
initializeCsrf();
setIsLoading(true);
Expand Down Expand Up @@ -181,7 +199,7 @@ export const Totp = ({ flow, setFlow }) => {
</Form>
)}
{!showForm && (
<Form onFinish={onSubmitUnLink}>
<Form onFinish={onFinishUnlink}>
<AletheiaButton
loading={isLoading}
htmlType="submit"
Expand Down
55 changes: 55 additions & 0 deletions src/components/TotpCheckPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React, { useEffect } from "react";
import { useAtom } from "jotai";
import { currentAuthentication, currentUserId } from "../atoms/currentUser";
import userApi from "../api/userApi";
import { useTranslation } from "next-i18next";
import { userBeingEdited } from "../atoms/userEdit";

const AalCheckPage = () => {
const { t } = useTranslation();

const [aal] = useAtom(currentAuthentication);
const [userId] = useAtom(currentUserId);

const aal2Activated = aal === "aal2";

const userDataUpdate = async () => {
try {
await userApi.updateTotp(userId, { totp: true });
} catch (e) {
console.error(e);
}
};

useEffect(() => {
if (aal2Activated) {
userDataUpdate();
}
}, [aal]);

return (
<div
style={{
width: "100%",
marginTop: "60px",
textAlign: "center",
fontSize: "1rem",
fontWeight: 600,
}}
>
<div>{t("checkAal:informationUpdated")}</div>
<a
href="/"
style={{
height: "60px",
fontSize: "1rem",
placeContent: "center",
}}
>
{t("checkAal:goBack")}
</a>
</div>
);
};

export default AalCheckPage;
13 changes: 13 additions & 0 deletions src/components/adminArea/AdminView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { startEditingItem } from "../../atoms/editDrawer";
import { atomUserList } from "../../atoms/userEdit";
import { User } from "../../types/User";
import HeaderUserStatus from "./Drawer/HeaderUserStatus";
import HeaderTotpStatus from "./Drawer/HeaderTotpStatus";

const AdminView = () => {
const { t } = useTranslation();
Expand Down Expand Up @@ -83,6 +84,18 @@ const AdminView = () => {
<HeaderUserStatus status={params.value} />
),
},
{
field: "totp",
headerName: t("admin:columnTotp"),
flex: 1,
valueGetter: (params: GridValueGetterParams) => {
console.log(params, "params");
return params.row.totp;
},
renderCell: (params) => (
<HeaderTotpStatus status={params.value} />
),
},
{
field: "actions",
type: "actions",
Expand Down
31 changes: 31 additions & 0 deletions src/components/adminArea/Drawer/HeaderTotpStatus.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React from "react";
import { Col } from "antd";
import { useTranslation } from "next-i18next";
import styled from "styled-components";
import colors from "../../../styles/colors";

const HeaderTotpStatusStyle = styled(Col)`
::before {
content: "";
display: inline-block;
width: 10px;
height: 10px;
border-radius: 10px;
background: ${({ statuscolor }) => statuscolor};
position: relative;
margin-right: 5px;
}
`;

const HeaderTotpStatus = ({ status }) => {
const { t } = useTranslation();
const statusColor = status === true ? colors.active : colors.inactive;

return (
<HeaderTotpStatusStyle statuscolor={statusColor}>
{t(`admin:user-status-${String(status)}`)}
</HeaderTotpStatusStyle>
);
};

export default HeaderTotpStatus;
21 changes: 21 additions & 0 deletions src/pages/totp-check-page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from "react";
import { NextPage } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { GetLocale } from "../utils/GetLocale";
import AalCheckPage from "../components/TotpCheckPage";

const TotpCheckPage: NextPage = () => {
return <AalCheckPage />;
};

export async function getServerSideProps({ locale, locales, req }) {
locale = GetLocale(req, locale, locales);
return {
props: {
...(await serverSideTranslations(locale)),
href: req.protocol + "://" + req.get("host") + req.originalUrl,
},
};
}

export default TotpCheckPage;
1 change: 1 addition & 0 deletions src/types/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export type User = {
role: Roles;
badges: Badge[];
state: Status;
totp: boolean;
};
3 changes: 2 additions & 1 deletion src/utils/GetUserRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ export const GetUserRole = () => {
(session.data.identity.traits.role as Roles) ||
Roles.Regular,
isLoggedIn: true,
aal: session.data.authenticator_assurance_level,
id: session.data.identity.traits.user_id,
status: session?.data.identity.state,
};
})
.catch(() => {
return { role: Roles.Regular, isLoggedIn: false, id: "" };
return { role: Roles.Regular, isLoggedIn: false, id: "", aal: "" };
});
};
Loading