<?php
namespace App\Controller\Patient\Auth;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RequestStack;
use ImperiumApp\Manager\AuthManager;
# AppsApi
use Imperium\AppsApi\Auth\Lecture as ApiAuth;
use Imperium\Config\iConfig;
use Imperium\StaticUtils\Utils;
use Imperium\InterfaceData\imp_health\Patients as IDataPatients;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Imperium\InterfaceToken\userToken;
use Imperium\InterfaceToken\cookieToken;
use Symfony\Component\Security\Core\User\UserInterface;
class AuthController extends AbstractController
{
protected $tokenStorage;
private $session;
protected $OTP;
protected $CryptSecretKey;
public function __construct(RequestStack $request,TokenStorageInterface $tokenStorage,SessionInterface $session)
{
iConfig::initConfig();
$this->tokenStorage = $tokenStorage;
$this->session = $session;
$this->OTP = $session->get('otp')??null;
$this->CryptSecretKey = iConfig::getCryptSecretKey();
}
public function getSignin()
{
return $this->render('patient/auth/index.html.twig');
}
public function postSigninEmail(Request $request)
{
self::verify_postSigninEmail($request);
$identifiant = $request->get('identifiant');
$params = [];
$params['args']['email'] = $identifiant;
$response = ApiAuth::getCompteByEmail($params);
if ( $response->compte == null ) {
return new JsonResponse(['status'=>401,"code"=>"unauthorized","title"=>"Unauthorized","message"=>"Email not found"],401);
}
if( $response->compte->Ip_Comptes->Validite == 0 ){ #ToDo => $response->compte->Ip_Comptes->Validite == 0
$identifiant = $request->get('identifiant');
$params = [];
$params['args']['email'] = $identifiant;
$params['args']['IdCompte'] = $response->compte->Ip_Comptes->IdCompte;
$otp = ApiAuth::generateOtp($params);
$params_twig= [];
// $otp->data->otp = 1111; //#ToDo remove this line
$this->session->set('otp',$otp->data->otp);
$params_twig['otp'] = Utils::CryptJWT($otp->data->otp,$this->CryptSecretKey);
$params_twig['IdCompte'] = Utils::CryptJWT($params['args']['IdCompte'],$this->CryptSecretKey);
$params_twig['identifiant'] = $identifiant;
return new JsonResponse(['status'=>1000,"code"=>"item_invalid","message"=>"account validated","data"=>$params_twig]);
}
$params_twig['IdCompte'] = Utils::CryptJWT($response->compte->Ip_Comptes->IdCompte,$this->CryptSecretKey);
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success","data"=>$params_twig]);
// $rsponse = ApiAuth::getCompteByEmail()
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success"]);
}
public function postValidatedCompte(Request $request)
{
self::verify_postValidatedCompte($request,$this->CryptSecretKey);
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success"]);
}
public function postValidatedCompteAuth(Request $request)
{
self::verify_postValidatedCompteAuth($request,$this->CryptSecretKey);
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$this->CryptSecretKey);
$password = $request->get('password');
$identifiant = $request->get('identifiant');
$params = [];
$params['username'] = $identifiant;
$params['password'] = $password;
$response = ApiAuth::usersSignin($params);
if( isset($response->token) ){
if( (new IDataPatients())->first(['IdComptePatient'=>$IdCompte]) ){
$compte = ApiAuth::usersVerify(['token'=>$response->token]);
self::loadSession($IdCompte,$identifiant,$this,$request);
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success"]);
}else{
throw (new JsonResponse(['code'=>'error','status'=>422,"title" => "account unconfigured","message"=>"The account is not configured","data"=>[
'account_unconfigured'=>true,
]],422))->send();
}
}else{
return new JsonResponse(['status'=>401,"code"=>"unauthorized","title"=>"Unauthorized","message"=>"Unauthorized"],401);
}
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success"]);
}
public function postCompteVerifyAuth(Request $request)
{
self::verify_postCompteVerifyAuth($request,$this->CryptSecretKey);
$password = $request->get('password');
$identifiant = $request->get('identifiant');
$IdCompte = $request->get('IdCompte');
$params = [];
$params['username'] = $identifiant;
$params['password'] = $password;
$response = ApiAuth::usersSignin($params);
if( isset($response->token) ){
$params = [];
$params['args']['email'] = $identifiant;
$params['args']['IdCompte'] = Utils::DecryptJWT($IdCompte,$this->CryptSecretKey);
$otp = ApiAuth::generateOtpSante($params); //#ToDo discomment this line
//dd($otp->data->otp);
$params_twig= [];
// $otp->data->otp = 1111; //#ToDo remove this line
$this->session->set('otp',$otp->data->otp);
$params_twig['otp'] = Utils::CryptJWT($otp->data->otp,$this->CryptSecretKey);
// $otp->data->otp = 1111; //#ToDo remove this line
// $this->session->set('otp',$otp->data->otp);
// $params_twig['otp'] = Utils::CryptJWT($otp->data->otp,$this->CryptSecretKey);
$params_twig['password'] = Utils::CryptJWT($password,$this->CryptSecretKey);
$params_twig['token'] = $response->token;
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success","data"=>$params_twig]);
}else{
return new JsonResponse(['status'=>401,"code"=>"unauthorized","title"=>"password invalid","message"=>"password invalid"],401);
}
}
public function postCompteAuth(Request $request)
{
self::verify_postCompteAuth($request,$this->CryptSecretKey);
// virify token
$token = $request->get('token');
$userToken = ApiAuth::usersVerify(['token'=>$token]);
if( $userToken->status == 401 ){
return new JsonResponse(['status'=>401,"code"=>"expired","title"=>"Expired","message"=>"expired token"],401);
}
$password = $request->get('password');
$identifiant = $request->get('identifiant');
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$this->CryptSecretKey);
if( (new IDataPatients())->first(['IdComptePatient'=>$IdCompte]) ){
self::loadSession($IdCompte,$identifiant,$this,$request);
}else{
throw (new JsonResponse(['code'=>'error','status'=>422,"title" => "account unconfigured","message"=>"The account is not configured","data"=>[
'account_unconfigured'=>true,
]],422))->send();
}
return new JsonResponse(['status'=>200,"code"=>"success","message"=>"success","data"=>[
'redirect'=>'/patient/dashboard'
]]);
}
protected static function verify_postCompteAuth($request,$keyCryptage)
{
$validators = [];
if( !$request->request->has('password') || empty($request->get('password'))){
$validators['fields'] = "Password is required";
}
if( !$request->request->has('token') || empty($request->get('token'))){
$validators['fields'] = "token is required";
}
if( !$request->request->has('identifiant') || empty($request->get('identifiant'))){
$validators['fields'] = "identifiant is required";
}
if( !$request->request->has('otp') || empty($request->get('otp'))){
$validators['fields'] = "otp is required";
}
if( !$request->request->has('codeOne') && !preg_match( '/^[0-9]+$/' , $request->get('codeOne') ) ){
$validators['codeAuthAccount1'] = "the codeOne field is mandatory .";
}
if( !$request->request->has('codeTwo') && !preg_match( '/^[0-9]+$/' , $request->get('codeTwo') ) ){
$validators['codeAuthAccount2'] = "the codeTwo field is mandatory .";
}
if( !$request->request->has('codeTree') && !preg_match(' /^[0-9]+$/', $request->get('codeTree') ) ){
$validators['codeAuthAccount3'] = "the codeTree field is mandatory .";
}
if( !$request->request->has('codeFour') && !preg_match(' /^[0-9]+$/', $request->get('codeFour') ) ){
$validators['codeAuthAccount4'] = "the codeFour field is mandatory .";
}
// concatenate otp code
$code = $request->get('codeOne') . $request->get('codeTwo') . $request->get('codeTree') . $request->get('codeFour');
$otp = Utils::DecryptJWT($request->get('otp'),$keyCryptage);
// compare otp code
if($code != $otp){
$validators['otp'] = "The OTP is not Valide . Please Provide the valide one .";
}
// check idcompte & idetifiant
$identifiant = $request->get('identifiant');
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$keyCryptage);
$params = [];
$params['args']['email'] = $identifiant;
$response = ApiAuth::getCompteByEmail($params);
if ( !($response->compte != null && isset($response->compte->Ip_Comptes->IdCompte) && $response->compte->Ip_Comptes->IdCompte == $IdCompte) ) {
$validators['fields'] = "some fields is required";
}
// check password & identifiant
$params = [];
$params['username'] = $identifiant;
$params['password'] = Utils::DecryptJWT($request->get('password'),$keyCryptage);
$response = ApiAuth::usersSignin($params);
if( $response == null ){
$validators['fields'] = "some fields is required";
}
if(count($validators)>0){
// return new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422);
throw (new JsonResponse(['code'=>'error','status'=>422,"title" => "Confirmation Erreur","message"=>"The data provided was invalid","data"=>$validators],422))->send();
}
}
protected static function verify_postCompteVerifyAuth($request,$keyCryptage)
{
$data = [];
$data["code"] = "error";
$data["status"] = 422;
$validators = [];
if( !$request->request->has('password') || empty($request->get('password'))){
$validators['password'] = "Password is required";
}
// check idcompte & idetifiant
$identifiant = $request->get('identifiant');
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$keyCryptage);
$params = [];
$params['args']['email'] = $identifiant;
$response = ApiAuth::getCompteByEmail($params);
if ( !($response->compte != null && isset($response->compte->Ip_Comptes->IdCompte) && $response->compte->Ip_Comptes->IdCompte == $IdCompte) ) {
$validators['fields'] = "some fields is required";
}
if(count($validators)>0){
// return new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422);
throw (new JsonResponse(['code'=>'error','status'=>422,"title" => "Confirmation Erreur","message"=>"The data provided was invalid","data"=>$validators],422))->send();
}
}
protected static function verify_postValidatedCompte($request,$keyCryptage)
{
$data = [];
$data["code"] = "error";
$data["status"] = 422;
$validators = [];
if( !$request->request->has('codeOne') && !preg_match( '/^[0-9]+$/' , $request->get('codeOne') ) ){
$validators['codemailphone1'] = "the codeOne field is mandatory .";
}
if( !$request->request->has('codeTwo') && !preg_match( '/^[0-9]+$/' , $request->get('codeTwo') ) ){
$validators['codemailphone2'] = "the codeTwo field is mandatory .";
}
if( !$request->request->has('codeTree') && !preg_match(' /^[0-9]+$/', $request->get('codeTree') ) ){
$validators['codemailphone3'] = "the codeTree field is mandatory .";
}
if( !$request->request->has('codeFour') && !preg_match(' /^[0-9]+$/', $request->get('codeFour') ) ){
$validators['codemailphone4'] = "the codeFour field is mandatory .";
}
if( !$request->request->has('IdCompte') || empty($request->get('IdCompte'))){
$validators['fields'] = "some fields is requireds";
}
if( !$request->request->has('identifiant') || empty($request->get('identifiant'))){
$validators['fields'] = "some fields is requireds";
}
// concatenate otp code
$code = $request->get('codeOne') . $request->get('codeTwo') . $request->get('codeTree') . $request->get('codeFour');
$otp = Utils::DecryptJWT($request->get('otp'),$keyCryptage);
// compare otp code
if($code != $otp){
$validators['otp'] = "The OTP is not Valide . Please Provide the valide one .";
}
// check idcompte & idetifiant
$identifiant = $request->get('identifiant');
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$keyCryptage);
$params = [];
$params['args']['email'] = $identifiant;
$response = ApiAuth::getCompteByEmail($params);
if ( !($response->compte != null && isset($response->compte->Ip_Comptes->IdCompte) && $response->compte->Ip_Comptes->IdCompte == $IdCompte) ) {
$validators['fields'] = "some fields is requireds";
}
if(count($validators)>0){
// return new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422);
throw (new JsonResponse(['code'=>'error','status'=>422,"title"=>"error","message"=>"The data provided was invalid","data"=>$validators],422))->send();
}
}
protected static function verify_postSigninEmail($request)
{
$data = [];
$data["code"] = "error";
$data["status"] = 422;
$validators = [];
if( !$request->request->has('identifiant') || empty($request->get('identifiant'))){
$validators['identifiant'] = "the identifiant field is mandatory";
}
if(count($validators)>0){
// return new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422);
throw (new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422))->send();
}
}
protected static function verify_postValidatedCompteAuth($request,$keyCryptage)
{
$data = [];
$data["code"] = "error";
$data["status"] = 422;
$validators = [];
if( !$request->request->has('password') || empty($request->get('password'))){
$validators['password'] = "some password is requireds";
}
if( !$request->request->has('confirmPassword') || empty($request->get('confirmPassword'))){
$validators['confirmPassword'] = "some confirmPassword is requireds";
}
if( $request->request->has('password') && $request->request->has('confirmPassword') && $request->get('password') != $request->get('confirmPassword')){
$validators['confirm'] = "Password confirmation is not valide";
}
if( !$request->request->has('IdCompte') || empty($request->get('IdCompte'))){
$validators['fields'] = "some fields is requireds";
}
if( !$request->request->has('identifiant') || empty($request->get('identifiant'))){
$validators['fields'] = "some fields is requireds";
}
// check idcompte & idetifiant
$identifiant = $request->get('identifiant');
$IdCompte = Utils::DecryptJWT($request->get('IdCompte'),$keyCryptage);
$params = [];
$params['args']['email'] = $identifiant;
$response = ApiAuth::getCompteByEmail($params);
if ( !($response->compte != null && isset($response->compte->Ip_Comptes->IdCompte) && $response->compte->Ip_Comptes->IdCompte == $IdCompte) ) {
$validators['fields'] = "some fields is requireds";
}
if(count($validators)>0){
// return new JsonResponse(['code'=>'error','status'=>422,"message"=>"The data provided was invalid","data"=>$validators],422);
throw (new JsonResponse(['code'=>'error','status'=>422,"title" => "Confirmation Erreur","message"=>"The data provided was invalid","data"=>$validators],422))->send();
}
}
protected static function loadSession($IdCompte,$identifiant,$current,$request)
{
$compte = ApiAuth::compteDetail($IdCompte);
$current->session->set('user', $compte->data->compte );
$current->session->set('compteid', $compte->data->compte->IdCompte );
$current->session->set('user_image', 'logo');
$user = new User();
$user->setId($compte->data->compte->IdCompte);
$user->setUserName($compte->data->compte->X_NOM.' '.$compte->data->compte->X_PRENOM);
$user->setEmail($identifiant);
$user->setFirstName($compte->data->compte->X_PRENOM);
$user->setLastName($compte->data->compte->X_NOM);
$user->setUserImage($compte->data->compte->pic_profile);
$user->setRoles(['ROLE_ADMIN']);
//Create session for symfony
$token = new UsernamePasswordToken($user, null, 'main', ['ROLE_ADMIN']);
$current->tokenStorage->setToken($token);
$request->getSession()->set('_security_main', serialize($token));
$dispatcher = new EventDispatcher();
$event = new InteractiveLoginEvent($request, $token);
$dispatcher->dispatch($event);
try {
//generate user token
$uToken = new userToken(null,$current->session);
$userToken = $uToken->authenticate($email, $password);
} catch ( \Exception $th) {
error_log( $th->getMessage() , 0);
}
try {
// must check $userToken->status == 200 before continue
//push cookie
$cToken = new cookieToken(null,$current->session);
$cToken->user_token = $userToken->token;
$cToken->set('lastName','wakrim');
$cToken->set('firstName','brahim');
$cToken->push();
} catch ( \Exception $th) {
error_log( $th->getMessage() , 0);
}
//test if request is xhr
if ($request->isXmlHttpRequest()){
return new JsonResponse(['message' => 'authenticated' , 'code' => 'authenticated' , 'status' => 200], 200);
}
}
}