Skip to content

Instantly share code, notes, and snippets.

@Anan5a
Last active December 21, 2018 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anan5a/eba3753c29d1c5e1ab8fc8d9bc103019 to your computer and use it in GitHub Desktop.
Save Anan5a/eba3753c29d1c5e1ab8fc8d9bc103019 to your computer and use it in GitHub Desktop.
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Service\Google;
use App\Service\EncryptionFactory;
use App\Entity\User;
use App\Form\SignupType;
/**
* @Route("/signup")
*/
class SignupController extends AbstractController
{
private $_theme;
const ACCESS_DENIED = 'Access Denied. You didn\'t allowed access in the consent screen.';
const NO_CODE = 'No Code in response. Please try again';
const E_STATE = 'Invalid signup state. Please try again.';
const E_EMAIL = 'Email already exists. Try with another account.';
const E_DATA = 'Error signing up. Data went wrong';
function __construct()
{
//set theme
$this->_theme = getenv('THEME');
}
/**
* @Route("/", name="signup")
*/
public function index(Google $google, SessionInterface $session)
{
$state = bin2hex(random_bytes(8));
$state_val = [
$state=>['valid'=> time()+3600],
];
$session->set('signup_state', $state_val);
return $this->render("$this->_theme/signup.html.twig", [
'g_signup_url' => $google->getAuthUrl($state),
]);
}
/**
* @Route("/2/{signup_slug}", name="signup_store")
*/
public function signup_2($signup_slug, Request $request, SessionInterface $session, UserPasswordEncoderInterface $passEncoder, EncryptionFactory $encryption)
{
//validate data
$session_data = $session->get('auth_signup', []);
if (!array_key_exists($signup_slug, $session_data)) {
//redirect to signup
return $this->redirectToRoute('signup_error', ['msg'=>'e_data']);
}
$signup_data = $session_data[$signup_slug];
$user = new User;
$form = $this->createForm(SignupType::class); $form->handleRequest($request);
if (is_array($signup_data)) {
$oauth_cipher = $encryption->encrypt(json_encode($signup_data['token']));
$signupdate = \DateTime::createFromFormat('d-m-Y H:i:s',date('d-m-Y H:i:s',time()));
$user->setOauthProvider('GOOGLE');
$user->setOauthData($oauth_cipher);
$user->setStatus('ACT');
$user->setDisplayName($signup_data['g_data']['display_name']);
$user->setEmail($signup_data['g_data']['email']);
$user->setProPic($signup_data['g_data']['propic']);
$user->setDlCount(0);
$user->setRoles(['ROLE_USER']);
$user->setSignupDate($signupdate);
}
if ($form->isSubmitted()) {
//var_dump($form->getData());
if($form->isValid()){
$encodedPassword = $passEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encodedPassword);
$doct = $this->getDoctrine()->getManager();
$doct->persist($user);
$doct->flush();
$this->addFlash(
'info',
'Signup successfull! Please login'
);
return $this->redirectToRoute('signup');
}
print_r($form->getErrors());
}
return $this->render("$this->_theme/signup.html.twig", [
'form' => $form->createView(),
]);
}
/**
* @Route("/g_cb", name="signup_callback")
*/
public function g_callback(Request $request, Google $google, SessionInterface $session)
{
$state = $request->query->get('state');
$code = $request->query->get('code');
$em = $this->getDoctrine()->getRepository(User::class);
if ($session->get('signup_state')[$state]['valid'] < time()) {
return $this->redirectToRoute('signup_error',[
'msg'=> 'e_state',
]);
}
if($request->query->get('error')){
return $this->redirectToRoute('signup_error',[
'msg'=> $request->query->get('error'),
]);
}
if (!$code) {
return $this->redirectToRoute('signup_error', [
'msg'=>'no_code',
]);
}
//validate code for token
//
$token = $google->getAccessTokenByCode($code);
if (!empty($token['error'])) {
return $this->redirectToRoute('signup_error',[
'msg'=> $token['error'],
]);
}
$g_data = $google->pullSignupInfo($token);
//check email
if ($em->findOneBy(['email'=>$g_data['email']])) {
return $this->redirectToRoute('signup_error', ['msg' => 'e_email']);
}
//end check email
$stoken = bin2hex(random_bytes(16));
$signup_data = [
$stoken=>[
'token'=> $token,
'g_data'=> $g_data,
]
];
$session->set('auth_signup', $signup_data);
return $this->redirectToRoute('signup_store', ['signup_slug' => $stoken]);
}
/**
* @Route("/error", name="signup_error")
*/
function error(Request $request)
{
$msg = $request->query->get('msg');
if(!$msg){
return $this->redirectToRoute('signup');
}
switch ($msg) {
case 'e_email':
$msg = self::E_EMAIL;
break;
case 'e_state':
$msg = self::E_STATE;
break;
case 'e_data':
$msg = self::E_DATA;
break;
case 'access_denied':
$msg = self::ACCESS_DENIED;
break;
case 'no_code':
$msg = self::NO_CODE;
break;
default:
$msg = 'No information for this error.';
break;
}
return $this->render($this->getParameter('theme').'/error.html.twig',[
'error'=>[
'name'=>'Signup Error',
'message'=>$msg
]
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment