baa6c4d47389f0d4aba92eede281c180f2e742f0
[pharext/pharext.org] / Callback.php
1 <?php
2
3 namespace app\Controller\Github;
4
5 use app\Controller\Github;
6 use app\Github\API;
7 use app\Model\Accounts;
8 use app\Session;
9 use app\Web;
10 use http\Cookie;
11
12 class Callback extends Github
13 {
14 /**
15 * @var Accounts
16 */
17 private $accounts;
18
19 function __construct(Web $app, API $github, Session $session, Accounts $accounts) {
20 parent::__construct($app, $github, $session);
21 $this->accounts = $accounts;
22 }
23
24 function __invoke(array $args = null) {
25 if ($this->app->getRequest()->getQuery("error")) {
26 $this->app->getView()->addData([
27 "error" => $this->app->getRequest()->getQuery("error_description")
28 ]);
29 } else {
30 $this->validateUser();
31
32 if (isset($this->session->returnto)) {
33 $returnto = $this->session->returnto;
34 unset($this->session->returnto);
35 $this->app->redirect($returnto);
36 } else {
37 $this->app->redirect(
38 $this->app->getBaseUrl()->mod("./github"));
39 }
40 }
41 $this->app->display("github/callback");
42 }
43
44 private function validateUser() {
45 $this->github->fetchToken(
46 $this->app->getRequest()->getQuery("code"),
47 $this->app->getRequest()->getQuery("state")
48 )->then(function($result) {
49 list($oauth) = $result;
50 $this->github->setToken($oauth->access_token);
51 return $this->github->readAuthUser()->then(function($result) use($oauth) {
52 list($user) = $result;
53 return $this->persistUser($oauth, $user);
54 });
55 })->done(function($result) {
56 $this->login(...$result);
57 });
58
59 $this->github->getClient()->send();
60 }
61
62 private function persistUser($oauth, $user) {
63 $tx = $this->accounts->getConnection()->startTransaction();
64
65 if (($cookie = $this->app->getRequest()->getCookie("account"))) {
66 $account = $this->accounts->find(["account=" => $cookie])->current();
67 } elseif (!($account = $this->accounts->byOAuth("github", $oauth->access_token, $user->login))) {
68 $account = $this->accounts->createOAuthAccount("github", $oauth->access_token, $user->login);
69 }
70 $token = $account->updateToken("github", $oauth->access_token, $oauth);
71 $owner = $account->updateOwner("github", $user->login, $user);
72
73 $tx->commit();
74
75 return [$account, $token, $owner];
76 }
77 }