def POST(self):
     webinput=web.input()
     cookies=web.cookies()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     a.activity_time=webinput[u'activity_time']
     a.activity_position=webinput[u'activity_position']
     a.activity_brief=webinput[u'activity_brief']
     uid=cookies[u'uid']
     people=[]
     u=user(uid=uid)
     for friend in u.get_friends_pachong():
         try:
             money=webinput["a"+str(friend[u'id'])]
             p={}
             p[u'state']="invited"
             p[u'money']=float(money)
             p[u'uid']=friend[u'id']
             p[u'screen_name']=friend[u'screen_name']
             people.append(p)
         except:
             continue
     a.people=people
     a.save()
     string=u"\u6d3b\u52a8\u5df2\u7ecf\u91cd\u65b0\u8bbe\u8ba1"
     for p in a.people:
         string+=" @"+p[u'screen_name']
     u.send_information(activity_id=int(a.weibo_id),string=string)
     url="activity?activity_id="+activity_id
     web.seeother(url)
示例#2
0
    def get_last_message(self) -> message:
        payload = {"offset": -1, "limit": 1}
        response = self.base_request("getUpdates", payload)

        message_id = int(
            json.loads(response)["result"][0]["message"]["message_id"])
        date = int(json.loads(response)["result"][0]["message"]["date"])
        text = str(json.loads(response)["result"][0]["message"]["text"])

        chat_id = int(
            json.loads(response)["result"][0]["message"]["chat"]["id"])
        chat_type = str(
            json.loads(response)["result"][0]["message"]["chat"]["type"])
        message_chat = chat.chat(chat_id, chat_type)

        user_id = int(
            json.loads(response)["result"][0]["message"]["from"]["id"])
        is_bot = bool(
            json.loads(response)["result"][0]["message"]["from"]["is_bot"])
        first_name = str(
            json.loads(response)["result"][0]["message"]["from"]["first_name"])
        username = str(
            json.loads(response)["result"][0]["message"]["from"]["username"])
        sender = user.user(user_id, is_bot, first_name, username)

        msg = message.message(message_id, date, text, message_chat, sender)
        return msg
 def GET(self):
     webinput=web.input()
     uid=webinput[u'uid']
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     index=-1
     for people in a.people:
         if str(people[u'uid'])==str(uid):
             index=a.people.index(people)
             break
     if index>=0:
         a.people[index][u'state']='payed'
         u=user(uid=uid)
         string="I am ready!"
         strtime=time.strftime('%m-%d %H:%M',time.localtime(time.time()))
         string+=str(strtime)
         u.send_information(activity_id=int(a.weibo_id),string=string)
         ifchange=True
         for people in a.people:
             if people[u'state']=='payed':
                 ifchange=True
             else:
                 ifchange=False
                 break
         if ifchange:
             if a.state=="wait_to_pay":
                 a.state="pay_finished"
             else:
                 a.state="fillmoney_end"
         a.save()
         web.seeother("/activity?activity_id="+activity_id)
     else:
         return "error"
 def POST(self):
     cookies=web.cookies()
     webinput=web.input()
     uid=cookies[u'uid']
     hostuser=user(uid=uid)
     friends=hostuser.get_friends_pachong()
     invite_list=[]
     for friend in friends:
         print "here"
         try:
             test=webinput[str(friend[u'id'])]
             invite_list.append(friend)
             print friend[u'id']
         except:
             continue
     activity_id=hostuser.set_a_activity(activity_name=webinput[u'ActivityName'],activity_money=webinput[u'ActivityMoney'],activity_time=webinput[u'ActivityTime'],activity_position=webinput[u'ActivityPosition'],activity_brief=webinput[u'ActivityBrief'],friends_in=invite_list)
     
     ''' 
     for friend in invite_list:
         u=user(type=1,uid=int(friend['id']),name=friend['screen_name'])
         u.inlist.append(activity_id)
         u.save()
     '''
     url="activity?activity_id="
     url+=str(activity_id)
     web.seeother(url)
示例#5
0
def context(request):
    assert isinstance(request, HttpRequest)
    b = book()
    u = user()
    b_info = b.find(parameter.getParameter(request, "id"))
    try:
        username = request.COOKIES["username"]
    except Exception as err:
        username = False
    return render(
        request,
        'content/context.html',
        context_instance=RequestContext(
            request, {
                'book':
                b_info,
                'next_book':
                b.findNext(int(parameter.getParameter(request, "id"))),
                'previous_book':
                b.findPrevious(int(parameter.getParameter(request, "id"))),
                'username':
                username,
                'context_user':
                u.getUserInfo(b_info.book_username)
            }))
示例#6
0
 def GET(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     informations=u.informations
     u.get_from_cookie()
     userinfor=u.get_user_info_weibo()
     return render.user_index(userinfor,informations,u.account)
 def GET(self):
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     friends=u.get_friends_pachong()
     return render.redesign_activity1(a,friends)
示例#8
0
 def run(self, data):
     auth = auth_util()
     username = input("enter admin username: "******"admin user " + username + " created with id " + u.id)
     print("log in with these details at /login")
     return True
 def GET(self):
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     a=activity(activity_id=int(activity_id))
     string=u"\u6211\u5df2\u7ecf\u9000\u6b3e\uff0c\u8bf7\u67e5\u6536"
     u.send_information(activity_id=int(a.weibo_id),string=string)
     web.seeother("/activity?activity_id="+activity_id)
 def POST(self):
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     u.attend_activity(int(activity_id))
     a=activity(activity_id=int(activity_id))
     string=u"\u6211\u53c2\u52a0\u4e86\u6d3b\u52a8"
     u.send_information(activity_id=int(a.weibo_id),string=string)
     web.seeother("/activity?activity_id="+activity_id)
示例#11
0
    def post() -> Response:
        """
        POST response method for creating user.
        :return: JSON object
        """

        data = request.get_json()
        post_user = user(**data)
        post_user.save()

        output = {'id': str(post_user.id)}
        return jsonify({'result': output})
示例#12
0
def login(request):
    assert isinstance(request, HttpRequest)
    u = user()
    username = request.REQUEST.get('username', '')
    password = request.REQUEST.get('password', '')
    if u.login(username, password):
        res = '{"status":1,"message":"success","username":"******"}'
        response = HttpResponse(res, content_type="application/json")
        response.set_cookie('username', username, 3000000)
    else:
        res = '{"status":0,"message":"error"}'
        response = HttpResponse(res, content_type="application/json")
    return response
 def POST(self):
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     a.state="refused"
     a.save()
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     string=u'\u62b1\u6b49\uff0c\u6211\u65e0\u6cd5\u53c2\u52a0\u8fd9\u4e2a\u6d3b\u52a8'
     u.send_information(activity_id=int(a.weibo_id),string=string)
     url="/activity?activity_id="+activity_id
     web.seeother(url)
示例#14
0
def login(request):
	assert isinstance(request,HttpRequest)
	u=user()
	username=request.REQUEST.get('username','')
	password=request.REQUEST.get('password','')
	if u.login(username,password):
		res='{"status":1,"message":"success","username":"******"}'
		response=HttpResponse(res,content_type="application/json")
		response.set_cookie('username',username, 3000000)
	else:
		res='{"status":0,"message":"error"}'
		response=HttpResponse(res,content_type="application/json")
	return response 
示例#15
0
def register(request):
    assert isinstance(request, HttpRequest)
    u = user()
    username = request.REQUEST.get('username', '')
    password = request.REQUEST.get('password', '')
    status = u.register(username, password)
    if status == True:
        res = res = '{"status":0,"message":"success","username":"******"}'
        response = HttpResponse(res, content_type="application/json")
        response.set_cookie('username', username, 3000000)
    else:
        res = '{"status":' + str(status) + ',"message":"error"}'
        response = HttpResponse(res, content_type="application/json")
    return response
示例#16
0
def register(request):
	assert isinstance(request,HttpRequest)
	u=user()
	username=request.REQUEST.get('username','')
	password=request.REQUEST.get('password','')
	status=u.register(username,password)
	if status==True:
		res=res='{"status":0,"message":"success","username":"******"}'
		response=HttpResponse(res,content_type="application/json")
		response.set_cookie('username',username, 3000000)
	else:
		res='{"status":'+str(status)+',"message":"error"}'
		response=HttpResponse(res,content_type="application/json")
	return response 
 def POST(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     a.state="start"
     a.save()
     string=u"\u6d3b\u52a8\u5f00\u59cb"
     for people in a.people:
         string+=" @"+people[u'screen_name']
     u.send_information(activity_id=int(a.weibo_id),string=string)
     web.seeother("/activity?activity_id="+activity_id)
 def GET(self):
     cookies=web.cookies()
     uid=cookies[u"uid"]
     u=user(uid=uid)
     current_host=[]
     for activity_id in u.hostlist:
         a=activity(activity_id=activity_id)
         if a.state=="wait_to_begin" or a.state=="wait_to_pay" or a.state=="pay_finished" or a.state=="start" or a.state=='people_all_in':
             current_host.append(a)
     current_in=[]
     for activity_id in u.inlist:
         a=activity(activity_id=activity_id)
         if a.state=='wait_to_pay' or a.state=="wait_to_begin" or a.state=="people_all_in" or a.state=="pay_finished" or a.state=="start":
             current_in.append(a)
     return render.activity_list(current_in,current_host,1)
 def GET(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     past_host=[]
     for activity_id in u.hostlist:
         a=activity(activity_id=activity_id)
         if a.state=="end" or a.state=="wait_to_fill" or a.state=="fillmoney_end":
             past_host.append(a)
     past_in=[]
     for activity_id in u.inlist:
         a=activity(activity_id=activity_id)
         if a.state=="end" or a.state=="wait_to_fill" or a.state=="fillmoney_end":
             past_in.append(a)
     return render.activity_list(past_in,past_host,2)
 def GET(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     refuse_host=[]
     for activity_id in u.hostlist:
         a=activity(activity_id=activity_id)
         if a.state=="refused":
             refuse_host.append(a)
     refuse_in=[]
     for activity_id in u.inlist:
         a=activity(activity_id=activity_id)
         if a.state=="refused":
             refuse_in.append(a)
     return render.activity_list(refuse_in,refuse_host,3)
 def POST(self):
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     cookies=web.cookies()
     a=activity(activity_id=int(activity_id))
     a.state="wait_to_pay"
     a.save()
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     string=u"\u6d3b\u52a8\u5f00\u59cb\u6536\u6b3e\u4e86"
     for p in a.people:
         string+=" @"+p[u'screen_name']
     u.send_information(activity_id=int(a.weibo_id),string=string)
     web.seeother("/activity?activity_id="+activity_id)
 def POST(self):
     webinput=web.input()
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     friends_invited=[]
     for friend in u.get_friends_pachong():
         try:
             uid=webinput[str(friend[u'id'])]
             friends_invited.append(friend)
         except:
             continue
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     return render.redesign_activity2(a,friends_invited)
示例#23
0
    def post(self) -> Response:
        """
        POST response method for creating user.
        JSON Web Token is required.
        Authorization is required: Access(admin=true)
        :return: JSON object
        """
        authorized: bool = user.objects.get(id=get_jwt_identity()).access.admin

        if authorized:
            data = request.get_json()
            post_user = user(**data).save()
            output = {'id': str(post_user.id)}
            return jsonify({'result': output})
        else:
            return forbidden()
示例#24
0
    def getUser(self, username):
        success = False

        os.chmod(self.usersFilePath, 400)
        with open(self.usersFilePath, 'r') as usersFile:
            for line in usersFile:
                str_user = line.split(':')
                if str_user[0] == username:
                    success = True
                    break

        os.chmod(self.usersFilePath, 000)
        if success:
            return user(str_user[0], str_user[1])
        else:
            raise UserDoestExistsException(username)
 def POST(self):
     webinput=web.input()
     cookies=web.cookies()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     host=user(uid=a.host_uid)
     account=host.account
     myuid=cookies[u'uid']
     money=-1
     for people in a.people:
         if str(people[u'uid'])==str(myuid):
             money=people[u'money']
             break
     if money>0:
         web.seeother("http://0.0.0.0:8000/raisepay?account="+account+"&money="+str(money)+"&activity_id="+activity_id+"&uid="+str(myuid))
     else:
         return "error"
 def POST(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     webinput=web.input()
     activity_id=webinput[u'activity_id']
     a=activity(activity_id=int(activity_id))
     a.state="wait_to_fillmoney"
     string=u"\u6d3b\u52a8\u9700\u8981\u8865\u6b3e"
     for people in a.people:
         index=a.people.index(people)
         a.people[index][u'state']="unpay"
         uid=people[u'uid']
         money=webinput["a"+str(uid)]
         a.people[index][u'money']=float(money)
         string+=" @"+people[u'screen_name']
     a.save()
     u.send_information(activity_id=int(a.weibo_id),string=string)
     web.seeother("/activity?activity_id="+activity_id)
示例#27
0
def updateIn(request):
	assert isinstance(request,HttpRequest)
	b=book()
	u=user()
	title=request.REQUEST.get('title','')
	image=request.REQUEST.get('image','')
	author=request.REQUEST.get('author','')
	introduction=request.REQUEST.get('introduction','')
	recommend=request.REQUEST.get('recommend','')
	line=request.REQUEST.get('line','')
	t=time.strftime('%Y-%m-%d',time.localtime(time.time()))
	username=u.getUsername(request.COOKIES["username"])
	try:
		if b.add(title,image,author,introduction,recommend,line,t,username):
			return HttpResponse('{"status":1}')
		else:
			return HttpResponse('{"status":0}');
	except Exception as err:
		return HttpResponse('{"status":0}');
示例#28
0
 def POST(self):
     webinput=web.input()
     cookies=web.cookies()
     account=webinput[u'account']
     uid=cookies[u'uid']
     u=user(uid=uid)
     u.set_account(account)
     u.get_from_cookie()
     userinfor=u.get_user_info_weibo()
     informations=u.informations
     try:
         activity_id=cookies[u'from_activity_id']
         a=activity(activity_id=int(activity_id))
         for p in a.people:
             if str(p[u'uid'])==str(uid):
                     web.seeother("/activity?activity_id="+activity_id)
         return render.user_index(userinfor,informations,u.account)
     except:
         return render.user_index(userinfor,informations,u.account)
示例#29
0
def context(request):
	assert isinstance(request,HttpRequest)
	b=book()
	u=user()
	b_info=b.find(parameter.getParameter(request,"id"))
	try:
		username=request.COOKIES["username"]
	except Exception as err:
		username=False
	return render(request,
		'content/context.html',
		context_instance = RequestContext(request,
		{
			'book':b_info,
			'next_book':b.findNext(int(parameter.getParameter(request,"id"))),
			'previous_book':b.findPrevious(int(parameter.getParameter(request,"id"))),
			'username' :username,
			'context_user':u.getUserInfo(b_info.book_username)
		}))
示例#30
0
def updateIn(request):
    assert isinstance(request, HttpRequest)
    b = book()
    u = user()
    title = request.REQUEST.get('title', '')
    image = request.REQUEST.get('image', '')
    author = request.REQUEST.get('author', '')
    introduction = request.REQUEST.get('introduction', '')
    recommend = request.REQUEST.get('recommend', '')
    line = request.REQUEST.get('line', '')
    t = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    username = u.getUsername(request.COOKIES["username"])
    try:
        if b.add(title, image, author, introduction, recommend, line, t,
                 username):
            return HttpResponse('{"status":1}')
        else:
            return HttpResponse('{"status":0}')
    except Exception as err:
        return HttpResponse('{"status":0}')
示例#31
0
    def GET(self):
        webinput=web.input()
        code=webinput[u'code']
        u=user(code=code)
        if u.account=="":
            web.seeother("/set_account_page")
        else:
            try:
                cookies=web.cookies()
                weibo_id=cookies[u'from_activity_id']
                a=activity(activity_id=int(weibo_id))
                for p in a.people:
                    if str(u.uid)==str(p[u'uid']):
                        web.seeother("activity?activity_id="+weibo_id)
                userinfor=u.get_user_info_weibo()
                informations=u.informations
                return render.user_index(userinfor,informations,u.account)

            except:
                userinfor=u.get_user_info_weibo()
                informations=u.informations
                return render.user_index(userinfor,informations,u.account)
示例#32
0
文件: routes.py 项目: Firkraag/RankIt
def reflectReq():
    adminInfo = admin.query.filter_by(username='******').first()
    wakeupEventInfo = wakeupEvent.query.filter_by(id=1).first()
    if not adminInfo or not wakeupEventInfo:
        db.session.close()
        return redirect('/init')
    _event = request.args.get('event')
    if _event:
        if _event == 'wakeup':
            try:
                _id = int(request.args.get('id'))
            except Exception, e:
                db.session.close()
                return abort(404)
            userInfo = user.query.filter_by(id=_id).first()
            if not userInfo:
                userInfo = user(_id, '')
                db.session.add(userInfo)
                db.session.commit()
            _date = time.strftime("%Y-%m-%d", time.localtime())
            _time = time.strftime('%H:%M',time.localtime())
            # Return transed off_ret if switch is off
            if not wakeupEventInfo.switch:
                _ret = str_misc.trans_str(wakeupEventInfo.off_ret, _time)
                db.session.close()
                return _ret
            wakeupRecInfo = wakeupRec.query.filter_by(user_id=_id, create_date=_date).first()
            if not wakeupRecInfo:
                # Return early_ret if user hasn't checked and time is earlier than the begin time
                if time_misc.check_double_time(_time, wakeupEventInfo.begin_time):
                    _ret = str_misc.trans_str(wakeupEventInfo.early_ret, _time)
                    db.session.close()
                    return _ret
                # Return late_ret if user hasn't checked and time is later than the begin time
                if time_misc.check_double_time(wakeupEventInfo.end_time, _time):
                    _ret = str_misc.trans_str(wakeupEventInfo.late_ret, _time)
                    db.session.close()
                    return _ret
                # Return acc_ret if all thing is right
                db.engine.execute('UPDATE wakeup_event SET last_total = total, last_update_time = %s WHERE last_update_time != %s',
                                  (_date, _date))
                db.engine.execute('UPDATE wakeup_event SET total = total + 1')
                wakeupRecInfo = wakeupRec(_id, _date, _time)
                db.session.add(wakeupRecInfo)
                db.session.commit()
                wakeupRecInfo = wakeupRec.query.filter_by(user_id=_id, create_date=_date).first()
                _rank = wakeupRecInfo._id - wakeupEvent.query.filter_by(id=1).first().last_total
                wakeupRecInfo.rank = _rank
                db.session.commit()
                _ret = str_misc.trans_str(wakeupEventInfo.acc_ret, _time, _time, str(_rank))
                db.session.close()
                return _ret
            else:
            # Return done_ret if user has checked in wakeupEvent
                _ret = str_misc.trans_str(wakeupEventInfo.done_ret, _time, wakeupRecInfo.create_time, str(wakeupRecInfo.rank))
                db.session.close()
                return _ret
        if _event == 'normal':
            try:
                event_id = int(request.args.get('event_id'))
            except Exception, e:
                db.session.close()
                return abort(404)
            try:
                _id = int(request.args.get('id'))
            except Exception, e:
                db.session.close()
                return abort(404)
示例#33
0
 def add_user(self,name,age_range):
     #Adiciona utente, utente tem uma faixa etária e um nome
     newUser = user(name,age_range)
     self.userList.append(newUser)
     familyManagement.unknown_Family.append(newUser)
示例#34
0
    def run(self):
        auth = auth_util()

        test_user_username = "******"
        test_user_password = "******"
        test_user_hash = auth.hash(test_user_password)
        test_user = user(test_user_username, test_user_hash)
        test_user_token = auth.token(test_user.id)

        self.header("valid hash test")
        result = auth.verify_hash(test_user_password, test_user_hash)
        self.record(result, "valid hash", result)

        self.header("invalid hash test")
        result = auth.verify_hash(
            "invalid-hash-probably-wouldnt-that-be-funny-though",
            test_user_password)
        self.record(result == False, "invalid hash", result)

        self.header("verify token test")
        result = auth.verify_token(test_user_token, test_user.id)
        self.record(result, "valid token", result)

        self.header("invalid token test")
        result = auth.verify_token(
            "invalid-token-really-though-think-about-it", test_user.id)
        self.record(result == False, "invalid token", result)

        test_user.save()

        # wrapped in a try catch so that we can delete the test user
        try:
            self.header("failed login test")
            rsp = self.post_request({
                "path": "/login",
            }, {
                "username": test_user_username,
                "password": "******"
            })
            expected = {'statusCode': 403, 'body': '"Forbidden"'}
            result = rsp['statusCode'] == 403 and rsp['body'] == '"Forbidden"'
            self.record(result, expected, rsp)

            self.header("successful login test")
            rsp = self.post_request({
                "path": "/login",
            }, {
                "username": test_user_username,
                "password": test_user_password
            })
            expected = "'statusCode': 200 and a valid token"
            token = json.loads(rsp['body'])
            token = token['token'] if 'token' in token.keys() else ""
            result = rsp['statusCode'] == 200 and auth.verify_token(
                token, test_user.id)
            self.record(result, expected, rsp)
        except Exception as e:
            self.fail(e)

        test_user.delete()

        return self.successful
示例#35
0
    def post(self, identification):
        '''
        Executa a autenticacao de usuario e retorna tokens de acesso (2h)
        '''
        url = request_handler(request)
        args = url.get_args()

        try:

            db_connection = database()
            conn, cursor = db_connection.open_connection()

            #Checa se existe informacao no body
            if 'payload' in args:
                current_user = user()
                current_user.uid = args['payload']
                current_user.identification = identification
                registered_user, current_user = current_user.check_user_register(
                    conn, cursor)

                #Caso o usuario seja valido, retorna as informacoes
                if registered_user:
                    access_token = create_access_token(identity=identification)
                    refresh_token = create_refresh_token(
                        identity=identification)

                    payload = {
                        "Identification": current_user.identification,
                        "Name": current_user.name,
                        "CreationDate": current_user.creation_date,
                        "FailedAttempts": current_user.failed_attempts,
                        "BlockedAccount": current_user.blocked_account
                    }

                    resp = jsonify({
                        'Data': {
                            'User': payload,
                            'Access': {
                                'AccessToken': access_token,
                                'RefreshToken': refresh_token
                            }
                        },
                        'StatusID': 'users_successful_authentication',
                        'StatusMessage': 'Successful authentication.',
                        'Links': {
                            'Self': url.self_url(),
                            'Next': SITE_URL + LOGIN_REDIRECT_URL
                        }
                    })
                    resp.status_code = 200
                    set_access_cookies(resp, access_token)
                    set_refresh_cookies(resp, refresh_token)

                else:
                    resp = jsonify({
                        'StatusID': 'users_invalid_credentials',
                        'StatusMessage': 'Invalid credentials.',
                        'Links': {
                            'Self': url.self_url()
                        }
                    })
                    resp.status_code = 401
            else:

                resp = jsonify({
                    'StatusID': 'users_missing_fields',
                    'StatusMessage':
                    'There are missing fields in your request.',
                    'Links': {
                        'Self': url.self_url()
                    }
                })
                resp.status_code = 401

        except db_driver.Error as e:

            resp = jsonify({
                'StatusId': 'users_database_error',
                'StatusMessage': 'Database error.',
                'DescriptionError': str(e),
                'Links': {
                    'Self': url.self_url()
                }
            })
            resp.status_code = 500
        except Exception as e:
            resp = jsonify({
                'StatusId': 'users_internal_error',
                'StatusMessage': 'Authentication error occurred.',
                'DescriptionError': str(e),
                'Links': {
                    'Self': url.self_url()
                }
            })
            resp.status_code = 500
        finally:
            return resp
示例#36
0
    def run(self):
        create_endpoint = "/new"

        test_blog_id = ""
        test_user_username = "******"
        test_user_password = "******"
        test_blog_data = {
            'title': "test blog title",
            'slug': "test-blog-slug",
            'text': "test blog text"
        }

        # create a temporary authenticated user
        auth = auth_util()
        test_user = user(test_user_username, auth.hash(test_user_password))
        test_user_token = auth.token(test_user.id)

        # post create unauthorized reject test
        self.header("POST create unauthorized test")
        rsp = self.post_request({
            "path": create_endpoint,
        }, test_blog_data)
        expected = {'statusCode': 403, 'body': '"Forbidden"'}
        result = rsp['statusCode'] == 403 and rsp['body'] == '"Forbidden"'
        self.record(result, expected, rsp)

        # post create test
        self.header("POST create test")
        rsp = self.post_request(
            {
                "path": create_endpoint,
                "headers": {
                    "token": test_user_token,
                    "userid": test_user.id
                }
            }, test_blog_data)
        expected = "'statusCode': 200 and 'id' in rsp['body'].keys()"
        rsp['body'] = json.loads(rsp['body'])
        result = rsp['statusCode'] == 200 and 'id' in rsp['body'].keys()
        self.record(result, expected, rsp)

        # so that we can remove test blog
        try:
            test_blog_id = rsp['body']['id']

            # duplicate reject test
            self.header("POST create reject duplicate slug")
            rsp = self.post_request(
                {
                    "path": create_endpoint,
                    "headers": {
                        "token": test_user_token,
                        "userid": test_user.id
                    }
                }, test_blog_data)
            expected = "'statusCode': 400"
            result = rsp['statusCode'] == 400
            self.record(result, expected, rsp)

            test_blog_data.update({
                'title': test_blog_data['title'] + "-edited",
                'slug': test_blog_data['slug'] + "-edited",
                'text': test_blog_data['text'] + "-edited"
            })

            # unauthorized edit reject
            self.header("POST edit reject unauthorized")
            rsp = self.post_request(
                {"path": self.get_edit_endpoint(test_blog_id)}, test_blog_data)
            expected = "'statusCode': 403"
            result = rsp['statusCode'] == 403
            self.record(result, expected, rsp)

            # successful edit
            self.header("POST edit successful")
            rsp = self.post_request(
                {
                    "path": self.get_edit_endpoint(test_blog_id),
                    "headers": {
                        "token": test_user_token,
                        "userid": test_user.id
                    }
                }, test_blog_data)

            expected = "'statusCode': 200 and " + test_blog_data[
                'title'] + " in rsp['body'] and " + test_blog_data[
                    'slug'] + " in rsp['body'] and " + test_blog_data[
                        'text'] + " in rsp['body']"
            result = rsp['statusCode'] == 200 and test_blog_data[
                'title'] in rsp['body'] and test_blog_data['slug'] in rsp[
                    'body'] and test_blog_data['text'] in rsp['body']
            self.record(result, expected, rsp)

        except Exception as e:
            self.fail(str(e))
            self.skip("cannot continue with blogauth tests, skipping")

        test_blog = blog.get(test_blog_id)
        if test_blog:
            test_blog.delete()

        return self.successful
示例#37
0
文件: routes.py 项目: Firkraag/RankIt
         return _ret
 if _event == 'normal':
     try:
         event_id = int(request.args.get('event_id'))
     except Exception, e:
         db.session.close()
         return abort(404)
     try:
         _id = int(request.args.get('id'))
     except Exception, e:
         db.session.close()
         return abort(404)
     normalEventInfo = normalEvent.query.filter_by(id=event_id).first()
     userInfo = user.query.filter_by(id=_id).first()
     if not userInfo:
         userInfo = user(_id, '')
         db.session.add(userInfo)
         db.session.commit()
     if not normalEventInfo:
         db.session.close()
         return abort(404)
     _time = time.strftime('%H:%M',time.localtime())
     normalRecInfo = normalRec.query.filter_by(user_id=_id, event_id=event_id).first()
     if normalRecInfo:
         _ret = str_misc.trans_str(normalEventInfo.done_ret, _time,
                                   normalRecInfo.create_time.strftime('%H:%M'),
                                   str(normalRecInfo.rank))
         db.session.close()
         return _ret
     now_datetime = datetime.datetime.now()
     if now_datetime < normalEventInfo.begin_time:
示例#38
0
 def GET(self):
     cookies=web.cookies()
     uid=cookies[u'uid']
     u=user(uid=uid)
     friends=u.get_friends_pachong()
     return render.design_activity(friends)