diff --git a/backend/.env.development.example b/backend/.env.development.example index 0b96f873..f809129d 100644 --- a/backend/.env.development.example +++ b/backend/.env.development.example @@ -6,6 +6,11 @@ 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 frontend from anywhere to access the backend (for testing purposes). Don't forget to remove this in production! +DWENGO_CORS_ALLOWED_ORIGINS=* diff --git a/backend/package.json b/backend/package.json index af8090f2..254158f1 100644 --- a/backend/package.json +++ b/backend/package.json @@ -24,7 +24,9 @@ "jwks-rsa": "^3.1.0", "uuid": "^11.1.0", "js-yaml": "^4.1.0", - "@types/js-yaml": "^4.0.9" + "@types/js-yaml": "^4.0.9", + "cors": "^2.8.5", + "@types/cors": "^2.8.17" }, "devDependencies": { "@mikro-orm/cli": "^6.4.6", diff --git a/backend/src/app.ts b/backend/src/app.ts index 521c40c5..250a6ebe 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -10,13 +10,13 @@ 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"; +import cors from "./middleware/cors"; const app: Express = express(); const port: string | number = getNumericEnvVar(EnvVars.Port); - // TODO Replace with Express routes app.get('/', (_, res: Response) => { res.json({ @@ -25,6 +25,7 @@ app.get('/', (_, res: Response) => { }); app.use(authenticateUser); +app.use(cors); app.use('/student', studentRouter); app.use('/group', groupRouter); @@ -32,8 +33,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); async function startServer() { diff --git a/backend/src/controllers/auth.ts b/backend/src/controllers/auth.ts new file mode 100644 index 00000000..800c3b99 --- /dev/null +++ b/backend/src/controllers/auth.ts @@ -0,0 +1,33 @@ +import {EnvVars, getEnvVar} from "../util/envvars"; + +type FrontendAuthConfig = { + student: FrontendIdpConfig, + teacher: FrontendIdpConfig +} + +type FrontendIdpConfig = { + authority: string, + clientId: string, + scope: string, + responseType: string +} + +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 + }, + }; +} diff --git a/backend/src/middleware/auth/auth.ts b/backend/src/middleware/auth/auth.ts index 0bf63e3d..d06e6df2 100644 --- a/backend/src/middleware/auth/auth.ts +++ b/backend/src/middleware/auth/auth.ts @@ -58,7 +58,6 @@ const verifyJwtToken = expressjwt({ * Get an object with information about the authenticated user from a given authenticated request. */ function getAuthenticationInfo(req: AuthenticatedRequest): AuthenticationInfo | undefined { - console.log("hi"); if (!req.jwtPayload) { return; } diff --git a/backend/src/middleware/cors.ts b/backend/src/middleware/cors.ts new file mode 100644 index 00000000..e246aadf --- /dev/null +++ b/backend/src/middleware/cors.ts @@ -0,0 +1,6 @@ +import cors from "cors"; +import {EnvVars, getEnvVar} from "../util/envvars"; + +export default cors({ + origin: getEnvVar(EnvVars.CorsAllowedOrigins).split(',') +}); diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts new file mode 100644 index 00000000..87c4183c --- /dev/null +++ b/backend/src/routes/auth.ts @@ -0,0 +1,10 @@ +import express from 'express' +import {getFrontendAuthConfig} from "../controllers/auth"; +const router = express.Router(); + +// returns auth configuration for frontend +router.get('/config', (req, res) => { + res.json(getFrontendAuthConfig()); +}); + +export default router; diff --git a/backend/src/routes/login.ts b/backend/src/routes/login.ts deleted file mode 100644 index 550e6d93..00000000 --- a/backend/src/routes/login.ts +++ /dev/null @@ -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 \ No newline at end of file diff --git a/backend/src/util/envvars.ts b/backend/src/util/envvars.ts index 2dfcf640..60aa8025 100644 --- a/backend/src/util/envvars.ts +++ b/backend/src/util/envvars.ts @@ -15,10 +15,13 @@ export const EnvVars: { [key: string]: EnvVar } = { 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' } + IdpAudience: { key: IDP_PREFIX + 'AUDIENCE', defaultValue: 'account' }, + CorsAllowedOrigins: { key: PREFIX + 'CORS_ALLOWED_ORIGINS', defaultValue: ''} } as const; /** diff --git a/frontend/package.json b/frontend/package.json index 2c2c2612..8c6f81d3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 7db110de..c1eb520c 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,4 +1,6 @@ diff --git a/frontend/src/config.ts b/frontend/src/config.ts new file mode 100644 index 00000000..6da56c15 --- /dev/null +++ b/frontend/src/config.ts @@ -0,0 +1,14 @@ +export const authConfig = { + student: { + authority: import.meta.env.VITE_STUDENT_AUTH_AUTHORITY || "https://auth.sel2-1.ugent.be/realms/student", + clientId: import.meta.env.VITE_STUDENT_AUTH_CLIENT_ID || "dwengo", + redirectUri: window.location.origin + "/callback", + scope: import.meta.env.VITE_STUDENT_AUTH_SCOPE || "openid profile email" + }, + teacher: { + authority: import.meta.env.VITE_TEACHER_AUTH_AUTHORITY || "https://auth.sel2-1.ugent.be/realms/teacher", + clientId: import.meta.env.VITE_TEACHER_AUTH_CLIENT_ID || "dwengo", + redirectUri: window.location.origin + "/callback", + scope: import.meta.env.VITE_TEACHER_AUTH_SCOPE || "openid profile email" + } +}; diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 8ce0fe3f..44a3eb52 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -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/discussions/CallbackPage.vue"; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), @@ -29,6 +30,10 @@ const router = createRouter({ name: "LoginPage", component: () => {return import("../views/LoginPage.vue")} }, + { + path: "/callback", + component: CallbackPage + }, { path: "/student/:id", component: MenuBar, diff --git a/frontend/src/services/api-client.ts b/frontend/src/services/api-client.ts new file mode 100644 index 00000000..146ad3c8 --- /dev/null +++ b/frontend/src/services/api-client.ts @@ -0,0 +1,10 @@ +import axios from "axios"; + +const apiClient = axios.create({ + baseURL: window.location.hostname == "localhost" ? "http://localhost:3000" : window.location.origin, + headers: { + "Content-Type": "application/json", + }, +}); + +export default apiClient; diff --git a/frontend/src/services/auth-service.ts b/frontend/src/services/auth-service.ts new file mode 100644 index 00000000..8acc41a1 --- /dev/null +++ b/frontend/src/services/auth-service.ts @@ -0,0 +1,106 @@ +import {User, UserManager} from "oidc-client-ts"; +import apiClient from "@/services/api-client.ts"; + +type FrontendAuthConfig = { + student: FrontendIdpConfig, + teacher: FrontendIdpConfig +} + +type FrontendIdpConfig = { + authority: string, + clientId: string, + scope: string, + responseType: string +} + +export type Role = "student" | "teacher"; +type UserManagersForRoles = {student: UserManager, teacher: UserManager}; + +class AuthService { + constructor(private userManagers: UserManagersForRoles) {} + + public async loginAs(role: Role) { + // Storing it in local storage so that it won't be lost when redirecting outside of the app. + this.setActiveRole(role); + await this.userManagers[role].signinRedirect(); + } + + public async logout() { + const activeRole = this.getActiveRole(); + if (activeRole) { + await this.userManagers[activeRole].signoutRedirect(); + this.deleteActiveRole(); + } + } + + public async getUser(): Promise { + const activeRole = this.getActiveRole(); + if (!activeRole) { + return null; + } + return await this.userManagers[activeRole].getUser(); + } + + public async getAccessToken(): Promise { + const user = await this.getUser(); + return user?.access_token || null; + } + + async renewToken() { + const activeRole = this.getActiveRole(); + if (!activeRole) { + throw new Error("Can't renew the token: Not logged in!"); + } + return this.userManagers[activeRole].signinSilent(); + } + + public getActiveRole(): Role | undefined { + return localStorage.getItem("activeRole") as Role | undefined; + } + + public async handleRedirectCallback(): Promise { + const activeRole = this.getActiveRole(); + if (!activeRole) { + throw new Error("Can't renew the token: Not logged in!"); + } + return this.userManagers[activeRole].signinCallback(); + } + + private setActiveRole(role: Role) { + localStorage.setItem("activeRole", role); + } + + private deleteActiveRole() { + localStorage.removeItem("activeRole"); + } +} + +async function initAuthService() { + const authConfig = await apiClient.get("auth/config").then(it => it.data); + + const oidcConfig = { + 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, + } + }; + + return new AuthService({ + student: new UserManager(oidcConfig.student), + teacher: new UserManager(oidcConfig.teacher) + }); +} + +export default await initAuthService(); diff --git a/frontend/src/store/auth-store.ts b/frontend/src/store/auth-store.ts new file mode 100644 index 00000000..0609fa0b --- /dev/null +++ b/frontend/src/store/auth-store.ts @@ -0,0 +1,40 @@ +import {computed, reactive} from "vue"; +import authService, {type Role} from "@/services/auth-service.ts"; +import type {User} from "oidc-client-ts"; + +type AuthState = { + user: User | null, + accessToken: string | null, + activeRole: Role | null +}; + +export const authState = reactive({ + user: null, + accessToken: null, + activeRole: authService.getActiveRole() || null +}); + +export const isLoggedIn = computed(() => authState.user !== null); + +export async function loadUser(): Promise { + const user = await authService.getUser(); + authState.user = user; + authState.accessToken = user?.access_token || null; + authState.activeRole = authService.getActiveRole() || null; +} + +export async function handleLoginCallback(): Promise { + console.log("Hallooo"); + authState.user = await authService.handleRedirectCallback() || null; +} + +export async function loginAs(role: Role): Promise { + await authService.loginAs(role); +} + +export async function logout(): Promise { + await authService.logout(); + authState.user = null; + authState.accessToken = null; + authState.activeRole = null; +} diff --git a/frontend/src/views/HomePage.vue b/frontend/src/views/HomePage.vue index 677f16f0..d2b3085b 100644 --- a/frontend/src/views/HomePage.vue +++ b/frontend/src/views/HomePage.vue @@ -1,10 +1,15 @@ - Welcome to the dwengo homepage + + Welcome to the dwengo homepage + + Hello {{authState.user?.profile.name}}! + Your access token for the backend is: {{authState.user?.access_token}} + diff --git a/package-lock.json b/package-lock.json index 50b2a6d4..415b6c9b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,9 @@ "@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", "dotenv": "^16.4.7", "express": "^5.0.1", "express-jwt": "^8.5.1", @@ -86,6 +88,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" @@ -1375,6 +1379,15 @@ "@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==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/eslint-config-prettier": { "version": "6.11.3", "dev": true, @@ -2272,9 +2285,19 @@ }, "node_modules/asynckit": { "version": "0.4.0", - "dev": true, "license": "MIT" }, + "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", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "license": "MIT" @@ -2761,7 +2784,6 @@ }, "node_modules/combined-stream": { "version": "1.0.8", - "dev": true, "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" @@ -2846,6 +2868,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, @@ -3004,7 +3039,6 @@ }, "node_modules/delayed-stream": { "version": "1.0.0", - "dev": true, "license": "MIT", "engines": { "node": ">=0.4.0" @@ -3239,7 +3273,6 @@ }, "node_modules/es-set-tostringtag": { "version": "2.1.0", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -3914,6 +3947,26 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreground-child": { "version": "3.3.0", "dev": true, @@ -3931,7 +3984,6 @@ }, "node_modules/form-data": { "version": "4.0.2", - "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -3945,7 +3997,6 @@ }, "node_modules/form-data/node_modules/mime-db": { "version": "1.52.0", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -3953,7 +4004,6 @@ }, "node_modules/form-data/node_modules/mime-types": { "version": "2.1.35", - "dev": true, "license": "MIT", "dependencies": { "mime-db": "1.52.0" @@ -4276,7 +4326,6 @@ }, "node_modules/has-tostringtag": { "version": "1.0.2", - "dev": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -4929,6 +4978,15 @@ "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, @@ -5839,6 +5897,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", @@ -5849,6 +5916,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", @@ -6397,6 +6476,12 @@ "node": ">= 0.10" } }, + "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": { "version": "3.0.2", "license": "MIT",
Hello {{authState.user?.profile.name}}!
Your access token for the backend is: {{authState.user?.access_token}}
{{authState.user?.access_token}}