-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Apply latest auth changes to the prototype (#1646)
- Loading branch information
Showing
20 changed files
with
315 additions
and
226 deletions.
There are no files selected for viewing
13 changes: 0 additions & 13 deletions
13
examples/todo-typescript/migrations/20240119141512_add_session/migration.sql
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import jwt from 'jsonwebtoken' | ||
import util from 'util' | ||
|
||
import config from 'wasp/core/config' | ||
|
||
const jwtSign = util.promisify(jwt.sign) | ||
const jwtVerify = util.promisify(jwt.verify) | ||
|
||
const JWT_SECRET = config.auth.jwtSecret | ||
|
||
export const signData = (data, options) => jwtSign(data, JWT_SECRET, options) | ||
export const verify = (token) => jwtVerify(token, JWT_SECRET) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,17 @@ | ||
import { removeLocalUserData } from 'wasp/api' | ||
import api, { removeLocalUserData } from 'wasp/api' | ||
import { invalidateAndRemoveQueries } from 'wasp/operations/resources' | ||
|
||
export default async function logout(): Promise<void> { | ||
removeLocalUserData() | ||
// TODO(filip): We are currently invalidating and removing all the queries, but | ||
// we should remove only the non-public, user-dependent ones. | ||
await invalidateAndRemoveQueries() | ||
try { | ||
await api.post('/auth/logout') | ||
} finally { | ||
// Even if the logout request fails, we still want to remove the local user data | ||
// in case the logout failed because of a network error and the user walked away | ||
// from the computer. | ||
removeLocalUserData() | ||
|
||
// TODO(filip): We are currently invalidating and removing all the queries, but | ||
// we should remove only the non-public, user-dependent ones. | ||
await invalidateAndRemoveQueries() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { Lucia } from "lucia"; | ||
import { PrismaAdapter } from "@lucia-auth/adapter-prisma"; | ||
import prisma from '../server/dbClient.js' | ||
import config from 'wasp/core/config' | ||
import { type User } from "../entities/index.js" | ||
|
||
const prismaAdapter = new PrismaAdapter( | ||
// Using `as any` here since Lucia's model types are not compatible with Prisma 4 | ||
// model types. This is a temporary workaround until we migrate to Prisma 5. | ||
// This **works** in runtime, but Typescript complains about it. | ||
prisma.session as any, | ||
prisma.auth as any | ||
); | ||
|
||
/** | ||
* We are using Lucia for session management. | ||
* | ||
* Some details: | ||
* 1. We are using the Prisma adapter for Lucia. | ||
* 2. We are not using cookies for session management. Instead, we are using | ||
* the Authorization header to send the session token. | ||
* 3. Our `Session` entity is connected to the `Auth` entity. | ||
* 4. We are exposing the `userId` field from the `Auth` entity to | ||
* make fetching the User easier. | ||
*/ | ||
export const auth = new Lucia<{}, { | ||
userId: User['id'] | ||
}>(prismaAdapter, { | ||
// Since we are not using cookies, we don't need to set any cookie options. | ||
// But in the future, if we decide to use cookies, we can set them here. | ||
|
||
// sessionCookie: { | ||
// name: "session", | ||
// expires: true, | ||
// attributes: { | ||
// secure: !config.isDevelopment, | ||
// sameSite: "lax", | ||
// }, | ||
// }, | ||
getUserAttributes({ userId }) { | ||
return { | ||
userId, | ||
}; | ||
}, | ||
}); | ||
|
||
declare module "lucia" { | ||
interface Register { | ||
Lucia: typeof auth; | ||
DatabaseSessionAttributes: {}; | ||
DatabaseUserAttributes: { | ||
userId: User['id'] | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import SecurePassword from 'secure-password' | ||
|
||
const SP = new SecurePassword() | ||
|
||
export const hashPassword = async (password: string): Promise<string> => { | ||
const hashedPwdBuffer = await SP.hash(Buffer.from(password)) | ||
return hashedPwdBuffer.toString("base64") | ||
} | ||
|
||
export const verifyPassword = async (hashedPassword: string, password: string): Promise<void> => { | ||
const result = await SP.verify(Buffer.from(password), Buffer.from(hashedPassword, "base64")) | ||
if (result !== SecurePassword.VALID) { | ||
throw new Error('Invalid password.') | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
waspc/data/Generator/templates/sdk/wasp/auth/session.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import { Request as ExpressRequest } from "express"; | ||
|
||
import { type User } from "../entities/index.js" | ||
import { type SanitizedUser } from '../server/_types/index.js' | ||
|
||
import { auth } from "./lucia.js"; | ||
import type { Session } from "lucia"; | ||
import { | ||
throwInvalidCredentialsError, | ||
deserializeAndSanitizeProviderData, | ||
} from "./utils.js"; | ||
|
||
import prisma from '../server/dbClient.js' | ||
|
||
// Creates a new session for the `authId` in the database | ||
export async function createSession(authId: string): Promise<Session> { | ||
return auth.createSession(authId, {}); | ||
} | ||
|
||
export async function getSessionAndUserFromBearerToken(req: ExpressRequest): Promise<{ | ||
user: SanitizedUser | null, | ||
session: Session | null, | ||
}> { | ||
const authorizationHeader = req.headers["authorization"]; | ||
|
||
if (typeof authorizationHeader !== "string") { | ||
return { | ||
user: null, | ||
session: null, | ||
}; | ||
} | ||
|
||
const sessionId = auth.readBearerToken(authorizationHeader); | ||
if (!sessionId) { | ||
return { | ||
user: null, | ||
session: null, | ||
}; | ||
} | ||
|
||
return getSessionAndUserFromSessionId(sessionId); | ||
} | ||
|
||
export async function getSessionAndUserFromSessionId(sessionId: string): Promise<{ | ||
user: SanitizedUser | null, | ||
session: Session | null, | ||
}> { | ||
const { session, user: authEntity } = await auth.validateSession(sessionId); | ||
|
||
if (!session || !authEntity) { | ||
return { | ||
user: null, | ||
session: null, | ||
}; | ||
} | ||
|
||
return { | ||
session, | ||
user: await getUser(authEntity.userId) | ||
} | ||
} | ||
|
||
async function getUser(userId: User['id']): Promise<SanitizedUser> { | ||
const user = await prisma.user | ||
.findUnique({ | ||
where: { id: userId }, | ||
include: { | ||
auth: { | ||
include: { | ||
identities: true | ||
} | ||
} | ||
} | ||
}) | ||
|
||
if (!user) { | ||
throwInvalidCredentialsError() | ||
} | ||
|
||
// TODO: This logic must match the type in _types/index.ts (if we remove the | ||
// password field from the object here, we must to do the same there). | ||
// Ideally, these two things would live in the same place: | ||
// https://github.com/wasp-lang/wasp/issues/965 | ||
const deserializedIdentities = user.auth.identities.map((identity) => { | ||
const deserializedProviderData = deserializeAndSanitizeProviderData( | ||
identity.providerData, | ||
{ | ||
shouldRemovePasswordField: true, | ||
} | ||
) | ||
return { | ||
...identity, | ||
providerData: deserializedProviderData, | ||
} | ||
}) | ||
return { | ||
...user, | ||
auth: { | ||
...user.auth, | ||
identities: deserializedIdentities, | ||
}, | ||
} | ||
} | ||
|
||
export function invalidateSession(sessionId: string): Promise<void> { | ||
return auth.invalidateSession(sessionId); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
// todo(filip): turn into a proper import/path | ||
export type { SanitizedUser as User, ProviderName, DeserializedAuthEntity } from 'wasp/server/_types/' | ||
export type { SanitizedUser as User, ProviderName, DeserializedAuthIdentity } from 'wasp/server/_types/' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.