Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
60.87% covered (warning)
60.87%
14 / 23
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
SSO_REST_Controller
60.87% covered (warning)
60.87%
14 / 23
66.67% covered (warning)
66.67%
2 / 3
4.96
0.00% covered (danger)
0.00%
0 / 1
 register_routes
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 get_item
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 check_permission
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace NewfoldLabs\WP\Module\SSO;
4
5class SSO_REST_Controller extends \WP_REST_Controller {
6
7    /**
8     * The namespace of this controller's route.
9     *
10     * @var string
11     */
12    protected $namespace = 'newfold-sso/v1';
13
14    /**
15     * Registers the settings route
16     */
17    public function register_routes() {
18
19        register_rest_route(
20            $this->namespace,
21            '/sso',
22            array(
23                array(
24                    'methods'             => \WP_REST_Server::READABLE,
25                    'callback'            => array( $this, 'get_item' ),
26                    'permission_callback' => array( $this, 'check_permission' ),
27                ),
28            )
29        );
30
31    }
32
33    /**
34     * Generate a token and login URL.
35     *
36     * @param \WP_REST_Request $request
37     *
38     * @return \WP_Error|\WP_HTTP_Response|\WP_REST_Response
39     */
40    public function get_item( $request ) {
41
42        // Create token
43        $token = SSO_Helpers::generateToken( get_current_user_id() );
44
45        // Save token
46        SSO_Helpers::saveToken( $token );
47
48        $query_string = http_build_query(
49            [
50                'action' => SSO_Helpers::ACTION,
51                'token'  => $token,
52            ]
53        );
54
55        // Return token and the magic login URL
56        return rest_ensure_response( admin_url( '/admin-ajax.php' ) . "?{$query_string}" );
57
58    }
59
60    /**
61     * Check permissions for routes.
62     *
63     * @return bool|\WP_Error
64     */
65    public function check_permission() {
66
67        // User must have both the permission and ability to login.
68        if ( ! current_user_can( 'read' ) ) {
69            return new \WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to access this endpoint.', 'wp-module-sso' ), array( 'status' => rest_authorization_required_code() ) );
70        }
71
72        return true;
73    }
74
75}