Пример #1
0
    def handle(self):

        # For convenience, create local copies of global variables
        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        uHandler = UserHandler(db, cursor)

        form = cgi.FieldStorage(keep_blank_values="True")

        #print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
        #print					# DITTO
        #print `form`

        if form.has_key("loginsubmit"):
            username = form.getvalue("loginusername_field")
            passwd = form.getvalue("loginpassword_field")

            if self.checkPermissions(username, passwd):
                session = SimpleCookie(os.environ['HTTP_COOKIE'])
                phpsessid = session['PHPSESSID'].value
                session["userinfo"] = self.__user

                utils.redirect(os.environ['HTTP_REFERER'])
Пример #2
0
	def handle(self):
		
		# For convenience, create local copies of global variables
		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
		
		uHandler = UserHandler(db, cursor)
		
		form = cgi.FieldStorage(keep_blank_values="True")
		
		#print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
		#print					# DITTO
		#print `form`
		
		if form.has_key("loginsubmit"):
			username = form.getvalue("loginusername_field")
			passwd = form.getvalue("loginpassword_field")
			
			if self.checkPermissions(username, passwd):
				session = SimpleCookie(os.environ['HTTP_COOKIE'])
				phpsessid = session['PHPSESSID'].value
				session["userinfo"] = self.__user

				utils.redirect(os.environ['HTTP_REFERER'])
Пример #3
0
    def submitBug(self, form):

        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        if form.has_key("request_type"):  # it must, but still
            request_type = form.getvalue("request_type")

        if form.has_key("modules"):
            module = form.getvalue("modules")

        if form.has_key("bug_description"):
            bug_description = form.getvalue("bug_description")

        if form.has_key("curr_userid"):
            userID = int(form.getvalue("curr_userid"))

            # insert into database - NOT MAKING A SEPARATE bug_handler.py module now, no need to!!!
        cursor.execute(
            "INSERT INTO BugReport_tbl(bug_type, module, bug_descr, requested_by) VALUES("
            + ` request_type `
            + ", "
            + ` module `
            + ", "
            + ` bug_description `
            + ", "
            + ` userID `
            + ")"
        )

        utils.redirect(hostname + "bugreport.php?Req=1")
Пример #4
0
async def signout(request):
    session = await get_session(request)
    if session.get('user'):
        del session['user']
        redirect(request, 'login')
    else:
        raise web.HTTPForbidden(body=b'Forbidden')
Пример #5
0
    def submitBug(self, form):

        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        if form.has_key("request_type"):  # it must, but still
            request_type = form.getvalue("request_type")

        if form.has_key("modules"):
            module = form.getvalue("modules")

        if form.has_key("bug_description"):
            bug_description = form.getvalue("bug_description")

        if form.has_key("curr_userid"):
            userID = int(form.getvalue("curr_userid"))

        # insert into database - NOT MAKING A SEPARATE bug_handler.py module now, no need to!!!
        cursor.execute(
            "INSERT INTO BugReport_tbl(bug_type, module, bug_descr, requested_by) VALUES("
            + ` request_type ` + ", " + ` module ` + ", " +
            ` bug_description ` + ", " + ` userID ` + ")")

        utils.redirect(hostname + "bugreport.php?Req=1")
Пример #6
0
def update(request, u):
    """
    用于增加新 todo 的路由函数
    """
    # uname = current_user(request)
    # u = User.find_by(username=uname)
    # if u is None:
    #     return redirect('/login')
    if request.method == 'POST':
        # 修改并且保存 todo
        form = request.form()
        #print('debug update', form)
        todo_id = form.get('id', -1)
        # 检查 id 是不是数字
        if todo_id == -1 or not todo_id.isdigit():
            return redirect('/todo')
        todo_id = int(todo_id)
        t = Todo.find_by(id=todo_id)
        # 检验用户权限
        if t is None or t.user_id != u.id:
            return redirect('/todo')
        t.title = form.get('title', t.title)
        t.update_time = int(time.time())
        t.save()
    # 浏览器发送数据过来被处理后, 重定向到首页
    # 浏览器在请求新首页的时候, 就能看到新增的数据了
    return redirect('/todo')
Пример #7
0
def user_update(request, u):
    # 认证石否为管理员
    if u.role != 1:
        log('admin not power', u)
        return redirect('/login')
    if request.method == 'POST':
        # 修改并且保存 todo
        form = request.form()
        #print('debug update', form)
        user_id = form.get('id', -1)
        password = form.get('password', '')
        # 检查 输入是否合法
        if password == '' or user_id == -1 or not user_id.isdigit():
            log('form error', form)
            return redirect('/admin/user')
        user_id = int(user_id)
        user = User.find_by(id=user_id)
        # 检查要修改的用户是否存在
        if user is None:
            log('user update', 'user not exist')
            return redirect('/admin/user')
        log('user update', user, 'admin', u)
        user.update_password(password)
    # 浏览器发送数据过来被处理后, 重定向到首页
    # 浏览器在请求新首页的时候, 就能看到新增的数据了
    return redirect('/admin/user')
Пример #8
0
    def __call__(self, environ, start_response):
        self.environ = environ
        request_method = self.environ["REQUEST_METHOD"]
        path_info = self.environ["PATH_INFO"]

        # Routing
        matches = search(ROUTE, path_info)
        # / -> /pages/index
        if path_info is "/":
            status, headers, body = redirect(301, "/pages/index")
        # /pages/index/ -> /pages/index
        elif path_info.endswith("/"):
            status, headers, body = redirect(301, path_info[:-1])
        # /pages/index/something -> not found
        elif not matches:
            status, headers, body = error(404)
        # BADMETHOD /pages/index -> unsupported
        elif not hasattr(self, request_method):
            status, headers, body = error(501)
        # GET /pages/index -> GET()
        else:
            method = getattr(self, request_method)
            status, headers, body = method(*matches.groups())

        start_response(status, headers)
        return body
Пример #9
0
def login_route(request):
    if request.Method == 'GET':
        header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection:Close\r\n'
        verify_session = request.cookies().get('username', '')
        username = session.get(verify_session, '')
        user = User.find_by(username)
        if user is not None:
            return redirect('/')
        else:
            body = template('login.html')
        r = header + '\r\n' + body
        return r
    if request.Method == 'POST':
        re_username = request.form().get('username', '')
        re_password = request.form().get('password', '')
        user = User.login_verify(re_username, re_password)
        if user:
            """如果登录成功,获取一个随机16位的字符串,和username一起放入session字典中"""
            user_session = create_session()
            session[user_session] = user.username
            return redirect('/', user_session)
        else:
            print '登录失败'
            my_word = '登录失败'
            header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection:Close\r\n'
            body = template(
                'login_success.html',
                my_word=my_word,
            )
            r = header + '\r\n' + body
            return r
Пример #10
0
async def signout(request):
    session = await get_session(request)
    if session.get('user'):
        del session['user']
        redirect(request, 'login')
    else:
        raise web.HTTPForbidden(body=b'Forbidden')
Пример #11
0
def delete_todo(request):
    u = request.login_user
    todo_id = int(request.query.get('id', -1))
    t = Todo.find_by(id=todo_id)
    if t is None or t.user_id != u.id:
        return redirect('/login')
    t.remove()
    return redirect('/todo')
Пример #12
0
def update(request):
    user = current_user(request)
    form = request.form()
    weibo = Weibo.find_by(id=int(form.get('id', None)))
    if user.id != weibo.user_id:
        return redirect('/login')
    weibo.content = form.get('content')
    weibo.save()
    return redirect('/weibo/index?user_id={}'.format(user.id))
Пример #13
0
def route_register(request):
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_register() is not None:
            log('注册成功', u)
            return redirect('/login')
        else:
            return redirect('/register')
    return html_response('register.html')
Пример #14
0
def route_register(request):
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_register():
            return redirect('/login')
        else:
            return redirect('/register')
    body = template('register.html')
    return http_response(body)
	def modifyContainerType(self, form):
		
		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
	
		contTypeID = form.getvalue("containerType")
		
		# plain redirect
		utils.redirect(hostname + "Location.php?View=6&Sub=4&contTypeID=" + contTypeID + "&Mod=1")
    def modifyContainerType(self, form):

        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        contTypeID = form.getvalue("containerType")

        # plain redirect
        utils.redirect(hostname + "Location.php?View=6&Sub=4&contTypeID=" +
                       contTypeID + "&Mod=1")
Пример #17
0
    def deleteContainer(self, form):
        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        lHandler = LocationHandler(db, cursor)

        if form.has_key("containerID"):
            containerID = int(form.getvalue("containerID"))
            delStatus = lHandler.deleteContainer(containerID)
            utils.redirect(hostname + "Location.php?View=5&Del=1")
Пример #18
0
def add_todo(request):
    if request.Method == 'POST':
        form = request.form()
        user = current_user(request)
        if not user:
            return redirect('/404')
        form['user_id'] = user.id
        todo = Todo(form)
        if form.get('content', ''):
            print '我不是空的!'
            todo.save()
        return redirect('/todo')
def register(request):
    if request.method == 'POST':
        form = request.form
        u = User.new(form)
        log(u.__dict__)
        if u.validate_register():
            return redirect('/login')
        else:
            return redirect('/register')

    body = render_template('register.html')
    return http_response(body)
Пример #20
0
    def addLab(self, form):

        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        lHandler = LabHandler(db, cursor)
        ucMapper = UserCategoryMapper(db, cursor)
        category_Name_ID_Map = ucMapper.mapCategoryNameToID()

        # print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
        # print					# DITTO
        # print `form`

        # Get form values
        labName = form.getvalue("labName")
        labHeadTitle = form.getvalue("titles")
        labHeadName = form.getvalue("labHead")
        labHead = labHeadTitle + " " + labHeadName
        labCode = form.getvalue("labCode").upper()
        labDescr = form.getvalue("labDescription")
        labAddress = form.getvalue("labAddress")
        labAccess = form.getvalue("system_access_level")
        defaultLabAccessLevel = category_Name_ID_Map[labAccess]  # map to database ID

        try:
            newLabID = lHandler.insertLab(labName, labDescr, labAddress, defaultLabAccessLevel, labHead, labCode)
            # print `newLabID`
            newLab = Laboratory(newLabID, labName, labDescr, labAccess, labAddress, labHead, labCode)
            self.printLabInfo("view", newLab)

        except DuplicateLabCodeException:

            d = DuplicateLabCodeException()
            utils.redirect(
                hostname
                + "User.php?View=3&labName="
                + labName
                + "&title="
                + labHeadTitle
                + "&labHead="
                + labHeadName
                + "&labCode="
                + labCode
                + "&labDescr="
                + labDescr
                + "&locn="
                + labAddress
                + "&access="
                + labAccess
                + "&ErrCode="
                + ` d.err_code() `
            )
Пример #21
0
def register(rq):
    if rq.method == 'POST':
        d = rq.form()
        user = User(d)
        if user.validate_register() is not None:
            response_msg = redirect('/login')
        else:
            response_msg = redirect('/register')
    else:
        body = template(env, 'register.html')
        response_msg = make_response_msg(body=body)
    return response_msg
Пример #22
0
def delete_todo(request):
    uname = current_user(request)
    u = User.find_by(username=uname)
    if u is None:
        return redirect('/login')
    todo_id = int(request.query.get('id', -1))
    t = Todo.find_by(id=todo_id)
    if t.user_id != u.id:
        return redirect('/login')
    if t is not None:
        t.remove()
    return redirect('/todo')
Пример #23
0
def update(request):
    uname = current_user(request)
    u = User.find_by(username=uname)
    if u is None:
        return redirect('/login')
    if request.method == 'POST':
        form = request.form()
        todo_id = int(form.get('id', -1))
        t = Todo.find_by(id=todo_id)
        t.title = form.get('title', t.title)
        t.save()
    return redirect('/todo')
Пример #24
0
def process(file):
    print_file(f'+ Working on PCAP: {file!r}', file=TIME)
    print(f'+ Working on PCAP: {file!r}')

    stem = pathlib.Path(file).stem
    uid = uuid.uuid4()

    dest_stem = f'{stem}-{uid}'
    with SALT_LOCK:
        file_salt(uid)

    env = os.environ
    env['BRO_LOG_SUFFIX'] = f'{uid}.log'
    env['BROAPT_PCAP'] = dest_stem

    args = ['bro']
    if BARE_MODE:
        args.append('--bare-mode')
    if NO_CHKSUM:
        args.append('--no-checksums')
    args.extend(['--readfile', file, os.path.join(ROOT, 'scripts')])

    start = time.time()
    stdout = open(f'stdout.{uid}.log', 'at', 1)
    stderr = open(f'stderr.{uid}.log', 'at', 1)
    print(f'+ {" ".join(args)}', file=stdout)
    print(f'+ {" ".join(args)}', file=stderr)
    try:
        subprocess.check_call(args, env=env, stdout=stdout, stderr=stderr)
    except subprocess.CalledProcessError:
        print_file(f'+ Failed on PCAP: {file!r}', file=TIME)
    stdout.close()
    stderr.close()
    end = time.time()

    with STDOUT_LOCK:
        redirect(src=stdout.name, dst=STDOUT, label=dest_stem)
    with STDERR_LOCK:
        redirect(src=stderr.name, dst=STDERR, label=dest_stem)

    dest = os.path.join(LOGS_PATH, dest_stem)
    os.makedirs(dest, exist_ok=True)

    for log in glob.glob(f'*.{uid}.log'):
        with contextlib.suppress(OSError):
            shutil.move(log,
                        os.path.join(dest, log.replace(f'.{uid}.log', '.log')))
    communicate(dest)

    print_file(f'+ Bro processing: {end-start} seconds', file=TIME)
    print_file(file, file=FILE)
    QUEUE.put(dest_stem)
Пример #25
0
def route_admin_user_edit(request):
    uid = request.query.get("id", -1)
    if uid != -1:
        if request.method == "POST":
            form = request.form()
            if form.get("password", ""):
                User.model_edit(form, id=int(uid))
            return redirect(request.headers, "/user/list")
        else:
            user = User.model_find_by(id=int(uid))
            body = template("user.edit.html", user=user)
            return http_response(body, request.headers)
    return redirect(request.headers, "/user/list")
Пример #26
0
 def test_openstack_out_get_field_ok_uuids_input(self):
     with utils.stringio(neutron_agent_list) as fin:
         with utils.redirect('stdin', iofile=fin):
             f = self.get_field(['-p', 'Metadata', '-c', '0', '--'])
             print(f)
             u = uuid.UUID(f[0][0])
             self.assertEqual(uuid.UUID, type(u))
     with utils.stringio(neutron_agent_list) as fin:
         with utils.redirect('stdin', iofile=fin):
             f = self.get_field(['-P', 'c7-netw', '--'])
             print(f)
             u = uuid.UUID(f[0][0])
             self.assertEqual(uuid.UUID, type(u))
Пример #27
0
def index():
    login_form = forms.LoginForm()
    reg_form = forms.RegisterForm()
    ws = existing_web_session()

    if (ws and 'user_id' in ws):
        redirect('profile')
    return {
        'login_form':login_form,
        'reg_form':reg_form,
        'message':'Your message would show up here.',
        'ws':ws
    }
Пример #28
0
 def test_openstack_out_get_field_ok_uuids_input(self):
     with utils.stringio(neutron_agent_list) as fin:
         with utils.redirect('stdin', iofile=fin):
             f = self.get_field(['-p', 'Metadata', '-c', '0', '--'])
             print(f)
             u = uuid.UUID(f[0][0])
             self.assertEqual(uuid.UUID, type(u))
     with utils.stringio(neutron_agent_list) as fin:
         with utils.redirect('stdin', iofile=fin):
             f = self.get_field(['-P', 'c7-netw', '--'])
             print(f)
             u = uuid.UUID(f[0][0])
             self.assertEqual(uuid.UUID, type(u))
Пример #29
0
def route_todo_list(request):
    uid = current_user(request)
    if request.method == "POST":
        redirect(request.headers, "/todo/add")
    todo_dict = Todo.model_find_all(uid=int(uid))
    # todo_list = [todo for todo in todo_list if todo.get_deleted() != True]
    todo_list = Todo.model_validate_all(todo_dict)
    # todo test
    # for todo in todo_list:
    #     print(todo.get_deleted())
    body = template("todo.html", todo_list=todo_list)
    r = http_response(body, request.headers)
    return r
Пример #30
0
    def decorated(*args, **kwargs):
        redir = False
        if web_session_exists():
            ws = existing_web_session()
            if 'user_id' not in ws:
                redir = True
        else:
            redir = True

        if redir:
            redirect()
            
        return f(*args, **kwargs)
Пример #31
0
def login(rq):
    if rq.method == 'POST':
        d = rq.form()
        user = User(d)
        if (u := user.validate_login()) is not None:
            session_id = make_session_id()
            session[session_id] = u.id
            headers = {
                'Set-Cookie': f'session_id={session_id}',
            }
            response_msg = redirect('/', headers)
            log('登录成功')
        else:
            response_msg = redirect('/login')
            log('账号或密码错误')
Пример #32
0
def comment_add(request):
    user = current_user(request)
    form = request.form()
    comment = Comment(form)
    comment.user_id = user.id
    comment.save()
    return redirect('/weibo/index?user_id={}'.format(user.id))
Пример #33
0
	def deleteProject(self, form):

		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
		
		#print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
		#print					# DITTO
		#print `form`

		pHandler = ProjectDatabaseHandler(db, cursor)

		# Get form values
		pID = int(form.getvalue("packetID"))
		success = int(pHandler.deleteProject(pID))
		utils.redirect(hostname + "Project.php?View=3&Success=" + `success` + "&pID=" + `pID`)
Пример #34
0
def index(request):
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_headers(headers)
    user_id = request.query.get('user_id', -1)
    user_id = int(user_id)
    user = User.find(user_id)
    if user is None:
        return redirect('/login')
    # 找到 user 发布的所有 weibo
    weibos = Tweet.find_all(user_id=user_id)
    log('weibos', weibos)

    def weibo_tag(weibo):
        return '<p>{} from {}@{} <a href="/tweet/delete?id={}">删除</a> <a href="/tweet/edit?id={}">修改</a></p>'.format(
            weibo.content,
            user.username,
            weibo.created_time,
            weibo.id,
            weibo.id,
        )

    weibos = '\n'.join([weibo_tag(w) for w in weibos])
    body = template('weibo_index.html', weibos=weibos)
    r = header + '\r\n' + body
    print(1)
    return r.encode(encoding='utf-8')
Пример #35
0
 def new_handler(request):
     user = session.get_user(request)
     if user is None:
         return redirect('/login')
     request.login_user = user
     log('login user is', user)
     return handler(request)
Пример #36
0
 def test_glancing_add_checksum(self):
     with utils.stringio() as output:
         with utils.redirect('stdout', output):
             self.assertFalse(glancing.add_checksum(self._CIRROS_MD5,
                              {'checksums': {'md5': '0' * 32}}))
             self.assertEqual(output.getvalue(), '%s: conflicting digests: %s:%s\n' %
                              (sys.argv[0], self._CIRROS_MD5, '0' * 32))
Пример #37
0
def add(request):
    user = current_user(request)
    form = request.form()
    weibo = Weibo(form)
    weibo.user_id = user.id
    weibo.save()
    return redirect('/weibo/index?user_id={}'.format(user.id))
Пример #38
0
    def deleteLab(self, form):
        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        lHandler = LabHandler(db, cursor)

        # print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
        # print					# DITTO
        # print `form`

        labID = form.getvalue("labID")

        lHandler.deleteLab(labID)

        utils.redirect(hostname + "User.php?View=5")
Пример #39
0
def route_register(request):
    """
    注册页面
    """
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_register():
            u.save()
            # on success
            return redirect('/login')
        else:
            # if failed
            return redirect('/register')
    body = template('register.html')
    return http_response(body)
Пример #40
0
def route_update(request):
    id = int(request.query.get('id', -1))
    t = Tweet.find_by(id=id)
    form = request.form()
    t.content = form.get('content', '')
    t.save()
    return redirect('/')
Пример #41
0
def add(rq):
    user = current_user(rq)
    d = rq.form()
    d['user_id'] = user.id
    t = Tweet(d)
    t.add()
    return redirect('/tweet')
Пример #42
0
def main_index(request):
    """
    将访问主页重定向到todo的首页
    :param request:
    :return:
    """
    return redirect('/todo_list/index')
	def deleteContainerType(self, form):
		
		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
	
		ltHandler = LocationTypeHandler(db, cursor)
		
		#print "Content-type:text/html"
		#print
		#print `form`
		
		contTypeID = form.getvalue("containerType")
		#print contTypeID
		
		ltHandler.deleteContainerType(contTypeID)
		utils.redirect(hostname + "Location.php?View=6&Sub=4&Del=1")
Пример #44
0
 def test_utils_redirect_print(self):
     with utils.stringio() as output:
         with utils.redirect('stdout', output):
             print('TOTOTITI')
             self.assertEqual('TOTOTITI\n', output.getvalue())
         self.assertEqual('TOTOTITI\n', output.getvalue())
     with self.assertRaises(ValueError):
         output.getvalue()
Пример #45
0
async def login(request):
    session = await get_session(request)
    if session.get('user'):
        redirect(request, 'main')

    form = LoginForm()
    if request.method == 'POST':
        form.process(await request.post())
        if form.validate():
            user = User(request.db)
            result = await user.authenticate(email=form.email.data, 
                                            password=form.password.data)
            if result and result.rowcount:
                row = await result.fetchone()
                session = await get_session(request)
                set_session(session, row['id'], request)
                redirect(request, 'main')
    return {'title': 'Please enter login or email', 'form': form} 
Пример #46
0
 def test_utils_redirect_close(self):
     tmp = None
     with utils.redirect('stdout'):
         print('toto')
         print('toto', file=sys.stdout)
         self.assertFalse(sys.stdout.closed)
         tmp = sys.stdout
     self.assertFalse(sys.stdout.closed)
     self.assertTrue(tmp.closed)
Пример #47
0
def downvote(request, category_slug, post_slug):
    post = get_object_or_404(Post, slug=post_slug, category__slug=category_slug)
    credit, created = Credit.objects.get_or_create(user=request.user, post=post)
    if created:
        credit.discredit()
    else:
        if credit.amount > 0:
            credit.discredit()
        else:
            credit.delete()
    return redirect(request)
Пример #48
0
 def test_multihash_gethash_serial_nonexistent_hash(self):
     mh = multihash.multihash_serial_exec()
     with utils.stringio() as output:
         with utils.redirect('stdout', output):
             nonexistent_hash = 'nonexistent_hash_algo'
             self.assertFalse(mh.get_hash(os.devnull, nonexistent_hash))
             out = ("%s: '%s%s': Cannot execute, please check it is properly"
                    " installed, and available through your PATH environment "
                    "variable.\n%s: [Errno 2] No such file or directory\n" %
                    (sys.argv[0], nonexistent_hash, 'sum', sys.argv[0]))
             out = out.split("\n")[0]
             self.assertEqual(output.getvalue().split("\n")[0], out)
	def updateContainerType(self, form):
		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
	
		ltHandler = LocationTypeHandler(db, cursor)
		
		contTypeID = form.getvalue("containerType")
		
		contName = ""
		contDesc = ""
		
		#print "Content-type:text/html"
		#print
		#print `form`
		
		contTypeID = int(form.getvalue("containerType"))
		
		contGroupName = form.getvalue("cont_group_name_field")
		contGroupCode = form.getvalue("cont_cont_code_field")
		
		if form.has_key("cont_cont_isolateActive_radio"):
			if form.getvalue("cont_cont_isolateActive_radio").upper() == 'YES':
				isoActive = form.getvalue("cont_cont_isolateActive_radio").upper()
				#print isoActive
			else:
				isoActive = "NO"
		else:
			isoActive = ltHandler.findIsolateActive(contTypeID)
			
		newContTypeFeatures = form.getlist("container_features")
		
		reagentTypes = form.getlist("reagent_types")	# feb. 9/10
		
		#print `reagentTypes`

		ltHandler.updateContainerType(contTypeID, contGroupName, contGroupCode, isoActive, newContTypeFeatures, reagentTypes)
		
		utils.redirect(hostname + "Location.php?View=6&Sub=4&contTypeID=" + `contTypeID`)
Пример #50
0
 def vprint_lines_verbose(self, verbosity, test_name):
     v = utils.get_verbose()
     utils.set_verbose(verbosity)
     with utils.stringio() as output:
         expected = ''
         if verbosity:
             expected = test_name + ': TOTO\n' + test_name + ': TITI\n'
         with utils.redirect('stdout', output):
             utils.vprint_lines('TOTO\nTITI', test_name)
             self.assertEqual(expected, output.getvalue())
         self.assertEqual(expected, output.getvalue())
     with self.assertRaises(ValueError):
         output.getvalue()
     utils.set_verbose(v)
Пример #51
0
    def deleteUser(self, form):
        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        uHandler = UserHandler(db, cursor)
        pHandler = ProjectDatabaseHandler(db, cursor)

        # print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
        # print					# DITTO
        # print `form`

        uid = form.getvalue("userID")

        # list of user IDs
        # deletionCandidates = form.getlist("deletionCandidates")

        # Delete users and revoke their access to projects
        # for uid in deletionCandidates:
        uHandler.deleteUser(uid)
        pHandler.deleteMemberFromllProjects(uid)

        utils.redirect(hostname + "User.php?View=2&Del=1")
	def addContainerType(self, form):
		
		db = self.__db
		cursor = self.__cursor
		hostname = self.__hostname
	
		ltHandler = LocationTypeHandler(db, cursor)
		
		# some form values may be blank, so initialize as empty
		contName = ""
		contDesc = ""
		
		#print "Content-type:text/html"
		#print
		#print `form`
		
		contGroupName = form.getvalue("cont_group_name_field")
		contGroupCode = form.getvalue("cont_cont_code_field")
		
		if form.has_key("cont_cont_isolateActive_radio"):
			if form.getvalue("cont_cont_isolateActive_radio").upper() == 'YES':
				isoActive = form.getvalue("cont_cont_isolateActive_radio").upper()
			else:
				isoActive = "NO"
		
		newContTypeFeatures = form.getlist("container_features")
		#print `newContTypeFeatures`
		newContTypeID = ltHandler.insertContainerType(contGroupName, isoActive, contGroupCode)
		
		ltHandler.addContainerTypeFeatures(newContTypeID, newContTypeFeatures)
		
		reagentTypes = form.getlist("cont_cont_group_selection")	# feb. 16/10
		#print `reagentTypes`
		ltHandler.updateContainerReagentTypes(newContTypeID, reagentTypes)
		
		utils.redirect(hostname + "Location.php?View=6&Sub=4&contTypeID=" + `newContTypeID`)
Пример #53
0
def new(request, category_slug=None):
    category = Category.objects.filter(slug=category_slug).first()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            return redirect(request, url=reverse("post", args=[post.category.slug, post.slug]))
    else:
        form = PostForm(initial={'category': category})
    context = {
        'form': form,
        'category': category
    }
    return render_to_response("posts/new.html", context, context_instance = RequestContext(request))
Пример #54
0
def post(request, category_slug, post_slug):
    post = get_object_or_404(Post, slug=post_slug, category__slug=category_slug)
    
    if request.POST:
        if request.user.is_anonymous():
            raise PermissionDenied # Redirect to login
        
        if request.POST["text"]:
            reply = Post(text=request.POST["text"], user=request.user, parent=post)
            reply.save()
            return redirect(request)
            
    context = {
        'post': post,
        'category': post.category,
        'breadcrumbs': post_breadcrumbs(post),
    }
    return render_to_response("posts/post.html", context, context_instance = RequestContext(request))
Пример #55
0
    def POST(self, name):
        document_uri = join(DB_URI, "%s.md" % name)
        # Read the body content
        length = int(self.environ["CONTENT_LENGTH"])
        input_data = self.environ["wsgi.input"].read(length)
        input_data = parse_qs(input_data)

        data = input_data.get("data", None)
        # Store the data in the corresponding file
        if data:
            data = "".join(data)
            with open(document_uri, "w") as document:
                document.write(data)
        # Or remove the file if there is no data
        else:
            remove(document_uri)

        status, headers, body = redirect(303, "/pages/%s" % name)
        return status, headers, body
Пример #56
0
def edit(request, category_slug, post_slug):
    post = get_object_or_404(Post, slug=post_slug, category__slug=category_slug)

    if request.user.is_anonymous() or request.user != post.user:
        raise PermissionDenied # Redirect to login
        
    if request.POST:
        post.text = request.POST["text"]
        post.edit_count += 1
        post.save()
        return redirect(request)
            
    context = {
        'post': post,
        'category': post.category,
        'next': request.META['HTTP_REFERER'],
        'breadcrumbs': post_edit_breadcrumbs(post),
    }
    return render_to_response("posts/edit.html", context, context_instance = RequestContext(request))
Пример #57
0
def delete(request, category_slug, post_slug):
    post = get_object_or_404(Post, slug=post_slug, category__slug=category_slug)

    if request.user.is_anonymous() or request.user != post.user:
        raise PermissionDenied # Redirect to login
        
    if request.POST:
        if not post.children.all() and request.POST["make_anonymous"] == "0":
            post.delete()
        else:
            post.user = None
            post.save()
        return redirect(request)
            
    context = {
        'post': post,
        'category': post.category,
        'next': request.META['HTTP_REFERER'],
        'breadcrumbs': post_edit_breadcrumbs(post),
    }
    return render_to_response("posts/delete.html", context, context_instance = RequestContext(request))
Пример #58
0
async def signin(request):
    session = await get_session(request)
    if session.get('user'):
        redirect(request, 'main')

    form = SignInForm()
    if request.method == 'POST':
        form.process(await request.post())
        if form.validate():
            user = User(request.db)
            check = await user.check_email(form.email.data)
            if check.rowcount:
                redirect(request, 'login')
            result = await user.create(form.data)
            if result and result.lastrowid:
                session = await get_session(request)
                set_session(session, result.lastrowid, request)
                redirect(request, 'login')
    return {'title': 'Please sign in', 'form': form}
Пример #59
0
 def test_utils_redirect_write(self):
     with utils.stringio() as output:
         with utils.redirect('stdout', output):
             sys.stdout.write('TOTO')
             self.assertEqual('TOTO', output.getvalue())
Пример #60
0
    def handle(self):

        db = self.__db
        cursor = self.__cursor
        hostname = self.__hostname

        mail_server = self.__mail_server  # August 19, 2011
        mail_admin = self.__mail_admin  # August 19, 2011

        clone_request = self.__clone_request

        form = cgi.FieldStorage(keep_blank_values="True")

        uHandler = UserHandler(db, cursor)

        # print "Content-type:text/html"		# TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!!
        # print					# DITTO
        # print `form`

        if form.has_key("curr_username"):
            # store the user ID for use throughout the session; add to other views in addition to create in PHP
            currUname = form.getvalue("curr_username")
            currUser = uHandler.getUserByDescription(currUname)

            Session.setUser(currUser)

        elif form.has_key("curr_user_id"):
            currUID = form.getvalue("curr_user_id")
            currUser = uHandler.getUserByID(currUID)
            Session.setUser(currUser)

        if form.has_key("add_user"):
            self.addUser(form)

        elif form.has_key("modify_user"):
            self.modifyUser(form)

        elif form.has_key("cancel_user"):
            self.cancelUserModification(form)

        elif form.has_key("save_user"):
            self.saveUser(form)

        elif form.has_key("delete_user"):
            self.deleteUser(form)

        elif (
            form.has_key("view_user")
            and form.getvalue("view_user") != ""
            and not form.has_key("modify_lab")
            and not form.has_key("delete_lab")
        ):
            self.viewUser(form)

            # Nov. 17/07 - Personal user page
        elif (
            form.has_key("view_user")
            and form.getvalue("view_user") == ""
            and not form.has_key("modify_lab")
            and not form.has_key("delete_lab")
        ):
            self.printUserInfo("view", currUser)

        elif form.has_key("add_lab"):
            self.addLab(form)

        elif form.has_key("view_lab"):
            self.viewLab(form)

        elif form.has_key("modify_lab"):
            self.modifyLab(form)

        elif form.has_key("save_lab"):
            self.saveLab(form)

        elif form.has_key("cancel_lab"):
            self.cancelLabModification(form)

        elif form.has_key("delete_lab"):
            self.deleteLab(form)

        elif form.has_key("bug_report"):
            self.submitBug(form)

        elif form.has_key("send_order"):

            ######################################################################
            # CHANGE SERVER NAME AND EMAIL TO YOUR LOCAL CREDENTIALS
            ######################################################################

            userID = form.getvalue("curr_user_id")
            userDescr = form.getvalue("curr_username")

            from_email = uHandler.findEmail(userID)

            if not from_email:
                from_email = userDescr

            to_email = clone_request

            email_subject = userDescr + ": Clone Request"

            f_in = form.getvalue("outputContent")
            infile = open(f_in, "rb")

            msg = email.MIMEMultipart.MIMEMultipart()
            # msg.attach(email.MIMEText.MIMEText(infile.read()))	# no, this attaches plain text
            msg["Subject"] = email_subject

            part = email.MIMEBase.MIMEBase("application", "octet-stream")
            part.set_payload(infile.read())
            email.Utils.base64.standard_b64encode(infile.read())
            part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(f_in))
            msg.attach(part)

            server = smtplib.SMTP(mail_server)

            server.set_debuglevel(1)

            # Send a request to your clone request address
            server.sendmail(from_email, to_email, msg.as_string())

            # AND send a copy to the user (change the subject)
            # msg['Subject'] = "Clone request confirmation"		# doesn't change, investigate later

            # Return email text changed March 31/08

            #######################################
            # CHANGE TEXT AS NEEDED
            #######################################
            msg.attach(
                email.MIMEText.MIMEText(
                    "This is a copy of your clone request.  Please retain for your records.  You will be notified by e-mail when your clone is ready."
                )
            )

            server.sendmail(to_email, from_email, msg.as_string())
            server.quit()

            # Method 2
            # sendmail = "/usr/sbin/sendmail"

            # o = os.popen("%s -t" %  sendmail,"w")
            # o.write("To: %s\r\n" %  to_email)

            # if from_email:
            # o.write("From: %s\r\n" %  from_email)
            # o.write("Subject: %s\r\n" %  email_subject)
            # o.write("\r\n")
            # o.write("%s\r\n" % msg)

            # o.close()

            os.remove(f_in)  # delete the file from /tmp dir

            utils.redirect(hostname + "User.php?View=8&Sent=1")

            # June 1, 2010: Automated password reset
        elif form.has_key("reset_pw"):

            # change June 2, 2010: Don't enter email, rather, ask users to enter their username - more secure
            # to_email = form.getvalue("email")

            from_email = mail_admin

            # success = True

            chars = string.letters + string.digits
            new_passwd = ""

            for i in range(10):
                new_passwd += choice(chars)

                # reset it in the database
            if form.has_key("uName"):
                u_name = form.getvalue("uName")

                userID = uHandler.findUserIDByUsername(u_name)

                if userID > 0:
                    u_descr = uHandler.findDescription(userID)

                    to_email = uHandler.findEmail(userID)

                    uHandler.setUserPropertyValue(userID, "password", new_passwd)

                    email_subject = "OpenFreezer Password Change"

                    msg = email.MIMEMultipart.MIMEMultipart()
                    # msg.attach(email.MIMEText.MIMEText(infile.read()))	# no, this attaches plain text

                    msg["Subject"] = email_subject

                    ###################################
                    # CHANGE TEXT AS NEEDED
                    ###################################
                    msg.attach(
                        email.MIMEText.MIMEText(
                            "Dear "
                            + u_descr
                            + ",\n\nYour password for OpenFreezer has been changed.\n\nYour temporary new password is: "
                            + new_passwd
                            + ".\n\nPlease change the temporary password as soon as you log into the system.\n\nYour username for OpenFreezer is '"
                            + u_name
                            + "'.\n\nFor any questions, please refer to http://openfreezer.org. \n\nSincerely,\nOpenFreezer support team.\n--------------------------------\nThis is an automatically generated e-mail message.  Please do not reply to this e-mail.  All questions should be directed to your local administrator."
                        )
                    )

                    server = smtplib.SMTP(mail_server)

                    server.set_debuglevel(1)

                    server.sendmail(from_email, to_email, msg.as_string())
                    server.quit()

                    utils.redirect(hostname + "User.php?View=6&Reset=1&uid=" + ` userID `)
                else:
                    # retry by description
                    if form.has_key("uDesc"):
                        u_descr = form.getvalue("uDesc")

                        # but account for whitespace
                        toks = u_descr.split(" ")

                        tmp_descr = ""

                        for tok in toks:
                            tmp_descr += tok.strip() + " "

                            # strip extra whitespace from end
                        tmp_descr = tmp_descr.strip()

                        userID = uHandler.findUserIDByDescription(tmp_descr)

                        if userID > 0:
                            u_name = uHandler.findUsername(userID)

                            to_email = uHandler.findEmail(userID)
                            uHandler.setUserPropertyValue(userID, "password", new_passwd)

                            email_subject = "OpenFreezer Password Change"

                            msg = email.MIMEMultipart.MIMEMultipart()
                            # msg.attach(email.MIMEText.MIMEText(infile.read()))	# no, this attaches plain text

                            msg["Subject"] = email_subject

                            ##############################
                            # CHANGE TEXT AS NEEDED
                            ##############################
                            msg.attach(
                                email.MIMEText.MIMEText(
                                    "Dear "
                                    + u_descr
                                    + ",\n\nYour password for OpenFreezer has been changed.\n\nYour temporary new password is: "
                                    + new_passwd
                                    + ".\n\nPlease change the temporary password as soon as you log into the system.\n\nYour username for OpenFreezer is '"
                                    + u_name
                                    + "'.\n\nPlease refer to http://openfreezer.org for additional support.\n\nSincerely,\nOpenFreezer support team.\n--------------------------------\nThis is an automatically generated e-mail message.  Please do not reply to this e-mail.  All questions should be directed to <a href='mailto:"
                                    + mail_admin
                                    + "'>"
                                    + mail_admin
                                    + "</a>"
                                )
                            )

                            server = smtplib.SMTP(mail_server)
                            server.set_debuglevel(1)

                            server.sendmail(from_email, to_email, msg.as_string())
                            server.quit()

                            utils.redirect(hostname + "User.php?View=6&Reset=1&uid=" + ` userID `)
                        else:
                            utils.redirect(hostname + "User.php?View=6&Reset=0")
                    else:
                        utils.redirect(hostname + "User.php?View=6&Reset=0")
            else:
                utils.redirect(hostname + "User.php?View=6&Reset=0")

        cursor.close()
        db.close()