Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 3 additions & 76 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,80 +1,7 @@
# phalcon-api
Baka API using Phalcon

[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/?branch=master)
[![Build Status](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/badges/build.png?b=master)](https://scrutinizer-ci.com/g/bakaphp/phalcon-api/build-status/master)


Implementation of an API application using the Phalcon Framework [https://phalconphp.com](https://phalconphp.com)

### Installation
- Clone the project
- Copy `storage/ci/.env.example` and paste it in the root of the project and rename it `.env`
- On `phalcon-api/.env` in `MYSQL_ROOT_PASSWORD` and `DATA_API_MYSQL_PASS` assign the root password for MySQL.
- On `phalcon-api/.env`, update MySQL credentials (`DATA_API_MYSQL_NAME,DATA_API_MYSQL_USER,DATA_API_MYSQL_PASS`)
- On `phalcon-api/.env`, change `DATA_API_MYSQL_HOST = localhost` to `DATA_API_MYSQL_HOST = mysql`
- Download [Canvas Core](https://github.com/bakaphp/canvas-core) and copy it on the same folder where `phalcon-api` is located(Both projects must be in the same folder).
- On `phalcon-api/library/Core/autoload.php` comment `require dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . '/vendor/canvas/core/src/Core/functions.php';` and uncomment `require '/ canvas-core/src/Core/functions.php';`
- On `phalcon-api/library/Core/autoload.php` uncomment `'Canvas' => '/canvas-core/src',`
- Run Docker containers with the `docker-compose up --build` command
- After the build, access the project main container with `docker exec -it id_of_docker_container sh`
- Inside the container's console run get inside the `apps` folder, `cd app/`
- Inside the container's console run `./vendor/bin/phinx migrate -e production` to create the db , you need to have the phinx.php file , if you dont see it on your main filder you can find the copy at `storage/ci/phinx.php`
- Inside the container's console run `./vendor/bin/phinx seed:run` to create the necesary initial data
- Inside the container's console run `php cli/cli.php acl` AND `php cli/cli.php acl crm` to create the default roles of the system
- Inside the container's console run `./vendor/bin/codecept run` to run project tests.

**NOTE** : This requires [docker](https://www.docker.com/) to be present in your system. Visit their site for installation instructions.

**NOTE** : To ensure the project runs smoothly in a development environment you must comment or remove `canvas/core": "dev-master"` dependency from composer.json

### CLI
- On every deploy crear the session caches `./app/php cli/cli.php clearcache`
- On every deploy update your DB `./app/vendor/bin/phinx migrate -e production`
- Queue to clear jwt sessions `./app/php cli/cli.php clearcache sessions`

### Features
- User Managament
- Registration , Login, Multi Tenant
- ACL *working on it
- Saas Configuracion *working on it
- Company Configuration
- Payment / Free trial flow
- Rapid API CRUD Creation

##### JWT Tokens
As part of the security of the API, [JWT](https://jwt.io) are used. JSON Web Tokens offer an easy way for a consumer of the API to send requests without the need to authenticate all the time. The expiry of each token depends on the setup of the API. An admin can easily keep the expiry very short, thus consumers will always have to log in first and then access a resource, or they can increase the "life" of each token, thus having less calls to the API.

##### Middleware
- Lazy loading to save resources per request
- Stop execution as early as possible when an error occurs
- Execution
- NotFound - 404 when the resource requested is not found
- Authentication - After a `/login` checks the `Authentication` header
- TokenUser - When a token is supplied, check if it corresponds to a user in the database
- TokenVerification - When a token is supplied, check if it is correctly signed
- TokenValidation - When a token is supplied, check if it is valid (`issuedAt`, `notBefore`, `expires`)

##### Baka HTTP
We use the library [Baka HTTP](https://github.com/bakaphp/http) to handle our Routing

### Usage

#### Requests

**Error**

```json
{
"errors": {
"Description of the error no 1",
"Description of the error no 2"
},
}
```
# Gewaer API
Gewaer Kanvas App CRM API


### TODO
- Create docs endpoint
- Create docs endpoint**
- Migrate Testing to Baka
7 changes: 3 additions & 4 deletions api/controllers/AffiliatesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Gewaer\Models\Affiliates;

/**
* Class CustomFieldsController
* Class CustomFieldsController.
*
* @package Gewaer\Api\Controllers
*
Expand All @@ -20,13 +20,12 @@
class AffiliatesController extends BaseController
{
/**
* set objects
* set objects.
*
* @return void
*/
public function onConstruct(): void
{
$this->model = new Affiliates();
}

}
}
7 changes: 3 additions & 4 deletions api/controllers/AgentsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Gewaer\Models\Agents;

/**
* Class CustomFieldsController
* Class CustomFieldsController.
*
* @package Gewaer\Api\Controllers
*
Expand All @@ -20,13 +20,12 @@
class AgentsController extends BaseController
{
/**
* set objects
* set objects.
*
* @return void
*/
public function onConstruct(): void
{
$this->model = new Agents();
}

}
}
17 changes: 0 additions & 17 deletions api/controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,8 @@
namespace Gewaer\Api\Controllers;

use Canvas\Api\Controllers\AuthController as CanvasAuthController;
use Phalcon\Http\Response;
use Gewaer\Models\Users;
use Stripe\Stripe;
use Stripe\Customer;
use function Canvas\Core\envValue;
use Canvas\Traits\AuthTrait;
use Phalcon\Security\Random;
use Throwable;
use Canvas\Models\UsersAssociatedApps;
use Phalcon\Di;
use Gewaer\Zoho;
use Gewaer\Models\Affiliates;
use Canvas\Models\UserLinkedSources;
use Phalcon\Validation\Validator\Confirmation;
use Phalcon\Validation\Validator\Email as EmailValidator;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\StringLength;
use Baka\Auth\Models\Sessions;
use Canvas\Validation as CanvasValidation;

/**
* Class AuthController.
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class IndexController extends CanvasIndexController
*/
public function index($id = null) : Response
{
return $this->response(['Woot Canvas']);
return $this->response(['Woot Gewaer']);
}

/**
Expand Down
67 changes: 29 additions & 38 deletions api/controllers/LeadsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@
use Gewaer\Models\LeadsLinkedSources;

/**
* Base controller
* Base controller.
*
*/
class LeadsController extends BaseController
{
/**
* set objects
* set objects.
*
* @return void
*/
Expand All @@ -33,17 +33,17 @@ public function onConstruct(): void
}

/**
* get Leads count for specific user
* get Leads count for specific user.
*
* @method GET
* url /v1/leads
*
* @param int $id
* @return \Phalcon\Http\Response
* @return Response
*/
public function getLeadCountByUserId($id = null): Response
{
$company_id = $this->request->get('company_id', 'string');
$companyId = $this->request->get('company_id', 'string');

$leadsCount = '
SELECT count(*) as total
Expand All @@ -54,7 +54,7 @@ public function getLeadCountByUserId($id = null): Response
';

$result = $this->db->prepare($leadsCount);
$result->execute([$id, $company_id]);
$result->execute([$id, $companyId]);
$leads = $result->fetch();

$stats = [
Expand All @@ -67,13 +67,10 @@ public function getLeadCountByUserId($id = null): Response
}

/**
* get item
*
* @method GET
* url /v1/leads/{id}
* get item.
*
* @param int $id
* @return \Phalcon\Http\Response
* @return Response
*/
public function getById($id): Response
{
Expand Down Expand Up @@ -104,17 +101,15 @@ public function getById($id): Response
}

/**
* Overwrite create funcions
* Overwrite create function.
*
* @method POST
* /v1/leads
*
* @return \Phalcon\Http\Response
* @return Response
*/
public function create(): Response
{
//if post is empty, then get it from raw body array style
$data = empty($this->request->getPost()) ? $this->request->getJsonRawBody(true) : $this->request->getPost();
$data = $this->request->getPostData();

// This gonna check if the email have withe spaces
if (key_exists('email', $data)) {
Expand All @@ -131,7 +126,7 @@ public function create(): Response
'key' => $publicKey,
]);

//register an attemp to the leave before saving anything to have a backup of the given data
//register an attempt to the leave before saving anything to have a backup of the given data
$attempt = new LeadsAttempt();
$attempt->request = json_encode($data);
$attempt->ip = $this->request->getClientAddress();
Expand Down Expand Up @@ -192,13 +187,11 @@ public function create(): Response
}

/**
* Update a new Entry
* Update a new Entry.
*
* @method PUT
* url /v1/leads/{id}
*
* @param int $id
* @return \Phalcon\Http\Response
* @return Response
*/
public function edit($id): Response
{
Expand All @@ -208,7 +201,7 @@ public function edit($id): Response
]);

if ($lead) {
$data = $this->request->getPut();
$data = $this->request->getPutData();

$publicKey = $this->request->getHeader('PUBLICKEY');

Expand Down Expand Up @@ -249,7 +242,7 @@ public function edit($id): Response

//update
$lead->updateOrFail($data, $this->updateFields);

$attempt->processed = 1;
$attempt->update();

Expand All @@ -260,7 +253,7 @@ public function edit($id): Response
}

/**
* This method update one or more leads by the query on url
* This method update one or more leads by the query on url.
*
* @return array of leads updated
*/
Expand Down Expand Up @@ -303,10 +296,8 @@ public function multipleUpdates(): Response
}

/**
* Return every field from leads model
* Return every field from leads model.
*
* @method POST
* @url /v1/business
*
* @return Phalcon\Http\Response
*/
Expand All @@ -321,7 +312,7 @@ public function getFields()
}

/**
* Return every stadistic showed in the dashboard
* Return every stadistic showed in the dashboard.
*
* @method GET
* @url /v1/leads/stats
Expand Down Expand Up @@ -427,7 +418,7 @@ public function getStats(): Response
}

/**
* Filter leads by a specific custom field
* Filter leads by a specific custom field.
* @param $memberId Member Id
* @return Response
*/
Expand All @@ -438,9 +429,9 @@ public function getLeadsByCustomField($memberId): Response

//lets search custom field's id
$customFieldId = CustomFields::findFirst([
'conditions' => 'name = ?0',
'bind' => [$searchBy]
]);
'conditions' => 'name = ?0',
'bind' => [$searchBy]
]);

if (!$customFieldId) {
throw new Exception('Custom field not found');
Expand Down Expand Up @@ -498,18 +489,18 @@ public function getLeadsByCustomField($memberId): Response
$limit = (int) $this->request->getQuery('limit', 'int', 25);

$newResult = [
'data' => $newResult,
'limit' => $limit,
'page' => $this->request->getQuery('page', 'int', 1),
'total_pages' => ceil($count / $limit)
];
'data' => $newResult,
'limit' => $limit,
'page' => $this->request->getQuery('page', 'int', 1),
'total_pages' => ceil($count / $limit)
];
}

return $this->response($newResult);
}

/**
* Fetch lead's linked zoho id
* Fetch lead's linked zoho id.
* @param $id
* @return Response
*/
Expand Down
Loading