Skip to content

Commit

Permalink
fix auth session
Browse files Browse the repository at this point in the history
  • Loading branch information
prostgles committed Nov 25, 2024
1 parent 772d027 commit 0e4353e
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 81 deletions.
68 changes: 22 additions & 46 deletions lib/Auth/AuthHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { LocalParams, PRGLIOSocket } from "../DboBuilder/DboBuilder";
import { DBOFullyTyped } from "../DBSchemaBuilder";
import { removeExpressRoute } from "../FileManager/FileManager";
import { DB, DBHandlerServer, Prostgles } from "../Prostgles";
import { Auth, AuthClientRequest, AuthResult, BasicSession, ExpressReq, ExpressRes, LoginClientInfo } from "./AuthTypes"
import { Auth, AuthClientRequest, AuthResult, BasicSession, ExpressReq, ExpressRes, LoginClientInfo, LoginParams } from "./AuthTypes"
import { getSafeReturnURL } from "./getSafeReturnURL";
import { setupAuthRoutes } from "./setupAuthRoutes";
import { getProviders } from "./setAuthProviders";
Expand Down Expand Up @@ -198,7 +198,7 @@ export class AuthHandler {
})
}

loginThrottled = async (params: AnyObject, client: LoginClientInfo): Promise<BasicSession> => {
loginThrottled = async (params: LoginParams, client: LoginClientInfo): Promise<BasicSession> => {
if (!this.opts?.login) throw "Auth login config missing";
const { responseThrottle = 500 } = this.opts;

Expand All @@ -219,6 +219,26 @@ export class AuthHandler {
return result;
}, responseThrottle);

};

loginThrottledAndSetCookie = async (req: ExpressReq, res: ExpressRes, loginParams: LoginParams) => {
const start = Date.now();
const { sid, expires } = await this.loginThrottled(loginParams, getLoginClientInfo({ httpReq: req })) || {};
await this.prostgles.opts.onLog?.({
type: "auth",
command: "login",
duration: Date.now() - start,
sid,
socketId: undefined,
});

if (sid) {

this.setCookieAndGoToReturnURLIFSet({ sid, expires }, { req, res });

} else {
throw ("Internal error: no user or session")
}
}


Expand Down Expand Up @@ -401,50 +421,6 @@ export class AuthHandler {
}
}


/**
* ARE THESE NEEDED?!
*/
// const {
// register,
// logout
// } = this.opts;
// const login = this.loginThrottled
// let handlers: {
// name: keyof Omit<AuthSocketSchema, "user">;
// ch: string;
// func: (...args: any) => any;
// }[] = [
// { func: (params: any, dbo: any, db: DB, client: LoginClientInfo) => register?.(params, dbo, db), ch: CHANNELS.REGISTER, name: "register" as keyof Omit<AuthSocketSchema, "user"> },
// { func: (params: any, dbo: any, db: DB, client: LoginClientInfo) => login(params, client), ch: CHANNELS.LOGIN, name: "login" as keyof Omit<AuthSocketSchema, "user"> },
// { func: (params: any, dbo: any, db: DB, client: LoginClientInfo) => logout?.(this.getSID({ socket }), dbo, db), ch: CHANNELS.LOGOUT, name: "logout" as keyof Omit<AuthSocketSchema, "user">}
// ].filter(h => h.func);


// handlers.map(({ func, ch, name }) => {
// auth[name] = true;

// socket.removeAllListeners(ch)
// socket.on(ch, async (params: any, cb = (..._callback: any) => { /** Empty */ }) => {

// try {
// if (!socket) throw "socket missing??!!";
// const id_address = (socket as any)?.conn?.remoteAddress;
// const user_agent = socket.handshake?.headers?.["user-agent"];
// const res = await func(params, this.dbo as any, this.db, { user_agent, id_address });
// if (name === "login" && res && res.sid) {
// /* TODO: Re-send schema to client */
// }

// cb(null, true);

// } catch (err) {
// console.error(name + " err", err);
// cb(err)
// }
// });
// });

const userData = await this.getClientInfo(clientReq);
const auth: AuthSocketSchema = {
providers: getProviders.bind(this)(),
Expand Down
28 changes: 18 additions & 10 deletions lib/Auth/AuthTypes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Express, NextFunction, Request, Response } from "express";
import { AnyObject, EmailSignupType, FieldFilter, UserLike } from "prostgles-types";
import { AnyObject, FieldFilter, UserLike } from "prostgles-types";
import { DB } from "../Prostgles";
import { DBOFullyTyped } from "../DBSchemaBuilder";
import { PRGLIOSocket } from "../DboBuilder/DboBuilderTypes";
Expand Down Expand Up @@ -73,14 +73,7 @@ type RegistrationProviders = ThirdPartyProviders & {
};
}

type RegistrationData =
| {
provider: "email";
profile: {
username: string;
password: string;
}
}
export type AuthProviderUserData =
| {
provider: "google";
profile: GoogleProfile;
Expand All @@ -106,6 +99,16 @@ type RegistrationData =
refreshToken: string;
}

export type RegistrationData =
| {
provider: "email";
profile: {
username: string;
password: string;
}
}
| AuthProviderUserData;

export type AuthRegistrationConfig = RegistrationProviders & {
/**
* Required for social login callback
Expand Down Expand Up @@ -218,7 +221,7 @@ export type Auth<S = void, SUser extends SessionUser = SessionUser> = {
*/
getUser: (sid: string | undefined, dbo: DBOFullyTyped<S>, db: DB, client: AuthClientRequest & LoginClientInfo) => Awaitable<AuthResult<SUser>>;

login?: (params: AnyObject, dbo: DBOFullyTyped<S>, db: DB, client: LoginClientInfo) => Awaitable<BasicSession> | BasicSession;
login?: (params: LoginParams, dbo: DBOFullyTyped<S>, db: DB, client: LoginClientInfo) => Awaitable<BasicSession> | BasicSession;
logout?: (sid: string | undefined, dbo: DBOFullyTyped<S>, db: DB) => Awaitable<any>;

/**
Expand All @@ -228,3 +231,8 @@ export type Auth<S = void, SUser extends SessionUser = SessionUser> = {
getSession: (sid: string | undefined, dbo: DBOFullyTyped<S>, db: DB) => Awaitable<BasicSession>
}
}


export type LoginParams =
| { type: "username"; username: string; password: string; [key: string]: any }
| ({ type: "provider"; } & AuthProviderUserData)
15 changes: 11 additions & 4 deletions lib/Auth/setAuthProviders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AUTH_ROUTES_AND_PARAMS, AuthHandler } from "./AuthHandler";
import type e from "express";
import { RequestHandler } from "express";
import { removeExpressRouteByName } from "../FileManager/FileManager";
import { getErrorAsObject } from "../DboBuilder/dboBuilderUtils";


export const upsertNamedExpressMiddleware = (app: e.Express, handler: RequestHandler, name: string) => {
Expand Down Expand Up @@ -76,7 +77,7 @@ export function setAuthProviders (this: AuthHandler, { registrations, app }: Req
async (accessToken, refreshToken, profile, done) => {
// This callback is where you would normally store or retrieve user info from the database
await onRegister({ provider: providerName as "google", accessToken, refreshToken, profile });
return done(null, profile);
return done(null, profile, { accessToken, refreshToken, profile });
}
)
);
Expand All @@ -87,9 +88,15 @@ export function setAuthProviders (this: AuthHandler, { registrations, app }: Req

app.get(callbackPath,
passport.authenticate(providerName, { session: false, failureRedirect: "/login" }),
(req, res) => {
// Successful authentication, redirect to main page
res.redirect("/");
async (req, res) => {
this.loginThrottledAndSetCookie(req, res, { type: "provider", provider: providerName, ...req.authInfo as any })
.then(() => {
// Successful authentication, redirect to main page
res.redirect("/");
})
.catch((e: any) => {
res.status(500).json(getErrorAsObject(e));
});
}
);
});
Expand Down
40 changes: 23 additions & 17 deletions lib/Auth/setupAuthRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { RequestHandler } from "express";
import { DBOFullyTyped } from "../DBSchemaBuilder";
import { AUTH_ROUTES_AND_PARAMS, AuthHandler, getLoginClientInfo, HTTPCODES } from "./AuthHandler";
import { AuthClientRequest, ExpressReq, ExpressRes } from "./AuthTypes";
import { AuthClientRequest, ExpressReq, ExpressRes, LoginParams } from "./AuthTypes";
import { setAuthProviders, upsertNamedExpressMiddleware } from "./setAuthProviders";

export async function setupAuthRoutes(this: AuthHandler) {
Expand Down Expand Up @@ -74,22 +74,28 @@ export async function setupAuthRoutes(this: AuthHandler) {

app.post(AUTH_ROUTES_AND_PARAMS.login, async (req: ExpressReq, res: ExpressRes) => {
try {
const start = Date.now();
const { sid, expires } = await this.loginThrottled(req.body || {}, getLoginClientInfo({ httpReq: req })) || {};
await this.prostgles.opts.onLog?.({
type: "auth",
command: "login",
duration: Date.now() - start,
sid,
socketId: undefined,
})
if (sid) {

this.setCookieAndGoToReturnURLIFSet({ sid, expires }, { req, res });

} else {
throw ("Internal error: no user or session")
}
// const start = Date.now();
const loginParams: LoginParams = {
type: "username",
...req.body,
};

await this.loginThrottledAndSetCookie(req, res, loginParams);
// const { sid, expires } = await this.loginThrottled(loginParams, getLoginClientInfo({ httpReq: req })) || {};
// await this.prostgles.opts.onLog?.({
// type: "auth",
// command: "login",
// duration: Date.now() - start,
// sid,
// socketId: undefined,
// })
// if (sid) {

// this.setCookieAndGoToReturnURLIFSet({ sid, expires }, { req, res });

// } else {
// throw ("Internal error: no user or session")
// }
} catch (err) {
console.log(err)
res.status(HTTPCODES.AUTH_ERROR).json({ err });
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prostgles-server",
"version": "4.2.144",
"version": "4.2.145",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion tests/server/package-lock.json

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

0 comments on commit 0e4353e

Please sign in to comment.