def api_register_user(*, email, name, passwd): #判断name是否为空: if not name or not name.strip(): raise APIValueError('name') #判断email是否为空及是否满足email格式: if not email or not _RE_EMAIL.match(email): raise APIValueError('email') #判断password首付为空及是否满足password格式: if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') #数据中查询对应的email信息: users = yield from User.findAll('email=?', [email]) #判断查询结果是否存在,若存在则返回异常提示邮件已存在: if len(users) > 0: raise APIError('register:failed', 'email', 'Email is already in use.') #生成唯一ID: uid = next_id() #重构唯一ID和password成新的字符串: sha1_passwd = '%s:%s' % (uid, passwd) #构建用户对象信息: #hashlib.sha1().hexdigest():取得SHA1哈希摘要算法的摘要值。 user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www(first).gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()) #将用户信息存储到数据库: yield from user.save() # make session cookie: #构造session cookie信息: r = web.Response() #aiohttp.web.StreamResponse().set_cookie():设置cookie的方法。 r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) #max_age:定义cookie的有效期(秒); user.passwd = '******' r.content_type = 'application/json' #以json格式序列化响应信息; ensure_ascii默认为True,非ASCII字符也进行转义。如果为False,这些字符将保持原样。 r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
async def api_register_user(*, email, name, passwd): if not name or not name.strip(): raise APIValueError("name") if not email or not _RE_EMAIL.match(email): raise APIValueError("email") if not passwd or not _RE_SHA1.match(passwd): raise APIValueError("passwd") users = await User.findAll("email=?", [email]) if len(users) > 0: raise APIError("register:failed", "email", "Email is already in use.") uid = next_id() sha1_passwd = "%s:%s" % (uid, passwd) user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode("utf-8")).hexdigest(), image="http://www.gravatar.com/avatar/%s?d=mm&s=120" % hashlib.md5(email.encode("utf-8")).hexdigest()) await user.save() # make session cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = "******" r.content_type = "application/json" r.body = json.dumps(user, ensure_ascii=False).encode("utf-8") return r
def testdb(loop): 'test class User - add a new user' print('Create db pool...') r = yield from orm.create_pool(loop=loop, host='127.0.0.1', port=3306, user='******', password='******', db='awesome') print('r : %s' % r) # 以下为测试: print('Create a new user...') "create a user with fixed <id> and <created_at>" #u = User(email='*****@*****.**', passwd='password', admin=True, name='testname2', image='blank', id='testid2',created_at='1.0') "create a user with fixed auto-generated <id> and <created_at>" u = User(email='*****@*****.**', passwd='password', admin=True, name='testname3', image='blank', id=None, created_at=None) # print('Save the new user into database...') r = yield from u.save() print('r : %s' % r)
def registerUser(*, email, name, password): if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not password or not password.strip(): raise APIValueError('password') users = yield from User.findAll('email=?', email) if len(users) > 0: raise APIError('register:failed', 'email', 'Email is already in use.') uid = nextId() sha1Password = '******' % (uid, password) sha1 = hashlib.sha1(sha1Password.encode('utf-8')).hexdigest() user = User( id=uid, name=name.strip(), email=email, password=sha1, image= 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542105917178&di=d1f6b6a11859ff9a2436460ed3c691dd&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2Fbba1cd11728b47104c5c00e9c9cec3fdfc0323a0.jpg' ) yield from user.save() r = web.Response() r.set_cookie(COOKIE_NAME, user2Cookie(user, 86400), max_age=86400, httponly=True) user.password = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
async def api_signup_user(*, email, name, passwd): if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') users = await User.findAll('email=?', [email]) if len(users) > 0: raise APIError('signup:failed', 'email', 'Email is already in use') uid = next_id() sha1_passwd = '%s:%s' % (uid, passwd) if name == 'sharon': admin = 1 else: admin = 0 user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), admin=admin) await user.save() # make session cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def test(loop): #创建连接池 yield from orm.create_pool(loop,user='******',password='******',database='awesome') #创建对象 u=User(name='Test231',email='test123@wxample',passwd='123456',image='about:blank') #调用保存方法 yield from u.save()
def api_register_user(*, email, name, passwd): # https://www.python.org/dev/peps/pep-3102/ if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') users = yield from User.findAll('email=?', [email]) if len(users) > 0: raise APIError('register:failed', 'email', 'email already in use') uid = next_id() sha1_passwd = '%s:%s' % (uid, passwd) # get SHA1 for uid+passwd user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()) yield from user.save() # make session cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def before_request(): #print "REQUEST_HOST='%s'" % (request.host,) host_name = request.host.lower() # if ':' in host_name: host_name = host_name[:host_name.find(':')] if host_name in Site.domain_to_tag: # This is for DNS resolved versions site_tag = Site.domain_to_tag[host_name] else: # This is for subdomains of the main site : Just strip off the subdomain site_tag = host_name[:host_name.find('.')].lower() #print "REQUEST_HOST_TAG='%s'" % (site_tag,) flask.g.site = Site.query().filter_by(tag=site_tag).first() if flask.g.site is None: print("FAILED TO FIND SITE_TAG : DEFAULTING") # Default if all else fails flask.g.site = Site.query().filter_by(tag=Site.tag_main).first() if 'userid' in session: flask.g.user = User.get(session['userid']) else: flask.g.user = User(flask.g.site.tag, '*****@*****.**', 'Not logged in') # Creates a user with id=None #session.pop('hash') if 'hash' not in session: session['hash'] = ''.join(['%02x' % ord(ch) for ch in urandom(4)]) print("Created session hash '%s'" % (session['hash'], )) flask.g.hash = session['hash'] flask.g.ip = request.remote_addr
def api_register_user(*, UserID, Phone, name, Pass): print(UserID) if not UserID: raise APIValueError('身份证号') if not name: raise APIValueError('姓名') if not Pass or not _RE_SHA1.match(Pass): raise APIValueError('密码') if not Phone: raise APIValueError('手机号') users = yield from User.findAll('Phone=?', [Phone]) if len(users) > 0: raise APIError('register:failed', 'phone', 'Phone is already in use.') sha1_Pass = '******' % (Phone, Pass) user = User(UserID=UserID, User=name, Pass=hashlib.sha1(sha1_Pass.encode('utf-8')).hexdigest(), Phone=Phone) yield from user.save() r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.Pass = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=True).encode('utf-8') return r
def test_expired_confirmation_token(self): u = User(password_hash='cat') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
def test(loop): yield from create_pool(loop=loop, user='******', password='******', db='test') u = User(name='aaa', email='*****@*****.**', passwd='aaa', image='about:blank') yield from u.save() # r = yield from u.findAll() # print(r) yield from destory_pool()
def api_register_user(*,email,name,passwd): if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') users=yield from User.findAll('email=?',[email]) if len(users)>0: raise APIError('register:failed','email','Email is already in use') uid=next_id() sha1_passwd='%s:%s'%(uid,passwd) user=User(id=uid,name=name.strip(),email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www.gravator.com/avatar/%s?d=mm&s=120'%hashlib.md5(email.encode('utf-8')).hexdigest()) yield from user.save() r=web.Response() r.set_cookie(COOKIE_NAME,user2cookie(user,86400),max_age=86400,httponly=True) user.passwd='******' r.content_type='application/json' r.body=json.dumps(user,ensure_ascii=False).encode('utf-8') return r
async def api_register_user(*, email, name, passwd): if not name or not name.strip(): raise APIValueError('name', 'Name must not be empty.') if not email or not _RE_EAMIL.match(email.lower()): raise APIValueError('email', 'Illegal email.') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd', 'Illegal passwd.') uid = next_id() passwd_solted = '%s:%s' % (uid, passwd) passwd_sha1 = hashlib.sha1(passwd_solted.encode('utf-8')).hexdigest() image_url = 'http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5( email.encode('utf-8')).hexdigest() user = User(id=uid, name=name.strip(), email=email, passwd=passwd_sha1, image=image_url) await user.save() # make session cookie r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def api_register(*, name, email, password): logging.info("enter") check_string(name=name) check_email_passwd(email, name) users = yield from User.findAll('email = ?', [email]) if users: raise APIValueError("email", "Email is already in used") uid = next_id() sha1_passwd = '%s:%s' % (email, password) user = User(name=name.strip(), email=email, password=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image="/static/img/user.png", admin=0) yield from user.save() #make session cooike r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.password = '******' r.content_type = "application/json" r.body = json.dumps(user, ensure_ascii=False).encode("utf-8") return r
def test_user(): user = User( email='*****@*****.**', password='******', admin=True, name='龙骑士', ) user.save()
def test_invalid_confirmation_token(self): u1 = User(password_hash='cat') u2 = User(password_hash='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u.generate_confirmation_token() self.assertFalse(u2.confirm(token))
def edit_profile(): here = url_for('edit_profile') next_url = request.args.get('next_url', here) # This is circular user = flask.g.user Audit(flask.g, '', '/user/profile', '', result='').write() form = dict() form['password'] = '' form['password2'] = '' if request.method == 'POST': valid = True if request.form['name']: user.name = request.form['name'] else: valid = False flash('Error: you have to provide a contact name', 'error') if request.form['email']: user.email = request.form['email'] else: valid = False flash('Error: you have to provide a contact email', 'error') if request.form['company']: user.set_data('company', request.form['company']) else: flash('Please provide a company name', 'warning') if request.form['phone']: user.set_data('phone', request.form['phone']) else: flash('Please provide a phone number', 'warning') if request.form['mobile']: user.set_data('mobile', request.form['mobile']) # Optional if valid: User.commit() if next_url == here: # only flash if we're coming back here... Audit(flask.g, '', '/user/profile', '', result='Update Success').write() flash('Profile successfully updated', 'success') return redirect(next_url) form['name'] = user.name form['email'] = user.email form['company'] = user.get_data('company', '') form['phone'] = user.get_data('phone', '') form['mobile'] = user.get_data('mobile', '') return render_template('user.profile.haml', form=form)
def api_get_users(*, page='1'): page_index = get_page_index(page) num = yield from User.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, users=()) users = yield from User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, users=users)
def test_save(): loop = asyncio.get_event_loop() loop.run_until_complete(www.orm.create_pool(loop, user='******', password='******', db='awesome')) u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') loop.run_until_complete(u.save()) loop.stop()
def test(): try: print('program start') yield from www.orm.create_pool(loop, user='******', password='******', db='chen') from www.models import User u = User(name='Test', email='*****@*****.**', passwd='111111', image='about:blank') yield from u.save() print('program end') except BaseException as e: logging.exception(e)
def test(loop): yield from orm.create_pool(loop=loop, user='******', password='******', database='awesome') u = User(name='Yao', email='*****@*****.**', passwd="sas", image='about:blank') yield from u.save()
def testSave(): yield from orm.create_pool(loop, user='******', password='******', db='awesome') u = User(name='awsome_admin', email='*****@*****.**', passwd='1234567890', image='about:blank', admin=True) yield from u.save()
def test(): yield from orm.create_pool(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') yield from u.save()
def apiGetUsers(*, page='1'): pageIndex = getPageIndex(page) num = yield from User.findNumber('count(id)') p = Page(num, pageIndex) if num == 0: return dict(page=p, users=()) users = yield from User.findAll(orderBy='createTime desc', limit=(p.offset, p.limit)) for u in users: u.password = '******' return dict(page=p, users=users)
def manage_users(*, page=1, size=10): num = yield from User.findNumber('count(id)') page = Page(num, set_valid_value(page), set_valid_value(size, 10)) if num == 0: return dict(page=page, users=()) users = yield from User.findAll(orderBy='created_at desc', limit=(page.offset, page.limit + num % page.limit)) for u in users: u.password = '******' return dict(page=page, users=users)
def edit_profile(): here = url_for('edit_profile') next_url = request.args.get('next_url', here) # This is circular user = flask.g.user Audit(flask.g, '', '/user/profile', '', result='').write() form=dict() form['password']='' form['password2']='' if request.method == 'POST': valid = True if request.form['name']: user.name = request.form['name'] else: valid = False flash(u'Error: you have to provide a contact name', 'error') if request.form['email']: user.email = request.form['email'] else: valid = False flash(u'Error: you have to provide a contact email', 'error') if request.form['company']: user.set_data('company', request.form['company']) else: flash(u'Please provide a company name', 'warning') if request.form['phone']: user.set_data('phone', request.form['phone']) else: flash(u'Please provide a phone number', 'warning') if request.form['mobile']: user.set_data('mobile', request.form['mobile']) # Optional if valid: User.commit() if next_url == here: # only flash if we're coming back here... Audit(flask.g, '', '/user/profile', '', result='Update Success').write() flash(u'Profile successfully updated', 'success') return redirect(next_url) form['name']=user.name form['email']=user.email form['company']=user.get_data('company', '') form['phone'] =user.get_data('phone', '') form['mobile'] =user.get_data('mobile', '') return render_template('user.profile.haml', form=form)
def test(loop): db_dict = {'user': '******', 'password': '******', 'db': 'awesome'} yield from orm.create_pool(loop=loop, **db_dict) # yield from orm.create_pool(user='******', password='******', database='awesome') u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') yield from u.save() yield from orm.destory_pool()
def test(loop): yield from www.orm.create_pool(loop=loop, host='localhost', port=3306, user='******', password='******', db='awesome') u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') yield from u.save()
def post(self): t = db.select("select * from users where email=?", request.form['email']) if t: raise APIValueError(data=request.form['email'], message="email has already been registered") user = User( email=request.form['email'], password=request.form['password'], name=request.form['username'], image=request.form['image'] if request.form.has_key('image') else "about:blank", admin=1, ) user.insert()
def save_test(loop): yield from orm.create_pool(loop=loop, host='123.206.178.243', user='******', password='******', db='awesome') u = User(name='sanji', email='*****@*****.**', passwd='123123', image='about:blank') yield from u.save()
def test(loop): yield from www.orm.create_pool(loop=loop, host='localhost', port=3306, user='******', password='******', db='awesome') u = User(name='test77', email='*****@*****.**', passwd='test', image='about:blank') yield from u.save()
def api_get_users(*, page='1'): #获取页面索引,默认为1: page_index = get_page_index(page) #查询数据库中User表中用户总数: num = yield from User.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, users=()) #查询数据库中User表中对应分页的用户结果;(limit为mysql的分页查询条件) users = yield from User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) for u in users: u.passwd = '******' return dict(page=p, users=users)
def test(): yield from www.orm.create_pool(loop, user='******', password='******', db='awesome') u = User(name='admin', email='*****@*****.**', passwd='123123', image='about:blank', admin=True) yield from u.save()
def test(loop): yield from orm.create_pool(loop=loop, user='******', password='******', database='awesome') u = User(admin=True, name='kHRYSTAL', email='*****@*****.**', passwd=hashlib.sha1( ('%s:%s' % (next_id(), 'yyg1990918')).encode('utf-8')).hexdigest(), image='about:blank') yield from u.save()
def test(loop): yield from orm.create_pool(loop=loop, host='127.0.0.1', port=3306, user='******', password='******', db='awesome') user = User(name='Test', email='*****@*****.**', passwd='123456', image='ablout:blank') print('-------create finish-----------') user.show() yield from user.save() yield from orm.destory_pool()
def register(): form = request.form name = form.get('name') user = User.get(name=name) password = form.get('password') if request.method == 'GET': return render('register.html') elif user is not None: error = 'UserName Is Registered' return render('register.html', error=error) password = md5_hash(password, salt=name) user = User(name=name, password=password) user.insert() return log_the_user_in()
def before_request(): #print "REQUEST_HOST='%s'" % (request.host,) host_name = request.host.lower() # if ':' in host_name: host_name = host_name[:host_name.find(':')] if host_name in Site.domain_to_tag: # This is for DNS resolved versions site_tag = Site.domain_to_tag[host_name] else: # This is for subdomains of the main site : Just strip off the subdomain site_tag = host_name[:host_name.find('.')].lower() #print "REQUEST_HOST_TAG='%s'" % (site_tag,) flask.g.site = Site.query().filter_by(tag=site_tag).first() if flask.g.site is None: print "FAILED TO FIND SITE_TAG : DEFAULTING" # Default if all else fails flask.g.site = Site.query().filter_by(tag=Site.tag_main).first() if 'userid' in session: flask.g.user = User.get(session['userid']) else: flask.g.user = User(flask.g.site.tag, '*****@*****.**', 'Not logged in') # Creates a user with id=None #session.pop('hash') if 'hash' not in session: session['hash'] = ''.join([ '%02x' % ord(ch) for ch in urandom(4) ]) print "Created session hash '%s'" % (session['hash'],) flask.g.hash = session['hash'] flask.g.ip = request.remote_addr
def authenticate(*, email, passwd): #判断email(用户名)及password是否为空;为空则抛出异常: if not email: raise APIValueError('email', 'Invalid email.') if not passwd: raise APIValueError('passwd', 'Invalid password.') #数据中查询对应的email信息: users = yield from User.findAll('email=?', [email]) #判断查询结果是否存在,若不存在则抛出异常: if len(users) == 0: raise APIValueError('email', 'Email not exist.') #获取查询结果集的第一条数据: user = users[0] # check passwd: #调用摘要算法SHA1组装登陆信息;计算摘要值同数据库中的信息进行比配: sha1 = hashlib.sha1() sha1.update(user.id.encode('utf-8')) sha1.update(b':') sha1.update(passwd.encode('utf-8')) if user.passwd != sha1.hexdigest(): #登陆信息不匹配则跑出异常: raise APIValueError('passwd', 'Invalid password.') # authenticate ok, set cookie: #构造session cookie信息: r = web.Response() #aiohttp.web.StreamResponse().set_cookie():设置cookie的方法。 r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' #以json格式序列化响应信息; ensure_ascii默认为True,非ASCII字符也进行转义。如果为False,这些字符将保持原样。 r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def cookie2user(cookie_str): ''' Parse cookie and load user if cookie is valid. ''' #若cookie信息为空在返回None: if not cookie_str: return None try: #将cookie信息按照‘-’进行切片处理: L = cookie_str.split('-') #若切片数组长度不为3,则返回None: if len(L) != 3: return None #分别取到uid,cookie有效期,用户信息摘要值: uid, expires, sha1 = L #若cookie有效期小于当前时间,则返回None: if int(expires) < time.time(): return None #根据uid在数据库中查询对应的用户信息: user = yield from User.find(uid) #查询结果为空,则返回None: if user is None: return None #重组用户信息并计算SHA1摘要值,同cookie中的用户信息摘要值比对: s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY) if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest(): #打印(无效SHA1摘要值)日志: logging.info('invalid sha1') return None user.passwd = '******' return user except Exception as e: logging.exception(e) return None
def cookie2user(cookie_str): ''' Parse cookie and load user if cookie is valid. ''' if not cookie_str: return None try: L = cookie_str.split('-') if len(L) != 3: return None uid, expires, sha1 = L if int(expires) < time.time(): return None user = yield from User.find(uid) if user is None: return None s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY) if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest(): logging.info('invalid sha1') return None user.passwd = '******' return user except Exception as e: logging.exception(e) return None
def login(): next_url = request.args.get('next_url', '/') # if we are already logged in, go back to were we came from if flask.g.user.id is not None: Audit(flask.g, '', '/user/login', '', result='Already logged in').write() return redirect(next_url) if request.method == 'POST': email = request.form['email'] user = User.get_if_password_valid(flask.g.site.tag, email, request.form['password']) print "Trying to Login : %s - %s" % (flask.g.site.tag, email, ) if user: print "Trying to Login - SUCCESS" flask.g.user = user # Fix up g, so that Audit works Audit(flask.g, '', '/user/login', email, result='Success').write() session['userid']=user.id return redirect(next_url) else: print "Trying to Login - FAILURE" Audit(flask.g, '', '/user/login', email, result='Failure').write() flash("Email and password don't match", 'error') Audit(flask.g, '', '/user/login', '', result='').write() # Previous request.form rolls over to next iteration automatically return render_template('user.login.haml', next_url=next_url)
def authenticate(*, email, passwd): if not email: raise APIValueError('email', 'Invalid email.') if not passwd: raise APIValueError('passwd', 'Invalid password.') users = yield from User.findAll('email=?', [email]) if len(users) == 0: raise APIValueError('email', 'Email not exist.') user = users[0] # check passwd: sha1 = hashlib.sha1() sha1.update(user.id.encode('utf-8')) sha1.update(b':') sha1.update(passwd.encode('utf-8')) if user.passwd != sha1.hexdigest(): raise APIValueError('passwd', 'Invalid password.') # authenticate ok, set cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def log_the_user_in(): form = request.form user = User.get(name=form['name']) sign = md5_hash(user.id + user.password) app.signed_cookie[user.name] = sign form['sign'] = sign del form['password'] request.set_cookie(form) return redirect('/hello')
def do_signup(sender, interval): logger("Entering do_signup (%s)" % (sender)) try: try: user = User(phonenumber=sender,interval=int(interval)) except (ValueError, IndexError): user = User(phonenumber=sender) user.save() except: logger("user already exists! %s" % sender) #TODO send a message back? fail silently? #raise Exception, "User '%s' already exists" % sender raise return signup_email = "Thank you for signing up! How to play: we will send you a message listing a definition and a choice of four words. You must choose the correct word corresponding to that definition. Respond with only the number of the word that you believe is correct. Text 'stats' to see how you're doing and 'quit' to leave WordiSMS." SMS(user.phonenumber, signup_email).send() logger("Exiting do_signup") return
def find_model(model, id): if model == 'blog': blog = yield from Blog.find(id) return blog if model == 'user': user = yield from User.find(id) return user if model == 'comment': comment = yield from Comment.find(id) return comment
def find_number(model, selectField, where=None, args=None): if model == 'blog': count = yield from Blog.findnumber(selectField=selectField, where=where, args=args) return count if model == 'user': count = yield from User.findnumber(selectField=selectField, where=where, args=args) return count if model == 'comment': count = yield from Comment.findnumber(selectField=selectField, where=where, args=args) return count
def login(): if request.method == 'GET': return render('log_in.html') form = request.form user = User.get(name=form.get('name')) password = md5_hash(form.get('password', ''), salt=form.get('name', '')) if user is None or user.password != password: error = 'UserName or Password Is Incorrect' return render('log_in.html', error=error) return log_the_user_in()
def find_models(model, where=None, args=None, **kw): if model == 'user': users = yield from User.findall(where=where, args=args, **kw) return users if model == 'blog': blogs = yield from Blog.findall(where=where, args=args, **kw) return blogs if model == 'comment': comments = yield from Comment.findall(where=where, args=args, **kw) return comments
def api_register_user(*, email, name, passwd): if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') users = yield from User.findAll('email=?', [email]) if len(users) > 0: raise APIError('register:failed', 'email', 'Email is already in use.') uid = next_id() sha1_password = '******' % (uid, passwd) user = User(id=uid, name=name.strip(), email=email,passwd=hashlib.sha1(sha1_password.encode('utf-8').hexdigest(), image='')) yield from user.save() r = web.Response() r.set_cookie(COOKIE_NAME,user2cookie(user, 86400), max_age=86400, httponly=True) user.passwd = '******' r.content_type = 'application/json' r.body = json.dumps(user,ensure_ascii=False).enconde('utf-8') return r
def post(self): parameters = self.request.POST parameters = utils.pythonize(dict(parameters)) email = parameters.get("email") password = parameters.get("password_raw") data = {} data["errors"] = {} if email: if not re.match(r"[^@]+@[^@]+\.[^@]+", email): data["errors"]["email"] = "This value must be a valid email address" else: data["errors"]["email"] = 'This value is required' if password: if len(password) < 8: data["errors"]["password"] = "******" else: data["errors"]["password"] = "******" if data["errors"]: self.write_json(json.dumps(data)) return user = None try: email = email.lower() user = self.auth.get_user_by_password(email, password) except InvalidAuthIdError: data["errors"]["email"]= "No user exists with this email." self.write_json(json.dumps(data)) return except InvalidPasswordError: data["errors"]["password"]= "******" self.write_json(json.dumps(data)) return user = User.get_by_id(user['user_id']) if not user: # this should never happen, but just to be safe data["redirect"] = self.uri_for('authenticate') elif user.has_roles(['ADMINISTRATOR', 'STAFF']): data["redirect"] = self.uri_for('admin_home') elif user.has_role('HACKER'): data["redirect"]= self.uri_for('register') else: data["errors"]["email"] = "Sorry, but you cannot authenticate here" self.auth.unset_session() self.write_json(json.dumps(data))
def register(request): dic = request.form name = dic.get("name") user = User.get(name=name) password = dic.get("password") error = "" if request.method == "GET": return render_for_response(request, "register.html") elif user is not None: error = "UserName Is Registered" elif not password or not name: error = "User Name or Password Is empty" if error: return render_for_response(request, "register.html", error=error) dic["password"] = md5_hash(password, salt=name) user = User(**dic) user.insert() request.status = "303 See Other" request.header.append(("Location", "/hello")) dic["sign"] = md5_hash(user.id + user.password) del dic["password"] signed_cookie[user.name] = dic["sign"] request.set_cookie(dic) return request
def register_check(*, email, password, name): """checking the information of the register user""" if not email or not email.strip(): raise APIValueError(field='email', message='Empty field.') if not password or not password.strip(): raise APIValueError(field='password', message='Empty field.') if not name or not name.strip(): raise APIValueError(field='name', message='Empty field.') # check email users = yield from find_models(model='user', where='email=?', args=[email]) if len(users) > 0: raise APIError(error='register:failed', data='email', message='Email is already exist.') uid = next_id() sha1_pwd = '%s:%s' % (uid, password) user = User(id=uid, name=name, email=email, password=hashlib.sha1(sha1_pwd.encode('utf-8')).hexdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()) yield from save_model(user) # make the session cookie r = web.Response() r.set_cookie(name=COOKIE_NAME, value=user2cookie(user, 86400), max_age=86400, httponly=True) user.password = '******' r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def reset(): if request.method == 'POST': email = request.form['email'] user = User.get_from_email(flask.g.site.tag, email) print "Password Reset request : %s - %s" % (flask.g.site.tag, email, ) if user: Audit(flask.g, '', '/user/reset', email, result='Success').write() send_reset_link(user) #return redirect(next_url) else: Audit(flask.g, '', '/user/reset', email, result='Failure').write() flash("Password Reset email sent : Click on the link in your email to create a new password", 'success') else: Audit(flask.g, '', '/user/reset', '', result='').write() return render_template('user.reset.haml', ) # next_url=next_url)
def login(request): if request.method == "GET": return render_for_response(request, "log_in.html") dic = request.form user = User.get(name=dic.get("name")) password = md5_hash(dic.get("password", ""), salt=dic.get("name", "")) if user is None or user.password != password: error = "UserName or Password Is Incorrect" return render_for_response(request, "log_in.html", error=error) request.status = "303 See Other" request.header.append(("Location", "/hello")) dic["sign"] = md5_hash(user.id + user.password) del dic["password"] signed_cookie[user.name] = dic["sign"] request.set_cookie(dic) return request
def admin_audit(): criteria=dict() for c in ['proj', 'email', 'action']: criteria[c] = request.form.get(c, None) if criteria[c]=='EMPTY': criteria[c]=None proj = criteria['proj'] Audit(flask.g, proj, '/admin/audit', '').write() if not flask.g.user.can_siteadmin(): Audit(flask.g, proj, '/admin/audit', '', result='NOT AUTHORIZED').write() return home_page() form = dict() crit_site = ( Audit.site_tag == flask.g.site.tag ) form['projects']= Audit.query_element(Audit.project.distinct()).filter(crit_site).order_by(Audit.project).all() form['emails'] = Audit.query_element(Audit.user_id.distinct(), User.email).filter(crit_site).join(User, Audit.user_id == User.id).order_by(User.email).all() form['actions'] = Audit.query_element(Audit.action.distinct()).filter(crit_site).order_by(Audit.action).all() # http://stackoverflow.com/questions/2678600/how-do-i-construct-a-slightly-more-complex-filter-using-or-or-and-in-sqlalchem crit_extra = True clause='' if criteria['proj'] is not None: crit_extra = (Audit.project == criteria['proj'].strip()) clause = ': Project = "%s"' % (criteria['proj'],) if criteria['email'] is not None: user = User.get(criteria['email']) if user and user.site_tag == flask.g.site.tag: crit_extra = (Audit.user_id == user.id) clause = ': Email = "%s"' % (user.email,) if criteria['action'] is not None: crit_extra = (Audit.action == criteria['action'].strip()) clause = ': Action = "%s"' % (criteria['action'],) trail = Audit.query_element(Audit, User.email).filter(crit_site).filter(crit_extra).order_by(Audit.ts.desc()).join(User, Audit.user_id == User.id).limit(100).all() form['clause']=clause return render_template('admin.audit.haml', form=form, trail=trail)
def getUsers(): users = yield from User.findAll() print(users)