Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fabricio Bellesa Silva #49

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
91 changes: 69 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,82 @@
![PicPay](https://user-images.githubusercontent.com/1765696/26998603-711fcf30-4d5c-11e7-9281-0d9eb20337ad.png)

# Teste Backend
# Lumen API + Vue.Js + Docker - Search User

O desafio é criar uma API REST que busca usuarios pelo nome e username a partir de uma palavra chave. Faça o download do arquivo [users.csv.gz](https://s3.amazonaws.com/careers-picpay/users.csv.gz) que contém o banco de dados que deve ser usado na busca. Ele contém os IDs, nomes e usernames dos usuários.
![](https://dzwonsemrish7.cloudfront.net/items/0c062c2b400K173M2q1G/Screen%20Recording%202018-09-26%20at%2012.54%20AM.gif?v=47303fe3)

###### Exemplo
| ID | Nome | Username |
|--------------------------------------|-------------------|----------------------|
| 065d8403-8a8f-484d-b602-9138ff7dedcf | Wadson marcia | wadson.marcia |
| 5761be9e-3e27-4be8-87bc-5455db08408 | Kylton Saura | kylton.saura |
| ef735189-105d-4784-8e2d-c8abb07e72d3 | Edmundo Cassemiro | edmundo.cassemiro |
| aaa40f4e-da26-42ee-b707-cb81e00610d5 | Raimundira M | raimundiram |
| 51ba0961-8d5b-47be-bcb4-54633a567a99 | Pricila Kilder | pricilakilderitaliani|
## Intro

- O gif acima foi gravado com a base de 8.000.000 de usários.
- A peformance foi resolvida apenas utilizando indices.
- Foi utilizado o Vue Material para o frontend.
- A aplicação é responsiva.📱
- A prioridade foi resolvida com uma coluna de `priority` no banco de dados. Que é atualizada por um serviço buscando informações dos textos disponibilizados.

## Prerequisites

Também são fornecidas duas listas de usuários que devem ser utilizadas para priorizar os resultados da busca. A lista 1 tem mais prioridade que a lista 2. Ou seja, se dois usuarios casam com os criterios de busca, aquele que está na lista 1 deverá ser exibido primeiro em relação àquele que está na lista 2. Os que não estão em nenhuma das listas são exibidos em seguida.
Docker instalado.

As listas podem ser encontradas na raiz deste repositório ([lista_relevancia_1.txt](lista_relevancia_1.txt) e [lista_relevancia_2.txt](lista_relevancia_2.txt)).
Os resultados devem ser retornados paginados de 15 em 15 registros.

Escolha as tecnologias que você vai usar e tente montar uma solução completa para rodar a aplicação.
## Installing

Faça um ***Fork*** deste repositório e abra um ***Pull Request***, **com seu nome na descrição**, para participar. Assim que terminar, envie um e-mail para ***[email protected]*** com o seu usuário do Github nos avisando.
Baixe o projeto

-----
```
Git clone
```

Vá para pasta do projeto

```
cd trabalhe-conosco-backend-dev
```

Suba os conteiners. (🕰 ± 20 min)

```
docker-compose up -d
```

Execute os comandos para migrar os dados (🕰 ± 30 min)

```
sh cmd.sh
```

## Frontend

Acesse a url: http://localhost:5000/#/

Faça login com os dados:

```
User: [email protected]
Password: 12345
```

[Buscando por 'charl' gif](https://dzwonsemrish7.cloudfront.net/items/230C0s0F0U3G1M1J2q15/Screen%20Recording%202018-09-26%20at%2001.00%20AM.gif?v=3ce63476)

## Backend

Documentação completa:
https://documenter.getpostman.com/view/5151635/RWaRMQVa

### POST Login

Exemplo:
```
http://localhost:8000/auth/[email protected]&password=12345
```

Após efetuado o login copie o token para realizar o request na Seach User.

### GET Search User

Exemplo:
```
http://localhost:8000/api/users/?q=Charl
```

Adicione o Token recebido na key `Authorization` no Header do request.

### Diferenciais

- Criar um frontend para realizar a busca com uma UX elaborada
- Criar uma solução de autenticação entre o frontend e o backend
- Ter um desempenho elevado num conjunto de dados muito grande
- Utilizar o Docker

20 changes: 20 additions & 0 deletions app/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=search-user-db
DB_PORT=3306
DB_DATABASE=picpay
DB_USERNAME=root
DB_PASSWORD=root

CACHE_DRIVER=file
QUEUE_DRIVER=sync

APP_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
JWT_SECRET=JhbGciOiJIUzI1N0eXAiOiJKV1QiLC
2 changes: 2 additions & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/vendor
composer.lock
54 changes: 54 additions & 0 deletions app/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
FROM alpine:3.8

RUN apk --update add --no-cache \
nginx \
curl \
supervisor \
php7 \
php7-dom \
php7-fpm \
php7-mbstring \
php7-mcrypt \
php7-opcache \
php7-pdo \
php7-pdo_mysql \
php7-xml \
php7-simplexml \
php7-phar \
php7-openssl \
php7-json \
php7-curl \
php7-ctype \
php7-session \
php7-gd \
php7-tokenizer \
php7-xmlwriter \
&& mv /usr/bin/php /usr/bin/php2 \
&& ln -s /usr/bin/php7 /usr/bin/php \
&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer \
&& mkdir -p /app \
&& addgroup -g 1000 -S www \
&& adduser -u 1000 -D -S -G www -h /app -g www www \
&& chown -R www:www /var/lib/nginx \
&& chown -R www:www /var/tmp/nginx

COPY /docker_config/nginx/nginx.conf /etc/nginx/nginx.conf
COPY /docker_config/nginx/default /etc/nginx/sites-enabled/default

COPY /docker_config/php/php.ini /etc/php7/php.ini
COPY /docker_config/php/www.conf /etc/php7/php-fpm.d/www.conf

COPY /docker_config/supervisord.conf /etc/supervisord.conf


COPY ./ ./app

WORKDIR /app

ADD /docker_config/cmd.sh /cmd.sh

RUN chmod +x /cmd.sh

RUN composer install

CMD ["/cmd.sh"]
Empty file.
29 changes: 29 additions & 0 deletions app/app/Console/Kernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
10 changes: 10 additions & 0 deletions app/app/Events/Event.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;

abstract class Event
{
use SerializesModels;
}
16 changes: 16 additions & 0 deletions app/app/Events/ExampleEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\Events;

class ExampleEvent extends Event
{
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
}
50 changes: 50 additions & 0 deletions app/app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];

/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}

/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
75 changes: 75 additions & 0 deletions app/app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php
namespace App\Http\Controllers;
use Validator;
use App\Profile;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\Hash;
use Laravel\Lumen\Routing\Controller as BaseController;
class AuthController extends BaseController
{
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
private $request;

/**
* Create a new controller instance.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct(Request $request) {
$this->request = $request;
}

/**
* Create a new token.
*
* @param \App\Profile $profile
* @return string
*/
protected function jwt(Profile $profile) {
$payload = [
'iss' => "lumen-jwt", // Issuer of the token
'sub' => $profile->id, // Subject of the token
'iat' => time(), // Time when JWT was issued.
'exp' => time() + 60*60 // Expiration time
];

return JWT::encode($payload, env('JWT_SECRET'));
}

/**
* Authenticate a profile and return the token if the provided credentials are correct.
*
* @param \App\Profile $profile
* @return mixed
*/
public function authenticate(Profile $profile) {
$this->validate($this->request, [
'email' => 'required|email',
'password' => 'required'
]);
// Find the profile by email
$profile = Profile::where('email', $this->request->input('email'))->first();
if (!$profile) {
return response()->json([
'error' => 'Email does not exist.'
], 400);
}
// Verify the password and generate the token
if (Hash::check($this->request->input('password'), $profile->password)) {
return response()->json([
'token' => $this->jwt($profile)
], 200);
}
// Bad Request response
return response()->json([
'error' => 'Email or password is wrong.'
], 400);
}
}
10 changes: 10 additions & 0 deletions app/app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
//
}
Loading