Esempio n. 1
0
    def post(self):
        request = self.request
        _ = request.translate

        model_state = request.model_state
        model_state.schema = LoginSchema()

        if not model_state.validate():
            return {}

        password = security.MakeRandomPassword()

        salt = security.MakeSalt()
        hash = security.Crypt(salt, password)
        hash_args = [security.DEFAULT_REPEAT, salt, hash]

        LoginName = model_state.value('LoginName')
        user = None
        with request.connmgr.get_connection() as conn:
            user = conn.execute('EXEC sp_Users_u_PwReset ?, ?, ?, ?', LoginName, *hash_args).fetchone()

        if user:
            gettext = get_translate_fn(request, user.Culture)

            subject = gettext('CIOC Community Manager Site Password Reset')
            welcome_message = gettext(pwreset_email_template) % {
                'FirstName': user.FirstName,
                'Password': password,
                'url': request.route_url('login')
            }

            email.email('*****@*****.**', user.Email, subject, welcome_message)

        request.session.flash(_('A new password was sent you your email address.'))
        return HTTPFound(location=request.route_url('home'))
Esempio n. 2
0
    def post(self):
        request = self.request
        _ = request.translate

        is_new = not not request.matched_route.name == 'user_new'
        is_request = not not request.matched_route.name == 'request_account'
        is_account = not not request.matched_route.name == 'account'

        reqid = None

        if is_new:
            reqid = self._get_request_id()
        elif is_account:
            uid = request.user.User_ID
        elif not is_request:
            validator = validators.IntID(not_empty=True)
            try:
                uid = validator.to_python(request.matchdict.get('uid'))
            except validators.Invalid:
                raise HTTPNotFound()

        if is_new and request.params.get('Reject'):
            return HTTPFound(location=request.route_url(
                'request_reject', _query=[('reqid', reqid)]))

        extra_validators = {}
        if is_new:
            extra_validators['user'] = NewUserValidator()
        elif is_account:
            extra_validators['user'] = BaseUserValidator()
            extra_validators['password'] = PasswordValidator(if_missing=None)
        elif not is_request:
            extra_validators['user'] = ManageUsersValidator()
            extra_validators['password'] = PasswordValidator(if_missing=None)
        else:
            extra_validators['user'] = RequestAccessValidator()
            extra_validators['TomorrowsDate'] = TomorrowsDateValidator

        if is_request or is_account:
            schema = UpdateProfileRequestAccessBase(**extra_validators)
        else:
            schema = ManageUserAddUserWrapper(**extra_validators)

        model_state = request.model_state
        model_state.form.variable_decode = True
        model_state.schema = schema

        if model_state.validate():
            form_data = model_state.data
            user = form_data['user']

            fields = list(schema.fields['user'].fields.keys())
            args = [user.get(x) for x in fields]

            if not is_request and not is_account:
                root = ET.Element('ManageAreas')
                if not user.get('Admin'):
                    for cmid in form_data.get('manage_areas') or []:
                        if cmid:
                            ET.SubElement(root, 'CM_ID').text = str(cmid)

                fields.append('ManageAreas')
                args.append(ET.tostring(root))

                root = ET.Element('ManageExternal')
                if not user.get('Admin'):
                    for code in form_data.get('manage_external') or []:
                        if code:
                            ET.SubElement(root, 'SystemCode').text = str(code)

                fields.append('ManageExternalSystems')
                args.append(ET.tostring(root))

                log.debug('args: %s', args)

            if is_new:
                fields.append('Request_ID')
                args.append(reqid)

            if not is_request:
                fields.append('MODIFIED_BY')
                args.append(request.user.UserName)

            password = None
            if not is_request:
                if is_new:
                    password = security.MakeRandomPassword()
                else:
                    password = model_state.value('password.Password')

                if password:
                    salt = security.MakeSalt()
                    hash = security.Crypt(salt, password)
                    hash_args = [security.DEFAULT_REPEAT, salt, hash]
                else:
                    hash_args = [None, None, None]

                fields.extend(
                    ['PasswordHashRepeat', 'PasswordHashSalt', 'PasswordHash'])
                args.extend(hash_args)

            user_id_sql = ''
            if is_new:
                user_id_sql = '@User_ID OUTPUT,'
            elif not is_request:
                fields.append('User_ID')
                args.append(uid)

            if is_request:
                sql = '''
                    DECLARE @RT int, @ErrMsg nvarchar(500), @Request_ID int

                    %s
                    EXEC @RT = sp_Users_AccountRequest_i @Request_ID OUTPUT, %s, @ErrMsg=@ErrMsg OUTPUT

                    SELECT @RT AS [Return], @ErrMsg AS ErrMsg, @Request_ID AS Request_ID
                '''
            else:
                sql = '''
                    DECLARE @RT int, @ErrMsg nvarchar(500), @User_ID int
                    SET @ErrMsg = NULL

                    EXEC @RT = sp_Users_u %s %s, @ErrMsg=@ErrMsg OUTPUT

                    SELECT @RT AS [Return], @ErrMsg AS ErrMsg, @User_ID AS [User_ID]

                '''

            sql = sql % (user_id_sql, ','.join('@%s=?' % x for x in fields))

            with request.connmgr.get_connection() as conn:
                result = conn.execute(sql, args).fetchone()

            if not result.Return:

                if is_new:
                    # force to language of request?
                    gettext = get_translate_fn(request, user['Culture'])

                    subject = gettext(
                        'Your CIOC Community Manager Site Account')
                    welcome_message = gettext(welcome_email_template) % {
                        'FirstName': user['FirstName'],
                        'UserName': user['UserName'],
                        'Password': password,
                        'url': request.route_url('login')
                    }

                    email.email('*****@*****.**', user['Email'], subject,
                                welcome_message)
                    request.session.flash(_('User Successfully Added'))
                    return HTTPFound(
                        location=request.route_url('user', uid=result.User_ID))
                elif is_request:
                    subject = 'CIOC Community Manager Account Request'
                    tmpl_args = {
                        'url':
                        request.route_url('user_new',
                                          _query=[('reqid', result.Request_ID)
                                                  ])
                    }
                    tmpl_args.update(user)
                    request_message = request_email_template % tmpl_args
                    email.email('*****@*****.**', '*****@*****.**', subject,
                                request_message)

                    return HTTPFound(
                        location=request.route_url('request_account_thanks'))

                if is_account:
                    request.session.flash(_('Account successfully updated'))
                else:
                    request.session.flash(_('User successfully modified'))

                return HTTPFound(location=request.current_route_url())

            model_state.add_error_for(
                '*',
                _('Could not add user: '******'manage_areas') or []

        else:
            data = model_state.data
            decoded = variable_decode(request.POST)
            data['manage_areas'] = manage_areas = decoded.get(
                'manage_areas') or []
            if is_account:
                manage_areas = request.user.ManageAreaList or []
            log.debug('errors: %s', model_state.form.errors)

        account_request = user = None
        cm_name_map = {}
        if not is_request:
            with request.connmgr.get_connection() as conn:
                if is_new:
                    account_request = conn.execute(
                        'EXEC sp_Users_AccountRequest_s ?', reqid).fetchone()
                else:
                    if is_account:
                        user = conn.execute('EXEC sp_Users_s ?',
                                            uid).fetchone()

                    else:
                        user = request.context.user

                cm_name_map = {
                    str(x[0]): x[1]
                    for x in conn.execute(
                        'EXEC sp_Community_ls_Names ?', ','.join(
                            str(x) for x in manage_areas)).fetchall()
                }

        if is_new:
            if not account_request:
                request.session.flash(_('Account Request Not Found'),
                                      'errorqueue')
                return HTTPFound(location=request.route_url('users'))
        elif not is_request:
            if not user:
                raise HTTPNotFound()

        if is_new:
            title_text = _('Add New User')
        elif is_request:
            title_text = _('Request Account')
        elif is_account:
            title_text = _('Update Account')
        else:
            title_text = _('Modify User')

        return {
            'title_text': title_text,
            'account_request': account_request,
            'user': user,
            'cm_name_map': cm_name_map,
            'is_admin': not is_request and not is_account,
            'is_account': is_account
        }
Esempio n. 3
0
    def post(self):
        request = self.request
        _ = request.translate

        is_new = not not request.matched_route.name == 'user_new'
        is_request = not not request.matched_route.name == 'request_account'
        is_account = not not request.matched_route.name == 'account'

        reqid = None

        if is_new:
            reqid = self._get_request_id()
        elif is_account:
            uid = request.user.User_ID
        elif not is_request:
            validator = validators.IntID(not_empty=True)
            try:
                uid = validator.to_python(request.matchdict.get('uid'))
            except validators.Invalid:
                raise HTTPNotFound()

        if is_new and request.params.get('Reject'):
            return HTTPFound(location=request.route_url('request_reject', _query=[('reqid', reqid)]))

        extra_validators = {}
        if is_new:
            extra_validators['user'] = NewUserValidator()
        elif is_account:
            extra_validators['user'] = BaseUserValidator()
            extra_validators['password'] = PasswordValidator(if_missing=None)
        elif not is_request:
            extra_validators['user'] = ManageUsersValidator()
            extra_validators['password'] = PasswordValidator(if_missing=None)
        else:
            extra_validators['user'] = RequestAccessValidator()
            extra_validators['TomorrowsDate'] = TomorrowsDateValidator

        if is_request or is_account:
            schema = UpdateProfileRequestAccessBase(**extra_validators)
        else:
            schema = ManageUserAddUserWrapper(**extra_validators)

        model_state = request.model_state
        model_state.form.variable_decode = True
        model_state.schema = schema

        if model_state.validate():
            form_data = model_state.data
            user = form_data['user']

            fields = schema.fields['user'].fields.keys()
            args = [user.get(x) for x in fields]

            if not is_request and not is_account:
                root = ET.Element('ManageAreas')
                if not user.get('Admin'):
                    for cmid in form_data.get('manage_areas') or []:
                        if cmid:
                            ET.SubElement(root, 'CM_ID').text = unicode(cmid)

                fields.append('ManageAreas')
                args.append(ET.tostring(root))

                root = ET.Element('ManageExternal')
                if not user.get('Admin'):
                    for code in form_data.get('manage_external') or []:
                        if code:
                            ET.SubElement(root, 'SystemCode').text = unicode(code)

                fields.append('ManageExternalSystems')
                args.append(ET.tostring(root))

                log.debug('args: %s', args)

            if is_new:
                fields.append('Request_ID')
                args.append(reqid)

            if not is_request:
                fields.append('MODIFIED_BY')
                args.append(request.user.UserName)

            password = None
            if not is_request:
                if is_new:
                    password = security.MakeRandomPassword()
                else:
                    password = model_state.value('password.Password')

                if password:
                    salt = security.MakeSalt()
                    hash = security.Crypt(salt, password)
                    hash_args = [security.DEFAULT_REPEAT, salt, hash]
                else:
                    hash_args = [None, None, None]

                fields.extend(['PasswordHashRepeat', 'PasswordHashSalt', 'PasswordHash'])
                args.extend(hash_args)

            user_id_sql = ''
            if is_new:
                user_id_sql = '@User_ID OUTPUT,'
            elif not is_request:
                fields.append('User_ID')
                args.append(uid)

            if is_request:
                sql = '''
                    DECLARE @RT int, @ErrMsg nvarchar(500), @Request_ID int

                    %s
                    EXEC @RT = sp_Users_AccountRequest_i @Request_ID OUTPUT, %s, @ErrMsg=@ErrMsg OUTPUT

                    SELECT @RT AS [Return], @ErrMsg AS ErrMsg, @Request_ID AS Request_ID
                '''
            else:
                sql = '''
                    DECLARE @RT int, @ErrMsg nvarchar(500), @User_ID int
                    SET @ErrMsg = NULL

                    EXEC @RT = sp_Users_u %s %s, @ErrMsg=@ErrMsg OUTPUT

                    SELECT @RT AS [Return], @ErrMsg AS ErrMsg, @User_ID AS [User_ID]

                '''

            sql = sql % (user_id_sql, ','.join('@%s=?' % x for x in fields))

            with request.connmgr.get_connection() as conn:
                result = conn.execute(sql, args).fetchone()

            if not result.Return:

                if is_new:
                    # force to language of request?
                    gettext = get_translate_fn(request, user['Culture'])

                    subject = gettext('Your CIOC Community Manager Site Account')
                    welcome_message = gettext(welcome_email_template) % {
                        'FirstName': user['FirstName'],
                        'UserName': user['UserName'],
                        'Password': password,
                        'url': request.route_url('login')}

                    email.email('*****@*****.**', user['Email'], subject, welcome_message)
                    request.session.flash(_('User Successfully Added'))
                    return HTTPFound(location=request.route_url('user', uid=result.User_ID))
                elif is_request:
                    subject = 'CIOC Community Manager Account Request'
                    tmpl_args = {'url': request.route_url('user_new', _query=[('reqid', result.Request_ID)])}
                    tmpl_args.update(user)
                    request_message = request_email_template % tmpl_args
                    email.email('*****@*****.**', '*****@*****.**', subject, request_message)

                    return HTTPFound(location=request.route_url('request_account_thanks'))

                if is_account:
                    request.session.flash(_('Account successfully updated'))
                else:
                    request.session.flash(_('User successfully modified'))

                return HTTPFound(location=request.current_route_url())

            model_state.add_error_for('*', _('Could not add user: '******'manage_areas') or []

        else:
            data = model_state.data
            decoded = variable_decode(request.POST)
            data['manage_areas'] = manage_areas = decoded.get('manage_areas') or []
            if is_account:
                manage_areas = request.user.ManageAreaList or []
            log.debug('errors: %s', model_state.form.errors)

        account_request = user = None
        cm_name_map = {}
        if not is_request:
            with request.connmgr.get_connection() as conn:
                if is_new:
                    account_request = conn.execute('EXEC sp_Users_AccountRequest_s ?', reqid).fetchone()
                else:
                    if is_account:
                        user = conn.execute('EXEC sp_Users_s ?', uid).fetchone()

                    else:
                        user = request.context.user

                cm_name_map = {str(x[0]): x[1] for x in
                               conn.execute('EXEC sp_Community_ls_Names ?',
                                            ','.join(str(x) for x in manage_areas)).fetchall()}

        if is_new:
            if not account_request:
                request.session.flash(_('Account Request Not Found'), 'errorqueue')
                return HTTPFound(location=request.route_url('users'))
        elif not is_request:
            if not user:
                raise HTTPNotFound()

        if is_new:
            title_text = _('Add New User')
        elif is_request:
            title_text = _('Request Account')
        elif is_account:
            title_text = _('Update Account')
        else:
            title_text = _('Modify User')

        return {'title_text': title_text, 'account_request': account_request,
                'user': user, 'cm_name_map': cm_name_map, 'is_admin': not is_request and not is_account,
                'is_account': is_account}