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

feat: Ilmoitus käyttäjlle järjestelmätason oikeuksien puuttumisesta; Korjaa uloskirjautumista #609

Merged
merged 3 commits into from
Feb 21, 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
10 changes: 10 additions & 0 deletions backend/src/error/NoHassuAccessError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ClientError } from "./ClientError";

export class NoHassuAccessError extends ClientError {
constructor(m?: string) {
super("NoHassuAccessError", m);

// Set the prototype explicitly.
Object.setPrototypeOf(this, NoHassuAccessError.prototype);
}
}
10 changes: 10 additions & 0 deletions backend/src/error/NoVaylaAuthenticationError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ClientError } from "./ClientError";

export class NoVaylaAuthenticationError extends ClientError {
constructor(m?: string) {
super("NoVaylaAuthenticationError", m);

// Set the prototype explicitly.
Object.setPrototypeOf(this, NoVaylaAuthenticationError.prototype);
}
}
6 changes: 4 additions & 2 deletions backend/src/user/userService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { DBProjekti } from "../database/model";
import { createSignedCookies } from "./signedCookie";
import { apiConfig } from "../../../common/abstractApi";
import { isAorL } from "../util/userUtil";
import { NoHassuAccessError } from "../error/NoHassuAccessError";
import { NoVaylaAuthenticationError } from "../error/NoVaylaAuthenticationError";

function parseRoles(roles: string): string[] | undefined {
return roles
Expand Down Expand Up @@ -47,7 +49,7 @@ const identifyLoggedInVaylaUser: IdentifyUserFunc = async (event: AppSyncResolve
roolit,
};
if (!isHassuKayttaja(user)) {
throw new IllegalAccessError("Ei käyttöoikeutta palveluun " + JSON.stringify(user));
throw new NoHassuAccessError("Ei käyttöoikeutta palveluun " + JSON.stringify(user));
}
// Create signed cookies only for nykyinenKayttaja operation
if (event.info?.fieldName === apiConfig.nykyinenKayttaja.name) {
Expand Down Expand Up @@ -98,7 +100,7 @@ export function getVaylaUser(): NykyinenKayttaja | undefined {

export function requireVaylaUser(): NykyinenKayttaja {
if (!(globalThis as any).currentUser) {
throw new IllegalAccessError("Väylä-kirjautuminen puuttuu");
throw new NoVaylaAuthenticationError("Väylä-kirjautuminen puuttuu");
}
return (globalThis as any).currentUser;
}
Expand Down
6 changes: 3 additions & 3 deletions backend/test/apiHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import * as sinon from "sinon";
import { projektiDatabase } from "../src/database/projektiDatabase";
import { ProjektiFixture } from "./fixture/projektiFixture";
import { UserFixture } from "./fixture/userFixture";
import { IllegalAccessError } from "../src/error/IllegalAccessError";
import { velho } from "../src/velho/velhoClient";
import { api } from "../integrationtest/api/apiClient";
import { personSearch } from "../src/personSearch/personSearchClient";
Expand Down Expand Up @@ -36,6 +35,7 @@ import { mockBankHolidays } from "./mocks";
import assert from "assert";
import fs from "fs";
import { SchedulerMock } from "../integrationtest/api/testUtil/util";
import { NoVaylaAuthenticationError } from "../src/error/NoVaylaAuthenticationError";

const chai = require("chai");
const { expect } = chai;
Expand Down Expand Up @@ -365,7 +365,7 @@ describe("apiHandler", () => {

// Verify that projekti is not visible for anonymous users
userFixture.logout();
await expect(api.lataaProjekti(fixture.PROJEKTI1_OID)).to.eventually.be.rejectedWith(IllegalAccessError);
await expect(api.lataaProjekti(fixture.PROJEKTI1_OID)).to.eventually.be.rejectedWith(NoVaylaAuthenticationError);
userFixture.loginAs(UserFixture.pekkaProjari);

// Send aloituskuulutus to be approved
Expand Down Expand Up @@ -439,7 +439,7 @@ describe("apiHandler", () => {

createProjektiStub.resolves();

await chai.assert.isRejected(api.tallennaProjekti(fixture.tallennaProjektiInput), IllegalAccessError);
await chai.assert.isRejected(api.tallennaProjekti(fixture.tallennaProjektiInput), NoVaylaAuthenticationError);
});
});

Expand Down
4 changes: 4 additions & 0 deletions migration-cli/package-lock.json

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

43 changes: 35 additions & 8 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@mui/material": "5.10.6",
"@mui/system": "5.10.6",
"@mui/x-date-pickers": "5.0.2",
"@types/js-cookie": "^3.0.2",
"@types/mime-types": "2.1.1",
"@types/nodemailer": "6.4.4",
"@types/pdfkit": "0.12.3",
Expand All @@ -42,6 +43,7 @@
"graphql": "14.7.0",
"graphql-tag": "2.12.5",
"html-react-parser": "3.0.8",
"js-cookie": "^3.0.1",
"jsonschema": "1.4.1",
"jsonwebtoken": "9.0.0",
"jwk-to-pem": "2.0.5",
Expand Down
41 changes: 37 additions & 4 deletions src/components/ApiProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ import { useRouter } from "next/router";
import useTranslation from "next-translate/useTranslation";
import { Translate } from "next-translate";
import { GraphQLError } from "graphql";
import { NoHassuAccessError } from "backend/src/error/NoHassuAccessError";
import { NoVaylaAuthenticationError } from "backend/src/error/NoVaylaAuthenticationError";
import Cookies from "js-cookie";

export const ApiContext = createContext<API>(api);

interface Props {
children?: ReactNode;
updateIsUnauthorizedCallback: (isUnauthorized: boolean) => void;
}

type GenerateErrorMessage = (errorResponse: ErrorResponse, isYllapito: boolean, t: Translate) => string;
Expand Down Expand Up @@ -42,20 +46,49 @@ const generateGenericErrorMessage: GenerateErrorMessage = (errorResponse, isYlla
return errorMessage;
};

function ApiProvider({ children }: Props) {
function ApiProvider({ children, updateIsUnauthorizedCallback }: Props) {
const { showErrorMessage } = useSnackbars();
const router = useRouter();
const isYllapito = router.asPath.startsWith("/yllapito");
const { t } = useTranslation("error");

const value: API = useMemo(() => {
const errorHandler: ErrorResponseHandler = (errorResponse) => {
const commonErrorHandler: ErrorResponseHandler = (errorResponse) => {
showErrorMessage(generateGenericErrorMessage(errorResponse, isYllapito, t));
};
return createApiWithAdditionalErrorHandling(errorHandler);
}, [isYllapito, showErrorMessage, t]);
const authenticatedErrorHandler: ErrorResponseHandler = (errorResponse: ErrorResponse) => {
const errors = errorResponse.response?.errors as GraphQLError | readonly GraphQLError[] | undefined;
if (!errors) {
// No errors - no need for further handling - return
return;
}
const errorArray: readonly GraphQLError[] = Array.isArray(errors) ? errors : [errors];
const unauthorized = errorArray.some((error) => (error as any)?.errorInfo?.errorSubType === new NoHassuAccessError().className);
updateIsUnauthorizedCallback(unauthorized);
// Do not show snackbar errors on unauthorized 'page'
if (!unauthorized) {
commonErrorHandler(errorResponse);
}
const noVaylaAuthentication = errorArray.some(
(error) => (error as any)?.errorInfo?.errorSubType === new NoVaylaAuthenticationError().className
);
if (noVaylaAuthentication) {
removeAWSALBAndCookieSessionCookies();
router.push("/yllapito/kirjaudu");
}
};
return createApiWithAdditionalErrorHandling(commonErrorHandler, authenticatedErrorHandler);
}, [isYllapito, router, showErrorMessage, t, updateIsUnauthorizedCallback]);

return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
}

function removeAWSALBAndCookieSessionCookies() {
Object.keys(Cookies.get() || {})
.filter((cookie) => cookie.startsWith("AWSALB") || cookie.startsWith("cookiesession"))
.forEach((cookie) => {
Cookies.remove(cookie);
});
}

export { ApiProvider };
39 changes: 39 additions & 0 deletions src/components/EiOikeuksia.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from "react";
import { styled } from "@mui/material";
import { ExternalStyledLink } from "./StyledLink";
import ContentSpacer from "./layout/ContentSpacer";
import InfoCardPageLayout from "@components/layout/InfoCardPageLayout";
import VaylaElyKuvat from "@components/VaylaElyKuvat";

const tukiEmail = "tuki.vayliensuunnittelu@vayla.fi";

export default function EiOikeuksiaSivu() {
const logoutHref = process.env.NEXT_PUBLIC_VAYLA_EXTRANET_URL;
return (
<InfoCardPageLayout>
<ContentSpacer gap={12}>
<ContentSpacer gap={7}>
<h1 className="text-primary-dark">Valtion liikenneväylien suunnittelu</h1>
<p className="vayla-subtitle">Sinulta puuttuu käyttöoikeudet järjestelmään</p>
<p>
Et pääse tarkastelemaan Valtion liikenneväylien suunnittelu -järjestelmän tietoja, sillä sinulta puuttuu oikeudet järjestelmään.
Jos tarvitset oikeudet järjestelmään, ota yhteys sähköpostitse <EmailLink href={`mailto:${tukiEmail}`}>{tukiEmail}</EmailLink>.
</p>
</ContentSpacer>
<VaylaElyKuvat />
<ContentSpacer gap={4}>
{logoutHref && (
<ExternalStyledLink href={logoutHref} sx={{ display: "block" }}>
Väyläviraston Extranet
</ExternalStyledLink>
)}
<ExternalStyledLink href="/" sx={{ display: "block" }}>
Valtion liikenneväylien suunnittelun julkinen puoli
</ExternalStyledLink>
</ContentSpacer>
</ContentSpacer>
</InfoCardPageLayout>
);
}

const EmailLink = styled("a")({ fontWeight: 700 });
23 changes: 23 additions & 0 deletions src/components/VaylaElyKuvat.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from "react";
import { experimental_sx as sx, styled } from "@mui/material";

export default function VaylaElyKuvat() {
return (
<KuvaContainer>
<Img src="/vayla_alla_fi_sv_rgb.png" alt="Väylävirasto logo" sx={{ maxHeight: "117px" }} />
<Img src="/ely_alla_fi_sv_rgb.png" alt="ELY logo" sx={{ maxHeight: "91px" }} />
</KuvaContainer>
);
}

const Img = styled("img")({});

const KuvaContainer = styled("div")(
sx({
display: "flex",
justifyContent: "center",
gap: 2,
flexWrap: "wrap",
alignItems: "center",
})
);
2 changes: 1 addition & 1 deletion src/components/layout/InfoCardPageLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { ReactNode } from "react";
import { styled } from "@mui/material";

const Background = styled("div")(({ theme }) => ({
backgroundImage: "url('rata_ja_tie_background.jpeg')",
backgroundImage: "url(/rata_ja_tie_background.jpeg)",
position: "relative",
"::after": {
content: "''",
Expand Down
Loading