11<?php
22
33use JSONms \Controllers \RestfulController ;
4+ use GuzzleHttp \Client as GuzzleClient ;
45
56class SessionController extends RestfulController {
67
@@ -28,6 +29,29 @@ private function getEndpoints($userId) {
2829 return [];
2930 }
3031
32+ private function getLoginUrl () {
33+
34+ $ httpClient = new GuzzleClient ([
35+ 'timeout ' => 3.0 ,
36+ 'connect_timeout ' => 3.0 ,
37+ ]);
38+
39+ try {
40+ // Google Client Configuration
41+ $ client = new Google_Client ();
42+ $ client ->setHttpClient ($ httpClient );
43+ $ client ->setClientId ($ _ENV ['GOOGLE_OAUTH_CLIENT_ID ' ]);
44+ $ client ->setClientSecret ($ _ENV ['GOOGLE_OAUTH_CLIENT_SECRET ' ]);
45+ $ client ->setRedirectUri ($ _ENV ['GOOGLE_OAUTH_CALLBACK_URL ' ]);
46+ $ client ->addScope ('email ' );
47+ $ client ->addScope ('profile ' );
48+
49+ return $ client ->createAuthUrl ();
50+ } catch (\Exception $ e ) {
51+ throwError (500 , $ e ->getMessage ());
52+ }
53+ }
54+
3155 public function indexAction () {
3256
3357 $ loggedIn = isset ($ _SESSION ['access_token ' ]) && $ _SESSION ['access_token ' ];
@@ -54,53 +78,11 @@ public function indexAction() {
5478 // User exists, fetch data
5579 $ user = $ stmt ->fetch (PDO ::FETCH_OBJ );
5680 } else {
57- // Google Client Configuration
58- $ client = new Google_Client ();
59- $ client ->setClientId ($ _ENV ['GOOGLE_OAUTH_CLIENT_ID ' ]);
60- $ client ->setClientSecret ($ _ENV ['GOOGLE_OAUTH_CLIENT_SECRET ' ]);
61- $ client ->setRedirectUri ($ _ENV ['GOOGLE_OAUTH_CALLBACK_URL ' ]);
62- $ client ->addScope ('email ' );
63- $ client ->addScope ('profile ' );
64- $ loginUrl = $ client ->createAuthUrl ();
81+ $ loginUrl = $ this ->getLoginUrl ();
6582 }
6683 }
6784 else {
68- try {
69- // Google Client Configuration
70- $ client = new Google_Client ();
71- $ client ->setClientId ($ _ENV ['GOOGLE_OAUTH_CLIENT_ID ' ]);
72- $ client ->setClientSecret ($ _ENV ['GOOGLE_OAUTH_CLIENT_SECRET ' ]);
73- $ client ->setRedirectUri ($ _ENV ['GOOGLE_OAUTH_CALLBACK_URL ' ]);
74- $ client ->addScope ('email ' );
75- $ client ->addScope ('profile ' );
76- $ loginUrl = $ client ->createAuthUrl ();
77- } catch (\Exception $ e ) {
78- throwError (500 , $ e ->getMessage ());
79- }
80-
81- try {
82- $ oauth2 = new Google_Service_Oauth2 ($ client );
83- $ oauth2 ->userinfo ->get ();
84- $ loggedIn = true ;
85- } catch (\Exception $ e ) {
86- $ this ->responseJson ([
87- 'error ' => $ e ->getMessage (),
88- 'loggedIn ' => false ,
89- 'user ' => $ user ,
90- 'googleOAuthSignInUrl ' => $ loginUrl ,
91- 'structures ' => $ structures ,
92- 'endpoints ' => $ endpoints ,
93- ]);
94- }
95-
96- // Check if user already exists
97- $ stmt = $ this ->query ('get-user-by-google-id ' , [
98- 'id ' => $ this ->getCurrentUserId (),
99- ]);
100-
101- if ($ stmt ->rowCount () > 0 ) {
102- $ user = $ stmt ->fetch (PDO ::FETCH_OBJ );
103- }
85+ $ loginUrl = $ this ->getLoginUrl ();
10486 }
10587
10688 if ($ loggedIn && isset ($ user )) {
0 commit comments