Thursday 28 March 2019

commands

git init
git status
git add .
git commit -m "Initial Rest api commit"
git remote add origin https://github.com/jojivijay/restapi.git
git remote -v
git push origin master
git log
git reflog
want to remove added url
git remote set-url origin https://github.com/jojivijay/fridayad-api.git
git remote rm origin
git remote add origin https://github.com/jojivijay/fridayad-api.git
git remote -v
git push origin master


grep -Rinw src/ -e 'consensu'
grep -Rinw ~/bin/ -e 'check_root'


sudo rm -rf var/cache/* var/logs/*
sudo chmod -R 777 var/cache var/logs
sudo php -d memory_limit=1000M bin/console cache:clear
sudo chmod -R 777 var/cache var/logs
sudo rm -rf var/cache/* var/logs/*
sudo chmod -R 777 var/cache var/logs
sudo chmod -R 777 var/cache var/logs
sudo -u nginx php -d memory_limit=1000M bin/console assets:install web --symlink
sudo -u nginx php -d memory_limit=1000M bin/console assetic:dump
sudo -u nginx php -d memory_limit=1000M bin/console cache:clear
sudo chmod -R 777 var/cache var/logs
sudo rm -rf var/cache/* var/logs/*
sudo chmod -R 777 var/cache var/logs
sudo chmod -R 777 var/cache var/logs


sudo rm -rf var/logs/*
sudo chmod -R 777 var/cache var/logs
sudo chmod -R 777 var/cache var/logs

sudo git config core.filemode false
sudo chmod -R 777 ../newfriday-ad/
sudo chown -R nginx:nginx ../newfriday-ad/
sudo git config core.filemode false
sudo chcon -R -t httpd_sys_content_rw_t ../newfriday-ad/
sudo chmod -R 777 ../newfriday-ad


sudo php -d memory_limit=1000M bin/console doctrine:schema:validate
sudo php -d memory_limit=1000M bin/console doctrine:schema:update --force
sudo chmod -R 777 var/cache var/logs
sudo rm -rf var/cache/* var/logs/*
sudo chmod -R 777 var/cache var/logs
sudo chmod -R 777 var/cache var/logs

git reflog --date=local

php bin/console debug:container



git init
 git remote add origin https://jojivijaykumar@bitbucket.org/fridaymediagroup/newfriday-ad.git
 git status
 git add README.md
 git commit -m "added readme file"
 git config --global user.name "Joji vijayakumar Namburi"
 git config --global user.email vijay.namburi@fridaymediagroup.com
 git commit --amend
 git push origin master
 git status
 vi .gitignore
 git status
 1git add .gitignore app/ bin/ cat_sql/ composer.json composer.lock data/ doc/ generate_cache.sh generate_sitemap.sh load.sh phpunit.xml.dist sitemap.sh sql_temp/ src/ test_load.sh tests/ var/ web/
git commit -m "first commit of symfony 3.4 upgrade"
 git push origin master
 git config core.filemode false
 git status
 

Signature

security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
        api_key_user_provider:
            id: App\Security\ApiUserProvider
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
           
        api_firewall:
            pattern: ^/(.*)
            stateless: true
            simple_preauth:
                authenticator: App\Security\ApiAuthenticator
            provider: api_key_user_provider
        # main:
            # anonymous: true
           

            # activate different ways to authenticate

            # http_basic: true
            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: true
            # https://symfony.com/doc/current/security/form_login_setup.html

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        # - { path: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }




<?php
namespace App\Security;

use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use App\Security\ApiUserProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ApiAuthenticator implements SimplePreAuthenticatorInterface
{
    /* protected $userProvider;
    protected $em;
    protected $container; */

    /* public function __construct(ApiUserProvider $userProvider, EntityManager $em, ContainerInterface $container)
    {
        $this->userProvider = $userProvider;
        $this->em = $em;
        $this->container = $container;
    } */

    public function createToken(Request $request, $providerKey)
    {
        $route = $request->get("_route");
        if((strpos($route, 'nelmio_api_doc_index') !== false) || $route == "app.swagger" || $route == "app.swagger_ui") {
            $token = "anonymous";
        }else{
            $signature = $request->headers->get('Signature');
            $timeStamp = $request->headers->get('Timestamp');
           
            $token = $request->headers->get('Token');
           
            if (!isset($token)) {
                $token = "anonymous";
            }
           
            if (!$signature || !$timeStamp) {
                throw new HttpException(Response::HTTP_BAD_REQUEST, "Missing Mandatory  Parameters in header");
            }
           
            $privateKey = '765022d2f23b3ae5b24abcc6a165449dff002ee16080b232cb4119a449e4aa70';// $this->container->getParameter('app_private_key');
            if(!$privateKey) {
                throw new HttpException(Response::HTTP_BAD_REQUEST, "Missing PrivateKey Parameters");
            }
           
            $generatedSignature = $this->generateSignature($privateKey, $timeStamp);
            if($signature != $generatedSignature) {
                throw new HttpException(Response::HTTP_BAD_REQUEST, "Invalid Signature");
            }
        }
       
        return new PreAuthenticatedToken(
                'anon.',
                $token,
                $providerKey
        );
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        $apiKey = $token->getCredentials();
       
        if (!$userProvider instanceof ApiUserProvider) {
            throw new \InvalidArgumentException(
                sprintf(
                    'The user provider must be an instance of ApiKeyUserProvider (%s was given).',
                    get_class($userProvider)
                    )
                );
        }
        $user = $userProvider->loadUserByUsername($apiKey);

        return new PreAuthenticatedToken(
                $user,
                $apiKey,
                $providerKey,
                $user->getRoles()
        );
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
    }
   
    public function generateSignature($privateKey, $timeStamp)
    {
        return urlencode(base64_encode(hash_hmac('sha256', $timeStamp.$privateKey, $privateKey, true)));
    }
}




<?php
namespace App\Security;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;

class ApiUserProvider implements UserProviderInterface
{
    private $em;
   
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function loadUserByUsername($username)
    {
        if($username == 'anonymous') {
            return new User(
                    $username,
                    null,
                    array('IS_AUTHENTICATED_ANONYMOUSLY')
            );
        }
       
        $request = Request::createFromGlobals();
        $api = explode("/", $request->getPathInfo());
        if (isset($api) && $api['1'] == "customerapi") {
            return $this->em->getRepository('AppBundle:CustomerReg')->loadUserByAuthToken($username);
        }
       
    }

    public function refreshUser(UserInterface $user)
    {
        throw new UnsupportedUserException();
    }

    public function supportsClass($class)
    {
        return ('Symfony\Component\Security\Core\User\User' === $class || 'AppBundle\Entity\CustomerReg' === $class);
    }
}

Wednesday 27 March 2019

symfony 4.2 necessary lib for REST API's

composer -v
composer clearcache
composer install
composer create-project symfony/skeleton myapi

/usr/local/bin/composer require server --dev
/usr/local/bin/composer require security-check --dev
/usr/local/bin/composer require profiler --dev
/usr/local/bin/composer require maker-bundle --dev
/usr/local/bin/composer require symfony/test-pack --dev

/usr/local/bin/composer guzzlehttp/guzzle
/usr/local/bin/composer require annotations
/usr/local/bin/composer require orm-pack
/usr/local/bin/composer require jms/serializer-bundle
/usr/local/bin/composer require symfony/serializer
/usr/local/bin/composer require friendsofsymfony/rest-bundle
/usr/local/bin/composer require security-bundle
/usr/local/bin/composer require form
/usr/local/bin/composer require validator
/usr/local/bin/composer require doctrine/annotations
/usr/local/bin/composer require translation
/usr/local/bin/composer require mailer
/usr/local/bin/composer require monolog
/usr/local/bin/composer require asset
/usr/local/bin/composer require twig


fos_rest:
    disable_csrf_role: ROLE_API
    param_fetcher_listener: true
    view:
        mime_types:
            json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1']
        view_response_listener: 'force'
        formats:
            xml: false
            json: true
        templating_formats:
            html: true
    format_listener:
        rules:
            - { path: ^/, priorities: [ json, html ], fallback_format: json, prefer_extension: true }
    exception:
        codes:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
        messages:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
        exception_controller: 'fos_rest.exception.controller:showAction'
    allowed_methods_listener: true
    access_denied_listener:
        json: true
    body_listener: true




 

nelmio_api_doc:
documentation:
info:
title: My App
description: This is an awesome app!
version: 1.0.0
areas: # to filter documented areas
path_patterns:
- ^/api(?!/doc$) # Accepts routes under /api except /api/doc



Serializer

ApiFormErrorHandler.php

<?php
namespace App\Serializer;

use JMS\Serializer\JsonSerializationVisitor;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
use Symfony\Component\Translation\TranslatorInterface;
use JMS\Serializer\Handler\FormErrorHandler as JMSFormErrorsHandler;
use JMS\Serializer\VisitorInterface;


class ApiFormErrorHandler extends JMSFormErrorsHandler
{
private $translator;

public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}

public function serializeFormToJson(JsonSerializationVisitor $visitor, Form $form, array $type)
{
return $this->convertFormToArray($visitor, $form);
}

public function serializeFormErrorToJson(JsonSerializationVisitor $visitor, FormError $formError, array $type)
{
return $this->getErrorMessage($formError);
}

private function getErrorMessage(FormError $error)
{
if (null !== $error->getMessagePluralization()) {
return $this->translator->transChoice($error->getMessageTemplate(), $error->getMessagePluralization(), $error->getMessageParameters());
}
return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters());
}

private function convertFormToArray(VisitorInterface $visitor, Form $data)
{
$isRoot = null === $visitor->getRoot();
$form = new \ArrayObject();
$errors = array();
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form['form_errors'] = $errors;
}
$children = array();
foreach ($data->all() as $child) {
if ($child instanceof Form) {
$errorList = $this->convertFieldToArray($visitor, $child);
if($errorList) {
$children[$child->getName()] = $errorList;
}
}
}
if ($children) {
$form['field_errors'] = $children;
}
if ($isRoot) {
$visitor->setRoot($form);
}
return $form;
}

private function convertFieldToArray(VisitorInterface $visitor, Form $data)
{
$isRoot = null === $visitor->getRoot();
$form = new \ArrayObject();
$errors = array();
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form = $errors;
}
$children = array();
foreach ($data->all() as $child) {
if ($child instanceof Form) {
$errorList = $this->convertFieldToArray($visitor, $child);
if(sizeof($errorList) > 0) {
$children[$child->getName()] = $errorList;
}
}
}
if ($children) {
$form = $children;
}
if ($isRoot) {
$visitor->setRoot($form);
}
return $form;
}
}




/**
*
* Action to be taken before persist
* @ORM\PrePersist
*
*/
public function prePersist()
{
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}


/**
*
* Action to be taken before update
* @ORM\PreUpdate
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime();
}



@ORM\HasLifecycleCallbacks

* @ORM\Table(name="player",
* indexes={
* @ORM\Index(name="first_name_index", columns={"firstName"}),
* @ORM\Index(name="last_name_index", columns={"lastName"}),
* }
* ) 



use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\myenity
use App\Form\myenityType;
use App\Service\myenityService;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface; 


 throw new HttpException(Response::HTTP_BAD_REQUEST, $e);

test_service:
class: App\Tests\Service
public: true
tags: ['%host%']


myenity_service:
class:
App\Service\myenityService
public: true
autowire: true 


$requestContent = $request->getContent();
$requestData = json_decode($requestContent, true);
if (empty($requestData)) {
$requestData = $request->request->all();
}


$form = $this->createForm()
$form->submit($requestData);
$res = $this->myentityservice->createmyenity($player);
$this->translator->trans('playerid')
array("method"=>"PUT")
->add('firstName', TextType::class, array('required' => true, 'constraints' => array(new NotNull())))
 

/**
* @Route("/myentity/{id}", name="getentity", methods={"GET"})
*/


use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\NotNull;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

use Symfony\Component\HttpKernel\Exception\HttpException; 

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use App\Tests\Service\Test;
use GuzzleHttp\Client;

 $data = json_encode(array())
$response = Test::sendRequest('player', 'POST', $data);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
$data = json_decode($response->getBody(), true);
$this->assertArrayHasKey('id', $data);



<?php

namespace App\Tests\Service;

use GuzzleHttp\Client;


class Test{

public static $host = "http://myunit.local/";

public static function sendRequest($endPoint, $method, $data, $id = null){
$client = new Client([
'base_uri' => self::$host
]);

switch ($method){
case 'POST':
$response = $client->post($endPoint, [
'body' => $data,
'headers' => [
'Content-Type' => 'application/json',
]
]);
break;
case 'GET':
$response = $client->get($endPoint.'/'.$data);
break;
case 'DELETE':
$response = $client->delete($endPoint.'/'.$data);
break;
case 'PUT':
$response = $client->put($endPoint, [
'body' => $data,
'headers' => [
'Content-Type' => 'application/json',
]
]);
break;
}

return $response;
}
}



<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="success">
<source>success</source>
<target>Successful</target>
</trans-unit>
<trans-unit id="failed">
<source>failed</source>
<target>Something went worng. Please try again !!!</target>
</trans-unit>
<trans-unit id="dasda">
<source>asdada</source>
<target>sda Id required</target>
</trans-unit>
</body>
</file>
</xliff> 


$form->handleRequest($request);
$request->query->get('id');
'allow_extra_fields' => true,
'csrf_protection' => false 



$builder->add('bookedServices',CollectionType::class, array(
'entry_type' => BookedServicesType::class,
'allow_add' => true,
));

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();

if(!isset($data['bookedServices']) || $data['bookedServices'] == '' || empty($data['bookedServices']) || empty($data['bookedServices'][0])) {
throw new HttpException(Response::HTTP_BAD_REQUEST, "Booked Services details not added");
}

$event->setData($data);
});

$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$data = $event->getData();

$bookedServices = $data->getBookedServices();
foreach ($bookedServices as $bookedService) {
$bookedService->setCustomerAppointment($data);
}

$event->setData($data);
});


use Symfony\Component\Form\Extension\Core\Type\CollectionType;

/**
* @ORM\ManyToOne(targetEntity="CustomerAppointment", inversedBy="bookedServices")
* @ORM\JoinColumn(name="customer_appointment_id", referencedColumnName="id")
*/
private $customerAppointment;


/**
* @Assert\Valid
* @ORM\OneToMany(targetEntity="BookedServices", mappedBy="customerAppointment", cascade={"persist"})
*/
private $bookedServices;


* @Assert\NotBlank(
* message = "Start Time index is required"
* )


use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\Constraints as BookingAssert;

* @BookingAssert\BookingOffset

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
* @Annotation
*/
class BookingOffset extends Constraint
{
public $message = 'Invalid offset';

public function getTargets()
{
return self::CLASS_CONSTRAINT;
}

public function validatedBy()
{
return get_class($this).'Validator';
}
}


namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use AppBundle\Entity\CustomerAppointment;

/**
* @Annotation
*/
class BookingOffsetValidator extends ConstraintValidator
{

public function __construct()
{

}
public function validate($object, Constraint $constraint)
{
$offset = $object->getOffset();
if ($offset < CustomerAppointment::MIN_OFFSET){ // || intval(fmod($offset, CustomerAppointment::MIN_OFFSET)) != 0
$this->context->buildViolation($constraint->message)
->atPath('offset')
->addViolation();
}
}



validator.unique.holiday:
class: AppBundle\Validator\Constraints\UniqueHolidayValidator
arguments: ["@service_container"]
tags:
- { name: validator.constraint_validator, alias: UniqueHolidayValidator }