Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/adapter-neo4j/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export function Neo4jAdapter(session: Session): Adapter {

return {
async createUser(data) {
const user = { id: crypto.randomUUID(), ...data }
const user = { ...data, id: crypto.randomUUID() }
await write(`CREATE (u:User $data)`, user)
return user
},
Expand Down
7 changes: 5 additions & 2 deletions packages/adapter-typeorm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,6 @@ export function TypeORMAdapter(
const m = await getManager(c)
await m.connection.close()
},
// @ts-expect-error
createUser: async (data) => {
const m = await getManager(c)
const user = await m.save(UserEntityName, data)
Expand Down Expand Up @@ -382,7 +381,11 @@ export function TypeORMAdapter(
},
async updateSession(data) {
const m = await getManager(c)
await m.update(SessionEntityName, { sessionToken: data.sessionToken }, data)
await m.update(
SessionEntityName,
{ sessionToken: data.sessionToken },
data
)
// TODO: Try to return?
return null
},
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/adapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export interface VerificationToken {
* :::
*/
export interface Adapter {
createUser?(user: Omit<AdapterUser, "id">): Awaitable<AdapterUser>
createUser?(user: AdapterUser): Awaitable<AdapterUser>
getUser?(id: string): Awaitable<AdapterUser | null>
getUserByEmail?(email: string): Awaitable<AdapterUser | null>
/** Using the provider id and the id of the user for a specific account, get the user. */
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/lib/actions/callback/handle-login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,8 @@ export async function handleLoginOrRegister(
user = await updateUser({ id: userByEmail.id, emailVerified: new Date() })
await events.updateUser?.({ user })
} else {
const { id: _, ...newUser } = { ...profile, emailVerified: new Date() }
// Create user account if there isn't one for the email address already
user = await createUser(newUser)
user = await createUser({ ...profile, emailVerified: new Date() })
await events.createUser?.({ user })
isNewUser = true
}
Expand Down Expand Up @@ -217,8 +216,7 @@ export async function handleLoginOrRegister(
// If no account matching the same [provider].id or .email exists, we can
// create a new account for the user, link it to the OAuth account and
// create a new session for them so they are signed in with it.
const { id: _, ...newUser } = { ...profile, emailVerified: null }
user = await createUser(newUser)
user = await createUser({ ...profile, emailVerified: null })
}
await events.createUser?.({ user })

Expand Down
10 changes: 7 additions & 3 deletions packages/core/src/lib/actions/callback/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export async function callback(
if (invalidInvite) throw new Verification({ hasInvite, expired })

const user = (await adapter!.getUserByEmail(identifier)) ?? {
id: identifier,
id: crypto.randomUUID(),
email: identifier,
emailVerified: null,
}
Expand Down Expand Up @@ -296,11 +296,15 @@ export async function callback(
Object.entries(query ?? {}).forEach(([k, v]) =>
url.searchParams.set(k, v)
)
const user = await provider.authorize(
const userFromAuthorize = await provider.authorize(
credentials,
// prettier-ignore
new Request(url, { headers, method, body: JSON.stringify(body) })
)
const user = userFromAuthorize && {
...userFromAuthorize,
id: userFromAuthorize?.id?.toString() ?? crypto.randomUUID(),
}

if (!user) throw new CredentialsSignin()

Expand All @@ -319,7 +323,7 @@ export async function callback(
name: user.name,
email: user.email,
picture: user.image,
sub: user.id?.toString(),
sub: user.id,
}

const token = await callbacks.jwt({
Expand Down
15 changes: 7 additions & 8 deletions packages/core/src/lib/actions/callback/oauth/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
Profile,
RequestInternal,
TokenSet,
User,
} from "../../../../types.js"
import type { OAuthConfigInternal } from "../../../../providers/index.js"
import type { Cookie } from "../../../utils/cookie.js"
Expand Down Expand Up @@ -193,14 +194,12 @@ async function getUserAndAccount(
logger: LoggerInstance
) {
try {
const user = await provider.profile(OAuthProfile, tokens)
user.email = user.email?.toLowerCase()

if (!user.id) {
throw new TypeError(
`User id is missing in ${provider.name} OAuth profile response`
)
}
const userFromProfile = await provider.profile(OAuthProfile, tokens)
const user = {
...userFromProfile,
id: userFromProfile.id?.toString() ?? crypto.randomUUID(),
email: userFromProfile.email?.toLowerCase(),
} satisfies User

return {
user,
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/lib/actions/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ export async function session(
// By default, only exposes a limited subset of information to the client
// as needed for presentation purposes (e.g. "you are logged in as...").
session: {
// @ts-expect-error missing `id`.
user: { name: user.name, email: user.email, image: user.image },
expires: session.expires.toISOString(),
},
Expand Down
17 changes: 9 additions & 8 deletions packages/core/src/lib/actions/signin/send-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { AuthorizedCallbackError } from "../../../errors.js"

import type { InternalOptions, RequestInternal } from "../../../types.js"
import type { Account } from "../../../types.js"
import type { AdapterUser } from "../../../adapters.js"

/**
* Starts an e-mail login flow, by generating a token,
Expand All @@ -19,21 +18,23 @@ export async function sendToken(
const normalizer = provider.normalizeIdentifier ?? defaultNormalizer
const email = normalizer(body?.email)

const defaultUser = { id: email, email, emailVerified: null }
const user = ((await adapter!.getUserByEmail(email)) ??
defaultUser) satisfies AdapterUser
const defaultUser = { id: crypto.randomUUID(), email, emailVerified: null }
const user = (await adapter!.getUserByEmail(email)) ?? defaultUser

const account: Account = {
const account = {
providerAccountId: email,
userId: user.id,
type: "email",
provider: provider.id,
}
} satisfies Account

let authorized
try {
const params = { user, account, email: { verificationRequest: true } }
authorized = await callbacks.signIn(params)
authorized = await callbacks.signIn({
user,
account,
email: { verificationRequest: true },
})
} catch (e) {
throw new AuthorizedCallbackError(e as Error)
}
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/providers/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ export interface OAuth2Config<Profile>
export interface OIDCConfig<Profile>
extends Omit<OAuth2Config<Profile>, "type" | "checks"> {
type: "oidc"
checks?: Array<(Exclude<OAuth2Config<Profile>["checks"], undefined>)[number] | "nonce">
checks?: Array<
Exclude<OAuth2Config<Profile>["checks"], undefined>[number] | "nonce"
>
}

export type OAuthConfig<Profile> = OIDCConfig<Profile> | OAuth2Config<Profile>
Expand Down
23 changes: 14 additions & 9 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,18 @@ export interface CallbacksOptions<P = Profile, A = Account> {
*/
session: (
params:
| {
session: Session
/** Available when {@link AuthConfig.session} is set to `strategy: "jwt"` */
token: JWT
/** Available when {@link AuthConfig.session} is set to `strategy: "database"`. */
user: AdapterUser
} & {
| (
| {
session: Session
/** Available when {@link AuthConfig.session} is set to `strategy: "database"`. */
user: AdapterUser
}
| {
session: Session
/** Available when {@link AuthConfig.session} is set to `strategy: "jwt"` */
token: JWT
}
) & {
/**
* Available when using {@link AuthConfig.session} `strategy: "database"` and an update is triggered for the session.
*
Expand All @@ -264,7 +269,7 @@ export interface CallbacksOptions<P = Profile, A = Account> {
* :::
*/
newSession: any
trigger: "update"
trigger?: "update"
}
) => Awaitable<Session | DefaultSession>
/**
Expand Down Expand Up @@ -461,7 +466,7 @@ export interface Session extends DefaultSession {}
* [`profile` OAuth provider callback](https://authjs.dev/guides/providers/custom-provider)
*/
export interface User {
id: string
id?: string
name?: string | null
email?: string | null
image?: string | null
Expand Down
1 change: 1 addition & 0 deletions packages/next-auth/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ async function getSession(headers: Headers, config: NextAuthConfig) {
const session =
// If the user defined a custom session callback, use that instead
(await config.callbacks?.session?.(...args)) ?? args[0].session
// @ts-expect-error either user or token will be defined
const user = args[0].user ?? args[0].token
return { user, ...session } satisfies Session
},
Expand Down
3 changes: 2 additions & 1 deletion packages/utils/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ export async function runBasicTests(options: TestOptions) {
await options.db.disconnect?.()
})

let user: any = options.fixtures?.user ?? {
let user = options.fixtures?.user ?? {
id: id(),
email: "[email protected]",
image: "https://www.fillmurray.com/460/300",
name: "Fill Murray",
Expand Down