105 lines
3.3 KiB
PHP
105 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Controller\ControllerBase;
|
|
|
|
use App\Form\Login as LoginForm;
|
|
|
|
class AuthController extends ControllerBase
|
|
{
|
|
public function indexAction()
|
|
{
|
|
$form = new LoginForm();
|
|
|
|
if ($this->request->isPost()) {
|
|
$data = $this->request->getPost();
|
|
if ($form->isValid($data)) {
|
|
|
|
$email = $form->getValue('Email');
|
|
$passwd = $form->getValue('Password');
|
|
|
|
// Perform login
|
|
if ($this->auth->login($email, $passwd)) {
|
|
$this->response->redirect('/');
|
|
} else {
|
|
$this->flash->message('error', "Invalid credentials");
|
|
}
|
|
} else {
|
|
$msg = '<ul>';
|
|
|
|
foreach($form->getMessages() as $message) {
|
|
$msg .= '<li><strong>' . $message->getField() . '</strong> '. $message->getMessage() . '</li>';
|
|
}
|
|
|
|
$msg .= '</ul>';
|
|
$this->flash->message('error', $msg);
|
|
}
|
|
}
|
|
|
|
$this->view->form = $form;
|
|
}
|
|
|
|
public function oauthAction($provider_name)
|
|
{
|
|
$client = $this->getDI()->get('oauth', [ $provider_name ]);
|
|
|
|
$code = $this->request->get('code');
|
|
$state = $this->request->get('state');
|
|
|
|
// Have code. Authenticate and fetch data.
|
|
if (strlen($code) > 0) {
|
|
|
|
try {
|
|
// NOTE: Should pass $state here also.
|
|
$data = $client->authenticate($code);
|
|
|
|
// If user is authed already, we connect.
|
|
$user = $this->auth->getUser();
|
|
if ($user) {
|
|
|
|
$name = ucfirst($provider_name);
|
|
$user->{'set' . $name . 'Id'}($data->getId());
|
|
$user->save();
|
|
|
|
$this->flash->message('success', "<strong>{$name}</strong> was connected!");
|
|
$this->response->redirect('/settings');
|
|
}
|
|
// Perform Auth.
|
|
else {
|
|
$result = $this->auth->loginOauth($data);
|
|
|
|
// There was an error when creating the account
|
|
if (is_array($result)) {
|
|
$msg = '';
|
|
foreach ($result as $message) {
|
|
$msg .= '<li>' . $message->getMessage() . '</li>';
|
|
}
|
|
$this->flash->message('error', "Failed to create account: <ul>{$msg}</ul>");
|
|
$this->response->redirect('/login');
|
|
} else {
|
|
$this->response->redirect('/');
|
|
}
|
|
}
|
|
} catch(\Exception $e) {
|
|
$this->flash->message('error', 'Failed to authenticate.');
|
|
if ($this->auth->getUser()) {
|
|
$this->response->redirect('/settings');
|
|
} else {
|
|
$this->response->redirect('/login');
|
|
}
|
|
}
|
|
}
|
|
// No code
|
|
else {
|
|
// redirect to provider and acquire code.
|
|
$this->response->redirect($client->getAuthorizationUrl(), true);
|
|
}
|
|
}
|
|
|
|
public function logoutAction()
|
|
{
|
|
$this->auth->clearIdentity();
|
|
$this->response->redirect('/');
|
|
}
|
|
}
|