2 namespace App\Controller;
4 use App\Controller\AppController;
6 use App\Traits\GoogleOauthTrait;
9 * Authorizer Controller
11 * This controller provides an entry point for authorization processes.
12 * So far this is just for Google's OAuth 2.0.
14 class AuthorizerController extends AppController
21 * This controller will provide a link for /authorizer/google_login where the oauth
22 * process can come back to our application from google. To make your client secret setup
23 * simpler, add a route at the top level like so:
24 * $routes->connect('/google_oauth', [ 'controller'=>'authorizer', 'action' => 'google_login']);
27 public function initialize()
33 * our callback from google oauth that is passed the oauth access token (or an error
34 * if authorization failed).
35 * before redirecting to this URL, one must use the GoogleOauth trait's
36 * setPostAuthorizationURL() and setRequestedScopes() methods to provide session
37 * parameters (since this link is invoked by google later, and they will not be
38 * providing any of this info).
40 public function googleLogin() {
41 if (session_status() == PHP_SESSION_NONE) {
45 // retrieve the scopes out of the session.
46 $scopes = $this->getRequestedScopes();
47 Log::debug('loaded scopes: ' . var_export($scopes, true));
49 // use the scopes in a new google client.
50 $client = $this->createGoogleClient ( $scopes );
52 // see if we already have the 'code' available from the google side.
53 if (! isset ( $_GET ['code'] )) {
54 // no code, so we need to jump over to google.
55 Log::Debug ( 'creating auth url to redirect to google oauth' );
56 $auth_url = $client->createAuthUrl ();
57 $this->redirect ( $auth_url );
59 // we've got our code, so now we can try to fetch our access token.
60 Log::Debug ( 'access token being actively acquired...' );
61 $client->fetchAccessTokenWithAuthCode ( $_GET ['code'] );
62 // clean out the scopes in session now that we're done with them.
63 $this->dropRequestedScopes();
65 // record the new token in our session.
66 $token = $client->getAccessToken ();
67 $this->setLastOAuthToken($token);
69 // fabulously bad idea to show this...
70 //Log::debug ( 'got access token: ' . var_export ( $token, true ) );
72 // go to the next point in our app where we can handle the newly stored token.
73 $redirect = $this->getPostAuthorizationURL();
75 // jump home if they registered no continuation. this is a serious error in flow.
76 $redirect = 'http://' . $_SERVER ['HTTP_HOST'] . '/';
77 Log::debug('failure to find the redirection location for our app after successful oauth');
79 $this->redirect ( $redirect );