-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathclass-token.php
110 lines (98 loc) · 2.58 KB
/
class-token.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace WP\OAuth2\Endpoints;
use WP_Error;
use WP_Http;
use WP\OAuth2\Client;
use WP_REST_Request;
/**
* Token endpoint handler.
*/
class Token {
public function register_routes() {
register_rest_route( 'oauth2', '/access_token', [
'methods' => 'POST',
'callback' => [ $this, 'exchange_token' ],
'args' => [
'grant_type' => [
'required' => true,
'type' => 'string',
'validate_callback' => [ $this, 'validate_grant_type' ],
],
'client_id' => [
'required' => true,
'type' => 'string',
'validate_callback' => 'rest_validate_request_arg',
],
'code' => [
'required' => true,
'type' => 'string',
'validate_callback' => 'rest_validate_request_arg',
],
'code_verifier' => [
'required' => false,
'type' => 'string',
'validate_callback' => 'rest_validate_request_arg',
],
],
] );
}
/**
* Validates the given grant type.
*
* @param string $type Grant type.
*
* @return bool Whether or not the grant type is valid.
*/
public function validate_grant_type( $type ) {
return $type === 'authorization_code';
}
/**
* Validates the token given in the request, and issues a new token for the user.
*
* @param WP_REST_Request $request Request object.
*
* @return array|WP_Error Token data on success, or error on failure.
*/
public function exchange_token( WP_REST_Request $request ) {
$client = Client::get_by_id( $request['client_id'] );
if ( empty( $client ) ) {
return new WP_Error(
'oauth2.endpoints.token.exchange_token.invalid_client',
sprintf( __( 'Client ID %s is invalid.', 'oauth2' ), $request['client_id'] ),
[
'status' => WP_Http::BAD_REQUEST,
'client_id' => $request['client_id'],
]
);
}
$auth_code = $client->get_authorization_code( $request['code'] );
if ( is_wp_error( $auth_code ) ) {
return $auth_code;
}
$is_valid = $auth_code->validate( [ 'code_verifier' => $request['code_verifier'] ] );
if ( is_wp_error( $is_valid ) ) {
// Invalid request, but code itself exists, so we should delete
// (and silently ignore errors).
$auth_code->delete();
return $is_valid;
}
// Looks valid, delete the code and issue a token.
$user = $auth_code->get_user();
if ( is_wp_error( $user ) ) {
return $user;
}
$did_delete = $auth_code->delete();
if ( is_wp_error( $did_delete ) ) {
return $did_delete;
}
$token = $client->issue_token( $user );
if ( is_wp_error( $token ) ) {
return $token;
}
$data = [
'access_token' => $token->get_key(),
'token_type' => 'bearer',
];
return $data;
}
}