public function execute(AuthenticationCredentials $authCreds) { $authService = AuthenticationService::instance(); // Make sure the creds are valid if (!$authCreds->isValid()) { Application::instance()->getLogger()->error(sprintf('Error validating auth credentials %s', var_export($authCreds, true))); throw new Exception('Invalid auth credentials'); } // Account merge if (Session::set('accountMerge') === '1') { // Must be logged in to do a merge if (!Session::hasRole(UserRole::USER)) { throw new Exception('Authentication required for account merge'); } $authService->handleAuthAndMerge($authCreds); return 'redirect: /profile/authentication'; } // Follow url *notice the set, returning and clearing the var $follow = Session::set('follow'); // If the user profile doesnt exist, go to the register page if (!$authService->getUserAuthProfileExists($authCreds)) { Session::set('authSession', $authCreds); $url = '/register?code=' . urlencode($authCreds->getAuthCode()); if (!empty($follow)) { $url .= '&follow=' . urlencode($follow); } return 'redirect: ' . $url; } // User exists, handle the auth $authService->handleAuthCredentials($authCreds); if (!empty($follow) && substr($follow, 0, 1) == '/') { return 'redirect: ' . $follow; } return 'redirect: /profile'; }
/** * @Route ("/admin/chat/broadcast") * @Secure ({"ADMIN"}) * * @param array $params * @param ViewModel $model * @throws Exception * @return string */ public function adminChatBroadcast(array $params, ViewModel $model) { $model->title = 'Chat'; FilterParams::required($params, 'message'); $chatIntegrationService = ChatIntegrationService::instance(); $chatIntegrationService->sendBroadcast($params['message']); Session::set('modelSuccess', sprintf('Sent broadcast: %s', $params['message'])); return 'redirect: /admin/chat'; }
/** * @param array $params * @return string * @throws Exception */ public function authenticate(array $params) { if (!isset($params['oauth_token']) || empty($params['oauth_token']) || !isset($params['oauth_verifier']) || empty($params['oauth_verifier'])) { throw new Exception('Authentication failed'); } $oauth = Session::set('oauth'); if ($params['oauth_token'] !== $oauth['oauth_token']) { throw new Exception('Invalid login session'); } $twitterOAuthConf = Config::$a['oauth']['providers']['twitter']; $tmhOAuth = new \tmhOAuth(array('consumer_key' => $twitterOAuthConf['clientId'], 'consumer_secret' => $twitterOAuthConf['clientSecret'], 'token' => $oauth['oauth_token'], 'secret' => $oauth['oauth_token_secret'], 'curl_connecttimeout' => Config::$a['curl']['connecttimeout'], 'curl_timeout' => Config::$a['curl']['timeout'], 'curl_ssl_verifypeer' => Config::$a['curl']['verifypeer'])); /** @noinspection PhpVoidFunctionResultUsedInspection */ $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url('oauth/access_token', ''), 'params' => array('oauth_verifier' => trim($params['oauth_verifier'])))); if ($code != 200) { throw new Exception('Failed to retrieve user data'); } $data = $tmhOAuth->extract_params($tmhOAuth->response['response']); $authCreds = $this->getAuthCredentials($oauth['oauth_token'], $data); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * @Route ("/login") * @HttpMethod ({"POST"}) * * @param array $params * @param ViewModel $model * @return string */ public function loginPost(array $params, ViewModel $model) { $userService = UserService::instance(); $authProvider = isset($params['authProvider']) && !empty($params['authProvider']) ? $params['authProvider'] : ''; $rememberme = isset($params['rememberme']) && !empty($params['rememberme']) ? true : false; if (empty($authProvider)) { $model->title = 'Login error'; $model->rememberme = $rememberme; $model->error = new Exception('Please select a authentication provider'); return 'login'; } Session::start(Session::START_NOCOOKIE); if ($rememberme) { Session::set('rememberme', 1); } if (isset($params['follow']) && !empty($params['follow'])) { Session::set('follow', $params['follow']); } switch (strtoupper($authProvider)) { case 'TWITCH': $authHandler = new TwitchAuthHandler(); return 'redirect: ' . $authHandler->getAuthenticationUrl(); case 'GOOGLE': $authHandler = new GoogleAuthHandler(); return 'redirect: ' . $authHandler->getAuthenticationUrl(); case 'TWITTER': $authHandler = new TwitterAuthHandler(); return 'redirect: ' . $authHandler->getAuthenticationUrl(); case 'REDDIT': $authHandler = new RedditAuthHandler(); return 'redirect: ' . $authHandler->getAuthenticationUrl(); default: $model->title = 'Login error'; $model->rememberme = $rememberme; $model->error = new Exception('Authentication type not supported'); return 'login'; } }
/** * @Route ("/subscription/process") * @Secure ({"USER"}) * * We were redirected here from PayPal after the buyer approved/cancelled the payment * * @param array $params * @return string * @throws Exception * @throws \Destiny\Common\Utils\FilterParamsException * TODO clean this method up */ public function subscriptionProcess(array $params) { FilterParams::required($params, 'subscriptionId'); FilterParams::required($params, 'token'); FilterParams::declared($params, 'success'); $userId = Session::getCredentials()->getUserId(); $userService = UserService::instance(); $ordersService = OrdersService::instance(); $subscriptionsService = SubscriptionsService::instance(); $payPalApiService = PayPalApiService::instance(); $chatIntegrationService = ChatIntegrationService::instance(); $authenticationService = AuthenticationService::instance(); $log = Application::instance()->getLogger(); $subscription = $subscriptionsService->getSubscriptionById($params['subscriptionId']); if (empty($subscription) || strcasecmp($subscription['status'], SubscriptionStatus::_NEW) !== 0) { throw new Exception('Invalid subscription record'); } try { $subscriptionType = $subscriptionsService->getSubscriptionType($subscription['subscriptionType']); $user = $userService->getUserById($subscription['userId']); if ($user['userId'] != $userId && $subscription['gifter'] != $userId) { throw new Exception('Invalid subscription'); } if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) { throw new Exception('Order request failed'); } if (!$payPalApiService->retrieveCheckoutInfo($params['token'])) { throw new Exception('Failed to retrieve express checkout details'); } FilterParams::required($params, 'PayerID'); // if the order status is an error, the payerID is not returned Session::set('subscriptionId'); Session::set('token'); // Create the payment profile // Payment date is 1 day before subscription rolls over. if ($subscription['recurring'] == 1 || $subscription['recurring'] == true) { $startPaymentDate = Date::getDateTime(); $nextPaymentDate = Date::getDateTime(); $nextPaymentDate->modify('+' . $subscriptionType['billingFrequency'] . ' ' . strtolower($subscriptionType['billingPeriod'])); $nextPaymentDate->modify('-1 DAY'); $reference = $subscription['userId'] . '-' . $subscription['subscriptionId']; $paymentProfileId = $payPalApiService->createRecurringPaymentProfile($params['token'], $reference, $user['username'], $nextPaymentDate, $subscriptionType); if (empty($paymentProfileId)) { throw new Exception('Invalid recurring payment profileId returned from Paypal'); } $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::ACTIVE, 'paymentProfileId' => $paymentProfileId, 'billingStartDate' => $startPaymentDate->format('Y-m-d H:i:s'), 'billingNextDate' => $nextPaymentDate->format('Y-m-d H:i:s'))); } // Record the payments as well as check if any are not in the completed state // we put the subscription into "PENDING" state if a payment is found not completed $subscriptionStatus = SubscriptionStatus::ACTIVE; $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $subscriptionType['amount']); $payments = $payPalApiService->getResponsePayments($DoECResponse); foreach ($payments as $payment) { $payment['subscriptionId'] = $subscription['subscriptionId']; $payment['payerId'] = $params['PayerID']; $ordersService->addPayment($payment); // TODO: Payment provides no way of telling if the transaction with ALL payments was successful if ($payment['paymentStatus'] != PaymentStatus::COMPLETED) { $subscriptionStatus = SubscriptionStatus::PENDING; } } // Update subscription status $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => $subscriptionStatus)); } catch (Exception $e) { $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => SubscriptionStatus::ERROR)); $log->critical($e->getMessage(), $subscription); return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/error'; } // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2 // we unban the user if no ban is found because it also unmutes $ban = $userService->getUserActiveBan($user['userId']); if (empty($ban) or (!empty($ban['endtimestamp']) or $subscriptionType['tier'] >= 2)) { $chatIntegrationService->sendUnban($user['userId']); } // Broadcast $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])]; if (!empty($subscription['gifter'])) { $gifter = $userService->getUserById($subscription['gifter']); $userName = $gifter['username']; $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $user['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote)); } else { $userName = $user['username']; $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $user['username'], $subscriptionType['tierLabel'], $randomEmote)); } $subMessage = Session::set('subMessage'); if (!empty($subMessage)) { $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage)); } // Update the user $authenticationService->flagUserForUpdate($user['userId']); // Redirect to completion page return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/complete'; }
/** * @Route ("/admin/user/{id}/subscription/{subscriptionId}/save") * @Route ("/admin/user/{id}/subscription/save") * @Secure ({"ADMIN"}) * @HttpMethod ({"POST"}) * * @param array $params * @param ViewModel $model * @throws Exception * @return string */ public function subscriptionSave(array $params, ViewModel $model) { FilterParams::required($params, 'subscriptionType'); FilterParams::required($params, 'status'); FilterParams::required($params, 'createdDate'); FilterParams::required($params, 'endDate'); $subscriptionsService = SubscriptionsService::instance(); $subscriptionType = $subscriptionsService->getSubscriptionType($params['subscriptionType']); $subscription = array(); $subscription['subscriptionType'] = $subscriptionType['id']; $subscription['subscriptionTier'] = $subscriptionType['tier']; $subscription['status'] = $params['status']; $subscription['createdDate'] = $params['createdDate']; $subscription['endDate'] = $params['endDate']; $subscription['userId'] = $params['id']; $subscription['subscriptionSource'] = isset($params['subscriptionSource']) && !empty($params['subscriptionSource']) ? $params['subscriptionSource'] : Config::$a['subscriptionType']; if (isset($params['subscriptionId']) && !empty($params['subscriptionId'])) { $subscription['subscriptionId'] = $params['subscriptionId']; $subscriptionId = $subscription['subscriptionId']; $subscriptionsService->updateSubscription($subscription); Session::set('modelSuccess', 'Subscription updated!'); } else { $subscriptionId = $subscriptionsService->addSubscription($subscription); Session::set('modelSuccess', 'Subscription created!'); } $authService = AuthenticationService::instance(); $authService->flagUserForUpdate($params['id']); return 'redirect: /admin/user/' . urlencode($params['id']) . '/subscription/' . urlencode($subscriptionId) . '/edit'; }
/** * Update/add a address * * @Route ("/profile/address/update") * @HttpMethod ({"POST"}) * @Secure ({"USER"}) * * @param array $params * @return string */ public function updateAddress(array $params) { FilterParams::required($params, 'fullName'); FilterParams::required($params, 'line1'); FilterParams::declared($params, 'line2'); FilterParams::required($params, 'city'); FilterParams::required($params, 'region'); FilterParams::required($params, 'zip'); FilterParams::required($params, 'country'); $userService = UserService::instance(); $userId = Session::getCredentials()->getUserId(); $address = $userService->getAddressByUserId($userId); if (empty($address)) { $address = array(); $address['userId'] = $userId; } $address['fullName'] = $params['fullName']; $address['line1'] = $params['line1']; $address['line2'] = $params['line2']; $address['city'] = $params['city']; $address['region'] = $params['region']; $address['zip'] = $params['zip']; $address['country'] = $params['country']; if (!isset($address['id']) || empty($address['id'])) { $userService->addAddress($address); } else { $userService->updateAddress($address); } Session::set('modelSuccess', 'Your address has been updated'); return 'redirect: /profile'; }
/** * @Route ("/subscription/process") * @Secure ({"USER"}) * @Transactional * * We were redirected here from PayPal after the buyer approved/cancelled the payment * * @param array $params */ public function subscriptionProcess(array $params, ViewModel $model) { FilterParams::isRequired($params, 'orderId'); FilterParams::isRequired($params, 'token'); FilterParams::isThere($params, 'success'); $ordersService = OrdersService::instance(); $userService = UserService::instance(); $subscriptionsService = SubscriptionsService::instance(); $payPalApiService = PayPalApiService::instance(); $chatIntegrationService = ChatIntegrationService::instance(); $authenticationService = AuthenticationService::instance(); $userId = Session::getCredentials()->getUserId(); // Get the order $order = $ordersService->getOrderByIdAndUserId($params['orderId'], $userId); if (empty($order) || strcasecmp($order['state'], OrderStatus::_NEW) !== 0) { throw new Exception('Invalid order record'); } try { // If we got a failed response URL if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) { throw new Exception('Order request failed'); } // Get the subscription from the order $orderSubscription = $subscriptionsService->getSubscriptionByOrderId($order['orderId']); $subscriptionUser = $userService->getUserById($orderSubscription['userId']); // Make sure the subscription is valid if (empty($orderSubscription)) { throw new Exception('Invalid order subscription'); } // Make sure the subscription is either owned or gifted by the user if ($subscriptionUser['userId'] != $userId && $orderSubscription['gifter'] != $userId) { throw new Exception('Invalid order subscription'); } $subscriptionType = $subscriptionsService->getSubscriptionType($orderSubscription['subscriptionType']); $paymentProfile = $ordersService->getPaymentProfileByOrderId($order['orderId']); // Get the checkout info $ecResponse = $payPalApiService->retrieveCheckoutInfo($params['token']); if (!isset($ecResponse) || $ecResponse->Ack != 'Success') { throw new Exception('Failed to retrieve express checkout details'); } // Moved this down here, as if the order status is error, the payerID is not returned FilterParams::isRequired($params, 'PayerID'); // Point of no return - we only every want a person to get here if their order was a successful sequence Session::set('token'); Session::set('orderId'); // Recurring payment if (!empty($paymentProfile)) { $createRPProfileResponse = $payPalApiService->createRecurringPaymentProfile($paymentProfile, $params['token'], $subscriptionType); if (!isset($createRPProfileResponse) || $createRPProfileResponse->Ack != 'Success') { throw new Exception('Failed to create recurring payment request'); } $paymentProfileId = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileID; $paymentStatus = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileStatus; if (empty($paymentProfileId)) { throw new Exception('Invalid recurring payment profileId returned from Paypal'); } // Set the payment profile to active, and paymetProfileId $ordersService->updatePaymentProfileId($paymentProfile['profileId'], $paymentProfileId, $paymentStatus); // Update the payment profile $subscriptionsService->updateSubscriptionPaymentProfile($orderSubscription['subscriptionId'], $paymentProfile['profileId'], true); } // Complete the checkout $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $order); if (isset($DoECResponse) && $DoECResponse->Ack == 'Success') { if (isset($DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo)) { $payPalApiService->recordECPayments($DoECResponse, $params['PayerID'], $order); $ordersService->updateOrderState($order['orderId'], $order['state']); } else { throw new Exception('No payments for express checkout order'); } } else { throw new Exception($DoECResponse->Errors[0]->LongMessage); } // If the user already has a subscription and ONLY if this subscription was NOT a gift if (!isset($orderSubscription['gifter']) || empty($orderSubscription['gifter'])) { $activeSubscription = $subscriptionsService->getUserActiveSubscription($subscriptionUser['userId']); if (!empty($activeSubscription)) { // Cancel any attached payment profiles $ordersService = OrdersService::instance(); $paymentProfile = $ordersService->getPaymentProfileById($activeSubscription['paymentProfileId']); if (!empty($paymentProfile)) { $payPalApiService->cancelPaymentProfile($activeSubscription, $paymentProfile); $subscriptionsService->updateSubscriptionRecurring($activeSubscription['subscriptionId'], false); } // Cancel the active subscription $subscriptionsService->updateSubscriptionState($activeSubscription['subscriptionId'], SubscriptionStatus::CANCELLED); } } // Check if this is a gift, check that the giftee is still eligable if (!empty($orderSubscription['gifter']) && !$subscriptionsService->getCanUserReceiveGift($userId, $subscriptionUser['userId'])) { // Update the state to ERROR and log a critical error Application::instance()->getLogger()->critical('Duplicate subscription attempt, Gifter: %d GifteeId: %d, OrderId: %d', $userId, $subscriptionUser['userId'], $order['orderId']); $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR); } else { // Unban the user if a ban is found $ban = $userService->getUserActiveBan($subscriptionUser['userId']); // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2 // we unban the user if no ban is found because it also unmutes if (empty($ban) or (!empty($ban['endtimestamp']) or $orderSubscription['subscriptionTier'] >= 2)) { $chatIntegrationService->sendUnban($subscriptionUser['userId']); } // Activate the subscription (state) $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ACTIVE); // Flag the user for 'update' $authenticationService->flagUserForUpdate($subscriptionUser['userId']); // Random emote $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])]; // Broadcast if (!empty($orderSubscription['gifter'])) { $gifter = $userService->getUserById($orderSubscription['gifter']); $userName = $gifter['username']; $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote)); } else { $userName = $subscriptionUser['username']; $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $randomEmote)); } // Get the subscription message, and remove it from the session $subMessage = Session::set('subMessage'); if (!empty($subMessage)) { $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage)); } } // Redirect to completion page return 'redirect: /subscription/' . urlencode($order['orderId']) . '/complete'; } catch (Exception $e) { if (!empty($order)) { $ordersService->updateOrderState($order['orderId'], OrderStatus::ERROR); } if (!empty($paymentProfile)) { $ordersService->updatePaymentStatus($paymentProfile['paymentId'], PaymentStatus::ERROR); } if (!empty($orderSubscription)) { $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR); } $log = Application::instance()->getLogger(); $log->error($e->getMessage(), $order); return 'redirect: /subscription/' . urlencode($order['orderId']) . '/error'; } }
/** * @param AuthenticationCredentials $authCreds * @throws Exception */ public function handleAuthCredentials(AuthenticationCredentials $authCreds) { $userService = UserService::instance(); $user = $userService->getUserByAuthId($authCreds->getAuthId(), $authCreds->getAuthProvider()); if (empty($user)) { throw new Exception('Invalid auth user'); } // The user has registed before... // Update the auth profile for this provider $authProfile = $userService->getUserAuthProfile($user['userId'], $authCreds->getAuthProvider()); if (!empty($authProfile)) { $userService->updateUserAuthProfile($user['userId'], $authCreds->getAuthProvider(), array('authCode' => $authCreds->getAuthCode(), 'authDetail' => $authCreds->getAuthDetail())); } // Renew the session upon successful login, makes it slightly harder to hijack $session = Session::instance(); $session->renew(true); $credentials = $this->getUserCredentials($user, $authCreds->getAuthProvider()); Session::updateCredentials($credentials); ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId()); // Variable is sent from the login form if (Session::set('rememberme')) { $this->setRememberMe($user); } }
/** * Updates the session last updated time to match the cache time * * @param int $userId * @param int $lastUpdated * @return boolean */ private function clearUserUpdateFlag($userId, $lastUpdated) { Session::set('lastUpdated', $lastUpdated); }
/** * @Route ("/register") * @HttpMethod ({"POST"}) * @Transactional * * Handle the confirmation request * @param array $params * @throws Exception */ public function registerProcess(array $params, ViewModel $model, Request $request) { $userService = UserService::instance(); $authService = AuthenticationService::instance(); $authCreds = $this->getSessionAuthenticationCredentials($params); $username = isset($params['username']) && !empty($params['username']) ? $params['username'] : ''; $email = isset($params['email']) && !empty($params['email']) ? $params['email'] : ''; $country = isset($params['country']) && !empty($params['country']) ? $params['country'] : ''; $rememberme = isset($params['rememberme']) && !empty($params['rememberme']) ? true : false; $authCreds->setUsername($username); $authCreds->setEmail($email); try { if (!isset($params['g-recaptcha-response']) || empty($params['g-recaptcha-response'])) { throw new Exception('You must solve the recaptcha.'); } $googleRecaptchaHandler = new GoogleRecaptchaHandler(); $googleRecaptchaHandler->resolve(Config::$a['g-recaptcha']['secret'], $params['g-recaptcha-response'], $request->ipAddress()); $authService->validateUsername($username); $authService->validateEmail($email); if (!empty($country)) { $countryArr = Country::getCountryByCode($country); if (empty($countryArr)) { throw new Exception('Invalid country'); } $country = $countryArr['alpha-2']; } $user = array(); $user['username'] = $username; $user['email'] = $email; $user['userStatus'] = 'Active'; $user['country'] = $country; $user['userId'] = $userService->addUser($user); $userService->addUserAuthProfile(array('userId' => $user['userId'], 'authProvider' => $authCreds->getAuthProvider(), 'authId' => $authCreds->getAuthId(), 'authCode' => $authCreds->getAuthCode(), 'authDetail' => $authCreds->getAuthDetail())); Session::set('authSession'); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); } catch (Exception $e) { $model->title = 'Register Error'; $model->username = $username; $model->email = $email; $model->follow = isset($params['follow']) ? $params['follow'] : ''; $model->authProvider = $authCreds->getAuthProvider(); $model->code = $authCreds->getAuthCode(); $model->error = $e; return 'register'; } }
/** * @param \Exception $e * @param ViewModel $model * @return string */ private function handleAuthError(\Exception $e, ViewModel $model) { if (Session::hasRole(UserRole::USER)) { Session::set('modelError', $e->getMessage()); return 'redirect: /profile/authentication'; } else { $model->title = 'Login error'; $model->error = $e; return 'login'; } }
/** * @Route ("/admin/user/{id}/auth/{provider}/delete") * @Secure ({"ADMIN"}) * @HttpMethod ({"POST"}) * * @param array $params * @return string */ public function authProviderDelete(array $params) { $apiAuthService = ApiAuthenticationService::instance(); $apiAuthService->deleteAuthProfileByUserId($params['id'], $params['provider']); Session::set('modelSuccess', 'Authentication profile removed!'); return 'redirect: /admin/user/' . urlencode($params['id']) . '/edit'; }