-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
90 lines (77 loc) · 2.97 KB
/
auth.php
File metadata and controls
90 lines (77 loc) · 2.97 KB
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
<?php
/**
* Auth controller
*/
namespace Application;
use Bluz\Controller\Controller;
use Bluz\Proxy\Config;
use Bluz\Proxy\Messages;
use Bluz\Proxy\Response;
use Bluz\Proxy\Router;
use Hybridauth\Exception\Exception as HybridauthException;
use Hybridauth\Hybridauth;
/**
* @param string $provider
*
* @return void
*/
return function ($provider = '') {
/**
* @var Controller $this
*/
try {
// Get configuration
$config = Config::get('auth', 'hybrid');
$provider = strtolower($provider);
// Check provider name
if (!array_key_exists($provider, $config['providers'])) {
throw new Exception('Invalid provider name');
}
$config['callback'] = Router::getFullUrl('auth', 'auth', ['provider' => $provider]);
// Feed configuration array to Hybridauth
$hybridauth = new Hybridauth($config);
// Attempt to authenticate users with a provider by name
$adapter = $hybridauth->authenticate(ucfirst($provider));
// Returns a boolean of whether the user is connected with provider
if ($adapter->isConnected()) {
// Retrieve the user's profile
$profile = $adapter->getUserProfile();
// Access token from provider
$accessToken = $adapter->getAccessToken();
// Check authRow
$authRow = Auth\Table::getAuthRow($provider, $profile->identifier);
// Inspect profile's public attributes
if ($this->user()) {
if ($authRow) {
Messages::addNotice('You have already linked to `%s`', $provider);
} else {
// Create token and link it with user profile
$authRow = new Auth\Row();
$authRow->userId = $this->user()->getId();
$authRow->provider = $provider;
$authRow->foreignKey = $profile->identifier;
$authRow->tokenSecret = $accessToken['access_token_secret'] ?? '';
$authRow->tokenType = $accessToken['token_type'] ?? Auth\Table::TYPE_ACCESS;
Messages::addNotice('Your account was linked to `%s` successfully!', $provider);
}
// Update access token
$authRow->token = $accessToken['access_token'];
$authRow->save();
Response::redirectTo('users', 'profile');
} elseif ($authRow) {
// Try to login
Auth\Provider\Token::login($authRow);
Messages::addNotice('You are signed');
} else {
// User not found
Messages::addError('Not found linked profile');
Response::redirectTo('users', 'signin');
}
// Disconnect the adapter
$adapter->disconnect();
}
} catch (HybridauthException $e) {
Messages::addError($e->getMessage());
}
Response::redirectTo('index');
};