Giter Site home page Giter Site logo

Comments (19)

MacFJA avatar MacFJA commented on August 12, 2024 1

Yes.
The module have been written on an old version of SvelteKit.

I need to update it to match newer version of SvelteKit.
I will try to do it next week

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024 1

@netcodedev I just release the version 2.0.0.

It's now fully compatible with the latest versions of SvelteKit (from version 1.0.0-next.492 to the latest)

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

@MacFJA thank you for updating. Since the update I get the following error:

Error: Cannot find module './utils'
Require stack:
- /mnt/dev/dev/Uni/Bachelorpraktikum/ThesisPortal/node_modules/@macfja/sveltekit-session/index.cjs
    at Module._resolveFilename (node:internal/modules/cjs/loader:985:15)
    at Function.<anonymous> (file:///mnt/dev/dev/Uni/Bachelorpraktikum/ThesisPortal/node_modules/vite/dist/node/chunks/dep-5605cfa4.js:53408:24)
    at Function.Module._load (node:internal/modules/cjs/loader:833:27)
    at Module.require (node:internal/modules/cjs/loader:1057:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/mnt/dev/dev/Uni/Bachelorpraktikum/ThesisPortal/node_modules/@macfja/sveltekit-session/index.cjs:3:13)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

What is the result of npm list @macfja/sveltekit-session ?

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024
└─┬ @macfja/[email protected]
  └── @macfja/[email protected]

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

@MacFJA I'm kind of in a hurry. Do you think you can fix this until Mid January? (The earlier the better)

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

I will publish a new version of @macfja/sveltekit-session that will fix the issue

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

I just release a new version of @macfja/sveltekit-session (1.1.0)
Can you try with the updated version ?

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

I updated everything to the latest version
Now i get the following error:

TypeError: Cannot read properties of undefined (reading 'sessionHook')

The code: (error comes from the line with sessionHook()

export const handle = sequence(
	sessionHook(),
	casHandler(
		`${CAS_HOST}:${CAS_PORT}`,
		CAS_VERSION,
		(event) => event.url.pathname.startsWith("/profile/"),
		(event, user) => {
			const regexp = event.url.pathname.match(/\/profile\/(\w+)/)
			return user !== regexp[1]
		}
	)
)

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

@MacFJA
I changed my code according to the example you provided in the casHandler-documentation:

import { serverHook } from "@macfja/sveltekit-session"
import { casHandler } from "@macfja/sveltekit-cas"
import { sequence } from "@sveltejs/kit/hooks"
import { CAS_HOST, CAS_PORT, CAS_VERSION } from '$env/static/private'

export const handle = sequence(
	serverHook, 
	casHandler(
		`${CAS_HOST}:${CAS_PORT}`,
		CAS_VERSION,
		(event) => event.url.pathname.startsWith("/profile/"),
		(event, user) => {
			const regexp = event.url.pathname.match(/\/profile\/(\w+)/)
			return user !== regexp[1]
		}
	)
)

Now it doesnt find the casHandler:

TypeError: Cannot read properties of undefined (reading 'casHandler')

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

I found the issue.
The CommonJS generation is wrong and seem to don't export anything.

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

I just release a new version (2.0.1).
Hopefully it solves the issue

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

Some things seem to work now.
As soon as i get redirected from the SSO i get the next error:

Invalid character in entity name
Line: 29
Column: 207
Char:  
Error: Invalid character in entity name
Line: 29
Column: 207
Char:  
    at error (<projectdir>/node_modules/sax/lib/sax.js:651:10)
    at strictFail (<projectdir>/node_modules/sax/lib/sax.js:677:7)
    at SAXParser.write (<projectdir>/node_modules/sax/lib/sax.js:1491:13)
    at Object.module.exports [as xml2js] (<projectdir>/node_modules/xml-js/lib/xml2js.js:346:12)
    at <projectdir>/node_modules/@macfja/sveltekit-cas/dist/index.cjs:1:1289
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

Look like the response from the ticket validation is not a valid XML 🤔

Can you replace the content of the file node_modules/@macfja/sveltekit-cas/dist/index.cjs with:

var xmlJs = require('xml-js');
function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}
const getCasHelper = (root, version, event) => {
    return {
        getValidationUrl(ticket) {
            let validationPath = "";
            switch (version) {
                case 2:
                    validationPath = "serviceValidate";
                    break;
                case 3:
                    validationPath = "p3/serviceValidate";
            }
            return `${root}/cas/${validationPath}?service=${encodeURI(this.sanitizedService())}&ticket=${ticket}`;
        },
        getLoginUrl() {
            return root + "/cas/login?service=" + encodeURI(this.sanitizedService());
        },
        sanitizedService() {
            const newUrl = new URL(event.url);
            if (newUrl.pathname.endsWith("/__data.json")) {
                newUrl.pathname = newUrl.pathname.substring(0, newUrl.pathname.length - "/__data.json".length);
            }
            newUrl.searchParams.delete("ticket");
            newUrl.searchParams.delete("x-sveltekit-invalidated");
            return newUrl.toString();
        }
    };
};
function getTicket(event) {
    if (!event.url.searchParams.has("ticket"))
        return undefined;
    const ticket = event.url.searchParams.get("ticket");
    return ticket.startsWith("ST-") ? ticket : undefined;
}
function redirect(url) {
    return new Response(null, {
        status: 301,
        headers: {
            location: url
        }
    });
}
function casHandler(casRoot, casVersion, authRequired = () => true, rejectAccess = () => false) {
    return function (input) {
        if (!authRequired(input.event)) {
            return input.resolve(input.event);
        }
        if (input.event.locals.session.cas) {
            if (rejectAccess(input.event, input.event.locals.session.cas)) {
                return new Response(null, {
                    status: 403
                });
            }
            return input.resolve(input.event);
        }
        switch (casVersion) {
            case 2:
                return cas23Hook(casRoot, 2, input.event);
            case 3:
            default:
                return cas23Hook(casRoot, 3, input.event);
        }
    };
}
function cas23Hook(casRoot, version, event) {
    return __awaiter(this, void 0, void 0, function* () {
        const casHelper = getCasHelper(casRoot, version, event);
        let ticket;
        if ((ticket = getTicket(event)) !== undefined) {
            const validation = yield event
                .fetch(casHelper.getValidationUrl(ticket))
                .then((response) => response.text())
                .then((response) => { console.log(response); return response })
                .then((response) => xmlJs.xml2js(response, { compact: true }));
            if (!Object.keys(validation).includes("serviceResponse")) {
                console.error("Unknown CAS validation response", casHelper.getValidationUrl(ticket), xmlJs.js2xml(validation));
                return new Response("Unknown CAS validation response", { status: 500 });
            }
            if (Object.keys(validation.serviceResponse).includes("authenticationFailure")) {
                return new Response(`Authentication failure: ${validation.serviceResponse.authenticationFailure._text}`, { status: 403 });
            }
            if (Object.keys(validation.serviceResponse).includes("authenticationSuccess")) {
                event.locals.session.cas = {
                    user: validation.serviceResponse.authenticationSuccess.user
                        ._text,
                    attributes: validation.serviceResponse.authenticationSuccess
                        .attributes
                };
                return redirect(casHelper.sanitizedService());
            }
            return new Response("Unknown CAS validation response", { status: 500 });
        }
        return redirect(casHelper.getLoginUrl());
    });
}
function getUsername(event) {
    var _a, _b;
    return (_b = (_a = event.locals.session) === null || _a === void 0 ? void 0 : _a.cas) === null || _b === void 0 ? void 0 : _b.user;
}
exports.casHandler = casHandler;
exports.getUsername = getUsername;

(Almost the same version as now, but not minified, without CAS version 1 and with a log added)

And see if the response is an XML and a valid XML

( ⚠️ Be careful if you share the content of the XML, as it can contain personal data! ⚠️ )

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

I replaced the content and now im not getting an error. But also no cookie is getting set and the ticket is not removed from the url
EDIT: played around a little and it seems like getTicket returns undefined
EDIT2: event.url reveals that searchParams is empty although the url contains the ticket. Maybe it gets called to early? href is still on the protected route /profile

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

I replaced the content and now im not getting an error. But also no cookie is getting set and the ticket is not removed from the url
EDIT: played around a little and it seems like getTicket returns undefined
EDIT2: event.url reveals that searchParams is empty although the url contains the ticket. Maybe it gets called to early? href is still on the protected route /profile

Are you sure that the URL you see and the URL in event.url are the same ? There are several redirections that are done, so maybe you don't have the right one.

Also, the default configuration of @macfja/sveltekit-session don't work with serveless, as its default storage is the server memory

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

Do You maybe have some time to fix it via discord?

from sveltekit-cas.

MacFJA avatar MacFJA commented on August 12, 2024

Do You maybe have some time to fix it via discord?

You can open a question on Svelte Discord, either in svelte-and-kit or ecosystem

We can start from there

from sveltekit-cas.

netcodedev avatar netcodedev commented on August 12, 2024

I just opened a thread
https://discord.com/channels/457912077277855764/1023340103071965194/threads/1061696138866077766

from sveltekit-cas.

Related Issues (1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.