예제 #1
0
파일: sqla.py 프로젝트: tim-werner/paperboy
    def process_request(self, req, resp):
        '''Get user from auth token'''
        if req.context.get('auth_token') is None:
            # If the user doesnt have a token, redirect to login
            if req.path not in (urljoin(self.config.baseurl, self.config.loginurl), urljoin(self.config.baseurl, self.config.registerurl)) and \
               urljoin(self.config.baseurl, 'static') not in req.path:
                raise falcon.HTTPFound(
                    urljoin(self.config.baseurl, self.config.loginurl))
        else:
            # try to get user

            # get sql session
            session = self.config.storage.sessionmaker()

            # query for user
            user = self.db.users.detail(req.context['auth_token'], req.params,
                                        session)

            if user is not None:
                # user not found
                req.context['user'] = user
                if req.path in (urljoin(self.config.baseurl,
                                        self.config.loginurl),
                                urljoin(self.config.baseurl,
                                        self.config.registerurl)):
                    raise falcon.HTTPFound(self.config.baseurl)

            elif req.path not in (urljoin(self.config.baseurl, self.config.loginurl), urljoin(self.config.baseurl, self.config.registerurl), urljoin(self.config.baseurl, self.config.logouturl)) and \
                    urljoin(self.config.baseurl, 'static') not in req.path:
                raise falcon.HTTPFound(
                    urljoin(self.config.baseurl, self.config.loginurl))
예제 #2
0
    def process_request(self, req, resp):

        if req.path in req.context['included_paths_user']:
            my_cookie_hash = req.cookies.get('pomodoro_login_hash', None)
            if my_cookie_hash is not None:
                try:
                    user_session = req.context['session'].query(
                        SessionModel, SessionModel.user_id).filter_by(
                        hash=my_cookie_hash).one()

                except NoResultFound as e:
                    # User session was not found, send user to session
                    # expired login
                    raise falcon.HTTPFound('/app/session_expired')

                else:
                    # User session was found, try to query user
                    try:
                        user = req.context['session'].query(
                            UserModel).filter_by(id=user_session.user_id).one()
                        a = ''

                    except NoResultFound as e:
                        # User was not found, send user to session
                        # expired login
                        raise falcon.HTTPFound('/app/session_expired')

                    else:
                        # User was found, pass it through the request context
                        req.context['user'] = user
예제 #3
0
def return_url(signature_id, event=None):  # pylint: disable=unused-argument
    """
    Handle the GET request from the user once they have successfully signed.

    :param signature_id: The ID of the signature they have just signed.
    :type signature_id: string
    :param event: The event GET flag sent back from the signing service provider.
    :type event: string | None
    """
    try:  # Load the signature based on ID.
        signature = get_signature_instance()
        signature.load(str(signature_id))
    except DoesNotExist as err:
        cla.log.error('Invalid signature_id provided when trying to send user back to their ' + \
                      'return_url after signing: %s', signature_id)
        return {'errors': {'signature_id': str(err)}}
    # Ensure everything went well on the signing service provider's side.
    if event is not None:
        # Expired signing URL - the user was redirected back immediately but still needs to sign.
        if event == 'ttl_expired' and not signature.get_signature_signed():
            # Need to re-generate a sign_url and try again.
            cla.log.info('DocuSign URL used was expired, re-generating sign_url')
            callback_url = signature.get_signature_callback_url()
            get_signing_service().populate_sign_url(signature, callback_url)
            signature.save()
            raise falcon.HTTPFound(signature.get_signature_sign_url())
    ret_url = signature.get_signature_return_url()
    if ret_url is not None:
        cla.log.info('Signature success - sending user to return_url: %s', ret_url)
        raise falcon.HTTPFound(ret_url)
    cla.log.info('No return_url set for signature - returning success message')
    return {'success': 'Thank you for signing'}
예제 #4
0
    def on_post(self, req, resp):
        """Handles POST requests"""

        # Add user to the DB
        email = req.get_param('email')
        first_name = req.get_param('first_name')
        middle_name = req.get_param('middle_name')
        last_name = req.get_param('last_name')
        display_name = req.get_param('display_name')
        password = req.get_param('password')
        today = datetime.utcnow()
        user_to_add = UserModel(email=email,
                                first_name=first_name,
                                middle_name=middle_name,
                                last_name=last_name,
                                display_name=display_name,
                                password=password,
                                created=today,
                                modified=today)
        try:
            req.context['session'].add(user_to_add)
            req.context['session'].commit()
        except IntegrityError as e:
            req.context['session'].rollback()
            raise falcon.HTTPFound('/app/create_email_exists')

        else:
            # Send user to the login page if their account was created
            raise falcon.HTTPFound('/app/login')
예제 #5
0
    def on_get(self, req, resp):
        """Handles GET requests"""
        cookies = req.cookies
        if 'pomodoro_login_hash' in cookies:
            my_cookie_hash = cookies.get('pomodoro_login_hash', None)
            if my_cookie_hash is not None:
                try:
                    my_session = req.context['session'].query(
                        SessionModel.hash, SessionModel.modified). \
                        filter_by(hash=my_cookie_hash).one()

                except NoResultFound:
                    resp.unset_cookie('pomodoro_login_hash')
                    raise falcon.HTTPFound('/app/login')

                else:
                    session_modified_time = my_session.modified
                    tdelta = datetime.timedelta(hours=22)
                    now = datetime.datetime.utcnow()
                    session_expire_time = session_modified_time + tdelta

                    if now > session_expire_time:
                        req.context['session'].query(SessionModel).filter_by(
                            user_id=req.context['user'].id).delete(
                                synchronize_session=False)
                        req.context['session'].commit()
                        raise falcon.HTTPFound('/app/session_expired')

        else:
            raise falcon.HTTPFound('/app/login')
예제 #6
0
    def sign_request(self, installation_id, github_repository_id,
                     change_request_id, request):
        """
        This method gets called when the OAuth2 app (NOT the GitHub App) needs to get info on the
        user trying to sign. In this case we begin an OAuth2 exchange with the 'user:email' scope.
        """
        cla.log.debug('Initiating GitHub sign request for repository %s',
                      github_repository_id)
        # Not sure if we need a different token for each installation ID...
        session = self._get_request_session(request)
        session['github_installation_id'] = installation_id
        session['github_repository_id'] = github_repository_id
        session['github_change_request_id'] = change_request_id

        origin_url = self.get_return_url(github_repository_id,
                                         change_request_id, installation_id)
        session['github_origin_url'] = origin_url
        if 'github_oauth2_token' in session:
            cla.log.debug('Using existing session OAuth2 token')
            return self.redirect_to_console(installation_id,
                                            github_repository_id,
                                            change_request_id, origin_url,
                                            request)
        else:
            cla.log.debug('Initiating GitHub OAuth2 exchange')
            authorization_url, state = self.get_authorization_url_and_state(
                installation_id, github_repository_id, change_request_id,
                ['user:email'])
            session['github_oauth2_state'] = state
            cla.log.debug(
                'GitHub OAuth2 request with state %s - sending user to %s',
                state, authorization_url)
            raise falcon.HTTPFound(authorization_url)
예제 #7
0
 def on_get(self, req, resp):
     resp.content_type = 'text/html'
     session = req.env['beaker.session']
     if session.get('logged_in', None):
         raise falcon.HTTPFound('/')
     else:
         tmpl = j2_env.get_template('login.html')
         resp.body = tmpl.render()
예제 #8
0
파일: sqla.py 프로젝트: tim-werner/paperboy
    def process_resource(self, req, resp, resource, params):
        required = getattr(resource, 'auth_required', True)
        token_value = req.context.get('auth_token', None)
        token_value = None if isinstance(token_value,
                                         Exception) else token_value

        if required and not token_value:
            raise falcon.HTTPFound(
                urljoin(self.config.baseurl, self.config.loginurl))
예제 #9
0
 def on_post(self, req, resp):
     session = req.env['beaker.session']
     tx = Tweet(**{
         'author_id': session['logged_in'],
         'text': req.params['text']
     })
     db.add(tx)
     db.commit()
     raise falcon.HTTPFound('/')
예제 #10
0
파일: utils.py 프로젝트: xNUTs/easycla
def redirect_user_by_signature(user, signature):
    """
    Helper method to redirect a user based on their signature status and return_url.

    :param user: The user object for this redirect.
    :type user: cla.models.model_interfaces.User
    :param signature: The signature object for this user.
    :type signature: cla.models.model_interfaces.Signature
    """
    return_url = signature.get_signature_return_url()
    if signature.get_signature_signed() and signature.get_signature_approved():
        # Signature already signed and approved.
        # TODO: Notify user of signed and approved signature somehow.
        cla.log.info('Signature already signed and approved for user: %s, %s',
                     user.get_user_emails(), signature.get_signature_id())
        if return_url is None:
            cla.log.info(
                'No return_url set in signature object - serving success message'
            )
            return {'status': 'signed and approved'}
        else:
            cla.log.info('Redirecting user back to %s', return_url)
            raise falcon.HTTPFound(return_url)
    elif signature.get_signature_signed():
        # Awaiting approval.
        # TODO: Notify user of pending approval somehow.
        cla.log.info('Signature signed but not approved yet: %s',
                     signature.get_signature_id())
        if return_url is None:
            cla.log.info(
                'No return_url set in signature object - serving pending message'
            )
            return {'status': 'pending approval'}
        else:
            cla.log.info('Redirecting user back to %s', return_url)
            raise falcon.HTTPFound(return_url)
    else:
        # Signature awaiting signature.
        sign_url = signature.get_signature_sign_url()
        signature_id = signature.get_signature_id()
        cla.log.info('Signature exists, sending user to sign: %s (%s)',
                     signature_id, sign_url)
        raise falcon.HTTPFound(sign_url)
예제 #11
0
def track(id: fields.Integer(required=True),
          val: fields.Integer(required=True), url: fields.Url(required=True)):
    """
	Save request parameters and redirect to url
	"""
    logger.info(f'{id}: value: {val} -> {url}')

    # Save results is processed asynchronously
    save_results(id, val)

    raise falcon.HTTPFound(url)
예제 #12
0
    def on_post(self, request, response, collection_id, link_index):
        link_idx = int(link_index)

        current_user = users.get_current_user()

        form_data = forms.edit_link(request.params)

        repositories.links.update(current_user, collection_id, link_idx,
                                  form_data)

        raise falcon.HTTPFound('/collection/{0}/view'.format(collection_id))
예제 #13
0
파일: utils.py 프로젝트: xNUTs/easycla
def request_individual_signature(installation_id,
                                 github_repository_id,
                                 user,
                                 change_request_id,
                                 callback_url=None):
    """
    Helper function send the user off to sign an signature based on the repository.

    :TODO: Update comments.

    :param repository: The repository object in question.
    :type repository: cla.models.model_interfaces.Repository
    :param user: The user in question.
    :type user: cla.models.model_interfaces.User
    :param change_request_id: The change request ID (used to redirect the user after signing).
    :type change_request_id: string
    :param callback_url: Optionally provided a callback_url. Will default to
        <SIGNED_CALLBACK_URL>/<repo_id>/<change_request_id>.
    :type callback_url: string
    """
    project_id = get_project_id_from_github_repository(github_repository_id)
    repo_service = get_repository_service('github')
    return_url = repo_service.get_return_url(github_repository_id,
                                             change_request_id,
                                             installation_id)
    if callback_url is None:
        callback_url = os.path.join(API_BASE_URL, 'v2/signed/individual',
                                    str(installation_id),
                                    str(change_request_id))

    signing_service = get_signing_service()
    return_url_type = 'Github'
    signature_data = signing_service.request_individual_signature(
        project_id, user.get_user_id(), return_url_type, return_url,
        callback_url)
    if 'sign_url' in signature_data:
        raise falcon.HTTPFound(signature_data['sign_url'])
    cla.log.error(
        'Could not get sign_url from signing service provider - sending user '
        'to return_url instead')
    raise falcon.HTTPFound(return_url)
예제 #14
0
 def on_get(self, req, resp):
     """Handles GET requests"""
     cookies = req.cookies
     if 'pomodoro_login_hash' in cookies:
         # This will remove the cookie because we are overriding the
         # existing one with a negative max_age
         resp.set_cookie('pomodoro_login_hash', '', max_age=-1, path='/')
         req.context['session'].query(SessionModel).filter_by(
             user_id=req.context['user'].id).delete(
                 synchronize_session=False)
         req.context['session'].commit()
     raise falcon.HTTPFound('/app/login')
예제 #15
0
파일: sqla.py 프로젝트: huxh/paperboy
    def process_request(self, req, resp):
        if req.context.get('auth_token') is None:
            if req.path not in (urljoin(self.config.baseurl, self.config.loginurl), urljoin(self.config.baseurl, self.config.registerurl)) and \
               urljoin(self.config.baseurl, 'static') not in req.path:
                raise falcon.HTTPFound(
                    urljoin(self.config.baseurl, self.config.loginurl))
        else:
            # try to get user
            session = self.config.storage.sessionmaker()
            user = self.db.users.detail(req.context['auth_token'], req.params,
                                        session)
            if user is not None:
                req.context['user'] = user
                if req.path in (urljoin(self.config.baseurl,
                                        self.config.loginurl),
                                urljoin(self.config.baseurl,
                                        self.config.registerurl)):
                    raise falcon.HTTPFound(self.config.baseurl)

            elif req.path not in (urljoin(self.config.baseurl, self.config.loginurl), urljoin(self.config.baseurl, self.config.registerurl), urljoin(self.config.baseurl, self.config.logouturl)) and \
                    urljoin(self.config.baseurl, 'static') not in req.path:
                raise falcon.HTTPFound(
                    urljoin(self.config.baseurl, self.config.loginurl))
예제 #16
0
    def process_request(self, req, resp):
        if self.skips(req) or self.is_secure(req):
            return

        xfp = req.get_header('X-FORWARDED-PROTO')
        if xfp and xfp.lower() == 'https':
            return

        if req.url.startswith('http://'):
            url = req.url.replace('http://', 'https://', 1)
            if self.permanent:
                raise falcon.HTTPMovedPermanently(url)
            else:
                raise falcon.HTTPFound(url)
예제 #17
0
 def on_post(self, req, resp):
     user = db.query(User).filter(User.id == req.params['username']).first()
     if user:
         sha256 = hashlib.sha256()
         sha256.update((user.salt + req.params['password']).encode())
         key = sha256.hexdigest()
         if key == user.key:
             session = req.env['beaker.session']
             session['logged_in'] = user.id
             session.save()
             raise falcon.HTTPFound('/')
     ermsg = 'Usuario o contraseña invalidos'
     resp.content_type = 'text/html'
     data = {'alerts': [Alert('urgent', '', ermsg)]}
     tmpl = j2_env.get_template('login.html')
     resp.body = tmpl.render(data)
예제 #18
0
def get_redirect(node):
    """
    Obtain all pods from namespace provided filtered by label.
    Return a redirect to that pod.

    Returning Exceptions instead of raising to be able to use lru_cache
    """
    headers = {"Authorization": "Bearer %s" % KUBERNETES_TOKEN}
    url = "%s/api/v1/namespaces/%s/pods?labelSelector=%s" % (
        KUBERNETES_URL, NAMESPACE, LABELSELECTOR)
    logger.debug("Requesting pods to kubernetes. url=%s, headers=%s" %
                 (url, headers))

    try:
        r = requests.get(url, headers=headers, verify=False)
    except Exception as ex:
        logger.warn("Error connecting to kubernetes: %s" % ex)
        return falcon.HTTPInternalServerError(
            title="Error connecting to kubernetes")

    if not r.ok:
        logger.warn("Error requesting pods from kubernetes: %s" % r.body)
        return falcon.HTTPInternalServerError(
            title="Error requesting pods from kubernetes")

    pods = r.json()
    logger.debug("Number of pods obtained: %s" % len(pods.get("items")))
    name = None

    logger.debug("Looking for a pod in node %s" % node)
    for pod in pods.get("items"):
        nodeName = pod.get("spec").get("nodeName")
        logger.debug("Comparing to %s" % nodeName)

        if re.match("(?i)%s.*" % node, nodeName):
            name = pod.get("metadata").get("name")
            ip = pod.get("status").get("podIP")
            logger.debug("Match. Pod name: %s, IP: %s" % (name, ip))
            break
        else:
            continue

    if name:
        return falcon.HTTPFound(REDIRECT.format(ip))

    return falcon.HTTPNotFound(title="Not found fluentd pod for that node")
예제 #19
0
    def on_post(self, req, resp):
        """Handles POST requests"""

        # Parse variables to be submitted to DB
        task = req.get_param('task')
        review = req.get_param('review')
        flags = req.get_param_as_list('flags')
        time_blocks = req.get_param_as_list('time_block')

        # Store form data that came in from the user
        form_data = {
            'distractions': req.get_param('distractions'),
            'pom_success': req.get_param('pom_success', default=0),
            'review': review,
            'task': task,
            'flags': flags,
            'selected_time_blocks': time_blocks
        }

        # Validate form
        try:
            PomodoroSchema().load({
                'task': task,
                'review': review,
                'flags': flags
            })
        except ValidationError as err:
            # User is missing 1 or more required fields
            message = ''
            for k, v in err.messages.items():
                message += '<br> * ' + v[0]
            data = {'form_data': form_data, 'message': message}
            raise falcon.HTTPBadRequest({
                'error': 'ValidationError',
                'data': data
            })

        else:
            raise falcon.HTTPFound('/api/poms/today')
예제 #20
0
    def redirect_to_console(self, installation_id, repository_id,
                            pull_request_id, redirect, request):
        console_endpoint = cla.conf['CONTRIBUTOR_BASE_URL']
        # Get repository using github's repository ID.
        repository = Repository().get_repository_by_external_id(
            repository_id, "github")
        if repository is None:
            cla.log.warning(
                'Could not find repository with the following repository_id: %s',
                repository_id)
            return None

        # Get project ID from this repository
        project_id = repository.get_repository_project_id()

        user = self.get_or_create_user(request)
        # Ensure user actually requires a signature for this project.
        # TODO: Skipping this for now - we can do this for ICLAs but there's no easy way of doing
        # the check for CCLAs as we need to know in advance what the company_id is that we're checking
        # the CCLA signature for.
        # We'll have to create a function that fetches the latest CCLA regardless of company_id.
        # icla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user)
        # ccla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user, company_id=?)
        # try:
        # document = cla.utils.get_project_latest_individual_document(project_id)
        # except DoesNotExist:
        # cla.log.debug('No ICLA for project %s' %project_id)
        # if signature is not None and \
        # signature.get_signature_document_major_version() == document.get_document_major_version():
        # return cla.utils.redirect_user_by_signature(user, signature)
        # Store repository and PR info so we can redirect the user back later.
        cla.utils.set_active_signature_metadata(user.get_user_id(), project_id,
                                                repository_id, pull_request_id)
        # Generate console URL
        console_url = 'https://' + console_endpoint + \
                      '/#/cla/project/' + project_id + \
                      '/user/' + user.get_user_id() + \
                      '?redirect=' + redirect
        raise falcon.HTTPFound(console_url)
예제 #21
0
 def on_post(self, req, resp):
     if req.params['password'] != req.params['password2']:
         ermsg = 'Ambos campos de contraseña deben coincidir'
         self._error(req, resp, ermsg)
         return
     salt = b64encode(os.urandom(18)).decode()
     sha256 = hashlib.sha256()
     sha256.update((salt + req.params['password']).encode())
     key = sha256.hexdigest()
     db.add(
         User(id=req.params['username'],
              salt=salt,
              key=key,
              email=req.params['email']))
     try:
         db.commit()
         session = req.env['beaker.session']
         session['logged_in'] = req.params['username']
         session.save()
         raise falcon.HTTPFound('/')
     except sqlalchemy.exc.IntegrityError:
         ermsg = 'El usuarion {} ya existe'.format(req.params['username'])
         self._error(req, resp, ermsg)
예제 #22
0
 def sign_request(self, repository_id, change_request_id, request):
     cla.log.info('Initiating GitLab sign request for repository %s',
                  repository_id)
     session = self._get_request_session(request)
     repository = cla.utils.get_repository_instance()
     try:
         # Load the repository in question.
         repository.load(repository_id)
     except DoesNotExist as err:
         cla.log.error('Error when initiating GitLab sign request for repository %s and ' + \
                       'change request %s: %s', repository_id, change_request_id, str(err))
         return {'errors': {'repository_id': str(err)}}
     if 'gitlab_oauth2_token' in session:
         cla.log.info('Using existing session OAuth2 token')
         return self.sign_workflow(repository, change_request_id, request)
     else:
         cla.log.info('Initiating GitLab OAuth2 exchange')
         authorization_url, state = self.get_authorization_url_and_state(
             repository_id, change_request_id, ['read_user'])
         session['gitlab_oauth2_state'] = state
         cla.log.info(
             'GitLab OAuth2 request with state %s - sending user to %s',
             state, authorization_url)
         raise falcon.HTTPFound(authorization_url)
예제 #23
0
 def on_get(self, request, response):
     #response.media = {'hello': 'world'}
     #response.status = falcon.HTTP_200
     raise falcon.HTTPFound('/static/index.html')
예제 #24
0
def _default_failed(req, resp, **kwargs):
    raise falcon.HTTPFound('/auth/login')
예제 #25
0
 def on_post(self, req, resp):
     raise falcon.HTTPFound('/found')
예제 #26
0
 def on_post(self, req, resp):
     raise falcon.HTTPFound('/found', headers={'foo': 'bar'})
예제 #27
0
파일: logout.py 프로젝트: swstephe/cm
 def on_get(self, req, resp):
     url = users.create_logout_url('/')
     raise falcon.HTTPFound(url)
 def _login_redirect(config, *args, **kwargs):
     raise falcon.HTTPFound(urljoin(config.baseurl, config.loginurl))
예제 #29
0
 def perform(self, request):
     raise falcon.HTTPFound("/rulr-web/html/index.html")
예제 #30
0
    def on_get(self, req, resp):
        print "Reached on_get"

        ret = {"success": False}

        # Query Params
        category_index = req.get_param_as_int('categoryIndex')
        threshold = req.get_param('threshold')
        get_multilabel_results = req.get_param_as_bool('getMultilabelResults')
        get_combined_results = req.get_param_as_bool('getCombinedResults')

        image_url = req.get_param('imageUrl', required=True)

        try:
            img = image_url  # Utils.get_cv2_img_array(image_url)

            # multilabel alone
            if get_multilabel_results:
                multilabel_output = neurodoll.get_multilabel_output(img)
                ret['multilabel_output'] = multilabel_output
                print('multilabel output:' + str(multilabel_output))
                if multilabel_output is not None:
                    ret["success"] = True
                # ret["success"] = bool(multilabel_output)

            # combined multilabel and nd
            if get_combined_results:
                combined_output = neurodoll.combine_neurodoll_v3labels_and_multilabel(
                    img)
                # ret['combined_output'] = combined_output
                # ret['mask'] = combined_output
                if combined_output is not None:
                    ret['results_page'] = "http://13.69.27.202:8099/"
                    ret['success'] = True
                    ret['found_categories'] = list(np.unique(combined_output))
                    ret['bbs'] = imutils.mask_to_rects(combined_output)

            # yonti style - single category mask
            ret["label_dict"] = constants.ultimate_21_dict

            # regular neurodoll call
            if not get_multilabel_results and not get_combined_results and not category_index:
                print "No special params, inferring..."
                ret["mask"], labels = neurodoll.infer_one(img)
                if ret["mask"] is not None:
                    ret["success"] = True
                    ret["bbs"] = imutils.mask_to_rects(ret["mask"])
                else:
                    ret["error"] = "No mask from ND"

        except Exception as e:
            traceback.print_exc()
            ret["error"] = traceback.format_exc()

        if ret["success"] and ret.get("redirect"):
            raise falcon.HTTPFound("http://13.69.27.202:8099/")

        resp.data = json.dumps(ret)
        resp.content_type = 'application/json'
        resp.status = falcon.HTTP_200
        return (ret)