Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change updateUser to updateSession #855

Merged
merged 3 commits into from
Oct 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ For other comprehensive examples, see the [EXAMPLES.md](./EXAMPLES.md) document.
- [withPageAuthRequired](https://auth0.github.io/nextjs-auth0/modules/helpers_with_page_auth_required.html#withpageauthrequired)
- [withMiddlewareAuthRequired](https://auth0.github.io/nextjs-auth0/modules/helpers_with_middleware_auth_required.html)
- [getSession](https://auth0.github.io/nextjs-auth0/modules/session_get_session.html)
- [updateUser](https://auth0.github.io/nextjs-auth0/modules/session_update_user.html)
- [updateSession](https://auth0.github.io/nextjs-auth0/modules/session_update_session.html)
- [getAccessToken](https://auth0.github.io/nextjs-auth0/modules/session_get_access_token.html)
- [initAuth0](https://auth0.github.io/nextjs-auth0/modules/instance.html)

Expand Down
20 changes: 10 additions & 10 deletions V2_MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Guide to migrating from `1.x` to `2.x`

- [`getSession` now returns a `Promise`](#getsession-now-returns-a-promise)
- [`updateUser` has been added](#updateuser-has-been-added)
- [`updateSession` has been added](#updatesession-has-been-added)
- [`getServerSidePropsWrapper` has been removed](#getserversidepropswrapper-has-been-removed)
- [Profile API route no longer returns a 401](#profile-api-route-no-longer-returns-a-401)
- [The ID token is no longer stored by default](#the-id-token-is-no-longer-stored-by-default)
Expand Down Expand Up @@ -37,7 +37,7 @@ async function myApiRoute(req, res) {
}
```

## `updateUser` has been added
## `updateSession` has been added

### Before

Expand All @@ -48,8 +48,8 @@ Previously your application could make modifications to the session during the l
import { getSession } from '@auth0/nextjs-auth0';

function myApiRoute(req, res) {
const { user } = getSession(req, res);
user.foo = 'bar';
const session = getSession(req, res);
session.foo = 'bar';
res.json({ success: true });
}
// The updated session is serialized and the cookie is updated
Expand All @@ -58,19 +58,19 @@ function myApiRoute(req, res) {

### After

We've introduced a new `updateUser` method which must be explicitly invoked in order to update the session's user.
We've introduced a new `updateSession` method which must be explicitly invoked in order to update the session.

This will immediately serialise the session, write it to the cookie and return a `Promise`.

```js
// /pages/api/update-user
import { getSession, updateUser } from '@auth0/nextjs-auth0';
import { getSession, updateSession } from '@auth0/nextjs-auth0';

async function myApiRoute(req, res) {
const { user } = await getSession(req, res);
const session = await getSession(req, res);
// The session is updated, serialized and the cookie is updated
// everytime you call `updateUser`.
await updateUser(req, res, { ...user, foo: 'bar' });
// everytime you call `updateSession`.
await updateSession(req, res, { ...session, user: { ...session.user, foo: 'bar' } });
res.json({ success: true });
}
```
Expand Down Expand Up @@ -214,7 +214,7 @@ export default handleAuth({
login: async (req, res) => {
try {
await handleLogin(req, res, {
authorizationParams: { connection: 'github' },
authorizationParams: { connection: 'github' }
});
} catch (error) {
// ...
Expand Down
4 changes: 2 additions & 2 deletions src/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ const instance: SignInWithAuth0 = {
getSession() {
throw new Error(serverSideOnly('getSession'));
},
updateUser() {
throw new Error(serverSideOnly('updateUser'));
updateSession() {
throw new Error(serverSideOnly('updateSession'));
},
getAccessToken() {
throw new Error(serverSideOnly('getAccessToken'));
Expand Down
12 changes: 6 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ import {
AccessTokenRequest,
GetAccessTokenResult,
Claims,
updateUserFactory,
UpdateUser
updateSessionFactory,
UpdateSession
} from './session/';
import {
withPageAuthRequiredFactory,
Expand Down Expand Up @@ -88,7 +88,7 @@ export const _initAuth = (params?: ConfigParameters): SignInWithAuth0 & { sessio

// Init Next layer (with next config)
const getSession = sessionFactory(sessionCache);
const updateUser = updateUserFactory(sessionCache);
const updateSession = updateSessionFactory(sessionCache);
const getAccessToken = accessTokenFactory(nextConfig, getClient, sessionCache);
const withApiAuthRequired = withApiAuthRequiredFactory(sessionCache);
const withPageAuthRequired = withPageAuthRequiredFactory(nextConfig.routes.login, () => sessionCache);
Expand All @@ -101,7 +101,7 @@ export const _initAuth = (params?: ConfigParameters): SignInWithAuth0 & { sessio
return {
sessionCache,
getSession,
updateUser,
updateSession,
getAccessToken,
withApiAuthRequired,
withPageAuthRequired,
Expand All @@ -116,7 +116,7 @@ export const _initAuth = (params?: ConfigParameters): SignInWithAuth0 & { sessio
/* c8 ignore start */
const getSessionCache = () => getInstance().sessionCache;
export const getSession: GetSession = (...args) => getInstance().getSession(...args);
export const updateUser: UpdateUser = (...args) => getInstance().updateUser(...args);
export const updateSession: UpdateSession = (...args) => getInstance().updateSession(...args);
export const getAccessToken: GetAccessToken = (...args) => getInstance().getAccessToken(...args);
export const withApiAuthRequired: WithApiAuthRequired = (...args) => getInstance().withApiAuthRequired(...args);
export const withPageAuthRequired: WithPageAuthRequired = withPageAuthRequiredFactory(getLoginUrl(), getSessionCache);
Expand Down Expand Up @@ -174,7 +174,7 @@ export {
WithPageAuthRequired,
SessionCache,
GetSession,
UpdateUser,
UpdateSession,
GetAccessToken,
Session,
Claims,
Expand Down
4 changes: 2 additions & 2 deletions src/instance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GetSession, GetAccessToken, UpdateUser } from './session';
import { GetSession, GetAccessToken, UpdateSession } from './session';
import { WithApiAuthRequired, WithPageAuthRequired } from './helpers';
import { HandleAuth, HandleCallback, HandleLogin, HandleLogout, HandleProfile } from './handlers';
import { ConfigParameters } from './auth0-session';
Expand All @@ -21,7 +21,7 @@ export interface SignInWithAuth0 {
/**
* Append properties to the user.
*/
updateUser: UpdateUser;
updateSession: UpdateSession;

/**
* Access token getter.
Expand Down
2 changes: 1 addition & 1 deletion src/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export {
GetAccessTokenResult
} from './get-access-token';
export { default as SessionCache } from './cache';
export { default as updateUserFactory, UpdateUser } from './update-user';
export { default as updateSessionFactory, UpdateSession } from './update-session';
45 changes: 45 additions & 0 deletions src/session/update-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { IncomingMessage, ServerResponse } from 'http';
import { NextApiRequest, NextApiResponse } from 'next';
import { Session, SessionCache } from '../session';
import { assertReqRes } from '../utils/assert';

/**
* Update the session object. The provided `session` object will replace the existing session.
*
* **Note** you can't use this method to login or logout - you should use the login and logout handlers for this.
* If no session is provided, it doesn't contain a user or the user is not authenticated; this is a no-op.
*
* ```js
* // pages/api/update-user.js
* import { getSession, updateSession } from '@auth0/nextjs-auth0';
*
* export default async function updateSession(req, res) {
* if (req.method === 'PUT') {
* const session = getSession(req, res);
* updateSession(req, res, { ...session, user: { ...user, foo: req.query.foo } });
* res.json({ success: true });
* }
* };
* ```
*
* @category Server
*/
export type UpdateSession = (
req: IncomingMessage | NextApiRequest,
res: ServerResponse | NextApiResponse,
user: Session
) => Promise<void>;

/**
* @ignore
*/
export default function updateSessionFactory(sessionCache: SessionCache): UpdateSession {
return async (req, res, newSession) => {
assertReqRes(req, res);
const session = await sessionCache.get(req, res);
if (!session || !newSession || !newSession.user) {
return;
}
await sessionCache.set(req, res, newSession);
};
}
44 changes: 0 additions & 44 deletions src/session/update-user.ts

This file was deleted.

2 changes: 1 addition & 1 deletion tests/fixtures/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ declare global {
namespace NodeJS {
interface Global {
getSession?: Function;
updateUser?: Function;
updateSession?: Function;
handleAuth?: Function;
withApiAuthRequired?: Function;
withPageAuthRequired?: Function;
Expand Down
6 changes: 3 additions & 3 deletions tests/fixtures/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const setup = async (
handleLogout,
handleProfile,
getSession,
updateUser,
updateSession,
getAccessToken,
withApiAuthRequired,
withPageAuthRequired
Expand All @@ -90,7 +90,7 @@ export const setup = async (
const handlers: Handlers = { onError, callback, login, logout, profile };
global.handleAuth = handleAuth.bind(null, handlers);
global.getSession = getSession;
global.updateUser = updateUser;
global.updateSession = updateSession;
global.withApiAuthRequired = withApiAuthRequired;
global.withPageAuthRequired = (): any => withPageAuthRequired(withPageAuthRequiredOptions);
global.withPageAuthRequiredCSR = withPageAuthRequired;
Expand All @@ -105,7 +105,7 @@ export const teardown = async (): Promise<void> => {
nock.cleanAll();
await stop();
delete global.getSession;
delete global.updateUser;
delete global.updateSession;
delete global.handleAuth;
delete global.withApiAuthRequired;
delete global.withPageAuthRequired;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from 'next';

export default async function sessionHandler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const session = await global.getSession?.(req, res);
const updated = { ...session?.user, ...req.body?.user };
await global.updateUser?.(req, res, updated);
const updated = { ...session, ...req.body?.session };
await global.updateSession?.(req, res, updated);
res.status(200).json(updated);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,25 @@ import { CookieJar } from 'tough-cookie';
describe('update-user', () => {
afterEach(teardown);

test('should update user', async () => {
test('should update session', async () => {
const baseUrl = await setup(withoutApi);
const cookieJar = await login(baseUrl);
const user = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(user).toEqual({ nickname: '__test_nickname__', sub: '__test_sub__' });
await post(baseUrl, '/api/update-user', { cookieJar, body: { user: { foo: 'bar' } } });
const updatedUser = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(updatedUser).toMatchObject({ foo: 'bar' });
await post(baseUrl, '/api/update-session', { cookieJar, body: { session: { foo: 'bar' } } });
const updatedSession = await get(baseUrl, '/api/session', { cookieJar });
expect(updatedSession).toMatchObject({
foo: 'bar',
user: expect.objectContaining({ nickname: '__test_nickname__', sub: '__test_sub__' })
});
});

test('should ignore updates if user is not defined', async () => {
test('should ignore updates if session is not defined', async () => {
const baseUrl = await setup(withoutApi);
const cookieJar = await login(baseUrl);
const user = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(user).toEqual({ nickname: '__test_nickname__', sub: '__test_sub__' });
await post(baseUrl, '/api/update-user', { cookieJar, body: { user: undefined } });
await post(baseUrl, '/api/update-session', { cookieJar, body: { session: undefined } });
const updatedUser = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(updatedUser).toEqual({ nickname: '__test_nickname__', sub: '__test_sub__' });
});
Expand All @@ -30,7 +33,17 @@ describe('update-user', () => {
const baseUrl = await setup(withoutApi);
const cookieJar = new CookieJar();
await expect(get(baseUrl, '/api/auth/me', { cookieJar })).resolves.toBe('');
await post(baseUrl, '/api/update-user', { body: { user: { sub: 'foo' } }, cookieJar });
await post(baseUrl, '/api/update-session', { body: { session: { sub: 'foo' } }, cookieJar });
await expect(get(baseUrl, '/api/auth/me', { cookieJar })).resolves.toBe('');
});

test('should ignore updates if user is not defined in update', async () => {
const baseUrl = await setup(withoutApi);
const cookieJar = await login(baseUrl);
const user = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(user).toEqual({ nickname: '__test_nickname__', sub: '__test_sub__' });
await post(baseUrl, '/api/update-session', { cookieJar, body: { session: { user: undefined } } });
const updatedUser = await get(baseUrl, '/api/auth/me', { cookieJar });
expect(updatedUser).toEqual({ nickname: '__test_nickname__', sub: '__test_sub__' });
});
});