示例#1
0
def new(request):

    myGroups = request.user.groups.exclude(name='agents') #user is agent
    errorMessage=""

    agents = User.objects.filter(groups__name=AGENTS_GROUP)
    
    if (request.user.groups.filter(name=AGENTS_GROUP).count()>0):
        agents = User.objects.filter(id=request.user.id)

    if (request.POST):
        form = groupForm(request.POST)
        form.fields['agent'] = forms.ModelChoiceField(required=True,queryset=agents,empty_label=None)
       
        if form.is_valid():
            otherGroups = Group.objects.filter(name=form.cleaned_data["name"]) #user is agent
            if otherGroups.count()>0:
                errorMessage=_("Group already exists")
            else:
                group = Group()
                group.name=form.cleaned_data["name"]
                group.save()
                
                #add targgueted agent too
                ag = form.cleaned_data["agent"]
                ag.groups.add(group)
                ag.save()

                #add admin
                amin = User.objects.get(username='******')
                amin.groups.add(group)
                amin.save()
               
                return HttpResponseRedirect('/groups/') # Redirect after POST
    else:
        form = groupForm()
        form.fields['agent'] = forms.ModelChoiceField(required=True,queryset=agents,empty_label=None)



    return render_to_response('groups/new.html',
            {
                'agents':agents,
                'myGroups':myGroups,
                'form':form,
                'section':SECTION_GROUPS,
                'errorMsg':errorMessage,
                },context_instance=RequestContext(request))
示例#2
0
def userView(uuid=None, function=None):
    # universal variables
    form = userForm()
    kwargs = {'contentTitle': 'Users', 'width': '', 'formWidth': '400'}

    # Get users
    if function == None:
        kwargs['tableColumns'] = ['User name', 'Email', 'Roles', 'Groups']
        kwargs['tableData'] = usersTable()
        return render_template('listView.html', **kwargs)

    elif function == 'delete':
        delUsr = deleteUser(uuid)
        if 'error' in delUsr:
            errorMessage(delUsr['error'])
        print delUsr
        return redirect(url_for('userBP.userView'))

    else:
        if function == 'update':
            usr = getUser(uuid=uuid,
                          includes=['includeRoles', 'includeGroups'])['user']
            kwargs['contentTitle'] = 'Update user'
            role = 'User'
            for r in usr['roles']:
                if r['title'] == 'Administrator':
                    role = 'Administrator'
                elif r['title'] == 'Superuser':
                    role = 'Superuser'
            grpForm = groupForm()
            usrForm = userForm(
                userName=usr['name'],
                userEmail=usr['email'],
                userPhone=usr['phone'],
                userGroups=[str(r['uuid']) for r in usr['groups']],
                userRole=role)

            # Get all groups
            usrForm.userGroups.choices = [(str(r['uuid']), r['name'])
                                          for r in getGroups()['groups']]
            if g.sijax.is_sijax_request:
                g.sijax.register_object(SijaxHandler)
                return g.sijax.process_request()

            if usrForm.validate_on_submit():
                dataDict = {
                    'name': usrForm.userName.data,
                    'email': usrForm.userEmail.data,
                    'phone': usrForm.userPhone.data,
                    'roles': [usrForm.userRole.data],
                    'groups': [usrForm.userGroups.data]
                }

                updateUser = putUser(dataDict=dataDict, uuid=uuid)
                if not 'error' in updateUser:
                    apiMessage(updateUser)
                    return redirect(url_for('userBP.userView'))
                else:
                    return unicode(updateUser)
            return render_template('user/userForm.html',
                                   usrForm=usrForm,
                                   grpForm=grpForm,
                                   **kwargs)

        elif function == 'new':
            usrForm = userForm(userRole='User')
            grpForm = groupForm()
            grpForm.groupUsers.choices = [(str(r['uuid']), r['email'])
                                          for r in getUsers()['users']]
            kwargs['contentTitle'] = 'New user'
            groups = [(str(r['uuid']), r['name'])
                      for r in getGroups()['groups']]
            usrForm.userGroups.choices = groups

            if g.sijax.is_sijax_request:
                g.sijax.register_object(SijaxHandler)
                return g.sijax.process_request()

            if usrForm.validate_on_submit():
                dataDict = {
                    'name': usrForm.userName.data,
                    'email': usrForm.userEmail.data,
                    'phone': usrForm.userPhone.data
                }

                roles = ['User']
                if usrForm.userRole.data == 'Superuser':
                    roles.append('Superuser')
                elif usrForm.userRole.data == 'Administrator':
                    roles.append('Superuser')
                    roles.append('Administrator')

                dataDict['roles'] = roles
                dataDict['groups'] = usrForm.userGroups.data
                newUser = postUser(dataDict)
                if 'success' in newUser:
                    successMessage('The user has been created')
                    subject = u'Confirm signup'
                    confirm_url = url_for('authBP.confirmEmailView',
                                          token=newUser['token'],
                                          _external=True)
                    html = render_template('email/verify.html',
                                           confirm_url=confirm_url)

                    sendMail(subject=subject,
                             sender='Henrik Poulsen',
                             recipients=[usrForm.userEmail.data],
                             html_body=html,
                             text_body=None)

                    return redirect(url_for('userBP.userView'))
                else:
                    apiMessage(newUser)
            return render_template('user/userForm.html',
                                   usrForm=usrForm,
                                   grpForm=grpForm,
                                   **kwargs)
示例#3
0
def groupView(function=None, uuid=None):
    # global variables
    kwargs = {
        'contentTitle': 'User groups',
        'width': '800',
        'formWidth': '350',
        'tableColumns':
        ['User group', 'Description', 'Users assigned to group']
    }

    if function == None:
        req = getGroups(includes=['includeUsers'])['groups']
        kwargs['tableData'] = [[
            r['uuid'], r['name'], r['desc'],
            len(r['users'])
        ] for r in req]
        return render_template('listView.html', **kwargs)

    elif function == 'delete':
        delGroup = deleteGroup(uuid)
        apiMessage(delGroup)
        return redirect(url_for('userBP.groupView'))

    else:
        if function == 'update':
            kwargs['contentTitle'] = 'Update User Group'
            grp = getGroup(uuid, includes=['includeUsers'])['group']
            form = groupForm(
                groupName=grp['name'],
                groupDesc=grp['desc'],
                groupUsers=[unicode(r['uuid']) for r in grp['users']])
            form.groupUsers.choices = [(unicode(r['uuid']), r['email'])
                                       for r in getUsers()['users']]
            if form.validate_on_submit():
                dataDict = {
                    'name': form.groupName.data,
                    'desc': form.groupDesc.data,
                    'users': [unicode(r) for r in form.groupUsers.data]
                }
                updateGroup = putGroup(dataDict=dataDict, uuid=uuid)
                if 'error' in updateGroup:
                    apiMessage(updateGroup)
                else:
                    apiMessage(updateGroup)
                    return redirect(url_for('userBP.groupView'))

        elif function == 'new':
            kwargs['contentTitle'] = 'New User Group'
            form = groupForm()
            form.groupUsers.choices = [(unicode(r['uuid']), r['email'])
                                       for r in getUsers()['users']]
            if form.validate_on_submit():
                dataDict = {
                    'name': form.groupName.data,
                    'desc': form.groupDesc.data,
                    'users': [unicode(r) for r in form.groupUsers.data]
                }
                newGroup = postGroup(dataDict)
                if 'error' in newGroup:
                    apiMessage(newGroup)
                else:
                    apiMessage(newGroup)
                    return redirect(url_for('userBP.groupView'))
        return render_template('user/groupForm.html', form=form, **kwargs)
示例#4
0
def groupView(function=None, uuid=None):
    # Universal vars
    viewName = 'Group'
    viewURL = 'userBP.groupView'
    listColumns = ['Title', 'Description', 'Users']
    templateView = 'user/group.html'

    # View kwargs
    kwargs = {
        'title': viewName + ' list',
        'details': False,
    }

    # Cruds
    listCrud = groupCrud.groupListData
    getCrud = groupCrud.getGroup
    postCrud = groupCrud.postGroup
    putCrud = groupCrud.putGroup
    deleteCrud = groupCrud.deleteGroup

    postForm = groupForm()
    postData = {
        'title': postForm.title.data,
        'desc': postForm.desc.data,
        'users': postForm.users.data
    }

    putForm = groupForm()
    putData = {
        'title': putForm.title.data,
        'desc': putForm.desc.data,
        'users': putForm.users.data
    }

    # put variables
    putExecs = [
        'data = groupCrud.getGroup(uuid)',
        'users = [r.uuid for r in data.users]',
        'putForm = groupForm(title=data.title,desc=data.desc,users=users)',
        'users = userCrud.userSelectData()', 'putForm.users.choices = users'
    ]

    # Post variables
    postExecs = [
        'users = userCrud.userSelectData()', 'postForm.users.choices = users'
    ]

    # --------------------------------------------------------------------------------------------
    # CRUD Views (Do not touch!)
    # Build list of all rows
    if function == None:
        kwargs['listColumns'] = listColumns
        kwargs['listData'] = listCrud()
        return render_template('dataTable.html', **kwargs)

    # Create new row
    elif function == 'new':
        # Function kwargs
        kwargs = {
            'contentTitle': 'Add new {}'.format(viewName),
            'submitStay': True
        }

        for r in postExecs:
            exec(r)

        if postForm.validate_on_submit():
            req = postCrud(data=postData)
            if 'success' in req:
                successMessage(req['success'])
                if not postForm.submitStay.data:
                    return redirect(url_for(viewURL))
                else:
                    return redirect(url_for(viewURL) + '/new')
            elif 'error' in req:
                errorMessage(req['error'])
        return render_template(templateView, form=postForm, **kwargs)

    # Edit single row
    elif function == 'edit' and uuid != None:
        # Function kwargs
        kwargs = {
            'contentTitle': 'Edit {}'.format(viewName),
            'submitStay': False
        }

        for r in putExecs:
            exec(r)

        if putForm.validate_on_submit():
            req = putCrud(data=putData, uuid=uuid)
            if 'success' in req:
                successMessage(req['success'])
                return redirect(url_for(viewURL))
            elif 'error' in req:
                errorMessage(req['error'])
        return render_template(templateView, form=putForm, **kwargs)

    # Edit single row
    elif function == 'delete' and uuid != None:
        req = deleteCrud(uuid=uuid)
        print req
        if 'success' in req:
            successMessage(req['success'])
        elif 'error' in req:
            errorMessage(req['error'])
        return redirect(url_for(viewURL))

    # View single row details
    elif function == 'details' and uuid != None:
        # Function kwargs
        data = getCrud(uuid)
        kwargs = {
            'contentTitle': '{} details'.format(viewName),
            'details': True,
            'detailsData': data,
            'submitStay': False,
            'modifiedUser': getUser(data.modifiedBy),
            'createdUser': getUser(data.createdBy)
        }

        return render_template(templateView, **kwargs)
示例#5
0
def groupView(function=None, id=None, lang=None):
    # global variables
    g.lang = lang
    kwargs = {
        'title': messageText('userGrpTitle'),
        'width': '600',
        'formWidth': '350',
        'breadcrumbs': breadCrumbs('userBP.groupView')
    }

    if function == None:
        # perform API request
        req = getGroups(includes=['includeUsers'])

        # set data for listView
        kwargs['tableColumns'] = columns(['usrGroupCol', 'usersCol'])
        kwargs['tableData'] = [[r['id'], r['name'],
                                len(r['users'])] for r in req]

        # return view
        return render_template(lang + '/listView.html', **kwargs)
    elif function == 'delete':
        delGroup = deleteGroup(id)

        if 'error' in delGroup:
            if delGroup['error'] == 'Group has users':
                flashMessage('grpHasUsers')
            else:
                errorFlash(delGroup['error'])
        elif 'success' in delGroup:
            flashMessage('grpDeleted')

        return redirect(url_for('userBP.groupView', lang=lang))

    else:
        if function == 'update':
            # Get single group
            grp = getGroup(id, includes=['includeUsers'])
            form = groupForm(name=grp['name'],
                             desc=grp['desc'],
                             users=[str(r['id']) for r in grp['users']])
            form.users.choices = [(str(r['id']), r['email'])
                                  for r in getUsers()]
            if form.validate_on_submit():
                dataDict = {
                    'name': form.name.data,
                    'desc': form.desc.data,
                    'users': [int(r) for r in form.users.data]
                }
                updateGroup = putGroup(dataDict=dataDict, id=id)
                if 'error' in updateGroup:
                    if updateGroup['error'] == 'Group already exist':
                        flashMessage('grpUpdated')
                    else:
                        errorFlash(updateGroup['error'])
                elif 'success' in updateGroup:
                    flashMessage('grpNew')

                return redirect(url_for('userBP.groupView', lang=lang))

        elif function == 'new':
            form = groupForm()
            form.users.choices = [(str(r['id']), r['email'])
                                  for r in getUsers()]

            if form.validate_on_submit():
                dataDict = {
                    'name': form.name.data,
                    'desc': form.desc.data,
                    'users': [int(r) for r in form.users.data]
                }
                newGroup = postGroup(dataDict)

                if 'error' in newGroup:
                    if newGroup['error'] == 'Group already exist':
                        flashMessage('grpExists')
                    else:
                        errorFlash(newGroup['error'])
                elif 'success' in newGroup:
                    flashMessage('grpNew')

                return redirect(url_for('userBP.groupView', lang=lang))
        return render_template(lang + '/user/groupForm.html', form=form)
示例#6
0
def groupView(function=None, id=None):
    # global variables
    kwargs = {
        'title': 'User groups',
        'width': '600',
        'formWidth': '350',
        'contentTitle': 'Add new user Group',
        'tableColumns':
        ['User group', 'Description', 'Users assigned to group']
    }

    if function == None:
        # perform API request
        req = getGroups(includes=['includeUsers'])['groups']

        # set data for listView
        kwargs['tableData'] = [[
            r['id'], r['name'], r['desc'],
            len(r['users'])
        ] for r in req]

        # return view
        return render_template('listView.html', **kwargs)
    elif function == 'delete':
        delGroup = deleteGroup(id)
        apiMessage(delGroup)

        return redirect(url_for('userBP.groupView'))

    else:
        if function == 'update':
            # Get single group
            grp = getGroup(id, includes=['includeUsers'])
            form = groupForm(groupName=grp['name'],
                             groupDesc=grp['desc'],
                             groupUsers=[str(r['id']) for r in grp['users']])
            form.groupUsers.choices = [(str(r['id']), r['email'])
                                       for r in getUsers()['users']]
            if form.validate_on_submit():
                dataDict = {
                    'name': form.groupName.data,
                    'desc': form.groupDesc.data,
                    'users': [int(r) for r in form.groupUsers.data]
                }
                updateGroup = putGroup(dataDict=dataDict, id=id)
                if 'error' in updateGroup:
                    apiMessage(updateGroup)
                else:
                    apiMessage(updateGroup)
                    return redirect(url_for('userBP.groupView'))

        elif function == 'new':
            form = groupForm()
            form.groupUsers.choices = [(str(r['id']), r['email'])
                                       for r in getUsers()['users']]

            if form.validate_on_submit():
                dataDict = {
                    'name': form.groupName.data,
                    'desc': form.groupDesc.data,
                    'users': [int(r) for r in form.groupUsers.data]
                }
                newGroup = postGroup(dataDict)
                if 'error' in newGroup:
                    apiMessage(newGroup)
                else:
                    apiMessage(newGroup)
                    return redirect(url_for('userBP.groupView'))
        return render_template('user/groupForm.html', form=form, **kwargs)