Skip to content

Commit

Permalink
refactor: reorg python and php docs (#730)
Browse files Browse the repository at this point in the history
* refactor: reorg python docs

* docs: improve php content

* docs: improve python content

---------

Co-authored-by: Gao Sun <[email protected]>
  • Loading branch information
darcyYe and gao-sun authored Jul 1, 2024
1 parent f52acc4 commit 5a0177d
Show file tree
Hide file tree
Showing 34 changed files with 360 additions and 229 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ Now, you can test your application:

1. Run your application, you will see the sign-in button.
2. Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
3. After you signed in, you will be redirected back to your application and see the user data with sign-out button.
3. After you signed in, you will be redirected back to your application and see the sign-out button.
4. Click the sign-out button to clear local storage and sign out.
5 changes: 4 additions & 1 deletion docs/quick-starts/fragments/_web-configure-redirect-uris.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import redirectUriFigure from '../assets/web-redirect-uri.png';

export const defaultBaseUrl = 'http://localhost:3000/';
export const defaultRedirectUri = `${defaultBaseUrl}callback`;

#### Configure redirect URIs

Switch to the application details page of Logto Console. Add a Redirect URI <code>{props.redirectUri ?? 'http://localhost:3000/callback'}</code>.

<img alt="Redirect URI in Logto Console" src={redirectUriFigure} width="600px" />

Just like signing in, users should be redirected to Logto for signing out of the shared session. Once finished, it would be great to redirect the user back to your website. For example, add `http://localhost:3000` as the post sign-out redirect URI section.
Just like signing in, users should be redirected to Logto for signing out of the shared session. Once finished, it would be great to redirect the user back to your website. For example, add <code>{defaultBaseUrl}</code> as the post sign-out redirect URI section.

Then click "Save" to save the changes.
25 changes: 19 additions & 6 deletions docs/quick-starts/framework/php/README.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ sidebar_custom_props:
import ApiResourcesDescription from '../../fragments/_api-resources-description.md';
import Checkpoint from '../../fragments/_checkpoint-test-your-application.md';
import FurtherReadings from '../../fragments/_further-readings.md';
import GetUserInfoApis from '../../fragments/_get-user-info-apis.mdx';
import AssumingUrl from '../../fragments/_web-assuming-url.md';
import WebConfigureRedirectUris from '../../fragments/_web-configure-redirect-uris.mdx';
import SignInFlowSummary from '../../fragments/_web-sign-in-flow-summary.mdx';

import GetUserInformation from './_get-user-information.mdx';
import PhpGuideTip from './_guide-tip.md';
import HandleAuthenticationStatus from './_handle-authentication-status.md';
import ImplementCallbackRoute from './_implement-callback-route.md';
import ImplementSignInRoute from './_implement-sign-in-route.mdx';
import ImplementSignOutRoute from './_implement-sign-out-route.mdx';
import InitLogtoClient from './_init-logto-client.mdx';
Expand All @@ -20,7 +24,6 @@ import Prerequisites from './_prerequisites.md';
import ConfigApiResources from './api-resources/_config-api-resources.mdx';
import FetchAccessTokenForApiResources from './api-resources/_fetch-access-token-for-api-resources.mdx';
import FetchOrganizationTokenForUser from './api-resources/_fetch-organization-token-for-user.mdx';
import ScopesAndClaims from './scopes-and-claims/_scopes-and-claims.mdx';

# PHP SDK guide

Expand All @@ -40,6 +43,18 @@ import ScopesAndClaims from './scopes-and-claims/_scopes-and-claims.mdx';

<InitLogtoClient />

### Configure redirect URIs

<SignInFlowSummary />

<AssumingUrl />

<WebConfigureRedirectUris />

### Handle callback

<ImplementCallbackRoute />

### Implement sign-in route

<ImplementSignInRoute />
Expand All @@ -56,11 +71,9 @@ import ScopesAndClaims from './scopes-and-claims/_scopes-and-claims.mdx';

## Get user information

<GetUserInfoApis getIdTokenClaimsApi="GetIdTokenClaims" fetchUserInfoApi="FetchUserInfo" />

<ScopesAndClaims />
<GetUserInformation />

## API resources
## API resources and organizations

<ApiResourcesDescription />

Expand Down
82 changes: 82 additions & 0 deletions docs/quick-starts/framework/php/_get-user-information.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import CodeBlock from '@theme/CodeBlock';

import CliamsNeedNetworkRequest from '../../fragments/_claims-need-network-request.mdx';
import FindUserInfoMissing from '../../fragments/_find-user-info-missing.mdx';
import ScopesAndClaims from '../../fragments/_scopes-and-claims.mdx';
import ScopesAndClaimsIntroduction from '../../fragments/_scopes-claims-introduction.md';

### Display user information

To display the user's information, you can use either the `getIdTokenClaims` method or `fetchUserInfo` method to get user information. While `getIdTokenClaims` returns the user information contains in the ID token, `fetchUserInfo` fetches the user information from the userinfo endpoint.

```php title="index.php"
Route::get('/userinfo', function () {
if ($client->isAuthenticated() === false) {
return "Not authenticated <a href='/sign-in'>Sign in</a>";
}

return (
// Get local ID token claims
json_decode($client->getIdTokenClaims())
. "<br>"
// Fetch user info from Logto userinfo endpoint
json_decode($client->fetchUserInfo())
);
});
```

Our data models are based on [JsonModel](https://github.com/logto-io/php/blob/master/docs/api/classes/Logto/Sdk/Models/JsonModel.md), which is safe to accept undefined keys while encoding or decoding JSON.

Note that a field (claim) with `null` value doesn't mean the field is set. The reason may be the related scope is not requested, or the user doesn't have the field.

For example, if we didn't request the `email` scope when signing in, and the `email` field will be `null`. However, if we requested the `email` scope, the `email` field will be the user's email address if available.

### Request additional claims

<FindUserInfoMissing method="getIdTokenClaims" />

<ScopesAndClaimsIntroduction />

To request additional scopes, you can configure the `scopes` option when initializing the Logto client:

```php title="index.php"
$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-next-line
scopes: ["email", "phone"], // Update per your needs
),
);
```

Alternatively, you can use the `UserScope` enum to add scopes:

```php title="index.php"
// highlight-next-line
use Logto\Sdk\Constants\UserScope;

$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-next-line
scopes: [UserScope::email, UserScope::phone], // Update per your needs
),
);
```

Then the additional claims will be available in the return value of `getIdTokenClaims` or `fetchUserInfo`.

<CliamsNeedNetworkRequest
type="method"
method="fetchUserInfo"
codeSnippet={
<CodeBlock
language="php"
title="index.php"
>{`$client->fetchUserInfo()->custom_data;`}</CodeBlock>
}
/>

### Scopes and claims

<ScopesAndClaims />
1 change: 0 additions & 1 deletion docs/quick-starts/framework/php/_guide-tip.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ This guide will show you how to integrate Logto into your PHP web application.
:::tip

- The [example](https://github.com/logto-io/php/blob/master/samples/index.php) uses Laravel, but the concepts are the same for other frameworks.
- This guide assumes your website is hosted on <code>http://localhost:8080</code>.

:::
19 changes: 2 additions & 17 deletions docs/quick-starts/framework/php/_handle-authentication-status.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,14 @@ In Logto SDK, we can use `$client->isAuthenticated()` to check the authenticatio
We also need to implement a home page for demonstration:

- If the user is not signed in, show a sign-in button;
- If the user is signed in, show some basic information about the user.
- If the user is signed in, show a sign-out button.

```php
Route::get('/', function () {
if ($client->isAuthenticated() === false) {
return "Not authenticated <a href='/sign-in'>Sign in</a>";
}

return (
// Get local ID token claims
json_decode($client->getIdTokenClaims())
. "<br>"
// Fetch user info from Logto userinfo endpoint
json_decode($client->fetchUserInfo())
. "<br><a href='/sign-out'>Sign out</a>"
);
return "<a href='/sign-out'>Sign out</a>";
});
```

Our data models are based on [JsonModel](https://github.com/logto-io/php/blob/master/docs/api/classes/Logto/Sdk/Models/JsonModel.md), which is safe to accept undefined keys while encoding or decoding JSON.

Note that a field (claim) with `null` value doesn't mean the field is set. The reason may be the related scope is not requested, or the user doesn't have the field.

For example, if we didn't request the `email` scope when signing in, and the `email` field will be `null`. However, if we requested the `email` scope, the `email` field will be the user's email address if available.

To learn more about scopes and claims, see [Get user information](#get-user-information).
4 changes: 2 additions & 2 deletions docs/quick-starts/framework/php/_implement-callback-route.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
After the user signs in, Logto will redirect the user to the callback URL you set in the Logto Console. In this example, we use `/sign-in-callback` as the callback URL:
After the user signs in, Logto will redirect the user to the callback URL you set in the Logto Console. In this example, we use `/callback` as the callback URL:

```php
Route::get('/sign-in-callback', function () {
Route::get('/callback', function () {
try {
$client->handleSignInCallback(); // Handle a lot of stuff
} catch (\Throwable $exception) {
Expand Down
48 changes: 18 additions & 30 deletions docs/quick-starts/framework/php/_implement-sign-in-route.mdx
Original file line number Diff line number Diff line change
@@ -1,41 +1,29 @@
import redirectUriFigure from '../../assets/go-redirect-uri.png';
import ConfigureRedirectUri from '../../fragments/_configure-redirect-uri.mdx';
import SignInFlowSummary from '../../fragments/_web-sign-in-flow-summary.mdx';
import CodeBlock from '@theme/CodeBlock';

import ImplementCallbackRoute from './_implement-callback-route.md';
import {
defaultRedirectUri,
defaultBaseUrl,
} from '../../fragments/_web-configure-redirect-uris.mdx';

<SignInFlowSummary />
In your web application, add a route to properly handle the sign-in request from users. For example:

Before you start implementing the sign-in flow, you need to add a redirect URI in the Admin Console for your application.
<CodeBlock language="php">
{`Route::get('/sign-in', function () {
return redirect($client->signIn('${defaultRedirectUri}'));
});`}
</CodeBlock>

<ConfigureRedirectUri
figureSrc={redirectUriFigure}
redirectUri="http://localhost:8080/sign-in-callback"
/>

In your web application, add a route to properly handle the sign-in request from users. Let's use `/sign-in` as an example:

```php
Route::get('/sign-in', function () {
return redirect($client->signIn('http://localhost:8080/sign-in-callback'));
});
```

Replace `http://localhost:8080/sign-in-callback` with the callback URL you set in your Logto Console for this application.
Replace <code>{defaultRedirectUri}</code> with the callback URL you set in your Logto Console for this application.

If you want to show the sign-up page on the first screen, you can set `interactionMode` to `signUp`:

```php
Route::get('/sign-in', function () {
return redirect($client->signIn('http://localhost:8080/sign-in-callback', InteractionMode::signUp));
});
```
<CodeBlock language="php">
{`Route::get('/sign-in', function () {
return redirect($client->signIn('${defaultRedirectUri}', InteractionMode::signUp));
});`}
</CodeBlock>

Now, whenever your users visit `http://localhost:8080/sign-in`, it will start a new sign-in attempt and redirect the user to the Logto sign-in page.
Now, whenever your users visit <code>{defaultBaseUrl}sign-in</code>, it will start a new sign-in attempt and redirect the user to the Logto sign-in page.

> **Note**
> Creating a sign-in route isn't the only way to start a sign-in attempt. You can always use the `signIn` method to get the sign-in URL and redirect the user to it.
#### Implement the callback route

<ImplementCallbackRoute />
20 changes: 8 additions & 12 deletions docs/quick-starts/framework/php/_implement-sign-out-route.mdx
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import postSignOutRedirectUriFigure from '../../assets/go-post-sign-out-redirect-uri.png';
import ConfigurePostSignOutRedirectUri from '../../fragments/_configure-post-sign-out-redirect-uri.mdx';
import CodeBlock from '@theme/CodeBlock';

import ImplementSignOutRouteNotice from '../../fragments/_implement-sign-out-route-notice.md';
import { defaultBaseUrl } from '../../fragments/_web-configure-redirect-uris.mdx';

After the user makes a signing-out request, Logto will clear all user authentication information in the session.

To clean up the PHP session and Logto session, a sign-out route can be implemented as follows:

<ConfigurePostSignOutRedirectUri
figureSrc={postSignOutRedirectUriFigure}
postSignOutRedirectUri="http://localhost:8080"
/>

```php
Route::get('/sign-out', function () {
<CodeBlock language="php">
{`Route::get('/sign-out', function () {
return redirect(
// Redirect the user to the home page after a successful sign-out
$client->signOut('http://localhost:8080')
$client->signOut('${defaultBaseUrl}')
);
});
```
});`}
</CodeBlock>

<ImplementSignOutRouteNotice />
6 changes: 3 additions & 3 deletions docs/quick-starts/framework/php/_init-logto-client.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import GetAppSecret from '../../fragments/_get-app-secret.mdx';

First, create a Logto config:

```php
use logto\sdk\LogtoClient;
```php title="index.php"
use Logto\Sdk\LogtoClient;
use Logto\Sdk\LogtoConfig;

$client = new LogtoClient(
Expand All @@ -19,7 +19,7 @@ $client = new LogtoClient(

By default, the SDK uses the built-in PHP session to store the Logto data. If you want to use other storage, you can pass a custom storage object as the second parameter:

```php
```php title="index.php"
$client = new LogtoClient(
new LogtoConfig(
// ...
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
```php
// highlight-next-line
use Logto\Sdk\Constants\UserScope;

$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-next-line
scopes: [UserScope::organizations], // Add scopes
),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
```php
```php title="index.php"
$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-next-line
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"], // Add API resources
),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
```php
```php title="index.php"
$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-start
scopes: ["shopping:read", "shopping:write", "store:read", "store:write"], // Add scopes
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"], // Add API resources
// highlight-end
),
);
```
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
```php
```php title="index.php"
$client = new LogtoClient(
new LogtoConfig(
// ...other configs
// highlight-start
scopes: ["read", "write"], // Add scopes
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"], // Add API resources
// highlight-end
),
);
```
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
```php
```php title="index.php"
$accessToken = $client->getAccessToken("https://shopping.your-app.com/api");
```
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
```php
```php title="index.php"
# Replace the parameter with a valid organization ID.
# Valid organization IDs for the user can be found in the ID token claim `organizations`.
$organizationToken = $client->getOrganizationToken("organization-id");
$organizationToken = $client->getOrganizationToken(organization_id);
# or
$claims = $client->getOrganizationTokenClaims("organization-id");
$claims = $client->getOrganizationTokenClaims(organization_id);
```
Loading

0 comments on commit 5a0177d

Please sign in to comment.