Example #1
0
 def decorated(*args, **kwargs):
     api_key = None
     if 'apikey' in request.form:
         api_key = request.form.get('apikey')
     elif 'X-Api-Key' in request.headers.keys():
         api_key = request.headers.get('X-Api-Key')
     # validate
     if not api_key:
         data = {'error': messages.NO_API_KEY}
         return generate_api_response(data, 401)
     user = User.get_by_api_key(api_key=api_key)
     organization = Organization.get_by_api_key(api_key=api_key)
     if not user and not organization:
         data = {'error': messages.INVALID_API_KEY}
         return generate_api_response(data, 401)
     requested_org = kwargs.get('organization','')
     # check that user is active
     if user:
         session['user'] = user
         # allow admins to see all orgs
         if user.is_admin():
             session['organization'] = Organization.get_by_name(requested_org)
         else:
             session['organization'] = Organization.get_by_uuid(user.organization)
         if not user.active:
             data = {'error': messages.ACCOUNT_INACTIVE}
             return generate_api_response(data, 403)
     if organization:
         session['organization'] = organization
     # check that user is authorized for the desired organization
     if requested_org and requested_org != session.get('organization').name.lower():
         data = {'error': messages.ACCESS_DENIED}
         return generate_api_response(data, 403)
     return f(*args, **kwargs)
Example #2
0
def get_provider_info(provider=None, organization=None, account=None):
    data = {}
    if not organization:
        organization = request.args.get('organization', None)
    if not account:
        account = request.args.get('account', None)
    organization = Organization.get_by_name(organization)
    account = Account.query.filter({'organization': organization.uuid, 'name': account}).first()
    provider_id = None
    provider_key = None
    provider_data = None
    if account:
        provider_id = account.provider_id
        provider_key = account.provider_key
        provider_data = {
            'keypair': account.keypair,
            'default_images': account.default_images,
        }
    data.update(
        provider = provider,
        provider_id = provider_id,
        provider_key = provider_key,
        provider_data = provider_data
    )
    return data
    async def post(self, *args, **kwargs) -> Response:
        json_body = await self.deserialize_body()
        organization = Organization()
        name = json_body.get('name')
        if name:
            organization.name = name
        contact_phone = json_body.get('contact_phone')
        if contact_phone:
            organization.contact_phone = contact_phone
        contact_url = json_body.get('contact_url')
        if contact_url:
            organization.contact_url = contact_url

        await organization.save()

        response = await self.serialize(data=organization)
        return await self.to_response(response, status_code=201)
Example #4
0
    async def get(self, id=None, *args, **kwargs) -> Response:
        if not id:
            raise OrganizationNotFound
        organization = Organization.get_item(id)
        if not organization:
            raise OrganizationNotFound

        return await self.to_response(await self.serialize(data=organization))
Example #5
0
def connect_organization(request):
    """
    Connect organization and user
    :param request:
    :return:
    """

    user = request.user
    application_title = settings.APPLICATION_TITLE

    context = {"title": "My Organization", "user": user}

    DEBUG = settings.DEBUG_SETTINGS

    if DEBUG:
        print(application_title, "in accounts.views.connect_organization")
        print("request.method:")
        print(request.method)
        print(request.POST)

    if request.method == 'POST':
        form = OrganizationCheckForm(data=request.POST)

        if form.is_valid():
            if DEBUG:
                print("form is valid")
                print("form", form.cleaned_data['domain'])
            org = Organization()
            org.domain = form.cleaned_data['domain']
            org.site_url = "http://" + form.cleaned_data['domain']
            org.owner = user
            org.name = org.domain
            org.save()

            u = request.user
            if DEBUG:
                print("user", u)
            u.affiliated_to = org
            u.organization_role = "primary"
            u.save()

            return redirect(reverse_lazy('accounts:manage_account'))
        else:
            print("OrganizationCheckForm", request.POST, " NOT Valid")
    else:
        form = OrganizationCheckForm()

    context['form'] = form

    if DEBUG:
        print(context)

    return render_to_response('accounts/connect_organization.html',
                              context,
                              context_instance=RequestContext(request))
Example #6
0
def create_user():
    try:
        username = raw_input("Username: "******"Email: ").strip()
        while True:
            password = getpass("Password: "******" (confirm): ")
            if password_confirm == password:
                break
            else:
                print("Passwords do not match... Try again...")
        u = User(username=username)
        u.email = email
        # check for org
        org = Organization.get_by_name("default")
        if not org:
            org = Organization()
            org.name = "default"
            org.owner = u.uuid
            org.save()
        u.organization = Organization.get_by_name("default").uuid
        u.set_password(password)
        u.add_role("admin")
        u.save()
        print("User created/updated successfully...")
    except KeyboardInterrupt:
        pass
Example #7
0
    async def delete(self, id=None, *args, **kwargs) -> Response:
        if not id:
            raise OrganizationNotFound
        organization = Organization.get_item(id)
        if not organization:
            raise OrganizationNotFound

        organization.delete()

        return JSONAPIResponse(status_code=204)
Example #8
0
def connect_organization(request):
    """
    Connect organization and user
    :param request:
    :return:
    """

    user = request.user
    application_title = settings.APPLICATION_TITLE

    context = {"title": "My Organization",
               "user": user}

    DEBUG = settings.DEBUG_SETTINGS

    if DEBUG:
        print(application_title, "in accounts.views.connect_organization")
        print("request.method:")
        print(request.method)
        print(request.POST)

    if request.method == 'POST':
        form = OrganizationCheckForm(data=request.POST)

        if form.is_valid():
            if DEBUG:
                print("form is valid")
                print("form", form.cleaned_data['domain'])
            org = Organization()
            org.domain = form.cleaned_data['domain']
            org.site_url = "http://"+form.cleaned_data['domain']
            org.owner = user
            org.name = org.domain
            org.save()

            u = request.user
            if DEBUG:
                print("user", u)
            u.affiliated_to = org
            u.organization_role = "primary"
            u.save()

            return redirect(reverse_lazy('accounts:manage_account'))
        else:
            print("OrganizationCheckForm", request.POST, " NOT Valid")
    else:
        form = OrganizationCheckForm()

    context['form'] = form

    if DEBUG:
        print(context)

    return render_to_response('accounts/connect_organization.html',
                             context,
                              context_instance=RequestContext(request))
Example #9
0
 def decorated(*args, **kwargs):
     # load provider info
     org = Organization.get_by_name(kwargs.get("organization"))
     org_name = None
     if org:
         org_name = org.name
     info = get_provider_info(kwargs.get("provider"), org_name, kwargs.get("account"))
     session["provider_info"] = info
     # check for info ; if missing return error
     if not info.get("provider_id") or not info.get("provider_key"):
         data = {"error": "Invalid or missing provider account information"}
         return generate_api_response(data, 400)
     return f(*args, **kwargs)
Example #10
0
def edit_organization(uuid=None):
    organization = Organization.get_by_uuid(uuid)
    form = forms.OrganizationForm(obj=organization)
    # HACK: WTForms doesn't do dynamic lookup on instantiation ; must set choices here otherwise
    # new users won't show up
    form.owner.choices = forms.get_user_choices()
    if form.validate_on_submit():
        # validate
        if organization:
            # update db
            data = form.data
            # update
            organization.update(**data)
            flash(messages.ORGANIZATION_UPDATED)
            return redirect(url_for('accounts.organizations'))
    ctx = {
        'organization': organization,
        'form': form,
    }
    return render_template('accounts/edit_organization.html', **ctx)
Example #11
0
    async def patch(self, id=None, *args, **kwargs) -> Response:
        if not id:
            raise OrganizationNotFound
        organization = Organization.get_item(id)
        if not organization:
            raise OrganizationNotFound

        json_body = await self.deserialize_body(partial=True)
        name = json_body.get('name')
        if name:
            organization.name = name
        contact_phone = json_body.get('contact_phone')
        if contact_phone:
            organization.contact_phone = contact_phone
        contact_url = json_body.get('contact_url')
        if contact_url:
            organization.contact_url = contact_url

        organization.save()

        return await self.to_response(await self.serialize(data=organization))
Example #12
0
    async def post(self, *args, **kwargs) -> Response:
        json_body = await self.deserialize_body()

        user = User()
        username = json_body.get('username')
        if username:
            user.username = username
        else:
            raise HTTPException(status_code=400,
                                detail='A valid `username` is required.')

        organization_id = json_body.get('organization')
        org = Organization.get_item(int(organization_id))
        if not org:
            raise OrganizationNotFound
        user.organization = org

        user.save()

        result = await self.serialize(data=user)
        return await self.to_response(result, status_code=201)
Example #13
0
    async def patch(self, id=None, *args, **kwargs) -> Response:
        if not id:
            raise UserNotFound
        user = User.get_item(id)
        if not user:
            raise UserNotFound

        json_body = await self.deserialize_body(partial=True)
        username = json_body.get('username')
        if username:
            user.username = username

        organization_id = json_body.get('organization')
        if organization_id:
            org = Organization.get_item(int(organization_id))
            if not org:
                raise OrganizationNotFound
            user.organization = org

        user.save()

        return await self.to_response(await self.serialize(data=user))
Example #14
0
def login():
    """
    User login

    """
    form = request.form
    if request.method == 'POST':
        organization = Organization.get_by_name(form.get('organization').lower())
        # validate
        user = User.get_by_username(form.get('username'), organization.uuid)
        if user:
            if utils.hash_password(form.get('password')) == user.password:
                login_user(user)
                session['user'] = user
                session['organization'] = organization
                current_app.logger.info('User {0} ({1}) login from {2}'.format(user.username, organization.name, \
                    request.remote_addr))
                return redirect(request.args.get("next") or url_for("index"))
        current_app.logger.warn('Invalid login for {0} ({1}) from {2}'.format(form.get('username'), organization.name, \
            request.remote_addr))
        flash(messages.INVALID_USERNAME_OR_PASSWORD, 'error')
    ctx = {
    }
    return render_template('accounts/login.html', **ctx)
Example #15
0
 async def get_all(self, *args, **kwargs) -> Response:
     organizations = Organization.get_items()
     return await self.serialize(data=organizations, many=True)
Example #16
0
def create_organization():
    org = Organization()
    org.name = request.form.get('name')
    org.owner = request.form.get('owner').lower()
    org.save()
    return redirect(url_for('accounts.organizations'))
Example #17
0
def delete_organizations(uuid=None):
    org = Organization.get_by_uuid(uuid)
    if org:
        org.remove()
    return redirect(url_for('accounts.organizations'))
Example #18
0
def get_org_from_uuid(uuid):
    return Organization.get_by_uuid(uuid).name
Example #19
0
 async def get_many(self, *args, **kwargs) -> Response:
     organizations = Organization.get_items()
     return await self.to_response(await self.serialize(data=organizations,
                                                        many=True,
                                                        paginate=True))