<?php
namespace App\Classes;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\Token;
use App\User;
class Auth
{
private function decryptUserFingerprint($fingerprint)
{
return openssl_decrypt($fingerprint, 'aes-256-cbc', env('PRIVATE_FINGERPRINT_KEY'));
}
public function checkUserPinAndFingerprint($request)
{
// if (!$this->hasPIN($request)) if (!$this->hasFingerPrint($request)) return response()->json(['message' => 'Informe PIN ou Fingerprint.'], 400);
if (!$this->hasPIN($request)) return response()->json(['message' => 'Autenticacao autorizada.'], 200);
if ($this->hasFingerPrint($request)) {
if (auth()->user()->user_id !== $this->decryptUserFingerprint($request->user_fingerprint)) return response()->json(['message' => 'FingerPrint Invalido.'], 400);
else return response()->json(['message' => 'Autenticacao autorizada.'], 200);
}
if ($this->getPinAttempts(auth('api')->user()->id) >= 2) {
$user = $this->getUser(auth('api')->user()->id);
$user->status = 0;
$user->is_online = 0;
$user->update();
$pushMsgBloqued = "Caro cliente " . $user->name . ", errou a SENHA 3 vezes. A tua conta está bloqueada. Pra recuperar a tua conta entre em contacto com a nossa linha de atendimento atraves dos nossos canais digitais, Facebook, Whatsapp ou pelo tefone 846002000.";
$pushBodyBloqued = "Caro cliente " . $user->name . ", a tua conta está bloqueada.";
if ($user->firebase_token)
$this->sendPush($pushBodyBloqued, $pushMsgBloqued, $user->firebase_token);
//? Update do dispositivo onde esta ser feito o login
$last_login = DB::table('user_login_devices')->where('user_id', $user->id)->first();
if ($last_login)
$this->destroyUserAccessToken($last_login->access_token);
return response()->json(['message' => 'Utilizador bloqueado, excedeu o número de tentativas de PIN', 'success' => 0], 400);
}
if (!$this->validatePIN(auth('api')->user()->id, $request->pin, auth('api')->user()->pin)) {
$user = $this->getUser(auth('api')->user()->id);
$pushMsg = "Caro cliente " . $user->name . ", restam te somente " . (3 - (int)$user->pin_attempts) . " tentativa(s). Se falhares 3 vezes o tem PIN a tua conta será bloqueada.";
$pushBody = "Caro cliente " . $user->name . ", a tua conta será bloqueada se digitares o pin incorrecto 3 vezes. Por favor verifique o teu PIN e tenta novamente.";
if ($user->firebase_token)
$this->sendPush($pushBody, $pushMsg, $user->firebase_token);
return response()->json(['message' => 'Pin Incorrecto, tente novamente', 'success' => 0], 400);
}
return response()->json(['message' => 'Autenticação autorizada', 'success' => 1], 200);
}
public function checkUserPin($request)
{
if (!$this->hasPIN($request)) return response()->json(['message' => 'Autenticação não autorizada.','success'=> 0], 400);;
if ($this->getPinAttempts(auth('api')->user()->id) >= 2) {
$user = $this->getUser(auth('api')->user()->id);
$user->status = 0;
$user->is_online = 0;
$user->update();
$pushMsgBloqued = "Caro cliente " . $user->name . ", errou a SENHA 3 vezes. A tua conta está bloqueada. Pra recuperar a tua conta entre em contacto com a nossa linha de atendimento atraves dos nossos canais digitais, Facebook, Whatsapp ou pelo tefone 846002000.";
$pushBodyBloqued = "Caro cliente " . $user->name . ", a tua conta está bloqueada.";
if ($user->firebase_token)
$this->sendPush($pushBodyBloqued, $pushMsgBloqued, $user->firebase_token);
//? Update do dispositivo onde esta ser feito o login
$last_login = DB::table('user_login_devices')->where('user_id', $user->id)->first();
if ($last_login)
$this->destroyUserAccessToken($last_login->access_token);
return response()->json(['message' => 'Utilizador bloqueado, excedeu o número de tentativas de PIN','success'=>0], 400);
}
if (!$this->validatePIN(auth('api')->user()->id, $request->pin, auth('api')->user()->pin)) {
$user = $this->getUser(auth('api')->user()->id);
$pushMsg = "Caro cliente " . $user->name . ", restam te somente " . (3 - (int)$user->pin_attempts) . " tentativa(s). Se falhares 3 vezes o tem PIN a tua conta será bloqueada.";
$pushBody = "Caro cliente " . $user->name . ", a tua conta será bloqueada se digitares o pin incorrecto 3 vezes. Por favor verifique o teu PIN e tenta novamente.";
if ($user->firebase_token)
$this->sendPush($pushBody, $pushMsg, $user->firebase_token);
return response()->json(['message' => 'Pin Incorrecto, tente novamente','success'=>0], 400);
}
return response()->json(['message' => 'Autenticação autorizada.','success'=> 1], 200);
}
private function hasPIN($request)
{
if ($request->has("pin") && $request->pin != "") return true;
return false;
}
private function hasFingerPrint($request)
{
if ($request->has("user_fingerprint") && $request->user_fingerprint != "") return true;
return false;
}
private function pinAttempts($userID)
{
$user = $this->getUser($userID);
$user->pin_attempts = $user->pin_attempts + 1;
$user->update();
}
private function getPinAttempts($userID)
{
$user = $this->getUser($userID);
return $user->pin_attempts;
}
private function validatePIN($userID, $pinFornecido, $pinUsuario)
{
if (Hash::check($pinFornecido, $pinUsuario)) {
$user = $this->getUser($userID);
$user->pin_attempts = 0;
$user->update();
return true;
}
$this->pinAttempts($userID);
return false;
}
private function destroyUserAccessToken($accessToken)
{
$token_parts = explode('.', $accessToken);
$token_header = $token_parts[1];
$token_header_json = base64_decode($token_header);
$token_header_array = json_decode($token_header_json, true);
$token_id = $token_header_array['jti'];
DB::table('oauth_refresh_tokens')->where('access_token_id', $token_id)->update(['revoked' => true]);
$token = Token::find($token_id);
$token->revoke();
}
private function getUser($userID)
{
return User::findOrFail($userID);
// return User::query()->where('id',$userID)->first();
}
//? Send Push before PIN error
private function sendPush($pushBody, $pushMsg, $pushFirebaseToken)
{
$notification = array(
'icon' => 'ic_i_mali_cover',
'title' => 'PIN incorrecto',
'body' => $pushBody,
'click_action' => 'com.imali.payapp.payment_NOTICIA',
'color' => '#ffffff'
);
$data = array(
'sms' => $pushMsg,
'route' => 'NOTICIA',
'terminal' => 'firebase'
);
$this->pushNotifification($pushFirebaseToken, $notification, $data);
}
public function pushNotifification($token, $notification = array(), $data = array())
{
$apiKey = 'AAAA8zVzEPQ:APA91bHl_DXB6UGb_6gZlmFnaLTQoANtX_OBjvl3nOy2bSlnFhxedvk6EhGj7cZoIvmlbKeCnqGxXbuyMH_rEPuhRXvuitXzo6Pfl2TMXLar1PlifXqEhYq6tS55UMrY2Kffzj-P_UH-';
$fields = array('to' => $token, 'notification' => $notification, 'data' => $data);
$headers = array('Authorization: key=' . $apiKey, 'Content-Type: application/json');
$url = 'https://fcm.googleapis.com/fcm/send';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result, true);
}
}