Exemple #1
0
 def current_user_info(self):
     
     if self.user_info is None:
         """Get the current user by lookup if we can"""
         if self.username:
             self.user_info = UserInfo.get_by_username(self.username)
         
         """Gets the current user. This involves a query. Its more efficient to perform 
         lookups with the username and verify that the user_info is current."""
         if self.google_user is not None:
             users_query = UserInfo.query( UserInfo.google_user==self.google_user)
             self.user_info = users_query.get()
         
         if self.oauth_user_id is not None:
             users_query = UserInfo.query( UserInfo.oauth_user_id==self.oauth_user_id)
             self.user_info = users_query.get()
         
         if self.user_info and self.username is None:
             self.username = self.user_info.username
         
         
     if self.user_info is not None and self.is_user_info_current(self.user_info):
         return self.user_info
     else:
         return None
Exemple #2
0
def register():
    dict1 = request.form
    mobile = dict1.get('mobile')
    yzm_image = dict1.get('yzm_image')
    yzm_sms = dict1.get('yzm_sms')
    pwd = dict1.get('pwd')
    if not all([mobile, yzm_image, yzm_sms, pwd]):
        return jsonify(result=1)
    if yzm_image != session['image_yzm']:
        return jsonify(result=2)
    if int(yzm_sms) != session['sms_yzm']:
        return jsonify(result=3)
    if not re.match(r'[a-zA-Z0-9_]{6,20}', pwd):
        return jsonify(result=4)
    mobile_count = UserInfo.query.filter_by(mobile=mobile).count()
    if mobile_count > 0:
        return jsonify(result=5)
    user = UserInfo()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = pwd
    try:
        db.session.add(user)
        db.session.commit()
    except:
        current_app.logger_xjzx.error('用户注册访问数据库失败')
        return jsonify(result=7)
    return jsonify(result=6)
Exemple #3
0
 def get_chat_data(self):
     """
     Get chat data from context, if it's first conversation save user info data
     :return: dialog_data(list) with: chat_id, command, step
     """
     dialog, created = DialogStepRouting.objects.\
         update_or_create(chat_id=self.context['message']['chat']['id'],
                          defaults={'chat_id': self.context['message']['chat']['id'],
                                    'command': self.context['message']['text'],
                                    'step': 0})
     if created:
         # If new dialog safe user info
         user_info = UserInfo(
             first_name=self.context['message']['from'].get(
                 'first_name', ''),
             last_name=self.context['message']['from'].get('last_name', ''),
             username=self.context['message']['from'].get('last_name', ''),
             chat_id=self.context['message']['from']['id'])
         user_info.save()
     dialog_data = {
         'chat_id': dialog.chat_id,
         'command': dialog.command,
         'step': dialog.step,
         'created': created
     }
     return dialog_data
Exemple #4
0
def register_new_user(email, password):
    user = UserInfo(
        email=email,
        password=password,
        id=email
    )
    user.put()
Exemple #5
0
def register():
    # 接收
    form = request.form
    mobile = form.get('mobile')  # '' None
    # sms_code = form.get('sms_code')
    pwd = form.get('pwd')
    # 验证
    # 1.所有数据不为空
    # if not all([mobile, sms_code, pwd]):  # 判断参数中是否有空值bool(x)
    #     return jsonify(result=1)  # 参数为空则返回1
    # # 2.验证短信是否正确
    # sms_code_session = str(session.get('sms_code'))
    # if sms_code != sms_code_session:
    #     return jsonify(result=2)  # 短信验证码错误
    # 3.验证手机号是否存在
    mobile_exists = UserInfo.query.filter_by(mobile=mobile).count()
    if mobile_exists:
        return jsonify(result=3)  # 手机号存在
    # 4.验证当前手机号是否与接收短信的手机号一致
    # mobile_session = session.get('mobile')
    # if mobile != mobile_session:
    #     return jsonify(result=5)  # 两次手机号不一致

    # 处理:新建对象并保存
    user = UserInfo()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = pwd
    # 添加
    db.session.add(user)
    # 保存到数据库
    db.session.commit()

    # 响应
    return jsonify(result=4)  # 注册成功
Exemple #6
0
def login():
    if 'Authorization' in request.headers:
        user = UserInfo.get_with_token(request.headers['Authorization'])
        if user is not None:
            login_user(user)
            response = {}
            response['code'] = 0
            response['cell'] = user.cell
            response['token'] = user.token
            return json.dumps(response)
            # return "User: "******"  successfully logged in by token"
    try:
        cell = request.json['cell']
        pwd = request.json['password']
        user = UserInfo.get_with_cell(cell=cell)
        if (user is not None) and (user.password == pwd):
            login_user(user, remember=True)
            response = {}
            response['code'] = 0
            response['cell'] = cell
            response['token'] = user.token
            return json.dumps(response)
        else:
            response = {'code': 1}
            return json.dumps(response)

    except (KeyError, TypeError, ValueError):
        response = {'code': -2}
        return json.dumps(response)
Exemple #7
0
def register():
    dict1 = request.form
    mobile = dict1.get('mobile')
    image_yzm = dict1.get('image_yzm')
    msg_yzm = dict1.get('msg_yzm')
    password = dict1.get('password')
    if not all((mobile, image_yzm, msg_yzm, password)):
        return jsonify(error_info='数据填写不完整')
    if len(mobile) != 11:
        return jsonify(error_info='手机号不合法')
    if UserInfo.query.filter_by(mobile=mobile).count():
        return jsonify(error_info='该手机号已经被注册过')
    if image_yzm != session['image_yzm']:
        return jsonify(error_info='图片验证码不正确')
    if msg_yzm != session['msg_yzm']:
        return jsonify(error_info='短信验证码不正确')
    if not re.match(r'\w{6,20}', password):
        return jsonify(error_info='密码格式不正确')
    user = UserInfo()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
        return jsonify(success_info='注册成功,请登录')
    except:
        return jsonify(error_info='服务器出错')
Exemple #8
0
def loginView(request):
    context = get_context(request)
    
    # Forget AccountAccesses to merge if user goes somewhere then back to login.
    if 'merge_access' in request.session:
        del request.session['merge_access']
    if 'merge_access_info' in request.session:
        del request.session['merge_access_info']
    
    if request.user.is_authenticated():
        try:
            access = request.user.accountaccess_set.all()[0]
        except IndexError:
            access = None
        else:
            client = access.api_client
            user_info = client.get_profile_info(raw_token=access.access_token)
            context['info'] = user_info

            user = request.user
            try:
                user_profile = UserProfile.objects.get(user=user)
            except UserProfile.DoesNotExist:
                new_user_info = UserInfo()
                new_user_info.save()
                user_profile, just_created = UserProfile.objects.get_or_create(user=user, user_info=new_user_info)

                # I'm not sure if this condition is necessary.
                if just_created:
                    standarize_user_info(user_info)
                    if 'gender' in user_info:
                        user_profile.gender = user_info['gender']
                    user.save()
                    user_profile.save()
    return render(request, 'login.html', context)
Exemple #9
0
 def get_prev_step(self):
     """
     Get previous step of dialog for this chat ID
     :return: dialog_date(list) with: chat_id, command, step
     """
     dialog, created = DialogStepRouting.objects. \
         get_or_create(chat_id=self.context['message']['chat']['id'],
                       defaults={'chat_id': self.context['message']['chat']['id'],
                                 'command': self.context['message'].get('text', ''),
                                 'step': 0})
     if created:
         # If new dialog safe user info
         user_info = UserInfo(
             first_name=self.context['message']['from'].get(
                 'first_name', ''),
             last_name=self.context['message']['from'].get('last_name', ''),
             username=self.context['message']['from'].get('last_name', ''),
             chat_id=self.context['message']['from']['id'])
         user_info.save()
     dialog_data = {
         'chat_id': dialog.chat_id,
         'command': dialog.command,
         'step': dialog.step,
         'created': created
     }
     return dialog_data
Exemple #10
0
def register(request):
    if request.method == 'POST': # If the form has been submitted...
        row = UserInfo(email_id = request.POST['email'], password = request.POST['pwd'],
                           full_name = request.POST['fullname'])
        row.save()
        email = request.POST['email'];
    return HttpResponseRedirect('alternative')
Exemple #11
0
 def set_username(self,username):
     errors = []
             
     match = re.search(r'^[\d\w_\-]+$', username)
     
     isvalid = match and 4 <= len(username) and len(username) <= 20;
     
     if not isvalid:
         errors.append('invalid_name')
     else:
         user_info = self.current_user_info()
         if user_info is None:
             user_info_key = UserInfo.create_key(username)
             
             #in the circumstances of a collision whoever asked last is the winner
             #of course if fifty 'Daniels' pile up then we have an issue
             user_info = user_info_key.get()
             if user_info is None:
                 user_info = UserInfo.put_new(username,oauth_user_id=self.oauth_user_id,google_user=self.google_user)
             else:
                 errors.append('other_has_name')
     
     if len(errors) == 0:
         return True, user_info
     else:
         return False, errors
Exemple #12
0
    def get(self, mode = ''):
        if mode == 'login':
            if 'allowed' in self.request.cookies and \
                    self.request.cookies['allowed'].count('_'):
                _twitter_id, _login_hash = \
                    self.request.cookies['allowed'].split('_', 1)
        
                user_info = UserInfo.all().filter('twitter_id =', _twitter_id).get()
                if user_info and _sha512(user_info.acc_key) == _login_hash:
                    self.session = Session()
                    self.session['twitter_id'] = _twitter_id
                    return self.redirect('/home')

            auth = _oauth_handler()
            auth_url = auth.get_authorization_url()
            memcache.set(auth.request_token.key,
                         auth.request_token.secret,
                         3600)
            return self.redirect(auth_url)

        elif mode == 'verify':
            auth = _oauth_handler()
            ver = self.request.get('oauth_verifier')
            req_key = self.request.get('oauth_token')
            req_sec = memcache.get(req_key)
            auth.set_request_token(req_key, req_sec)
            acc_token = auth.get_access_token(ver)

            api = tweepy.API(auth_handler = auth)
            me = api.me()

            if not UserInfo.all().filter('twitter_id =', str(me.id)).get():
                user_info = UserInfo(twitter_id = str(me.id),
                                     screen_name = me.screen_name,
                                     name = me.name,
                                     image = me.profile_image_url,
                                     acc_key = acc_token.key,
                                     acc_sec = acc_token.secret)
                user_info.put()

            self.session = Session()
            self.session.delete_item('twitter_id')
            self.session['twitter_id'] = str(me.id)

            c = SimpleCookie()
            c['allowed'] = '%d_%s' % (me.id, _sha512(acc_token.key))
            c['allowed']['path'] = '/auth'
            c['allowed']['expires'] = 86400 * 10
            self.response.headers.add_header('Set-Cookie', c.output(header = ''))

            return self.redirect('/home')

        elif mode == 'logout':
            user_info = _login_user(self)
            if user_info:
                self.session = Session()
                self.session.delete_item('twitter_id')

            return self.redirect('/')
Exemple #13
0
def login():
    mobile = request.form.get('mobile')
    passwd = request.form.get('passwd')
    user = UserInfo().query.filter_by(mobile=mobile).first()
    if user and user.check_pwd(passwd):
        session['user_id'] = user.id
        return jsonify(res=2, nick_name=user.nick_name, avatar=user.avatar)
    return jsonify(res=1)
Exemple #14
0
 def run(self):
     mobile = input('请输入账号:')
     password = input("请输入密码")
     user = UserInfo()
     user.mobile = mobile
     user.password = password
     user.isAdmin = True
     db.session.add(user)
     db.session.commit()
Exemple #15
0
 def test_signals(self):
     old_count = LogEntry.objects.count()
     userobject = UserInfo(name='testname', \
                           surname='testsurname', \
                           birthday='2010-02-17', \
                           about='test', \
                           contacts='test');
     userobject.save()
     self.assertNotEqual(old_count, LogEntry.objects.count())
Exemple #16
0
 def auth(self, *args, **kwargs):
     user = UserInfo.query.filter(UserInfo.id == 1).first()
     if not user:
         user = UserInfo()
         user.id = 1
         user.name = '匿名'
         user.username = '******'
         db.session.add(user)
         db.session.commit()
     self.login_user(user)
Exemple #17
0
    def user_info():
        res = dict()
        if request.method == 'GET':
            openid = request.args.get('openid')
            user_info = UserInfo.query.filter_by(openid=openid).first()
            if user_info is not None:
                res = user_info.to_dict()

        elif request.method == 'POST':
            # '{"nickName":"我不是大哥","gender":1,"language":"zh_CN","city":"Xinzhou","province":"Shanxi","country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eokAGkics0CTDoLhUsukAmy4sTvb167M3kBKyGfYmBv0tj5InBiahpqhgXBaWic1Bz3OYXC2oYHCzNvg/132"}'
            if request.get_data() is not None:  # wx小程序请求格式

                json_data = str(request.get_data(), encoding="utf-8")
                json_dict = json.loads(json_data)
                json_dict.setdefault("")

                openid = json_dict.get('openid')
                nick_name = json_dict.get('nickName')
                avatar_url = json_dict.get('avatarUrl')
                gender = json_dict.get('gender')
                language = json_dict.get('language')
                province = json_dict.get('province')
                country = json_dict.get('country')
                city = json_dict.get('city')

            else:  # 普通post请求格式
                openid = request.form.get("openid")
                nick_name = request.form.get("nick_name")
                gender = str(request.form.get("gender", type=int, default=0))
                language = request.form.get("language")
                city = request.form.get("city")
                province = request.form.get("province")
                country = request.form.get("country")
                avatar_url = request.form.get("avatar_url")

            user_info_obj = UserInfo.query.filter_by(openid=openid).first()
            if user_info_obj is not None:  # 如果在数据库中已经有记录,则更新记录
                user_info_obj.nick_name = nick_name
                user_info_obj.gender = gender
                user_info_obj.language = language
                user_info_obj.city = city
                user_info_obj.province = province
                user_info_obj.country = country
                user_info_obj.avartar_url = avatar_url
            else:
                user_info_obj = UserInfo(openid, nick_name, gender, language,
                                         city, country, avatar_url)
            db.session.add(user_info_obj)
            db.session.commit()
            res = user_info_obj.to_dict()
        else:
            pass
        return Response(json.dumps(res), mimetype='application/json')
Exemple #18
0
 def run(self):
     user_list = []
     for i in range(1000):
         user = UserInfo()
         user.mobile = str(i)
         user.create_time = datetime(2018, random.randint(1, 6),
                                     random.randint(1, 28))
         user.update_time = datetime(2018, random.randint(1, 6),
                                     random.randint(1, 28))
         user_list.append(user)
     db.session.add_all(user_list)
     db.session.commit()
Exemple #19
0
def create_root(email, password, fullname):
    hash = argon2.hash(password)
    new_root = User(fullname=fullname, email=email, hash=hash, is_root=True)
    try:
        new_root.save()
        root = User.fetchone(email=email)
        root_info = UserInfo(
            user_id=root.id,
            permission_groups=[group.name for group in all_permission_groups])
        root_info.save()
    except UniqueViolatedError:
        print('Duplicated root user')
Exemple #20
0
def user_pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    passwd_old = request.form.get('passwd_old')
    passwd_new = request.form.get('passwd_new')
    user_id = session.get('user_id')
    user = UserInfo().query.get(user_id)
    if user.check_pwd(passwd_old):
        user.password = passwd_new
        db.session.commit()
        del session['user_id']
        return jsonify(res=1)
    return jsonify(res=2)
Exemple #21
0
def index(name):
    lst = []
    user_info = UserInfo()
    data = user_info.get_users(name)
    for item in data:
        dic = dict()
        dic["img_url"] = item["img_url"]
        dic["title"] = item["title"]
        dic["aut_name"] = item["aut_name"]
        dic["nid"] = str(item["_id"])  # object id
        desc = ",".join(item["materials"].keys())
        dic["desc"] = desc[:25] + '...' if len(desc) > 25 else desc  # 描述
        lst.append(dic)
    return jsonify(lst)
Exemple #22
0
def create_user():
    data = request.json["User"]
    name = data["Name"]
    email = data["Email"]
    _password = data["Password"]
    # new user created
    new_user = UserInfo(name, email)
    new_user.hash_password(_password)
    try:
        session.add(new_user)
        session.commit()
        return jsonify(new_user.toJSON()), 201
    except:
        return {"Error": "Internal Server Error"}, 500
Exemple #23
0
	def post(self):
		userinfo = self.currentuser
		if userinfo == None:
			userinfo = UserInfo()
		
		userinfo.nickname = cgi.escape(self.request.get('nickname'))
		if is_empty(userinfo.nickname):
			self.render_edit("nickname can't be empty")
			return
		
		email = cgi.escape(self.request.get('email'))
		avatar = self.request.get('avatar')
		first_login = self.request.get('first_login')
		
		if avatar != '':
			avatar = images.resize(avatar, 128)
			userinfo.avatar = db.Blob(avatar)
			
		if email == '':
			email = 'none'
		userinfo.email = email

		if first_login != '':
			userinfo.lastposted = date.today()
			userinfo.lastvoted = userinfo.lastposted
			
		userinfo.put()
		self.redirect('/')
Exemple #24
0
def search():
    lst = []
    user_info = UserInfo()
    string = request.args.get("string")
    data = user_info.get_search_result(string)
    for item in data:
        dic = dict()
        dic["img_url"] = item["img_url"]
        dic["title"] = item["title"]
        dic["aut_name"] = item["aut_name"]
        dic["nid"] = str(item["_id"])  # object id
        desc = ",".join(item["materials"].keys())
        dic["desc"] = desc[:25] + '...' if len(desc) > 25 else desc  # 描述
        lst.append(dic)
    return jsonify(lst)
Exemple #25
0
 def run(self):
     """创建管理员"""
     mobile = input('请输入账号:')
     pwd = input('请输入密码')
     user_exists = UserInfo.query.filter_by(mobile=mobile).count()
     if user_exists > 0:
         print('此账号已经存在')
         return
     user = UserInfo()
     user.mobile = mobile
     user.password = pwd
     user.isAdmin = True
     db.session.add(user)
     db.session.commit()
     print('管理员创建成功')
Exemple #26
0
def check_user():
    user = users.get_current_user()
    if not user:
        return None
    else:
        key = ndb.Key('UserInfo', user.user_id())
        stuser = key.get()
        if not stuser:
            stuser = UserInfo(key=key,
                              name=user.nickname(),
                              email=user.email(),
                              page_count=0)
        stuser.page_count += 1
        stuser.put()
        return stuser
Exemple #27
0
def checkIdAndEmail(userId, email):
  query = UserInfo.all()
  query.filter('userId = ', userId).filter('email = ', email)
  if query.count() == 0:
    return False;
  else:
    return True;
Exemple #28
0
    def import_user_es(self):
        try:
            self._cursor.execute(self.SQL)
            result_list = self._cursor.fetchall()
            for res in result_list:
                userinfo = UserInfo(_userlink=res[0],
                                    _nickname=res[1],
                                    _bio=res[2],
                                    _weibo=res[3],
                                    _location=res[4],
                                    _business=res[5],
                                    _career=res[6],
                                    _education=res[7],
                                    _upvote=res[8],
                                    _thanks=res[9],
                                    _collection=res[10],
                                    _share=res[11],
                                    _followees=res[12],
                                    _followers=res[13],
                                    _views=res[14])
                self.generate_user_model(userinfo=userinfo,
                                         esmodel=self._esmodel)
                print "Import successfully"

        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
Exemple #29
0
def add_info():
    try:
        req_data = request.get_json()
        u_id = req_data["u_id"]
        u_name = req_data["u_name"]
        u_sex = req_data["u_sex"]
        u_height = req_data["u_height"]
        u_weight = req_data["u_weight"]
        print(req_data)
    except:
        return jsonify({
            "status": 400,
            "msg": "请求参数错误"
        })
    else:
        query = db.session.query(UserInfo).filter(UserInfo.u_id == u_id)
        if query.count() == 0:
            new_info = UserInfo(u_id=u_id, u_height=u_height, u_weight=u_weight, u_relname=u_name, u_sex=u_sex)
            db.session.add(new_info)
            db.session.commit()
            return jsonify({
                "status": 200,
                "msg": "添加用户详细信息成功"
            })
        else:
            return jsonify({
                "status": 300,
                "msg": "记录已存在"
            })
Exemple #30
0
    def __init__(self):
        self.user = users.get_current_user()
        userinfo_query = UserInfo.all().filter('ownerid =',self.user)
        self.userinfo = userinfo_query.get()

        if self.userinfo is None:
            userinfo = UserInfo()
            userinfo.ownerid = self.user

        self.template_values = {
            'user' : self.user,
            'nickname' : self.user.nickname(),
            }

        key = ""
        template_path = ""
Exemple #31
0
def add_user():
    fname = request.form['fname']
    lbrand = request.form['lbrand']
    phone = request.form['phone']
    email = request.form['email']
    gender = request.form['gender']
    left_power = request.form['left_power']
    right_power = request.form['right_power']
    age = request.form['age']
    paid = request.form['paid']
    address = request.form['address']
    price = request.form['price']
    date = datetime.date.today()
    #valdate = datetime.datetime.strptime(age,"%Y-%m-%d").date()
    me = UserInfo(first_name=fname,
                  mobile=phone,
                  email=email,
                  gender=gender,
                  age=age,
                  address=address)
    db.session.add(me)
    db.session.flush()
    sp = Spectacles(user_spec_id=me.user_id,
                    lens_brand=lbrand,
                    left_power=left_power,
                    right_power=right_power,
                    purchase_date=date,
                    price=price,
                    paid=paid)
    db.session.add(sp)
    db.session.commit()
    print("Registered")
    return redirect(url_for('register'))
Exemple #32
0
def authService(userId, passwd):
  query = UserInfo.all()
  query.filter('userId = ', userId).filter('passwd = ', passwd)
  if query.count() == 0:
    return False;
  else:
    return True;
Exemple #33
0
def checkUserId(userId):
  query = UserInfo.all()
  query.filter('userId = ', userId)
  if query.count() == 0:
    return False;
  else:
    return True;
Exemple #34
0
def checkEmail(email):
  query = UserInfo.all()
  query.filter('email = ', email)
  if query.count() == 0:
    return False;
  else:
    return True;
Exemple #35
0
 def get(self):
   user = users.get_current_user()
   if user:
     code = self.request.get("code")
     if code:
       old_userinfos = UserInfo.all().filter('user ='******'ApplicationError: 5') >= 0:
           pass # if something bad happens on OAuth, then it currently just redirects to the signup page
                #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
         else:
           raise err
       try:
         manage_foursquare_data.update_user_info(userinfo)
         manage_foursquare_data.fetch_and_store_checkins_next(userinfo, limit=50)
       except foursquare.FoursquareRemoteException, err:
         if str(err).find('403 Forbidden') >= 0:
           pass # if a user tries to sign up while my app is blocked, then it currently just redirects to the signup page
                #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
         else:
           raise err
       except DownloadError:
         pass #TODO make this better, but I'd rather throw the user back to the main page to try again than show the user an error.
Exemple #36
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
def add_user():
    fname = request.form['fname']
    lname = request.form['lname']
    phone = request.form['phone']
    email = request.form['email']
    gender = request.form['gender']
    left_power = request.form['left_power']
    right_power = request.form['right_power']
    dob = request.form['dob']
    address = request.form['address']
    price = request.form['price']
    date = datetime.date.today()
    me = UserInfo(first_name=fname,
                  last_name=lname,
                  mobile=phone,
                  email=email,
                  gender=gender,
                  dob=dob,
                  address=address)
    db.session.add(me)
    db.session.flush()
    sp = Spectacles(user_spec_id=me.user_id,
                    left_power=left_power,
                    right_power=right_power,
                    purchased_date=date,
                    price=price)
    db.session.add(sp)
    db.session.commit()
    print "Registered"
    return redirect(url_for('register'))
Exemple #38
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete
    _multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Exemple #39
0
def saveregister(request):
    try:
        uname = request.POST['user_name']
        upwd = request.POST['pwd']
        s = hashlib.md5()
        s.update(upwd)

        request.session['uname'] = uname
        request.session['upwd'] = upwd
        uemail = request.POST['email']
        user = UserInfo()
        user2 = user.create(uname.encode("utf-8"), s.hexdigest(), uemail)
        user2.save()
        return redirect(reverse('register:login'))
    except:
        return HttpResponse(u'失败!' + uname)
Exemple #40
0
def submit_bm(feed, user, title, url, comment):
    bm = Bookmarks()

    result = urlfetch.fetch(url=url, follow_redirects=True, allow_truncated=True, deadline=60)
    if result.status_code == 200 and result.final_url:
        a = result.final_url
    elif result.status_code == 500:
        pass
    else:
        a = url

    url_candidate = a.lstrip().rstrip().split('?utm_source')[0].split('&feature')[0]

    url_parsed = urlparse(url_candidate)
    query = parse_qs(url_parsed.query)
    name = url_parsed.path.split('/')[-1]
    ext = name.split('.')[-1].lower()

    bm.title = url_candidate if title == '' or None else title

    if url_parsed.netloc == 'www.youtube.com':
        bm.url = 'http://www.youtube.com/watch?v=%s' % query["v"][0]
        bm.comment = """<embed
        width="640" height="360"
        src="http://www.youtube.com/v/%s"
        type="application/x-shockwave-flash">
        </embed>""" % query["v"][0]

    elif url_parsed.netloc == 'vimeo.com':
        bm.url = 'http://vimeo.com/%s' % name
        bm.comment = '''<iframe src="http://player.vimeo.com/video/%s?color=ffffff"
        width="640" height="360" frameborder="0" webkitAllowFullScreen mozallowfullscreen
        allowFullScreen></iframe>''' % name

    elif ext in ['jpg', 'png', 'jpeg', 'gif']:
        bm.url = url_candidate
        blob_key = upload_to_blobstore(url_candidate, ext)
        bm.comment = '<img src="%s" />' % images.get_serving_url(blob_key, size=1600)
    else:
        bm.comment = comment
        bm.url = url_candidate

    bm.domain = url_parsed.netloc
    bm.user = user
    bm.feed = feed
    bm.put()
    Bookmarks.index_bm(bm.key)

    copie = Bookmarks.query(Bookmarks.url == bm.url,
                            Bookmarks.user == user)

    if copie.get():
        ndb.delete_multi([cp.key for cp in copie])

    ui = UserInfo.get_or_insert(str(user.user_id()), user=user)
    if feed is None and ui.mys is True:
        deferred.defer(util.send_bm, bm.key, _queue="email")
    elif feed is not None and feed.get().notify == 'email':
        deferred.defer(util.send_bm, bm.key, _queue="email")
Exemple #41
0
 def get(self):
   user = users.get_current_user()
   if user:
     userinfo = UserInfo.all().filter('user ='******',' + str(userinfo.is_ready) + ',' + str(userinfo.checkin_count))
       return
   self.response.out.write('error')
Exemple #42
0
 def get(self):
   user = users.get_current_user()
   if user:
     auth_token = self.request.get("oauth_token")
     if auth_token:
       credentials = constants.get_client().get_credentials(auth_token)
       old_userinfos = UserInfo.all().filter('user ='******'token'], secret = credentials['secret'], is_ready=False, is_authorized=True, last_checkin=0, last_updated=datetime.now(), color_scheme='fire', level_max=int(constants.level_const), checkin_count=0, venue_count=0)
       fetch_foursquare_data.update_user_info(userinfo)
       fetch_foursquare_data.fetch_and_store_checkins(userinfo, limit=10)
       taskqueue.add(url='/fetch_foursquare_data/all_for_user/%s' % userinfo.key())#, queue_name='initial-checkin-fetching')
       self.redirect("/")
     else:
       self.redirect(constants.get_client().get_authorization_url())
   else:
     self.redirect(users.create_login_url(self.request.uri))
Exemple #43
0
 def get(self):
   user = users.get_current_user()
   if user:
     userinfo = UserInfo.all().filter('user ='******'-created')
     if userinfo:
         self.response.out.write(str(userinfo.is_ready) + ',' + str(userinfo.checkin_count))
         return
   self.response.out.write("")
Exemple #44
0
 def get_like_value(self,branch):
     userinfo = UserInfo.get_by_username(self.username)    
     if userinfo and self.is_user_info_current(userinfo):
         like_key = Like.create_key(branch.key,self.username)
         like = like_key.get();
         if like:
             return like.value
     return 0
Exemple #45
0
def regist(request):
    # 所有返回数据都写到这里面
    return_data = dict()
    if request.method == "POST":
        user_name = request.POST.get("user_name","")
        user_psw = request.POST.get("user_psw","")
        # 通过正则匹配密码强度,匹配做两次,防止有人恶意更改
        result = UserInfo.objects.filter(user_name=user_name)
        if result:
            return_data["status"] = 0
            return_data["msg"] = "用户名已存在,请换个名字"
            return HttpResponse(json.dumps(return_data),content_type="application/json",status=404)
        else:
            if user_name == "" or user_psw == "":
                return_data["status"] = 0
                return_data["msg"] = "用户名密码不能为空"
                return HttpResponse(json.dumps(return_data), content_type="application/json", status=404)
            user = UserInfo()
            user.user_name = user_name
            user.user_psw = secure.md5_32(user_psw)
            user.user_head = ""
            user.save()
            return_data["status"] = 1
            return_data["msg"] = "注册成功"
            return HttpResponse(json.dumps(return_data), content_type="application/json", status=200)

    return render(request,"regist.html",{
        "title":"注册页面",
    })
Exemple #46
0
def register_handle(request):
    """注册验证"""
    # 获取注册信息
    post = request.POST
    uname = post.get('user_name')
    upwd1 = post.get('pwd')
    upwd2 = post.get('cpwd')
    uemail = post.get('email')
    # 验证两次密码是否相同
    if upwd1 == upwd2:
        # 密码加密
        s1 = sha1()
        s1.update(upwd1)
        upwd3 = s1.hexdigest()

        #存入数据库
        user = UserInfo()
        user.uname = uname
        user.upwd = upwd3
        user.uemail = uemail
        user.save()

        return redirect('/user/login/')

    else:
        return redirect('/user/register/')
Exemple #47
0
 def post(self):
     user = users.get_current_user()
     upload_files = self.get_uploads('file')
     blob_info = upload_files[0]
     ui = UserInfo.query(UserInfo.user == user).get()
     ui.delicious = blob_info.key()
     ui.put()
     self.redirect('/')
     deferred.defer(delicious, ui.delicious, user, _queue="delicious")
Exemple #48
0
 def get(self):
   user = users.get_current_user()
   if user:
     userinfo = UserInfo.all().filter('user ='******'-created').get()
     if userinfo:
         self.response.out.write(str(userinfo))
     template_data = { 'uservenues': constants.provider.get_user_data(user=user)}
     os_path = os.path.dirname(__file__)
     self.response.out.write(template.render(os.path.join(os_path, 'templates/uservenue_list.html'), template_data))
def fetch_and_store_checkins_for_all():
  userinfos = UserInfo.all().order('last_updated').fetch(100)#.filter('is_authorized = ', True).
  for userinfo in userinfos:
    if userinfo.is_authorized:
      num_added = fetch_and_store_checkins(userinfo)
      logging.info("updating %d checkins for %s" % (num_added, userinfo.user) )
    else:
      logging.debug("did not update checkins for %s" % userinfo.user)
    userinfo.last_updated = datetime.now()
    userinfo.put()
Exemple #50
0
 def get(self):
     ui = UserInfo.query(UserInfo.user == users.get_current_user()).get()
     if ui.twitt == False:
         ui.twitt = True
         html = '<i class="icon-thumbs-up"></i> <strong>Enabled </strong>'
     else:
         ui.twitt = False
         html = '<i class="icon-thumbs-down"></i> <strong>Disabled</strong>'
     ui.put()
     self.response.write(html)
Exemple #51
0
def credentials_valid_and_user_registered(email, password):
    """
    Only returns true if the email exists in the datastore,
    and the password is correct.
    """
    #TODO(rushiagr): put all the server-side validation code here
    
    user = UserInfo.get_by_id(email)
    if user is not None and user.password == password:
        return True
    return False
Exemple #52
0
def register():
	confirm = request.form['confirm']
	email = request.form['email']
	userID = request.form['hiddenfield']
	password = request.form['hiddenfield2']
	print userID," ",password
	
	if password == confirm:
		hashedPassword = generate_password_hash(password)
		user = UserInfo(userID= userID,email= email,password= hashedPassword)
		
		try:
			user.save()
			if login_user(user):
				return redirect(url_for('GetList'))
			else:
				error="Unable to Log you in due to inactive account"
		except Exception,e:
			print str(e)
			error="UserId taken. Please try another."
Exemple #53
0
def adduser(request):
	posData = request.POST
	uid = posData.get('uid')
	username = posData.get('username')
	name = posData.get('name')
	gender = posData.get('gender')
	email = posData.get('email')
	if gender == 'null':
		gender = None
	elif int(gender) == 0:
		gender = 0
	else:
		gender = 1
	if username and name and email:
		if uid:
			UserInfo.objects.filter(uid=int(uid)).update(username=username, realName=name, gender=gender, email=email)
		else:
			userInfo = UserInfo(username=username, realName=name, gender=gender, email=email)
			userInfo.save()
	return HttpResponseRedirect('/userlist/')
Exemple #54
0
	def initialize(self, request, response):
		self.currentuser = UserInfo.gql("WHERE user = :1", users.get_current_user()).get()
		path = request.path.lstrip('/')
		slashindex = path.find('/')
		if slashindex == -1:
			groupname = path
		else:
			groupname = path[:slashindex]
		self.currentgroup = Group.gql("WHERE shortname = :1", groupname).get()
		
		super(LDContextHandler, self).initialize(request, response)
Exemple #55
0
  def get(self):
    user = users.get_current_user()
    if user:
      oauth_token = self.request.get("oauth_token")

      def get_new_fs_and_credentials():
        oauth_token, oauth_secret = constants.get_oauth_strings()
        credentials = foursquare.OAuthCredentials(oauth_token, oauth_secret)
        fs = foursquare.Foursquare(credentials)
        return fs, credentials

      if oauth_token:
        old_userinfos = UserInfo.all().filter('user ='******'token =', oauth_token).get()
        
        try:
          user_token = fs.access_token(oauth.OAuthToken(apptoken.token, apptoken.secret))
          credentials.set_access_token(user_token)
          userinfo = UserInfo(user = user, token = credentials.access_token.key, secret = credentials.access_token.secret, is_ready=False, is_authorized=True, last_checkin=0, last_updated=datetime.now(), color_scheme='fire', level_max=int(constants.level_const), checkin_count=0, venue_count=0)
        except DownloadError, err:
          if str(err).find('ApplicationError: 5') >= 0:
            pass # if something bad happens on OAuth, then it currently just redirects to the signup page
                 #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
          else:
            raise err
        try:
          fetch_foursquare_data.update_user_info(userinfo)
          fetch_foursquare_data.fetch_and_store_checkins(userinfo, limit=10)
          taskqueue.add(url='/fetch_foursquare_data/all_for_user/%s' % userinfo.key())
        except foursquare.FoursquareRemoteException, err:
          if str(err).find('403 Forbidden') >= 0:
            pass # if a user tries to sign up while my app is blocked, then it currently just redirects to the signup page
                 #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
          else:
            raise err
        except DownloadError:
          pass #TODO make this better, but I'd rather throw the user back to the main page to try again than show the user an error.