Merge pull request #74 from SELab-2/chore/login

feat: Login systeem
This commit is contained in:
Gerald Schmittinger 2025-03-10 15:55:43 +01:00 committed by GitHub
commit 11023b1ef0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 5677 additions and 33 deletions

View file

@ -4,3 +4,13 @@ DWENGO_DB_PORT=5431
DWENGO_DB_USERNAME=postgres
DWENGO_DB_PASSWORD=postgres
DWENGO_DB_UPDATE=true
DWENGO_AUTH_STUDENT_URL=http://localhost:7080/realms/student
DWENGO_AUTH_STUDENT_CLIENT_ID=dwengo
DWENGO_AUTH_STUDENT_JWKS_ENDPOINT=http://localhost:7080/realms/student/protocol/openid-connect/certs
DWENGO_AUTH_TEACHER_URL=http://localhost:7080/realms/teacher
DWENGO_AUTH_TEACHER_CLIENT_ID=dwengo
DWENGO_AUTH_TEACHER_JWKS_ENDPOINT=http://localhost:7080/realms/teacher/protocol/openid-connect/certs
# Allow Vite dev-server to access the backend (for testing purposes). Don't forget to remove this in production!
DWENGO_CORS_ALLOWED_ORIGINS=http://localhost:5173

View file

@ -1,11 +1,22 @@
#
# Basic configuration
#
DWENGO_PORT=3000 # The port the backend will listen on
DWENGO_DB_HOST=domain-or-ip-of-database
DWENGO_DB_PORT=5432
PORT=3000 # The port the backend will listen on
# Change this to the actual credentials of the user Dwengo should use in the backend
DWENGO_DB_USERNAME=postgres
DWENGO_DB_PASSWORD=postgres
#
# Advanced configuration
#
# Set this to true when the database scheme needs to be updated. In that case, take a backup first.
DWENGO_DB_UPDATE=false
# Data for the identity provider via which the students authenticate.
DWENGO_AUTH_STUDENT_URL=http://localhost:7080/realms/student
DWENGO_AUTH_STUDENT_CLIENT_ID=dwengo
DWENGO_AUTH_STUDENT_JWKS_ENDPOINT=http://localhost:7080/realms/student/protocol/openid-connect/certs
# Data for the identity provider via which the teachers authenticate.
DWENGO_AUTH_TEACHER_URL=http://localhost:7080/realms/teacher
DWENGO_AUTH_TEACHER_CLIENT_ID=dwengo
DWENGO_AUTH_TEACHER_JWKS_ENDPOINT=http://localhost:7080/realms/teacher/protocol/openid-connect/certs
# LOKI_HOST=http://localhost:3102 # The address of the Loki instance, used for logging

View file

@ -22,12 +22,16 @@
"axios": "^1.8.1",
"dotenv": "^16.4.7",
"express": "^5.0.1",
"express-jwt": "^8.5.1",
"jwks-rsa": "^3.1.0",
"uuid": "^11.1.0",
"js-yaml": "^4.1.0",
"loki-logger-ts": "^1.0.2",
"response-time": "^2.3.3",
"uuid": "^11.1.0",
"winston": "^3.17.0",
"winston-loki": "^6.1.3"
"winston-loki": "^6.1.3",
"cors": "^2.8.5",
"@types/cors": "^2.8.17"
},
"devDependencies": {
"@mikro-orm/cli": "^6.4.6",

View file

@ -11,7 +11,9 @@ import assignmentRouter from './routes/assignment.js';
import submissionRouter from './routes/submission.js';
import classRouter from './routes/class.js';
import questionRouter from './routes/question.js';
import loginRouter from './routes/login.js';
import authRouter from './routes/auth.js';
import { authenticateUser } from './middleware/auth/auth.js';
import cors from './middleware/cors.js';
import { getLogger, Logger } from './logging/initalize.js';
import { responseTimeLogger } from './logging/responseTimeLogger.js';
import responseTime from 'response-time';
@ -22,8 +24,10 @@ const logger: Logger = getLogger();
const app: Express = express();
const port: string | number = getNumericEnvVar(EnvVars.Port);
app.use(cors);
app.use(express.json());
app.use(responseTime(responseTimeLogger));
app.use(authenticateUser);
// TODO Replace with Express routes
app.get('/', (_, res: Response) => {
@ -39,8 +43,7 @@ app.use('/assignment', assignmentRouter);
app.use('/submission', submissionRouter);
app.use('/class', classRouter);
app.use('/question', questionRouter);
app.use('/login', loginRouter);
app.use('/auth', authRouter);
app.use('/theme', themeRoutes);
app.use('/learningPath', learningPathRoutes);
app.use('/learningObject', learningObjectRoutes);

View file

@ -0,0 +1,33 @@
import { EnvVars, getEnvVar } from '../util/envvars.js';
type FrontendIdpConfig = {
authority: string;
clientId: string;
scope: string;
responseType: string;
};
type FrontendAuthConfig = {
student: FrontendIdpConfig;
teacher: FrontendIdpConfig;
};
const SCOPE = 'openid profile email';
const RESPONSE_TYPE = 'code';
export function getFrontendAuthConfig(): FrontendAuthConfig {
return {
student: {
authority: getEnvVar(EnvVars.IdpStudentUrl),
clientId: getEnvVar(EnvVars.IdpStudentClientId),
scope: SCOPE,
responseType: RESPONSE_TYPE,
},
teacher: {
authority: getEnvVar(EnvVars.IdpTeacherUrl),
clientId: getEnvVar(EnvVars.IdpTeacherClientId),
scope: SCOPE,
responseType: RESPONSE_TYPE,
},
};
}

13
backend/src/exceptions.ts Normal file
View file

@ -0,0 +1,13 @@
export class UnauthorizedException extends Error {
status = 401;
constructor(message: string = 'Unauthorized') {
super(message);
}
}
export class ForbiddenException extends Error {
status = 403;
constructor(message: string = 'Forbidden') {
super(message);
}
}

View file

@ -0,0 +1,141 @@
import { EnvVars, getEnvVar } from '../../util/envvars.js';
import { expressjwt } from 'express-jwt';
import { JwtPayload } from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import { AuthenticatedRequest } from './authenticated-request.js';
import { AuthenticationInfo } from './authentication-info.js';
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
const JWKS_CACHE = true;
const JWKS_RATE_LIMIT = true;
const REQUEST_PROPERTY_FOR_JWT_PAYLOAD = 'jwtPayload';
const JWT_ALGORITHM = 'RS256'; // Not configurable via env vars since supporting other algorithms would
// Require additional libraries to be added.
const JWT_PROPERTY_NAMES = {
username: 'preferred_username',
firstName: 'given_name',
lastName: 'family_name',
name: 'name',
email: 'email',
};
function createJwksClient(uri: string): jwksClient.JwksClient {
return jwksClient({
cache: JWKS_CACHE,
rateLimit: JWKS_RATE_LIMIT,
jwksUri: uri,
});
}
const idpConfigs = {
student: {
issuer: getEnvVar(EnvVars.IdpStudentUrl),
jwksClient: createJwksClient(getEnvVar(EnvVars.IdpStudentJwksEndpoint)),
},
teacher: {
issuer: getEnvVar(EnvVars.IdpTeacherUrl),
jwksClient: createJwksClient(getEnvVar(EnvVars.IdpTeacherJwksEndpoint)),
},
};
/**
* Express middleware which verifies the JWT Bearer token if one is given in the request.
*/
const verifyJwtToken = expressjwt({
secret: async (_: express.Request, token: jwt.Jwt | undefined) => {
if (!token?.payload || !(token.payload as JwtPayload).iss) {
throw new Error('Invalid token');
}
const issuer = (token.payload as JwtPayload).iss;
const idpConfig = Object.values(idpConfigs).find((config) => config.issuer === issuer);
if (!idpConfig) {
throw new Error('Issuer not accepted.');
}
const signingKey = await idpConfig.jwksClient.getSigningKey(token.header.kid);
if (!signingKey) {
throw new Error('Signing key not found.');
}
return signingKey.getPublicKey();
},
audience: getEnvVar(EnvVars.IdpAudience),
algorithms: [JWT_ALGORITHM],
credentialsRequired: false,
requestProperty: REQUEST_PROPERTY_FOR_JWT_PAYLOAD,
});
/**
* Get an object with information about the authenticated user from a given authenticated request.
*/
function getAuthenticationInfo(req: AuthenticatedRequest): AuthenticationInfo | undefined {
if (!req.jwtPayload) {
return;
}
const issuer = req.jwtPayload.iss;
let accountType: 'student' | 'teacher';
if (issuer === idpConfigs.student.issuer) {
accountType = 'student';
} else if (issuer === idpConfigs.teacher.issuer) {
accountType = 'teacher';
} else {
return;
}
return {
accountType: accountType,
username: req.jwtPayload[JWT_PROPERTY_NAMES.username]!,
name: req.jwtPayload[JWT_PROPERTY_NAMES.name],
firstName: req.jwtPayload[JWT_PROPERTY_NAMES.firstName],
lastName: req.jwtPayload[JWT_PROPERTY_NAMES.lastName],
email: req.jwtPayload[JWT_PROPERTY_NAMES.email],
};
}
/**
* Add the AuthenticationInfo object with the information about the current authentication to the request in order
* to avoid that the routers have to deal with the JWT token.
*/
const addAuthenticationInfo = (req: AuthenticatedRequest, res: express.Response, next: express.NextFunction) => {
req.auth = getAuthenticationInfo(req);
next();
};
export const authenticateUser = [verifyJwtToken, addAuthenticationInfo];
/**
* Middleware which rejects unauthenticated users (with HTTP 401) and authenticated users which do not fulfill
* the given access condition.
* @param accessCondition Predicate over the current AuthenticationInfo. Access is only granted when this evaluates
* to true.
*/
export const authorize =
(accessCondition: (auth: AuthenticationInfo) => boolean) =>
(req: AuthenticatedRequest, res: express.Response, next: express.NextFunction): void => {
if (!req.auth) {
throw new UnauthorizedException();
} else if (!accessCondition(req.auth)) {
throw new ForbiddenException();
} else {
next();
}
};
/**
* Middleware which rejects all unauthenticated users, but accepts all authenticated users.
*/
export const authenticatedOnly = authorize((_) => true);
/**
* Middleware which rejects requests from unauthenticated users or users that aren't students.
*/
export const studentsOnly = authorize((auth) => auth.accountType === 'student');
/**
* Middleware which rejects requests from unauthenticated users or users that aren't teachers.
*/
export const teachersOnly = authorize((auth) => auth.accountType === 'teacher');

View file

@ -0,0 +1,9 @@
import { Request } from 'express';
import { JwtPayload } from 'jsonwebtoken';
import { AuthenticationInfo } from './authentication-info.js';
export interface AuthenticatedRequest extends Request {
// Properties are optional since the user is not necessarily authenticated.
jwtPayload?: JwtPayload;
auth?: AuthenticationInfo;
}

View file

@ -0,0 +1,11 @@
/**
* Object with information about the user who is currently logged in.
*/
export type AuthenticationInfo = {
accountType: 'student' | 'teacher';
username: string;
name?: string;
firstName?: string;
lastName?: string;
email?: string;
};

View file

@ -0,0 +1,7 @@
import cors from 'cors';
import { EnvVars, getEnvVar } from '../util/envvars.js';
export default cors({
origin: getEnvVar(EnvVars.CorsAllowedOrigins).split(','),
allowedHeaders: getEnvVar(EnvVars.CorsAllowedHeaders).split(','),
});

View file

@ -0,0 +1,23 @@
import express from 'express';
import { getFrontendAuthConfig } from '../controllers/auth.js';
import { authenticatedOnly, studentsOnly, teachersOnly } from '../middleware/auth/auth.js';
const router = express.Router();
// Returns auth configuration for frontend
router.get('/config', (req, res) => {
res.json(getFrontendAuthConfig());
});
router.get('/testAuthenticatedOnly', authenticatedOnly, (req, res) => {
res.json({ message: 'If you see this, you should be authenticated!' });
});
router.get('/testStudentsOnly', studentsOnly, (req, res) => {
res.json({ message: 'If you see this, you should be a student!' });
});
router.get('/testTeachersOnly', teachersOnly, (req, res) => {
res.json({ message: 'If you see this, you should be a teacher!' });
});
export default router;

View file

@ -1,14 +0,0 @@
import express from 'express';
const router = express.Router();
// Returns login paths for IDP
router.get('/', (req, res) => {
res.json({
// Dummy variables, needs to be changed
// With IDP endpoints
leerkracht: '/login-leerkracht',
leerling: '/login-leerling',
});
});
export default router;

View file

@ -1,5 +1,9 @@
const PREFIX = 'DWENGO_';
const DB_PREFIX = PREFIX + 'DB_';
const IDP_PREFIX = PREFIX + 'AUTH_';
const STUDENT_IDP_PREFIX = IDP_PREFIX + 'STUDENT_';
const TEACHER_IDP_PREFIX = IDP_PREFIX + 'TEACHER_';
const CORS_PREFIX = PREFIX + 'CORS_';
type EnvVar = { key: string; required?: boolean; defaultValue?: any };
@ -11,6 +15,15 @@ export const EnvVars: { [key: string]: EnvVar } = {
DbUsername: { key: DB_PREFIX + 'USERNAME', required: true },
DbPassword: { key: DB_PREFIX + 'PASSWORD', required: true },
DbUpdate: { key: DB_PREFIX + 'UPDATE', defaultValue: false },
IdpStudentUrl: { key: STUDENT_IDP_PREFIX + 'URL', required: true },
IdpStudentClientId: { key: STUDENT_IDP_PREFIX + 'CLIENT_ID', required: true },
IdpStudentJwksEndpoint: { key: STUDENT_IDP_PREFIX + 'JWKS_ENDPOINT', required: true },
IdpTeacherUrl: { key: TEACHER_IDP_PREFIX + 'URL', required: true },
IdpTeacherClientId: { key: TEACHER_IDP_PREFIX + 'CLIENT_ID', required: true },
IdpTeacherJwksEndpoint: { key: TEACHER_IDP_PREFIX + 'JWKS_ENDPOINT', required: true },
IdpAudience: { key: IDP_PREFIX + 'AUDIENCE', defaultValue: 'account' },
CorsAllowedOrigins: { key: CORS_PREFIX + 'ALLOWED_ORIGINS', defaultValue: '' },
CorsAllowedHeaders: { key: CORS_PREFIX + 'ALLOWED_HEADERS', defaultValue: 'Authorization,Content-Type' },
} as const;
/**

View file

@ -29,6 +29,30 @@ services:
- dwengo_grafana_data:/var/lib/grafana
restart: unless-stopped
idp: # Based on: https://medium.com/@fingervinicius/easy-running-keycloak-with-docker-compose-b0d7a4ee2358
image: quay.io/keycloak/keycloak:latest
volumes:
- ./idp:/opt/keycloak/data/import
environment:
KC_HOSTNAME: localhost
KC_HOSTNAME_PORT: 7080
KC_HOSTNAME_STRICT_BACKCHANNEL: 'true'
KC_BOOTSTRAP_ADMIN_USERNAME: admin
KC_BOOTSTRAP_ADMIN_PASSWORD: admin
KC_HEALTH_ENABLED: 'true'
KC_LOG_LEVEL: info
healthcheck:
test: ['CMD', 'curl', '-f', 'http://localhost:7080/health/ready']
interval: 15s
timeout: 2s
retries: 15
command: ['start-dev', '--http-port', '7080', '--https-port', '7443', '--import-realm']
ports:
- '7080:7080'
- '7443:7443'
depends_on:
- db
volumes:
dwengo_postgres_data:
dwengo_loki_data:

View file

@ -18,7 +18,9 @@
"dependencies": {
"vue": "^3.5.13",
"vue-router": "^4.5.0",
"vuetify": "^3.7.12"
"vuetify": "^3.7.12",
"oidc-client-ts": "^3.1.0",
"axios": "^1.8.1"
},
"devDependencies": {
"@playwright/test": "^1.50.1",

View file

@ -1,4 +1,7 @@
<script setup lang="ts"></script>
<script setup lang="ts">
import auth from "@/services/auth/auth-service.ts";
auth.loadUser();
</script>
<template>
<router-view />

5
frontend/src/config.ts Normal file
View file

@ -0,0 +1,5 @@
export const apiConfig = {
baseUrl: window.location.hostname == "localhost" ? "http://localhost:3000" : window.location.origin,
};
export const loginRoute = "/login";

View file

@ -15,6 +15,7 @@ import NotFound from "@/components/errors/NotFound.vue";
import CreateClass from "@/views/classes/CreateClass.vue";
import CreateAssignment from "@/views/assignments/CreateAssignment.vue";
import CreateDiscussion from "@/views/discussions/CreateDiscussion.vue";
import CallbackPage from "@/views/CallbackPage.vue";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@ -29,6 +30,10 @@ const router = createRouter({
name: "LoginPage",
component: () => import("../views/LoginPage.vue"),
},
{
path: "/callback",
component: CallbackPage,
},
{
path: "/student/:id",
component: MenuBar,

View file

@ -0,0 +1,10 @@
import axios from "axios";
import { apiConfig } from "@/config.ts";
const apiClient = axios.create({
baseURL: apiConfig.baseUrl,
headers: {
"Content-Type": "application/json",
},
});
export default apiClient;

View file

@ -0,0 +1,27 @@
import apiClient from "@/services/api-client.ts";
import type { FrontendAuthConfig } from "@/services/auth/auth.d.ts";
/**
* Fetch the authentication configuration from the backend.
*/
export async function loadAuthConfig() {
const authConfig = (await apiClient.get<FrontendAuthConfig>("auth/config")).data;
return {
student: {
authority: authConfig.student.authority,
client_id: authConfig.student.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.student.responseType,
scope: authConfig.student.scope,
post_logout_redirect_uri: window.location.origin,
},
teacher: {
authority: authConfig.teacher.authority,
client_id: authConfig.teacher.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.teacher.responseType,
scope: authConfig.teacher.scope,
post_logout_redirect_uri: window.location.origin,
},
};
}

View file

@ -0,0 +1,134 @@
/**
* Service for all authentication- and authorization-related tasks.
*/
import { computed, reactive } from "vue";
import type { AuthState, Role, UserManagersForRoles } from "@/services/auth/auth.d.ts";
import { User, UserManager } from "oidc-client-ts";
import { loadAuthConfig } from "@/services/auth/auth-config-loader.ts";
import authStorage from "./auth-storage.ts";
import { loginRoute } from "@/config.ts";
import apiClient from "@/services/api-client.ts";
import router from "@/router";
import type { AxiosError } from "axios";
const authConfig = await loadAuthConfig();
const userManagers: UserManagersForRoles = {
student: new UserManager(authConfig.student),
teacher: new UserManager(authConfig.teacher),
};
/**
* Load the information about who is currently logged in from the IDP.
*/
async function loadUser(): Promise<User | null> {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
return null;
}
const user = await userManagers[activeRole].getUser();
authState.user = user;
authState.accessToken = user?.access_token || null;
authState.activeRole = activeRole || null;
return user;
}
/**
* Information about the current authentication state.
*/
const authState = reactive<AuthState>({
user: null,
accessToken: null,
activeRole: authStorage.getActiveRole() || null,
});
const isLoggedIn = computed(() => authState.user !== null);
/**
* Redirect the user to the login page where he/she can choose whether to log in as a student or teacher.
*/
async function initiateLogin() {
await router.push(loginRoute);
}
/**
* Redirect the user to the IDP for the given role so that he can log in there.
* Only call this function when the user is not logged in yet!
*/
async function loginAs(role: Role): Promise<void> {
// Storing it in local storage so that it won't be lost when redirecting outside of the app.
authStorage.setActiveRole(role);
await userManagers[role].signinRedirect();
}
/**
* To be called when the user is redirected to the callback-endpoint by the IDP after a successful login.
*/
async function handleLoginCallback(): Promise<void> {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
throw new Error("Login callback received, but the user is not logging in!");
}
authState.user = (await userManagers[activeRole].signinCallback()) || null;
}
/**
* Refresh an expired authorization token.
*/
async function renewToken() {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
console.log("Can't renew the token: Not logged in!");
await initiateLogin();
return;
}
try {
return await userManagers[activeRole].signinSilent();
} catch (error) {
console.log("Can't renew the token:");
console.log(error);
await initiateLogin();
}
}
/**
* End the session of the current user.
*/
async function logout(): Promise<void> {
const activeRole = authStorage.getActiveRole();
if (activeRole) {
await userManagers[activeRole].signoutRedirect();
authStorage.deleteActiveRole();
}
}
// Registering interceptor to add the authorization header to each request when the user is logged in.
apiClient.interceptors.request.use(
async (reqConfig) => {
const token = authState?.user?.access_token;
if (token) {
reqConfig.headers.Authorization = `Bearer ${token}`;
}
return reqConfig;
},
(error) => Promise.reject(error),
);
// Registering interceptor to refresh the token when a request failed because it was expired.
apiClient.interceptors.response.use(
(response) => response,
async (error: AxiosError<{ message?: string }>) => {
if (error.response?.status === 401) {
if (error.response!.data.message === "token_expired") {
console.log("Access token expired, trying to refresh...");
await renewToken();
return apiClient(error.config!); // Retry the request
} // Apparently, the user got a 401 because he was not logged in yet at all. Redirect him to login.
await initiateLogin();
}
return Promise.reject(error);
},
);
export default { authState, isLoggedIn, initiateLogin, loadUser, handleLoginCallback, loginAs, logout };

View file

@ -0,0 +1,26 @@
import type { Role } from "@/services/auth/auth.d.ts";
export default {
/**
* Get the role the user is currently logged in as from the local persistent storage.
*/
getActiveRole(): Role | undefined {
return localStorage.getItem("activeRole") as Role | undefined;
},
/**
* Set the role the user is currently logged in as from the local persistent storage.
* This should happen when the user logs in with another account.
*/
setActiveRole(role: Role) {
localStorage.setItem("activeRole", role);
},
/**
* Remove the saved current role from the local persistent storage.
* This should happen when the user is logged out.
*/
deleteActiveRole() {
localStorage.removeItem("activeRole");
},
};

22
frontend/src/services/auth/auth.d.ts vendored Normal file
View file

@ -0,0 +1,22 @@
import { type User, UserManager } from "oidc-client-ts";
export type AuthState = {
user: User | null;
accessToken: string | null;
activeRole: Role | null;
};
export type FrontendAuthConfig = {
student: FrontendIdpConfig;
teacher: FrontendIdpConfig;
};
export type FrontendIdpConfig = {
authority: string;
clientId: string;
scope: string;
responseType: string;
};
export type Role = "student" | "teacher";
export type UserManagersForRoles = { student: UserManager; teacher: UserManager };

View file

@ -0,0 +1,22 @@
<script setup lang="ts">
import { useRouter } from "vue-router";
import { onMounted } from "vue";
import auth from "../services/auth/auth-service.ts";
const router = useRouter();
onMounted(async () => {
try {
await auth.handleLoginCallback();
await router.replace("/"); // Redirect to home (or dashboard)
} catch (error) {
console.error("OIDC callback error:", error);
}
});
</script>
<template>
<p>Logging you in...</p>
</template>
<style scoped></style>

View file

@ -1,8 +1,28 @@
<script setup lang="ts"></script>
<script setup lang="ts">
import auth from "@/services/auth/auth-service.ts";
import apiClient from "@/services/api-client.ts";
import { ref } from "vue";
const testResponse = ref(null);
async function testAuthenticated() {
testResponse.value = await apiClient.get("/auth/testAuthenticatedOnly");
}
</script>
<template>
<main>
<b> Welcome to the dwengo homepage</b>
<!-- TODO Placeholder implementation to test the login - replace by a more beautiful page later -->
<b>Welcome to the dwengo homepage</b>
<div v-if="auth.isLoggedIn.value">
<p>Hello {{ auth.authState.user?.profile.name }}!</p>
<p>
Your access token for the backend is: <code>{{ auth.authState.user?.access_token }}</code>
</p>
</div>
<v-btn @click="testAuthenticated">Send test request</v-btn>
<p v-if="testResponse">Response from the test request: {{ testResponse }}</p>
</main>
</template>
<style scoped></style>

View file

@ -1,7 +1,34 @@
<script setup lang="ts"></script>
<script setup lang="ts">
import auth from "@/services/auth/auth-service.ts";
function loginAsStudent() {
auth.loginAs("student");
}
function loginAsTeacher() {
auth.loginAs("teacher");
}
function performLogout() {
auth.logout();
}
</script>
<template>
<main></main>
<main>
<!-- TODO Placeholder implementation to test the login - replace by a more beautiful page later -->
<div v-if="!auth.isLoggedIn.value">
<p>You are currently not logged in.</p>
<v-btn @click="loginAsStudent">Login as student</v-btn>
<v-btn @click="loginAsTeacher">Login as teacher</v-btn>
</div>
<div v-if="auth.isLoggedIn.value">
<p>
You are currently logged in as {{ auth.authState.user!.profile.name }} ({{ auth.authState.activeRole }})
</p>
<v-btn @click="performLogout">Logout</v-btn>
</div>
</main>
</template>
<style scoped></style>

9
idp/README.md Normal file
View file

@ -0,0 +1,9 @@
# Testdata in de IDP
De IDP in `docker-compose.yml` is zo geconfigureerd dat hij automatisch bij het starten een testconfiguratie inlaadt. Deze houdt in:
- Een realm `student` die de IDP voor leerlingen representeert.
- Hierin de gebruiker met username `testleerling1`, wachtwoord `password`.
- Een realm `teacher` die de IDP voor leerkrachten representeert.
- Hierin de gebruiker met username `testleerkracht1`, wachtwoord `password`.
- De admin-account (in de realm `master`) heeft username `admin` en wachtwoord `admin`.

2347
idp/student-realm.json Normal file

File diff suppressed because it is too large Load diff

2345
idp/teacher-realm.json Normal file

File diff suppressed because it is too large Load diff

354
package-lock.json generated
View file

@ -32,14 +32,18 @@
"@mikro-orm/postgresql": "^6.4.6",
"@mikro-orm/reflection": "^6.4.6",
"@mikro-orm/sqlite": "6.4.6",
"@types/cors": "^2.8.17",
"@types/js-yaml": "^4.0.9",
"cors": "^2.8.5",
"axios": "^1.8.1",
"dotenv": "^16.4.7",
"express": "^5.0.1",
"express-jwt": "^8.5.1",
"js-yaml": "^4.1.0",
"jwks-rsa": "^3.1.0",
"uuid": "^11.1.0",
"loki-logger-ts": "^1.0.2",
"response-time": "^2.3.3",
"uuid": "^11.1.0",
"winston": "^3.17.0",
"winston-loki": "^6.1.3"
},
@ -86,6 +90,8 @@
"name": "dwengo-1-frontend",
"version": "0.0.1",
"dependencies": {
"axios": "^1.8.1",
"oidc-client-ts": "^3.1.0",
"vue": "^3.5.13",
"vue-router": "^4.5.0",
"vuetify": "^3.7.12"
@ -958,6 +964,44 @@
"url": "https://github.com/sponsors/nzakas"
}
},
"node_modules/@intlify/core-base": {
"version": "10.0.5",
"license": "MIT",
"dependencies": {
"@intlify/message-compiler": "10.0.5",
"@intlify/shared": "10.0.5"
},
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/kazupon"
}
},
"node_modules/@intlify/message-compiler": {
"version": "10.0.5",
"license": "MIT",
"dependencies": {
"@intlify/shared": "10.0.5",
"source-map-js": "^1.0.2"
},
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/kazupon"
}
},
"node_modules/@intlify/shared": {
"version": "10.0.5",
"license": "MIT",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/kazupon"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"dev": true,
@ -1625,6 +1669,15 @@
},
"node_modules/@types/connect": {
"version": "3.4.38",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/cors": {
"version": "2.8.17",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz",
"integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==",
"dev": true,
"license": "MIT",
"dependencies": {
@ -1687,8 +1740,24 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/jsonwebtoken": {
"version": "9.0.9",
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.9.tgz",
"integrity": "sha512-uoe+GxEuHbvy12OUQct2X9JenKM3qAscquYymuQN4fMWG9DBQtykrQEFcAbVACF7qaLw9BePSodUL0kquqBJpQ==",
"license": "MIT",
"dependencies": {
"@types/ms": "*",
"@types/node": "*"
}
},
"node_modules/@types/mime": {
"version": "1.3.5",
"license": "MIT"
},
"node_modules/@types/ms": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
"dev": true,
"license": "MIT"
},
@ -2554,6 +2623,8 @@
},
"node_modules/axios": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.1.tgz",
"integrity": "sha512-NN+fvwH/kV01dYUQ3PTOZns4LWtWhOFCAhQ/pHb88WQ1hNe5V/dvFwc4VJcDL11LT9xSX0QtsR8sWUuyOuOq7g==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
@ -2725,6 +2796,12 @@
"ieee754": "^1.1.13"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause"
},
"node_modules/bundle-name": {
"version": "4.1.0",
"dev": true,
@ -3046,6 +3123,7 @@
},
"node_modules/color-name": {
"version": "1.1.4",
"dev": true,
"license": "MIT"
},
"node_modules/color-string": {
@ -3181,6 +3259,19 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/create-require": {
"version": "1.1.1",
"dev": true,
@ -3424,6 +3515,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/editorconfig": {
"version": "1.0.4",
"dev": true,
@ -4038,6 +4138,26 @@
"node": ">= 18"
}
},
"node_modules/express-jwt": {
"version": "8.5.1",
"resolved": "https://registry.npmjs.org/express-jwt/-/express-jwt-8.5.1.tgz",
"integrity": "sha512-Dv6QjDLpR2jmdb8M6XQXiCcpEom7mK8TOqnr0/TngDKsG2DHVkO8+XnVxkJVN7BuS1I3OrGw6N8j5DaaGgkDRQ==",
"license": "MIT",
"dependencies": {
"@types/jsonwebtoken": "^9",
"express-unless": "^2.1.3",
"jsonwebtoken": "^9.0.0"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/express-unless": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/express-unless/-/express-unless-2.1.3.tgz",
"integrity": "sha512-wj4tLMyCVYuIIKHGt0FhCtIViBcwzWejX0EjNxveAa6dG+0XBCQhMbx+PnkLkFCxLC69qoFrxds4pIyL88inaQ==",
"license": "MIT"
},
"node_modules/express/node_modules/debug": {
"version": "4.3.6",
"license": "MIT",
@ -5028,6 +5148,15 @@
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/jose": {
"version": "4.15.9",
"resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz",
"integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-beautify": {
"version": "1.15.3",
"dev": true,
@ -5178,6 +5307,99 @@
"graceful-fs": "^4.1.6"
}
},
"node_modules/jsonwebtoken": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
"integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",
"license": "MIT",
"dependencies": {
"jws": "^3.2.2",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^7.5.4"
},
"engines": {
"node": ">=12",
"npm": ">=6"
}
},
"node_modules/jwa": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
"integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jwks-rsa": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jwks-rsa/-/jwks-rsa-3.1.0.tgz",
"integrity": "sha512-v7nqlfezb9YfHHzYII3ef2a2j1XnGeSE/bK3WfumaYCqONAIstJbrEGapz4kadScZzEt7zYCN7bucj8C0Mv/Rg==",
"license": "MIT",
"dependencies": {
"@types/express": "^4.17.17",
"@types/jsonwebtoken": "^9.0.2",
"debug": "^4.3.4",
"jose": "^4.14.6",
"limiter": "^1.1.5",
"lru-memoizer": "^2.2.0"
},
"engines": {
"node": ">=14"
}
},
"node_modules/jwks-rsa/node_modules/@types/express": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz",
"integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==",
"license": "MIT",
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^4.17.33",
"@types/qs": "*",
"@types/serve-static": "*"
}
},
"node_modules/jwks-rsa/node_modules/@types/express-serve-static-core": {
"version": "4.19.6",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz",
"integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==",
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/qs": "*",
"@types/range-parser": "*",
"@types/send": "*"
}
},
"node_modules/jws": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
"license": "MIT",
"dependencies": {
"jwa": "^1.4.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"dev": true,
@ -5284,6 +5506,11 @@
"node": ">= 0.8.0"
}
},
"node_modules/limiter": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz",
"integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA=="
},
"node_modules/locate-path": {
"version": "6.0.0",
"dev": true,
@ -5302,6 +5529,48 @@
"version": "4.17.21",
"license": "MIT"
},
"node_modules/lodash.clonedeep": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
"integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
"license": "MIT"
},
"node_modules/lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
"license": "MIT"
},
"node_modules/lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
"license": "MIT"
},
"node_modules/lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
"license": "MIT"
},
"node_modules/lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
"license": "MIT"
},
"node_modules/lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
"license": "MIT"
},
"node_modules/lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
"license": "MIT"
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"dev": true,
@ -5338,6 +5607,12 @@
"integrity": "sha512-ka87Jz3gcx/I7Hal94xaN2tZEOPoUOEVftkQqZx2EeQRN7LGdfLlI3FvZ+7WDplm+vK2Urx9ULrvSowtdCieng==",
"license": "Apache-2.0"
},
"node_modules/lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
"license": "MIT"
},
"node_modules/loupe": {
"version": "3.1.3",
"dev": true,
@ -5348,6 +5623,34 @@
"dev": true,
"license": "ISC"
},
"node_modules/lru-memoizer": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/lru-memoizer/-/lru-memoizer-2.3.0.tgz",
"integrity": "sha512-GXn7gyHAMhO13WSKrIiNfztwxodVsP8IoZ3XfrJV4yH2x0/OeTO/FIaAHTY5YekdGgW94njfuKmyyt1E0mR6Ug==",
"license": "MIT",
"dependencies": {
"lodash.clonedeep": "^4.5.0",
"lru-cache": "6.0.0"
}
},
"node_modules/lru-memoizer/node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"license": "ISC",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/lru-memoizer/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"license": "ISC"
},
"node_modules/magic-string": {
"version": "0.30.17",
"license": "MIT",
@ -6044,6 +6347,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"license": "MIT",
@ -6054,6 +6366,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/oidc-client-ts": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/oidc-client-ts/-/oidc-client-ts-3.1.0.tgz",
"integrity": "sha512-IDopEXjiwjkmJLYZo6BTlvwOtnlSniWZkKZoXforC/oLZHC9wkIxd25Kwtmo5yKFMMVcsp3JY6bhcNJqdYk8+g==",
"license": "Apache-2.0",
"dependencies": {
"jwt-decode": "^4.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"license": "MIT",
@ -6646,6 +6970,8 @@
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/pump": {
@ -7583,6 +7909,14 @@
"node": ">=8"
}
},
"node_modules/strip-ansi-cjs/node_modules/ansi-regex": {
"version": "5.0.1",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/strip-bom": {
"version": "3.0.0",
"dev": true,
@ -8521,6 +8855,24 @@
"url": "https://opencollective.com/eslint"
}
},
"node_modules/vue-i18n": {
"version": "10.0.5",
"license": "MIT",
"dependencies": {
"@intlify/core-base": "10.0.5",
"@intlify/shared": "10.0.5",
"@vue/devtools-api": "^6.5.0"
},
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://github.com/sponsors/kazupon"
},
"peerDependencies": {
"vue": "^3.0.0"
}
},
"node_modules/vue-router": {
"version": "4.5.0",
"license": "MIT",