def cookie2user(cookie_str): 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 Users.find('id=?',[uid]) if user is None: return None s = '%s-%s-%s-%s' % (uid, user.password, expires, _COOKIE_KEY) if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest(): logging.info('invalid sha1') return None user.password = "******" return user except Exception as e: logging.exception(e) return None
def register_user(email, name, password, image=_DEFAULT_IMAGE): 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 _RE_SHA1.match(password): raise APIValueError('password') user = yield from Users.find('email=?',[email]) if user: raise APIError('register:failed','email','Email is already used.') uid = next_id() sha1_password = '******' % (uid, password) user = Users(id=uid, name=name, email=email, password=hashlib.sha1(sha1_password.encode('utf-8')).hexdigest(),image=image) yield from user.save() r = aiohttp.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 api_authenticate(email, password): if not email: raise APIValueError('email', 'Invalid email.') if not password: raise APIValueError('password','Invalid password.') user = yield from Users.find('email=?',[email]) if not user: raise APIValueError('email','Email not exist.') #check password sha1 = hashlib.sha1() sha1.update(user.id.encode('utf-8')) sha1.update(b':') sha1.update(password.encode('utf-8')) if user.password != sha1.hexdigest(): raise APIValueError('password','Invalid password') r = aiohttp.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