Check if the user have a active session
@param Request $request
@param $userId
@param $sessionCode
@return string
348138
public function getValidUserSession(Request $request, $userId, $sessionCode)
    {
        $session = SecUserSessions::whereuserid($userId)
            ->wheresessioncode($sessionCode)
            ->wheredateins(date('Y-m-d'))
            ->wherestatus(1)
            ->first();

        $ipAddress = $request->ip();

        if ($session) {

            if ($session->datetimeUpd < date('Y-m-d H:m:s')) {
                $session->update(['ipAddress' => $ipAddress, 'datetimeUpd' => date('Y-m-d H:m:s')]);
            }

            if ($session->datetimeUpd < date('Y-m-d H:m:s') || $session->ipAddress == $ipAddress) {

                $data = $session->user;
                $data->ipAddress = $ipAddress;
                $data->sessionCode = $session->sessionCode;
                $data->userSessionId = $session->userSessionId;
                $data->environment = $this->environment;
                $data->remember_token = $session->user->remember_token;

                $this->responseData = $data;
                $this->responseSuccess = true;
            }

        }

        return EncryptAes::encrypt(json_encode($this->responseRagnarok->make(
            $this->responseSuccess, $this->responseData
        )));
    }
240478
public function checkSourceActive($userId)
    {
        $active = true;

        $values['gso_active'] = $active ? 1 : 0;
        $values['gso_status'] = $active ? 'Active' : 'Inactive';

        $this->_updateSource($values, $userId);

        return $active;
    }
887041
public function startSession($user_id)
    {
        $this->deleteOldSessions();

        $user_id = (int)$user_id;
        $sid = $this->generateUserSid($user_id);

        $session = UsersSessionEntityRepository::findOneEntityByCriteria([
            'sid'     => $sid,
            'user_id' => $user_id,
        ]);
        if (!$session) {
            $session = new UsersSessionEntity();
        }
        $session->setSid($sid);
        $session->setUserId($user_id);
        $session->save();

        return $sid;
    }
99899
public function getActivate($userId, $activationCode)
    {
        // Is user logged in?
        if (Sentinel::check())
        {
            if (Sentinel::inRole('admin'))
                return Redirect::route('home');
            else
                return Redirect::route('user.home');
        }

        // Find the user using the password reset code
        if(!$user = Sentinel::findById($userId))
        {
            // Redirect to the forgot password page
            return Redirect::route('login')->with('error', Lang::get('base.auth.activate.error'));
        }
        // $activation = Activation::exists($user);

        if (Activation::complete($user, $activationCode))
        {
            $user->status = 1;
            $user->save();
            
            // Activation was successful
            // Redirect to the login page
            return Redirect::route('login')->with('success', Lang::get('base.auth.activate.success'));
        }
        else
        {
            // Activation not found or not completed.
            $error = Lang::get('base.auth.activate.error');
            return Redirect::route('login')->with('error', $error);
        }

    }
79591
public function validateRequest(RequestInterface $request, ResponseInterface $response)
	{
		// check for session id
		if (!$sessionId = $this->storage->getSessionIdFromCookie())
		{
			$response->setError(401, 'session_authentication_invalid', 'Unable to find a valid session id.');
			return false;
		}

		// get user for session id
		if (!$userId = $this->storage->getUserIdFromSessionId($sessionId))
		{
			$response->setError(401, 'session_authentication_invalid', 'Unable to authenticate via active session.');
			return false;
		}

		// store our session & user id
		$this->userInfo = array(
			'user_id'    => $userId,
			'session_id' => $sessionId
		);
		return true;
	}
539428
public function requestRememberPasswordAction(Request $request, $userClass)
    {
        $form = $this->get('form.factory')->createNamedBuilder('', RequestRememberPasswordType::class, null, [
            'csrf_protection' => false,
        ])->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            try {
                $this->get('bengor_user.' . $userClass . '.api_command_bus')->handle(
                    $form->getData()
                );

                return new JsonResponse();
            } catch (UserDoesNotExistException $exception) {
                return new JsonResponse(
                    sprintf(
                        'The "%s" user email does not exist ',
                        $form->getData()->email()
                    ),
                    400
                );
            }
        }

        return new JsonResponse(FormErrorSerializer::errors($form), 400);
    }
1075127
public function shouldValidateUserActivity(SymfonySession $session)
    {
        return $this->config->get('concrete.security.session.invalidate_inactive_users.enabled') &&
            $session->has('uID') && $session->get('uID') > 0 && $session->has('uOnlineCheck') &&
            $session->get('uOnlineCheck') > 0;
    }
563633
public function getByUser($userId, $paginate = null)
    {
        $query = $this->model->where('user_id', $userId);

        if (!is_null($paginate)) {
            return $query->paginate($paginate);
        }

        return $query->get();
    }
58145
public function authSucc($userid){
	    if (!$this->access_token && !$this->checkAuth()) return false;
	    $result = $this->http_get(self::API_URL_PREFIX.self::AUTHSUCC_URL.'access_token='.$this->access_token.'&userid='.$userid);
	    if ($result)
	    {
	        $json = json_decode($result,true);
	        if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
	            $this->errCode = $json['errcode'];
	            $this->errMsg = $json['errmsg'];
	            return false;
	        }
	        return $json;
	    }
	    return false;
	}
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
369259
public function updateUser($userId, Request $request)
    {
        $user = $this->userService->loadUser($userId);

        $updateStruct = $this->inputDispatcher->parse(
            new Message(
                array(
                    'Content-Type' => $request->headers->get('Content-Type'),
                    // @todo Needs refactoring! Temporary solution so parser has access to URL
                    'Url' => $request->getPathInfo(),
                ),
                $request->getContent()
            )
        );

        if ($updateStruct->sectionId !== null) {
            $section = $this->sectionService->loadSection($updateStruct->sectionId);
            $this->sectionService->assignSection(
                $user->getVersionInfo()->getContentInfo(),
                $section
            );
        }

        $updatedUser = $this->userService->updateUser($user, $updateStruct->userUpdateStruct);
        $updatedContentInfo = $updatedUser->getVersionInfo()->getContentInfo();
        $mainLocation = $this->locationService->loadLocation($updatedContentInfo->mainLocationId);
        $contentType = $this->contentTypeService->loadContentType($updatedContentInfo->contentTypeId);

        return new Values\RestUser(
            $updatedUser,
            $contentType,
            $updatedContentInfo,
            $mainLocation,
            $this->contentService->loadRelations($updatedUser->getVersionInfo())
        );
    }
1064962
public function isCacheable(Request $request, $user)
    {
        if (!$this->active) {
            return false;
        }

        if ($user) {
            return false;
        }

        if ($request->hasSession() && $request->getSession()->get('no_cache', false)) {
            $request->getSession()->remove('no_cache');

            return false;
        }

        if ($this->env != 'prod') {
            return false;
        }

        if ($request->getMethod() != 'GET') {
            return false;
        }

        return true;
    }
544143
public function findTokenByParams($userId, $code, $type)
    {
        return $this->findToken([
            'user_id' => $userId,
            'code'    => $code,
            'type'    => $type,
        ])->one();
    }
352851
public function assignRoleToUser($userId, Request $request)
    {
        $roleAssignment = $this->inputDispatcher->parse(
            new Message(
                array('Content-Type' => $request->headers->get('Content-Type')),
                $request->getContent()
            )
        );

        $user = $this->userService->loadUser($userId);
        $role = $this->roleService->loadRole($roleAssignment->roleId);

        try {
            $this->roleService->assignRoleToUser($role, $user, $roleAssignment->limitation);
        } catch (LimitationValidationException $e) {
            throw new BadRequestException($e->getMessage());
        }

        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);

        return new Values\RoleAssignmentList($roleAssignments, $user->id);
    }
265358
public function send(Provider $provider, $userId, $requestScope, Request $request)
    {
        $accessToken = $this->getAccessToken($provider, $userId, $requestScope);
        if (false === $accessToken) {
            return false;
        }

        if ($accessToken->isExpired($this->dateTime)) {
            // access_token is expired, try to refresh it
            if (null === $accessToken->getRefreshToken()) {
                // we do not have a refresh_token, delete this access token, it
                // is useless now...
                $this->tokenStorage->deleteAccessToken($userId, $accessToken);

                return false;
            }

            // try to refresh the AccessToken
            $accessToken = $this->refreshAccessToken($provider, $userId, $accessToken);
            if (false === $accessToken) {
                // didn't work
                return false;
            }
        }

        // add Authorization header to the request headers
        $request->setHeader('Authorization', \sprintf('Bearer %s', $accessToken->getToken()));

        $response = $this->httpClient->send($request);
        if (401 === $response->getStatusCode()) {
            // the access_token was not accepted, but isn't expired, we assume
            // the user revoked it, also no need to try with refresh_token
            $this->tokenStorage->deleteAccessToken($userId, $accessToken);

            return false;
        }

        return $response;
    }
828942
public function check(Users $user, string $sessionId, string $userIp, int $pageId): Users
    {
        $currentTime = time();

        $pageId = (int) $pageId;

        //
        // session_id exists so go ahead and attempt to grab all
        // data in preparation
        //
        $sql = "SELECT user.*, session.*
                FROM Baka\Auth\Models\Sessions session, Baka\Auth\Models\Users user
                WHERE session.id = :session_id:
                    AND user.id = session.users_id";

        $result = $this->getModelsManager()->createQuery($sql);
        $result = $result->execute([
                'session_id' => $sessionId,
            ]);

        //session data
        $userData = $result->getFirst();

        if (empty($userData)) {
            throw new Exception('Invalid Session');
        }

        //wtf? how did you get this token to mimic another user?
        if ($userData->user->getId() != $user->getId()) {
            throw new Exception('Invalid Token');
        }

        //
        // Did the session exist in the DB?
        //
        if ($userData->user) {
            //
            // Do not check IP assuming equivalence, if IPv4 we'll check only first 24
            // bits ... I've been told (by vHiker) this should alleviate problems with
            // load balanced et al proxies while retaining some reliance on IP security.
            /**
             * @todo reviar esto del chekeo de las ips
             */
            $ip_check_s = substr($userData->session->ip, 0, 6);
            $ip_check_u = substr($userIp, 0, 6);

            if ($ip_check_s == $ip_check_u) {
                //
                // Only update session DB a minute or so after last update
                //
                if ($currentTime - $userData->session->time > 60) {
                    //update the user session
                    $session = self::findFirstById($sessionId);
                    $session->session_time = $currentTime;
                    $session->session_page = $pageId;

                    if (!$session->update()) {
                        throw new Exception(current($session->getMessages()));
                    }

                    //update user
                    $user->users_id = $userData->user->getId();
                    $user->session_time = $currentTime;
                    $user->session_page = $pageId;
                    $user->update();

                    $this->clean($sessionId);
                }

                $user->session_id = $sessionId;

                return $user;
            }
        }

        throw new Exception(_('No Session Token Found'));
    }
155391
public function isInputtedTwoFactorAuthCodeCorrect($userId=null) {
        $inputted2faCode = $this->request->input('2facode');

        if (isset($userId)) {
            $sent2faCode     = $this->getUserSmsToken($userId);
        } else {
            $sent2faCode     = $this->request->session()->get('codeToInput');
        }


        if ($inputted2faCode == $sent2faCode) {
            return true;
        }

        return false;
    }