예제 #1
0
 /**
  * @param array $params
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     if (!isset($params['authtoken']) || empty($params['authtoken'])) {
         return new Response(Http::STATUS_FORBIDDEN, 'Invalid or empty authToken');
     }
     $authToken = ApiAuthenticationService::instance()->getAuthToken($params['authtoken']);
     if (empty($authToken)) {
         return new Response(Http::STATUS_FORBIDDEN, 'Auth token not found');
     }
     $user = UserService::instance()->getUserById($authToken['userId']);
     if (empty($user)) {
         return new Response(Http::STATUS_FORBIDDEN, 'User not found');
     }
     $credentials = new SessionCredentials($user);
     $credentials->setAuthProvider('API');
     $credentials->addRoles(UserRole::USER);
     $credentials->addFeatures(UserFeaturesService::instance()->getUserFeatures($authToken['userId']));
     $credentials->addRoles(UserService::instance()->getUserRolesByUserId($authToken['userId']));
     $subscription = SubscriptionsService::instance()->getUserActiveSubscription($authToken['userId']);
     if (!empty($subscription)) {
         $credentials->addRoles(UserRole::SUBSCRIBER);
         $credentials->addFeatures(UserFeature::SUBSCRIBER);
         if ($subscription['subscriptionTier'] == 2) {
             $credentials->addFeatures(UserFeature::SUBSCRIBERT2);
         }
         if ($subscription['subscriptionTier'] == 3) {
             $credentials->addFeatures(UserFeature::SUBSCRIBERT3);
         }
     }
     $response = new Response(Http::STATUS_OK, json_encode($credentials->getData()));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
예제 #2
0
 /**
  * @Route ("/impersonate")
  * @HttpMethod ({"GET"})
  *
  * @param array $params
  * @throws Exception
  * @return string
  */
 public function impersonate(array $params)
 {
     if (!Config::$a['allowImpersonation']) {
         throw new Exception('Impersonating is not allowed');
     }
     $userId = isset($params['userId']) && !empty($params['userId']) ? $params['userId'] : '';
     $username = isset($params['username']) && !empty($params['username']) ? $params['username'] : '';
     if (empty($userId) && empty($username)) {
         throw new Exception('[username] or [userId] required');
     }
     $authService = AuthenticationService::instance();
     $userService = UserService::instance();
     if (!empty($userId)) {
         $user = $userService->getUserById($userId);
     } else {
         if (!empty($username)) {
             $user = $userService->getUserByUsername($username);
         }
     }
     if (empty($user)) {
         throw new Exception('User not found. Try a different userId or username');
     }
     $credentials = $authService->getUserCredentials($user, 'impersonating');
     Session::start();
     Session::updateCredentials($credentials);
     ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
     return 'redirect: /';
 }
예제 #3
0
 /**
  * @Route ("/admin/chat/ip")
  * @Secure ({"ADMIN"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @throws Exception
  * @return string
  */
 public function adminChatIp(array $params, ViewModel $model)
 {
     $model->title = 'Chat';
     FilterParams::required($params, 'ip');
     $userService = UserService::instance();
     $model->usersByIp = $userService->findUsersWithIP($params['ip']);
     $model->searchIp = $params['ip'];
     return 'admin/chat';
 }
예제 #4
0
 /**
  * @Route ("/banned")
  * @Secure ({"USER"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @return string
  */
 public function banned(array $params, ViewModel $model, Request $request)
 {
     $userService = UserService::instance();
     $creds = Session::getCredentials();
     $model->ban = $userService->getUserActiveBan($creds->getUserId(), $request->ipAddress());
     $model->banType = 'none';
     if (!empty($model->ban)) {
         if (!$model->ban['endtimestamp']) {
             $model->banType = 'permanent';
         } else {
             $model->banType = 'temporary';
         }
     }
     $model->user = $creds->getData();
     return 'banned';
 }
예제 #5
0
 private function sendResubscribeBroadcast(array $subscription)
 {
     $log = Application::instance()->getLogger();
     $userService = UserService::instance();
     $user = $userService->getUserById($subscription['userId']);
     if (!empty($user)) {
         try {
             // the subscription endDate has not been updated with the new subscription time
             $months = max(1, Date::getDateTime($subscription['createdDate'])->diff(Date::getDateTime($subscription['endDate']))->m);
             $months = $months > 1 ? $months . " months" : $months . " month";
             $chatIntegrationService = ChatIntegrationService::instance();
             $chatIntegrationService->sendBroadcast(sprintf("%s has resubscribed! Active for %s", $user['username'], $months));
         } catch (\Exception $e) {
             $log->critical('Could not send resubscribe broadcast', $subscription);
         }
     }
 }
예제 #6
0
 /**
  * @param array $params
  * @return Response
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     if (!isset($params['authtoken']) || empty($params['authtoken'])) {
         return new Response(Http::STATUS_FORBIDDEN, 'Invalid or empty authToken');
     }
     $authToken = ApiAuthenticationService::instance()->getAuthToken($params['authtoken']);
     if (empty($authToken)) {
         return new Response(Http::STATUS_FORBIDDEN, 'Auth token not found');
     }
     $user = UserService::instance()->getUserById($authToken['userId']);
     if (empty($user)) {
         return new Response(Http::STATUS_FORBIDDEN, 'User not found');
     }
     $authenticationService = AuthenticationService::instance();
     $credentials = $authenticationService->getUserCredentials($user, 'API');
     $response = new Response(Http::STATUS_OK, json_encode($credentials->getData()));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
예제 #7
0
 /**
  * @Route ("/register")
  * @HttpMethod ({"POST"})
  * @Transactional
  *
  * Handle the confirmation request
  * @param array $params
  * @throws Exception
  */
 public function registerProcess(array $params, ViewModel $model)
 {
     $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 {
         AuthenticationService::instance()->validateUsername($username);
         AuthenticationService::instance()->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 = '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';
     }
 }
예제 #8
0
 /**
  * Checks the users current session status
  * Does a remember me login
  * @return void
  */
 public function init()
 {
     $app = Application::instance();
     $authService = AuthenticationService::instance();
     // If the session hasnt started, or the data is not valid (result from php clearing the session data), check the Remember me cookie
     if (!Session::isStarted() || !Session::getCredentials()->isValid()) {
         $userId = $authService->getRememberMe();
         if ($userId !== false) {
             $userManager = UserService::instance();
             $user = $userManager->getUserById($userId);
             if (!empty($user)) {
                 Session::start(Session::START_NOCOOKIE);
                 $credentials = $authService->getUserCredentials($user, 'rememberme');
                 Session::updateCredentials($credentials);
                 ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
                 $authService->setRememberMe($user);
             }
         }
     }
 }
 /**
  * @param AuthenticationCredentials $authCreds
  * @return string
  * @throws Exception
  */
 public function execute(AuthenticationCredentials $authCreds)
 {
     $authService = AuthenticationService::instance();
     $userService = UserService::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');
     }
     if ($authCreds->getEmail()) {
         $authService->validateEmail($authCreds->getEmail(), null, true);
     }
     // 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 (!$userService->getUserAuthProviderExists($authCreds->getAuthId(), $authCreds->getAuthProvider())) {
         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';
 }
예제 #10
0
 /**
  * @param array $params         
  * @throws Exception
  */
 public function authenticate(array $params)
 {
     $UserService = UserService::instance();
     $authService = AuthenticationService::instance();
     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']));
     $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);
 }
예제 #11
0
 /**
  * @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';
     }
 }
예제 #12
0
 /**
  * @Route ("/gift/check")
  * @Secure ({"USER"})
  *
  * @param array $params
  * @return Response
  */
 public function giftCheckUser(array $params)
 {
     FilterParams::required($params, 's');
     $userService = UserService::instance();
     $subscriptionService = SubscriptionsService::instance();
     $userId = Session::getCredentials()->getUserId();
     $data = array('valid' => false, 'cangift' => false, 'username' => $params['s']);
     $user = $userService->getUserByUsername($params['s']);
     if (!empty($user)) {
         $data['cangift'] = $subscriptionService->getCanUserReceiveGift($userId, $user['userId']);
         $data['valid'] = true;
     }
     $response = new Response(Http::STATUS_OK);
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     $response->setBody(json_encode($data));
     return $response;
 }
예제 #13
0
 /**
  * Flag a user session for update
  * So that on their next request, the session data is updated.
  * Also does a chat session refresh
  *
  * @param int $userId
  */
 public function flagUserForUpdate($userId)
 {
     $user = UserService::instance()->getUserById($userId);
     if (!empty($user)) {
         $cache = Application::instance()->getCacheDriver();
         $cache->save(sprintf('refreshusersession-%s', $userId), time(), intval(ini_get('session.gc_maxlifetime')));
         ChatIntegrationService::instance()->refreshChatUserSession($this->getUserCredentials($user, 'session'));
     }
 }
예제 #14
0
 /**
  * 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';
 }
예제 #15
0
 /**
  * @Route ("/admin/user/{id}/subscription/{subscriptionId}/edit")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"GET"})
  *
  * @param array $params         
  * @param ViewModel $model          
  * @throws Exception
  * @return string
  */
 public function subscriptionEdit(array $params, ViewModel $model)
 {
     FilterParams::required($params, 'id');
     FilterParams::required($params, 'subscriptionId');
     $subscriptionsService = SubscriptionsService::instance();
     $userService = UserService::instance();
     $ordersService = OrdersService::instance();
     $subscription = array();
     $payments = array();
     $order = array();
     if (!empty($params['subscriptionId'])) {
         $subscription = $subscriptionsService->getSubscriptionById($params['subscriptionId']);
         $order = $ordersService->getOrderById($subscription['orderId']);
         $payments = $ordersService->getPaymentsByOrderId($subscription['orderId']);
     }
     if (Session::get('modelSuccess')) {
         $model->success = Session::get('modelSuccess');
         Session::set('modelSuccess');
     }
     $model->user = $userService->getUserById($params['id']);
     $model->subscriptions = Config::$a['commerce']['subscriptions'];
     $model->subscription = $subscription;
     $model->order = $order;
     $model->payments = $payments;
     $model->title = 'Subsription';
     return "admin/subscription";
 }
예제 #16
0
 /**
  * @Route ("/api/addtwitchsubscription")
  * @HttpMethod ({"POST"})
  *
  * Expects the following POST variables:
  *     privatekey=XXXXXXXX
  *
  * @param array $params
  * @return Response
  */
 public function addSubscription(array $params)
 {
     $response = array();
     // TODO GET RID OF THE COPY PASTE
     try {
         FilterParams::required($params, 'privatekey');
         if (!$this->checkPrivateKey($params['privatekey'])) {
             throw new Exception('Invalid shared private key.');
         }
         /*
          * The expected json schema is: {"123": 1, "431": 0}
          * where the key is the twitch user id and the value is whether
          * the user is a subscriber or not
          */
         $data = json_decode(file_get_contents('php://input'), true);
         $userService = UserService::instance();
         $authid = $userService->getTwitchIDFromNick($data['nick']);
         if ($authid) {
             $users = $userService->updateTwitchSubscriptions(array($authid => 1));
             $chatIntegrationService = ChatIntegrationService::instance();
             $authenticationService = AuthenticationService::instance();
             foreach ($users as $user) {
                 $authenticationService->flagUserForUpdate($user['userId']);
                 if (!$user['istwitchsubscriber']) {
                     // do not announce non-subs
                     continue;
                 }
                 $chatIntegrationService->sendBroadcast(sprintf("%s is now a Twitch subscriber!", $user['username']));
             }
         }
         $response = new Response(Http::STATUS_NO_CONTENT);
     } catch (Exception $e) {
         $response['success'] = false;
         $response['error'] = $e->getMessage();
         $response = new Response(Http::STATUS_BAD_REQUEST, json_encode($response));
         $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     }
     return $response;
 }
예제 #17
0
 /**
  * @Route ("/auth/minecraft")
  * @HttpMethod ({"POST"})
  *
  * @param array $params
  * @return Response
  * @throws Exception
  */
 public function authMinecraftPOST(array $params)
 {
     if (!$this->checkPrivateKey($params)) {
         return new Response(Http::STATUS_BAD_REQUEST, 'privatekey');
     }
     if (empty($params['uuid']) || strlen($params['uuid']) > 36) {
         return new Response(Http::STATUS_BAD_REQUEST, 'uuid');
     }
     if (!preg_match('/^[a-f0-9-]{32,36}$/', $params['uuid'])) {
         return new Response(Http::STATUS_BAD_REQUEST, 'uuid');
     }
     if (empty($params['name']) || mb_strlen($params['name']) > 16) {
         return new Response(Http::STATUS_BAD_REQUEST, 'name');
     }
     $user = UserService::instance();
     $userid = $user->getUserIdFromMinecraftName($params['name']);
     if (!$userid) {
         return new Response(Http::STATUS_NOT_FOUND, 'nameNotFound');
     }
     $ban = $user->getUserActiveBan($userid, @$params['ipaddress']);
     if (!empty($ban)) {
         return new Response(Http::STATUS_FORBIDDEN, 'userBanned');
     }
     $sub = SubscriptionsService::instance()->getUserActiveSubscription($userid);
     $userRow = $user->getUserById($userid);
     if (empty($userRow)) {
         return new Response(Http::STATUS_NOT_FOUND, 'userNotFound');
     }
     if (empty($sub)) {
         if ($userRow['istwitchsubscriber']) {
             $sub = array('endDate' => date('Y-m-d H:i:s', strtotime('+1 hour')));
         } else {
             return new Response(Http::STATUS_FORBIDDEN, 'subscriptionNotFound');
         }
     }
     try {
         $success = $user->setMinecraftUUID($userid, $params['uuid']);
         if (!$success) {
             $existingUserId = $user->getUserIdFromMinecraftUUID($params['uuid']);
             // only fail if the already set uuid is not the same
             if (!$existingUserId or $existingUserId != $userid) {
                 return new Response(Http::STATUS_FORBIDDEN, 'uuidAlreadySet');
             }
         }
     } catch (\Doctrine\DBAL\DBALException $e) {
         return new Response(Http::STATUS_BAD_REQUEST, 'duplicateUUID');
     }
     $response = array('nick' => $userRow['username'], 'end' => strtotime($sub['endDate']) * 1000);
     $response = new Response(Http::STATUS_OK, json_encode($response));
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     return $response;
 }
예제 #18
0
 /**
  * @Route ("/profile/messages/{targetuserid}")
  * @Secure ({"USER"})
  * @HttpMethod ({"GET"})
  *
  * @param array $params
  * @return Response
  */
 public function message(array $params, ViewModel $viewModel)
 {
     FilterParams::required($params, 'targetuserid');
     $privateMessageService = PrivateMessageService::instance();
     $userService = UserService::instance();
     $userId = Session::getCredentials()->getUserId();
     $username = Session::getCredentials()->getUsername();
     $targetuser = $userService->getUserById($params['targetuserid']);
     if (empty($targetuser)) {
         throw new Exception('Invalid user');
     }
     $messages = $privateMessageService->getMessagesBetweenUserIdAndTargetUserId($userId, $params['targetuserid'], 0, 1000);
     $privateMessageService->markMessagesRead($userId, $params['targetuserid']);
     $viewModel->targetuser = $targetuser;
     $viewModel->messages = $messages;
     $viewModel->username = $username;
     $viewModel->userId = $userId;
     $viewModel->title = 'Message';
     return 'profile/message';
 }
예제 #19
0
 /**
  * @Route ("/admin/user/find")
  * @Secure ({"ADMIN"})
  *
  * @param array $params
  * @return Response
  */
 public function adminUserFind(array $params)
 {
     FilterParams::required($params, 's');
     $userService = UserService::instance();
     $users = $userService->searchUsers(10, 0, trim($params['s']));
     $response = new Response(Http::STATUS_OK);
     $response->addHeader(Http::HEADER_CONTENTTYPE, MimeType::JSON);
     $response->setBody(json_encode($users));
     return $response;
 }
예제 #20
0
 /**
  * Flag a user session for update
  * @param int $userId
  */
 public function flagUserForUpdate($userId)
 {
     $user = UserService::instance()->getUserById($userId);
     $credentials = $this->getUserCredentials($user, 'session');
     if (Session::instance() != null && Session::getCredentials()->getUserId() == $userId) {
         // Update the current session if the userId is the same as the credential user id
         Session::updateCredentials($credentials);
         // Init / create the current users chat session
         ChatIntegrationService::instance()->setChatSession($credentials, Session::getSessionId());
     } else {
         // Otherwise set a session variable which is picked up by the remember me service to update the session
         $cache = Application::instance()->getCacheDriver();
         $cache->save(sprintf('refreshusersession-%s', $userId), time(), intval(ini_get('session.gc_maxlifetime')));
     }
     ChatIntegrationService::instance()->refreshChatUserSession($credentials);
 }
예제 #21
0
 /**
  * @Route ("/admin/user/{userId}/ban/remove")
  * @Secure ({"ADMIN"})
  *
  * @param array $params
  */
 public function removeBan(array $params)
 {
     if (!isset($params['userId']) || empty($params['userId'])) {
         throw new Exception('userId required');
     }
     $userService = UserService::instance();
     $authenticationService = AuthenticationService::instance();
     // if there were rows modified there were bans removed, so an update is
     // required, removeUserBan returns the number of rows modified
     if ($userService->removeUserBan($params['userId'])) {
         $authenticationService->flagUserForUpdate($params['userId']);
     }
     if (isset($params['follow']) and substr($params['follow'], 0, 1) == '/') {
         return 'redirect: ' . $params['follow'];
     }
     return 'redirect: /admin/user/' . $params['userId'] . '/edit';
 }
예제 #22
0
 /**
  * @Route ("/register")
  * @HttpMethod ({"POST"})
  *
  * @param array $params
  * @param ViewModel $model
  * @param Request $request
  * @return string
  * @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);
     if ($rememberme) {
         Session::set('rememberme', 1);
     }
     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'];
         }
     } 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';
     }
     $log = Application::instance()->getLogger();
     $conn = Application::instance()->getConnection();
     $conn->beginTransaction();
     try {
         $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()));
         $conn->commit();
         Session::set('authSession');
     } catch (\Exception $e) {
         $log->critical("Error registering user");
         $conn->rollBack();
         throw $e;
     }
     $authCredHandler = new AuthenticationRedirectionFilter();
     return $authCredHandler->execute($authCreds);
 }