From Tiny Mosquito, 10 Years ago, written in Plain Text.
Embed
  1. <?php namespace Momentum\V1_1\Services\Membership;
  2.  
  3. use Auth;
  4. use Exception;
  5. use Illuminate\Auth\EloquentUserProvider;
  6. use Illuminate\Auth\Guard;
  7. use Illuminate\Support\Str;
  8. use Momentum\V1_1\Entities\Device\Profile;
  9. use Momentum\V1_1\Entities\Device\PushNotificationDevice;
  10. use Momentum\V1_1\Entities\Membership\AnonymousUser;
  11. use Momentum\V1_1\Entities\Membership\User;
  12. use Momentum\V1_1\Entities\OAuth\AccessToken;
  13. use Momentum\V1_1\Entities\OAuth\Client;
  14. use Momentum\V1_1\Entities\OAuth\Session;
  15. use Request;
  16.  
  17. class OAuthService {
  18.  
  19.     /**
  20.      * @var
  21.      */
  22.     protected $guzzleClient;
  23.  
  24.     public function __construct()
  25.     {
  26.         $this->guzzleClient = new \Guzzle\Http\Client;
  27.     }
  28.  
  29.     /**
  30.      * @param $data
  31.      * @return array|\Guzzle\Http\Message\Response
  32.      * @throws Exception
  33.      */
  34.     public function attemptLogin($data)
  35.     {
  36.         $data = array_merge($this->getClientData() + ["grant_type" => "password", "scope" => "mobile"], $data);
  37.         $response = $this->guzzleClient->post('http://'.env('API_DOMAIN').'/v1.1/oauth/access_token', [], $data)->send();
  38.  
  39.         if ($this->isValidResponse($response)) {
  40.             $parsedResponse = $this->parseResponse($response);
  41.  
  42.             // Login was successful, check for the "application" param and create a new if it doesn't exist yet
  43.             $accessToken = AccessToken::whereId($parsedResponse['accessToken'])->first();
  44.             $session = Session::whereId($accessToken->session_id)->first();
  45.             $ownerId = $session->owner_id;
  46.             $user = User::where("userId", $ownerId)->first();
  47.  
  48.             if(isset($user)) {
  49.                 if(isset($user) && is_null($user) && $user) {
  50.                     $application = isset($data["application"]) ? $data["application"] : "sipsup";
  51.                     if (!$user->hasApplication($application)) $user->addApplication($application);
  52.                 }
  53.  
  54.                 if (Request::has('test')) {
  55.                     if (!$this->validateDeviceProfile($user)) {
  56.                         throw new \Exception('invalid_login_exception', 400);
  57.                     }
  58.  
  59.                     // Enable push notifications
  60.                     $this->enablePushNotifications($user);
  61.                 }
  62.             }
  63.  
  64.             return $parsedResponse;
  65.         }
  66.  
  67.         return $response;
  68.     }
  69.  
  70.     /**
  71.      * @return array|\Guzzle\Http\Message\Response
  72.      */
  73.     public function attemptTokenRefresh()
  74.     {
  75.         $cookie = Request::has('refresh_token_cookie') ? Request::input('refresh_token_cookie') : $request->cookie('refreshToken');
  76.         $scope = Request::has('scope') ? Request::input('scope') : "mobile";
  77.         $data = array_merge($this->getClientData() + ["grant_type" => "refresh_token", "scope" => $scope], ["refresh_token" => $cookie]);
  78.         $response = $this->guzzleClient->post('http://'.env('API_DOMAIN').'/v1.1/oauth/access_token', [], $data)->send();
  79.  
  80.         if ($this->isValidResponse($response)) {
  81.             $parsedResponse = $this->parseResponse($response);
  82.             return $parsedResponse;
  83.         }
  84.  
  85.         return $response;
  86.     }
  87.  
  88.     /**
  89.      * @param $email
  90.      * @param $password
  91.      * @param $loginType
  92.      * @return bool
  93.      */
  94.     public function verifyCredentials($email, $password, $loginType)
  95.     {
  96.         if ($loginType == "facebook" and Str::contains($email, "fb:") and Str::contains($password, "fb:")) {
  97.             $facebookId = explode(":", $email)[1];
  98.             $user = User::where('facebookId', $facebookId)->first();
  99.             if ($user) return $user->userId;
  100.             return false;
  101.         } else if ($loginType == "regular" and is_user_anonymous(['primaryEmail' => $email])) {
  102.  
  103.             Auth::extend('anonymousAuth', function($app){
  104.                 $myProvider = new EloquentUserProvider($app['hash'], AnonymousUser::class);
  105.                 return new Guard($myProvider, $app['session.store']);
  106.             });
  107.  
  108.             $validate = Auth::driver('anonymousAuth')->attempt([
  109.                 'primaryEmail' => $email,
  110.                 'password' => $password
  111.             ], false, true);
  112.  
  113.             if ($validate) return Auth::driver('anonymousAuth')->id();
  114.  
  115.             return false;
  116.         } else if ($loginType == "regular") {
  117.             $validate = Auth::attempt([
  118.                 'primaryEmail' => $email,
  119.                 'password' => $password
  120.             ], false, true);
  121.  
  122.             if ($validate) return Auth::id();
  123.  
  124.             return false;
  125.         }
  126.  
  127.         return false;
  128.     }
  129.  
  130.     /**
  131.      * @param $response
  132.      * @return array
  133.      */
  134.     private function parseResponse($response)
  135.     {
  136.         return [
  137.             'accessToken'            => $response->json()['access_token'],
  138.             'accessTokenExpiration'  => $response->json()['expires_in'],
  139.             'refreshToken'           => $response->json()['refresh_token'],
  140.             'refreshTokenExpiration' => $response->json()['refresh_token_expires_in']
  141.         ];
  142.     }
  143.  
  144.     /**
  145.      * @param $response
  146.      * @return bool
  147.      */
  148.     private function isValidResponse($response)
  149.     {
  150.         return isset($response->json()['access_token']);
  151.     }
  152.  
  153.     /**
  154.      * @return array
  155.      */
  156.     private function getClientData()
  157.     {
  158.         $client = Client::whereName('MobileApp')->first();
  159.         return ['client_id' => $client->id, 'client_secret' => $client->secret];
  160.     }
  161.  
  162.     /**
  163.      * @param $user
  164.      * @return bool
  165.      */
  166.     private function validateDeviceProfile($user)
  167.     {
  168.         if ($user->isAnonymous()) return true;
  169.  
  170.         $deviceIdHeader = Request::get('deviceId');
  171.         if (isset($deviceIdHeader)) {
  172.             $deviceProfile = Profile::where('deviceId', $deviceIdHeader)->where('userId', $user->userId)->first();
  173.  
  174.             if ($deviceProfile) {
  175.                 // If device profile exists and active = 0, return false;
  176.                 if ($deviceProfile->active == 0) return false;
  177.                 return true;
  178.             }
  179.  
  180.             // Create device profile and return true
  181.             $deviceProfile = Profile::create([
  182.                 'deviceId' => $deviceIdHeader,
  183.                 'userId' => $user->userId,
  184.                 'active' => 1
  185.             ]);
  186.  
  187.             if (!$deviceProfile) return false;
  188.             return true;
  189.         }
  190.  
  191.         return false;
  192.     }
  193.  
  194.     /**
  195.      * @param $user
  196.      */
  197.     private function enablePushNotifications($user)
  198.     {
  199.         if ($user->isAnonymous()) return;
  200.  
  201.         $pushIdHeader = Request::get('pushId');
  202.         $deviceIdHeader = Request::get('deviceId');
  203.  
  204.         if ($pushIdHeader and $deviceIdHeader) {
  205.  
  206.             $pushNotificationDevice = PushNotificationDevice::where('pushId', $pushIdHeader)->first();
  207.  
  208.             if ($pushNotificationDevice) {
  209.                 $pushNotificationDevice->active = 1;
  210.                 $pushNotificationDevice->save();
  211.                 return;
  212.             }
  213.  
  214.             $pushNotificationDevice = PushNotificationDevice::create([
  215.                 'pushId' => $pushIdHeader,
  216.                 'deviceId' => $deviceIdHeader,
  217.                 'userId' => $user->userId,
  218.                 'created' => date('Y-m-d H:i:s'),
  219.                 'active' => 1
  220.             ]);
  221.  
  222.             return;
  223.         }
  224.  
  225.         return;
  226.     }
  227.  
  228. }