Skip to content

Commit

Permalink
Update createSession() and createKey() (#772)
Browse files Browse the repository at this point in the history
  • Loading branch information
pilcrowonpaper authored Jun 25, 2023
1 parent d48f7ed commit 1a34f2d
Show file tree
Hide file tree
Showing 19 changed files with 201 additions and 141 deletions.
6 changes: 6 additions & 0 deletions .auri/$1y6p4pf3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "lucia" # package name
type: "major" # "major", "minor", "patch"
---

Update `Auth.createSession()` params
6 changes: 6 additions & 0 deletions .auri/$5x4qpfml.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "lucia" # package name
type: "major" # "major", "minor", "patch"
---

Update `Auth.createKey()` params
6 changes: 6 additions & 0 deletions .auri/$k0r7njuv.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "lucia" # package name
type: "major" # "major", "minor", "patch"
---

Remove `generateUserId()` configuration
6 changes: 6 additions & 0 deletions .auri/$kbvxwfic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "@lucia-auth/oauth" # package name
type: "major" # "major", "minor", "patch"
---

Update `ProviderUserAuth.createUser()` params
6 changes: 6 additions & 0 deletions .auri/$lnise28p.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
package: "lucia" # package name
type: "major" # "major", "minor", "patch"
---

Add optional `userId` to `Auth.createUser()` params
15 changes: 0 additions & 15 deletions documentation-v2/content/main/basics/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ type Configuration = {
// optional
allowedRequestOrigins: string[];
csrfProtection?: boolean;
generateUserId?: () => MaybePromise<string>;
getSessionAttributes?: (databaseSession: SessionSchema) => Record<any, any>;
getUserAttributes?: (databaseUser: UserSchema) => Record<any, any>;
middleware?: Middleware<any>;
Expand Down Expand Up @@ -97,20 +96,6 @@ Enabled by default. When enabled, [`AuthRequest.validate()`](/reference/lucia/in
| `true` | CSRF protection enabled |
| `false` | CSRF protection disabled |

### `generateUserId()`

Generated a random user id. By default, user ids are 15 characters long.

```ts
const generateUserId: () => MaybePromise<string>;
```

##### Returns

| type | description |
| -------- | ----------- |
| `string` | A user id |

### `getSessionAttributes()`

Generates session attributes for the user. The returned properties will be included in [`Session`](/reference/lucia/interfaces#session) as is.
Expand Down
3 changes: 1 addition & 2 deletions documentation-v2/content/main/basics/handle-requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ const authRequest = auth.handleRequest();
const session = authRequest.validate();
authRequest.setSession(session);

const session = authRequest.validateBearerToken(); // renew
const session = authRequest.renewBearerToken(); // renew session stored in bearer token
const session = authRequest.validateBearerToken();
```

However, every framework and runtime has their own representation of an incoming request and outgoing response, such as the web standard `Request`/`Response` and Node.js' `IncomingMessage`/`OutgoingMessage`. Lucia uses its own implementation of `RequestContext` as well, which is the default parameter type of `Auth.handleRequest()`. Since this is an annoying problem that is easy to solve, Lucia provides _middleware_.
Expand Down
8 changes: 5 additions & 3 deletions documentation-v2/content/main/basics/keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ import { auth } from "./lucia.js";
import { LuciaError } from "lucia";

try {
const key = await auth.createKey(userId, {
const key = await auth.createKey({
userId,
providerId: "email",
providerUserId: "[email protected]",
password: "123456"
Expand All @@ -64,7 +65,8 @@ try {
```

```ts
const key = await auth.createKey(userId, {
const key = await auth.createKey({
userId,
providerId: "github",
providerUserId: githubUserId,
password: null // a value must be provided
Expand All @@ -82,7 +84,7 @@ import { auth } from "./lucia.js";
import { LuciaError } from "lucia";

try {
const user await auth.createUser({
const user = await auth.createUser({
key: {
providerId,
providerUserId,
Expand Down
10 changes: 7 additions & 3 deletions documentation-v2/content/main/basics/sessions.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,17 @@ const { sessionId, createdAt } = session;

## Create sessions

[`Auth.createSession()`](/reference/lucia/interfaces/auth#createsession) can be used to create a new session. It takes a user id and returns the newly created session. If the user id is invalid, it will throw `AUTH_INVALID_USER_ID`.
[`Auth.createSession()`](/reference/lucia/interfaces/auth#createsession) can be used to create a new session. It takes a user id and the attributes (empty for default configuration), and returns the newly created session. If the user id is invalid, it will throw `AUTH_INVALID_USER_ID`.

```ts
import { auth } from "./lucia.js";
import { LuciaError } from "lucia";

try {
const session = await auth.createSession(userId);
const session = await auth.createSession({
userId,
attributes: {} // expects `Lucia.DatabaseSessionAttributes`
});
const sessionCookie = auth.createSessionCookie(session);
setSessionCookie(session);
} catch (e) {
Expand All @@ -83,7 +86,8 @@ import { auth } from "./lucia.js";
import { LuciaError } from "lucia";

try {
const session = await auth.createSession(userId, {
const session = await auth.createSession({
userId,
attributes: {
created_at: new Date()
} // expects `Lucia.DatabaseSessionAttributes`
Expand Down
19 changes: 16 additions & 3 deletions documentation-v2/content/main/basics/users.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const user = {

#### User id

The primary way to identify users is by their user id. It's randomly generated by Lucia and it's 15 characters long. You can of course configure it to [generate your own user id](/basics/configuration#generateuserid).
The primary way to identify users is by their user id. It's randomly generated by Lucia and it's 15 characters long. You can pass a custom user id when creating a user as well.

#### User attributes

Expand Down Expand Up @@ -84,6 +84,17 @@ await auth.createUser({

If the user attributes provided violates a database rule (such a unique constraint), Lucia will throw the database/driver/ORM error instead of a regular `LuciaError`. For example, if you're using Prisma, Lucia will throw a Prisma error.

### Custom user id

You can use your own user id by passing `userId` to [`Auth.createUser()`](/reference/lucia/interfaces/auth#createuser).

```ts
await auth.createUser({
userId: generateCustomUserId(),
attributes: {}
});
```

## Get user

You can get users by their user id with [`Auth.getUser()`](/reference/lucia/interfaces/auth#getuser).
Expand Down Expand Up @@ -125,7 +136,10 @@ const user = await auth.updateUserAttributes(userId, {
role: "admin" // new privileges
});
await auth.invalidateAllUserSessions(user.userId); // invalidate all user sessions => logout all sessions
const session = await auth.createSession(user.userId); // new session
const session = await auth.createSession({
userId: user.userId,
attributes: {}
}); // new session
// store new session
```

Expand All @@ -143,5 +157,4 @@ await auth.deleteUser(userId);

You can configure users in a few ways:

- User id with [`generateUserId()`](/basics/configuration#generateuserid)
- User attributes with [`getUserAttributes()`](/basics/configuration#getuserattributes)
10 changes: 6 additions & 4 deletions documentation-v2/content/main/basics/using-bearer-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,12 @@ await Promise([

## Renew bearer tokens

You can renew the bearer token using [`AuthRequest.renewBearerToken()`](/reference/lucia/interfaces/authrequest#renewbearertoken), which returns a session if successful or `null` if the session is invalid.
Bearer tokens can be renewed by [getting them manually](#read-bearer-tokens) and calling [`Auth.renewSession()`]().

```ts
const authRequest = auth.handleRequest();

const renewedSession = await authRequest.renewBearerToken();
const authorizationHeader = request.headers.get("Authorization"); // get authorization header
const sessionId = auth.readBearerToken(authorizationHeader);
if (sessionId) {
const renewedSession = await auth.renewSession(sessionId);
}
```
5 changes: 4 additions & 1 deletion documentation-v2/content/main/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ const user = await auth.createUser({
username
}
});
const session = await auth.createSession(user.userId);
const session = await auth.createSession({
userId: user.userId,
attributes: {} // custom attributes
});
const sessionCookie = auth.createSessionCookie(session);
```

Expand Down
38 changes: 36 additions & 2 deletions documentation-v2/content/main/start-here/migrate-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ const auth = lucia({

// autoDatabaseCleanup: false, <= removed for now
csrfProtection: true, // no change
generateUserId: () => generateRandomString(16), // previously `generateCustomUserId()`
// generateCustomUserId, <= removed
passwordHash, // previously `hash`
allowedRequestOrigins: ["https://foo.example.com"], // previously `origin`
sessionCookie: {
Expand All @@ -138,6 +138,39 @@ const auth = lucia({
});
```

### Use custom user id

While `generateCustomUserId()` configuration has been removed, you can now pass a custom user id to [`Auth.createUser()`]().

```ts
await auth.createUser({
userId: generateCustomUserId(),
attributes: {}
});
```

## Creating sessions and keys

`Auth.createSession()` and `Auth.createKey()` now takes a single parameter.

```ts
// v1
await auth.createSession(userId);
await auth.createKey(userId, {
// ...
});

// v2
await auth.createSession({
userId,
attributes: {} // must be defined!
});
await auth.createKey({
userId
// ...
});
```

## Validating sessions

`Auth.validateSessionUser()` and `AuthRequest.validateUser()` has been removed. The User object can now be accessed via `Session.user`.
Expand Down Expand Up @@ -226,7 +259,8 @@ await auth.createKey(userId, {
});

// v2
await auth.createKey(userId, {
await auth.createKey({
userId,
providerId,
providerUserId,
password
Expand Down
10 changes: 7 additions & 3 deletions documentation-v2/content/oauth/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,18 @@ const getUser = async () => {
if (existingUser) return existingUser;
// create a new user if the user does not exist
return await createUser({
// attributes
username: githubUser.login
attributes: {
username: githubUser.login
}
});
};
const user = await getUser();

// login user
const session = await auth.createSession(user.userId);
const session = await auth.createSession({
userId: user.userId,
attributes: {}
});
const authRequest = await auth.handleRequest();
authRequest.setSession(session); // store session cookie
```
Expand Down
Loading

0 comments on commit 1a34f2d

Please sign in to comment.