Ejemplo n.º 1
0
def authenticate(username, password):
    """Check if there is a user with this username-pw-combo
    and return the user object if a matching user has been found."""
    user = current_session.query(tm.User).filter_by(name=username).one_or_none()
    if not(user and sha256_crypt.verify(password, user.password)):
        raise ResourceNotFoundError(tm.User)
    return user
Ejemplo n.º 2
0
def user():
    form = AddUserForm(request.form)
    if request.method == 'POST':
        if form.validate():
            user = User(name=form.username.data,
                        email=form.email.data,
                        birth_date=form.birth_date.data,
                        password=form.password.data)
            current_session.add(user)
            current_session.commit()
            flash('New user created!')
            return redirect(url_for('user_route.user'))
        else:
            flash('Form is not valid! User was not created.')
    all_users = current_session.query(User).all()
    return render_template('user.html', form=form, user=all_users)
Ejemplo n.º 3
0
def _get_proxy_group_id():
    """
    Get users proxy group id from the current token, if possible.
    Otherwise, check the database for it.

    Returnns:
        int: id of proxy group associated with user
    """
    proxy_group_id = get_users_proxy_group_from_token()

    if not proxy_group_id:
        user = (current_session.query(User).filter(
            User.id == current_token["sub"]).first())
        proxy_group_id = user.google_proxy_group_id

    return proxy_group_id
Ejemplo n.º 4
0
def has_oauth(scope=None):
    scope = scope or set()
    scope.update({"openid"})
    try:
        access_token_claims = validate_jwt(aud=scope, purpose="access")
    except JWTError as e:
        raise Unauthorized("failed to validate token: {}".format(e))
    user_id = access_token_claims["sub"]
    user = current_session.query(User).filter_by(id=int(user_id)).first()
    if not user:
        raise Unauthorized("no user found with id: {}".format(user_id))
    # set some application context for current user and client id
    flask.g.user = user
    # client_id should be None if the field doesn't exist or is empty
    flask.g.client_id = access_token_claims.get("azp") or None
    flask.g.token = access_token_claims
Ejemplo n.º 5
0
def get_service_account(client_id, user_id):
    """
    Return the service account (from Fence db) for given client.

    Get the service account that is associated with the given client
    for this user. There will be a single service account per client.

    NOTE: The user themselves have a "primary" service account which you
          can retrieve by passing in `None` as the client_id.

    Returns:
        fence.models.GoogleServiceAccount: Client's service account
    """
    service_account = (current_session.query(GoogleServiceAccount).filter_by(
        client_id=client_id, user_id=user_id).first())

    return service_account
Ejemplo n.º 6
0
    def post(self, id_):
        """
        Dry run for registering a new service account

        Args:
            id_ (str): Must be "_dry_run", otherwise, error
        """
        if id_ != "_dry_run":
            raise UserError("Cannot post with account id_.")

        user_id = current_token["sub"]
        payload = flask.request.get_json(silent=True) or {}

        project_access = payload.get("project_access")

        if len(project_access) > config["SERVICE_ACCOUNT_LIMIT"]:
            return UserError(
                "Exceeded Allowable Number of Projects. Maximum {} Projects allowed per account."
                .format(config["SERVICE_ACCOUNT_LIMIT"]))

        sa = GoogleServiceAccountRegistration(
            email=payload.get("service_account_email"),
            project_access=project_access,
            google_project_id=payload.get("google_project_id"),
            user_id=user_id,
        )

        error_response = _get_service_account_error_status(sa)

        sa_exists = (current_session.query(UserServiceAccount).filter_by(
            email=sa.email).all())

        if sa_exists:
            error_response["success"] = False
            error_response["errors"]["service_account_email"] = {
                "status": 409,
                "error": "Conflict",
                "error_description": "Service Account already registered.",
            }

        if error_response.get("success") is True:
            status = 200
        else:
            status = 400

        return error_response, status
Ejemplo n.º 7
0
 def post(self):
     data = emailParser.parse_args()
     email = data['email']
     user = current_session.query(UserModel).filter(UserModel.email == email).scalar()
     if user is None:
         return {'status': 'success'}
     
     secret_code = PasswordResetRequest.generate_secret_code()
     reset_request = PasswordResetRequest(user_id=user.id, secret_code=secret_code)
     current_session.add(reset_request)
     current_session.commit()
     msg = Message("Reset Your Password",
         sender="*****@*****.**",
         recipients=[user.email],
         html=render_template('reset_password.html', **{'user': user, 'reset_request': reset_request, 'REACT_URL': 'http://localhost:3000'})
     )
     mail.send(msg)
     return {'status': 'success'}
Ejemplo n.º 8
0
    def avatar():
        form = UploadAvatar()
        if request.method == 'POST':
            if form.validate():
                avatar_f = Avatar(user=form.user.data,
                                  filename=form.upload.data.filename
                                  )  #, avatar=form.author.data)
                f_name = secure_filename(form.upload.data.filename)
                form.upload.data.save('upload/avatar/' + f_name)
                current_session.add(avatar_f)
                current_session.commit()
                flash('avatar uploaded!')
                return redirect(url_for('avatar'))
            else:
                flash('Form is not valid!')
        all_avatars = current_session.query(Avatar).all()

        return render_template('avatar.html', form=form, avatars=all_avatars)
Ejemplo n.º 9
0
def login_user(request, username, provider):
    user = query_for_user(session=current_session, username=username)

    if not user:
        user = User(username=username)
        idp = (current_session.query(IdentityProvider).filter(
            IdentityProvider.name == provider).first())
        if not idp:
            idp = IdentityProvider(name=provider)
        user.identity_provider = idp
        current_session.add(user)
        current_session.commit()
    flask.session["username"] = username
    flask.session["provider"] = provider
    flask.session["user_id"] = str(user.id)
    flask.g.user = user
    flask.g.scopes = ["_all"]
    flask.g.token = None
Ejemplo n.º 10
0
def revert(link):
    """ the link to make the latest version the one selected.
    """

    latest = request.args.get('latest', None)
    if latest is not None:
        oldone = wiki_for(link)
        newone = (current_session.query(Wiki).filter(Wiki.link == link).filter(
            Wiki.id == int(latest)).first())

        oldone.latest = 0
        newone.latest = 1
        current_session.add(newone)
        current_session.add(oldone)
        current_session.commit()
        return redirect(url_for('wiki.index', link=link, id=newone.id))
    else:
        abort(404)
Ejemplo n.º 11
0
    def delete(self, access_key):
        """
        .. http:get: /google/(string: access_key)
        Delete a keypair for user

        :param access_key: existing access key that belongs to this user

        :statuscode 204 Success
        :statuscode 403 Forbidden to delete access key
        :statuscode 404 Access key doesn't exist
        """
        user_id = current_token["sub"]
        with GoogleCloudManager() as g_cloud:
            client_id = current_token.get("azp") or None
            service_account = get_service_account(client_id, user_id)

            if service_account:
                keys_for_account = g_cloud.get_service_account_keys_info(
                    service_account.google_unique_id)

                # Only delete the key if is owned by current client's SA
                all_client_keys = [
                    key["name"].split("/")[-1] for key in keys_for_account
                ]
                if access_key in all_client_keys:
                    g_cloud.delete_service_account_key(
                        service_account.google_unique_id, access_key)

                    db_entry = (current_session.query(GoogleServiceAccountKey).
                                filter_by(key_id=access_key).first())
                    if db_entry:
                        current_session.delete(db_entry)
                        current_session.commit()
                else:
                    flask.abort(
                        404,
                        "Could not delete key " + access_key +
                        ". Not found for current user.",
                    )
            else:
                flask.abort(
                    404, "Could not find service account for current user.")

        return "", 204
Ejemplo n.º 12
0
def recent():
    """ Show recently modified wiki pages.
    """

    pages = (current_session.query(Wiki).order_by(
        Wiki.datetimeon.desc()).limit(30).all())

    from itertools import groupby

    def grouper(item):
        if not item.datetimeon:
            return (None, None, None)
        return item.datetimeon.year, item.datetimeon.month, item.datetimeon.day

    day_groups = []
    for ((year, month, day), items) in groupby(pages, grouper):
        day_groups.append(((year, month, day), list(items)))

    return render_template('wiki/recent.html', day_groups=day_groups)
Ejemplo n.º 13
0
def profile(id):
    form = BlogPostForm()
    if id == current_user.id and request.method == 'GET':
        posts = current_session.query(Post).filter(
            Post.user == current_user).all()
        return render_template('post.html', form=form, posts=posts)

    elif request.method == 'POST' and id == current_user.id and form.validate(
    ):
        post = Post(user=current_user,
                    title=form.title.data,
                    content=form.content.data)
        current_session.add(post)
        current_session.commit()
        flash('post_created')
        route_to = '/profile/' + str(current_user.id)
        return redirect(route_to)
    else:
        return redirect(url_for('login_route.login'))
Ejemplo n.º 14
0
def mark_comment(comment_post_id, action):
    """ with comment_post_id as deleted or spam.
    """
    comment = (current_session.query(CommentPost).filter(
        CommentPost.id == comment_post_id).first())
    if not comment:
        abort(404)
    if action == 'delete':
        comment.is_deleted = True
        flash('Comment marked deleted.')
    elif action == 'spam':
        comment.is_spam = True
        flash('Comment marked spam.')
    else:
        abort(404)

    current_session.add(comment)
    current_session.commit()

    return redirect('/')
Ejemplo n.º 15
0
def add_feature_request(feature):
    """
    Adds a feature to the database, handles updating conflicting priorities.

    Note: This should be reimplemented to use a priority queue
    """
    client_id = feature.client_id
    new_feature = session.query(
        FeatureRequest.id, FeatureRequest.priority).filter(
            FeatureRequest.client_id == client_id,
            FeatureRequest.priority == feature.priority).first()

    if new_feature is not None:
        feature_id, priority = new_feature
        increment_priority(feature_id=feature_id,
                           client_id=client_id,
                           priority=priority)

    session.add(feature)
    session.commit()
Ejemplo n.º 16
0
def login():
    form = LoginForm()
    # registered_user = None
    if form.validate_on_submit():
        user = current_session.query(User).filter(
            User.name == form.username.data).first(
            )  #, User.password == form.password.data).first()
        print('USER!!!', user)
        if user:
            flash(u'Logged in as %s' % current_user.name)
            user.is_authenticated = True
            # session['user_id'] = form.username.id
            login_user(user, remember=True)
            route_to = '/profile/' + str(current_user.id)
            print(route_to)
            return redirect(route_to)
        # session['user_id'] = form.user.id
        # print(session['user_id'])

        return redirect(url_for('login_route.login'))
    return render_template('login.html', form=form)
Ejemplo n.º 17
0
def _get_primary_service_account_key(user_id, username, proxy_group_id):
    user_service_account_key = None

    # Note that client_id is None, which is how we store the user's SA
    user_google_service_account = get_service_account(
        client_id=None, user_id=user_id, username=username
    )

    if user_google_service_account:
        user_service_account_key = (
            current_session.query(GoogleServiceAccountKey)
            .filter(
                GoogleServiceAccountKey.service_account_id
                == user_google_service_account.id
            )
            .filter(GoogleServiceAccountKey.private_key.isnot(None))
            .order_by(desc(GoogleServiceAccountKey.expires))
            .first()
        )

    return user_service_account_key
Ejemplo n.º 18
0
def revert(link):
    """ the link to make the latest version the one selected.
    """
    if wiki_for(link).locked and not current_user.has_role('admin'):
        flash('Wiki page locked.')
        return current_app.login_manager.unauthorized()

    latest = request.args.get('latest', None)
    if latest is not None:
        oldone = wiki_for(link)
        newone = (current_session.query(Wiki).filter(Wiki.link == link).filter(
            Wiki.id == int(latest)).first())

        oldone.latest = 0
        newone.latest = 1
        current_session.add(newone)
        current_session.add(oldone)
        current_session.commit()
        return redirect(url_for('wiki.index', link=link, id=newone.id))
    else:
        abort(404)
Ejemplo n.º 19
0
    def get(self) -> List[District]:
        def district_recursive_model(max_deep=None):
            if max_deep is None:
                max_deep = current_app.config['DISTRICTS_TREE_MAX_DEEP']
            tree_fields = {
                'district_id': fields.Integer(),
                'name': fields.String(),
            }
            if max_deep:
                tree_fields['sub_districts'] = fields.List(
                    fields.Nested(district_recursive_model(max_deep - 1)))
            return api.model(f'Districts Tree {max_deep}', tree_fields)

        def prepare_tree(root_district):
            return {
                'district_id':
                root_district.district_id,
                'name':
                root_district.name,
                'sub_districts': [
                    prepare_tree(sub_district) for sub_district in
                    sub_districts_map[root_district.district_id]
                ],
            }

        districts = current_session.query(District).all()
        sub_districts_map = defaultdict(list)
        roots = []
        for district in districts:
            if district.parent_district_id is None:
                roots.append(district)
            else:
                sub_districts_map[district.parent_district_id].append(district)

        return api.marshal(
            [prepare_tree(district) for district in roots],
            district_recursive_model(),
            envelope='districts_tree',
        )
Ejemplo n.º 20
0
def upload_certificate(certificate):
    extension = flask.request.args.get("extension")
    allowed_extension = ["pdf", "png", "jpg", "jpeg", "txt"]
    if not extension or extension not in allowed_extension:
        raise UserError(
            "Invalid extension in parameter, acceptable extensions are {}".
            format(", ".join(allowed_extension)))

    if not flask.g.user.application:
        flask.g.user.application = Application()
        current_session.merge(flask.g.user)
    cert = (current_session.query(Certificate).filter(
        Certificate.name == certificate).filter(
            Certificate.application_id == flask.g.user.application.id).first())
    if not cert:
        cert = Certificate(name=certificate)
    cert.application_id = flask.g.user.application.id
    cert.extension = extension
    cert.data = flask.request.data
    current_session.merge(cert)

    certificates = flask.g.user.application.certificates_uploaded
    if set(REQUIRED_CERTIFICATES.keys()).issubset(
            set(c.name for c in certificates)):
        title = "User application for {}".format(flask.g.user.username)
        if getattr(flask.g, "client"):
            title += " from {}".format(flask.g.client)
        if "EMAIL_SERVER" in config:
            content = "Application for user: {}\n" "email: {}".format(
                flask.g.user.username, flask.g.user.email)
            send_mail(
                config["SEND_FROM"],
                config["SEND_TO"],
                title,
                text=content,
                server=config["EMAIL_SERVER"],
                certificates=certificates,
            )
    return "", 201
Ejemplo n.º 21
0
def upload_certificate(certificate):
    extension = flask.request.args.get('extension')
    allowed_extension = ['pdf', 'png', 'jpg', 'jpeg', 'txt']
    if not extension or extension not in allowed_extension:
        raise UserError(
            "Invalid extension in parameter, acceptable extensions are {}".
            format(", ".join(allowed_extension)))

    if not flask.g.user.application:
        flask.g.user.application = Application()
        current_session.merge(flask.g.user)
    cert = (current_session.query(Certificate).filter(
        Certificate.name == certificate).filter(
            Certificate.application_id == flask.g.user.application.id).first())
    if not cert:
        cert = Certificate(name=certificate)
    cert.application_id = flask.g.user.application.id
    cert.extension = extension
    cert.data = flask.request.data
    current_session.merge(cert)

    certificates = flask.g.user.application.certificates_uploaded
    if set(REQUIRED_CERTIFICATES.keys()).issubset(
            set(c.name for c in certificates)):
        title = 'User application for {}'.format(flask.g.user.username)
        if getattr(flask.g, 'client'):
            title += ' from {}'.format(flask.g.client)
        if 'EMAIL_SERVER' in flask.current_app.config:
            content = ("Application for user: {}\n"
                       "email: {}".format(flask.g.user.username,
                                          flask.g.user.email))
            send_mail(flask.current_app.config['SEND_FROM'],
                      flask.current_app.config['SEND_TO'],
                      title,
                      text=content,
                      server=flask.current_app.config['EMAIL_SERVER'],
                      certificates=certificates)
    return "", 201
Ejemplo n.º 22
0
def tags(tag):
    """ shows the projects for the tag.
    """
    top_tag_counts = top_tags(current_session)

    per_page = 30
    start = int(request.args.get('start', 0))
    prev_start = start - per_page
    if prev_start < 0:
        prev_start = None
    next_start = start + per_page

    # all is a special tag, meaning show all.
    if tag == 'all':
        projectsq = (current_session.query(Project)
                     .join(User)
                     .join(Release)
                     .filter(Release.project_id == Project.id)
                     .filter(User.id == Project.users_id)
                     .order_by(Release.datetimeon.desc()))
    else:
        projectsq = (current_session
                     .query(Project)
                     .filter(Tags.project_id == Project.id)
                     .filter(Tags.value == tag))

    projects = (projectsq
                .offset(start)
                .limit(per_page)
                .all())

    return render_template('project/tags.html',
                           tag=tag,
                           tags=tags,
                           top_tag_counts=top_tag_counts,
                           projects=inchunks(projects, 3),
                           prev_start=prev_start,
                           next_start=next_start)
Ejemplo n.º 23
0
def get_or_create_proxy_group_id():
    """
    If no username returned from token or database, create a new proxy group
    for the give user. Also, add the access privileges.

    Returns:
        int: id of (possibly newly created) proxy group associated with user
    """
    proxy_group_id = _get_proxy_group_id()
    if not proxy_group_id:
        user_id = current_token["sub"]
        username = current_token.get("context", {}).get("user",
                                                        {}).get("name", "")
        proxy_group_id = _create_proxy_group(user_id, username).id

        privileges = current_session.query(AccessPrivilege).filter(
            AccessPrivilege.user_id == user_id)

        for p in privileges:
            storage_accesses = p.project.storage_access

            for sa in storage_accesses:
                if sa.provider.name == STORAGE_ACCESS_PROVIDER_NAME:

                    flask.current_app.storage_manager.logger.info(
                        "grant {} access {} to {} in {}".format(
                            username, p.privilege, p.project_id,
                            p.auth_provider))

                    flask.current_app.storage_manager.grant_access(
                        provider=(sa.provider.name),
                        username=username,
                        project=p.project,
                        access=p.privilege,
                        session=current_session,
                    )

    return proxy_group_id
Ejemplo n.º 24
0
def _create_proxy_group(user_id, username):
    """
    Create a proxy group for the given user

    Args:
        user_id (int): unique integer id for user
        username (str): unique name for user

    Return:
        userdatamodel.user.GoogleProxyGroup: the newly created proxy group
    """

    with GoogleCloudManager() as g_cloud:
        prefix = get_prefix_for_google_proxy_groups()
        new_proxy_group = g_cloud.create_proxy_group_for_user(
            user_id, username, prefix=prefix
        )

    proxy_group = GoogleProxyGroup(
        id=new_proxy_group["id"], email=new_proxy_group["email"]
    )

    # link proxy group to user
    user = current_session.query(User).filter_by(id=user_id).first()
    user.google_proxy_group_id = proxy_group.id

    current_session.add(proxy_group)
    current_session.commit()

    logger.info(
        "Created proxy group {} for user {} with id {}.".format(
            new_proxy_group["email"], username, user_id
        )
    )

    return proxy_group
Ejemplo n.º 25
0
def list_profiles():

    page = flask.request.args.get('page', type=int, default=1)

    query = current_session.query(models.Profile)

    profiles = (
        query.offset(settings.PROFILES_PER_PAGE * (page - 1))
        .limit(settings.PROFILES_PER_PAGE)
    )

    pagination = Pagination(
        page=page,
        per_page=settings.PROFILES_PER_PAGE,
        total=query.count(),
        record_name='profiles',
        css_framework='bootstrap3',
    )

    form = ProfileForm()

    if form.validate_on_submit():
        data = form.data.copy()
        data.pop('csrf_token', None)
        profile = models.Profile(**data)
        current_session.add(profile)
        current_session.commit()
        return flask.redirect(flask.url_for('.view_profile', id=profile.id))

    return flask.render_template(
        'list_profiles.html',
        form=form,
        pagination=pagination,
        profiles=profiles,
        show_modal=flask.request.method == 'POST',
    ), 200 if flask.request.method == 'GET' else 400
Ejemplo n.º 26
0
def _delete_service_account_key(g_cloud, service_account_id, access_key):
    """
    Internal function for deleting a given key for a service account, also
    removes entry from our db if it exists
    """
    try:
        response = g_cloud.delete_service_account_key(service_account_id, access_key)
    except Exception:
        logger.debug(
            "Deleting service account {} key {} from Google FAILED. Response: {}. "
            "We did NOT delete it from our DB either.".format(
                service_account_id, access_key, str(response)
            )
        )
        raise

    logger.debug(
        "Deleting service account {} key {} from Google succeeded. Response: {}".format(
            service_account_id, access_key, str(response)
        )
    )

    db_entry = (
        current_session.query(GoogleServiceAccountKey)
        .filter_by(key_id=access_key)
        .first()
    )
    if db_entry:
        current_session.delete(db_entry)
        current_session.commit()

    logger.info(
        "Removed Google Service Account {} Key with ID: {} from Google and our DB.".format(
            service_account_id, access_key
        )
    )
Ejemplo n.º 27
0
 def query_me():
     return s.query(UserTable, UserTable.user_name).all()
Ejemplo n.º 28
0
    def test_user(self):
        print 'testing ... '

        user = current_session.query(UserModel).get(1)
        assert user in UserModel.query.all()
Ejemplo n.º 29
0
 def query_db(name_user):
     #return the User_class table
     obj = s.query(UserTable)
     #returns one if username exists, otherwise zero.
     unames = obj.filter(UserTable.user_name == name_user).one_or_none()
     return unames
Ejemplo n.º 30
0
 def read_from_db(ride_id):
     return s.query(RideUsersTable).filter(
         RideUsersTable.ride_table_id == ride_id).all()
Ejemplo n.º 31
0
 def get_from_ride_id(ride_id):
     return s.query(RideTable).filter(
         RideTable.ride_id == ride_id).one_or_none()
Ejemplo n.º 32
0
 def read_from_username(username):
     return s.query(RideTable).filter(
         RideTable.created_by == username).one_or_none()
Ejemplo n.º 33
0
def load_user(payload):
    """Lookup the user for a token payload."""
    # if the scope creates a problem consider using
    # http://flask-sqlalchemy-session.readthedocs.io/en/v1.1/
    user = current_session.query(tm.User).get(payload['uid'])
    return user