Beispiel #1
0
async def api_login(*, email, password, rememberme):
    if not email:
        raise APIValueError('email', 'Invalid email.')
    if not password:
        raise APIValueError('password', 'Invalid password.')
    users = await User.findAll(where='email=?', args=[email])
    if len(users) == 0:
        raise APIValueError('email', 'Email not exist.')
    user = users[0]
    # 检查密码
    sha1 = hashlib.sha1()
    sha1.update(user.id.encode('utf-8'))
    sha1.update(b':')
    sha1.update(password.encode('utf-8'))
    logging.info('password:%s' % user.password)
    logging.info('sha1:%s' % sha1.hexdigest())
    if user.password != sha1.hexdigest():
        raise APIValueError('password', 'Invalid password.')
    # 密码正确,设置cookie
    r = web.Response()
    if rememberme:
        max_age = configs.cookie.max_age_long
    else:
        max_age = configs.cookie.max_age
    r.set_cookie(configs.cookie.name,
                 user2cookie(user, max_age),
                 max_age=max_age,
                 httponly=True)
    user.password = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Beispiel #2
0
async def api_modify_password(request, *, user_id, password0, password1,
                              password2):
    if request.__user__ is None:
        raise APIPermissionError('You must login first!')
    if not user_id or not user_id.strip():
        raise APIValueError('user_id', 'user_id can not be empty.')
    if not password0 or not password0.strip():
        raise APIValueError('password0', 'old password can not be empty.')
    if not password1 or not RE_SHA1.match(password1):
        raise APIValueError('password1', 'Invalid new password.')
    if not password2 or not RE_SHA1.match(password2):
        raise APIValueError('password2', 'Invalid confirmimg password.')

    user = await User.find(user_id)
    if user is None:
        raise APIResourceNotFoundError('User not found')
    # 检查密码
    sha1 = hashlib.sha1()
    sha1.update(user_id.encode('utf-8'))
    sha1.update(b':')
    sha1.update(password0.encode('utf-8'))
    if user.password != sha1.hexdigest():
        raise APIValueError('password', 'Invalid old password.')
    # 修改密码
    sha1_password = '******' % (user_id, password1)
    user.password = hashlib.sha1(sha1_password.encode('utf-8')).hexdigest()
    await user.update()
    return dict(user_id=user_id)
Beispiel #3
0
async def api_update_blog(id, request, *, title, summary, content, cat_name):
    if request.__user__ is None or not request.__user__.admin:
        raise APIPermissionError('Only admin can do this!')
    if not title or not title.strip():
        raise APIValueError('title', 'Title can not be empty.')
    if not summary or not summary.strip():
        summary = content.strip()[:200]
    elif len(summary.strip()) > 200:
        raise APIValueError('summary',
                            'Length of summary can not be larger than 200.')
    if not content or not content.strip():
        raise APIValueError('content', 'Content can not be empty.')
    blog = await Blog.find(id)
    blog.title = title.strip()
    blog.summary = summary.strip()
    blog.content = content.strip()
    if not cat_name or not cat_name.strip():
        blog.cat_name = None
        blog.cat_id = None
    else:
        blog.cat_name = cat_name.strip()
        cats = await Category.findAll(where='name=?', args=[cat_name.strip()])
        if (len(cats) == 0):
            raise APIValueError('cat_name',
                                'cat_name is not belong to Category.')
        blog.cat_id = cats[0].id
    await blog.update()
    return blog
Beispiel #4
0
async def authenticate(*, email, passwd):
    if not email:
        raise APIValueError('email', 'invalid email.')
    if not passwd:
        raise APIValueError('passwd', 'invalid password.')
    users = await User.findAll('email=?', [email])
    if len(users) == 0:
        raise APIValueError('email', 'Email not exist.')
    user = users[0]
    # check passwd
    #print(user.id)
    sha1_pwd = '%s:%s' % (user.id, passwd)
    #print(passwd)
    passwd_has1 = hashlib.sha1(sha1_pwd.encode('utf-8')).hexdigest()

    if passwd_has1 != user.passwd:

        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
Beispiel #5
0
async def api_signin(*, 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 RE_SHA1.match(password):
        raise APIValueError('password')

    users = await User.findAll(where='email=?', args=[email])
    if len(users) > 0:
        raise APIError('signup:failed', 'email', 'Email is already in use.')
    uid = next_id()
    sha1_password = '******' % (uid, password)
    user = User(id=uid,
                name=name.strip(),
                email=email,
                password=hashlib.sha1(
                    sha1_password.encode('utf-8')).hexdigest(),
                image=configs.web_meta.user_image)
    await user.save()
    # 设置cookie
    r = web.Response()
    r.set_cookie(configs.cookie.name,
                 user2cookie(user, configs.cookie.max_age),
                 max_age=configs.cookie.max_age,
                 httponly=True)
    user.password = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Beispiel #6
0
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
async def authenticate(*,email,passwd):
    if not email:
        raise APIValueError('email')
    if not passwd:
        raise APIValueError('passwd')
    users = await User.findAll(where='email=?',args=[email]) # 在数据库中查找email,将以list形式返回
    if len(users) == 0:
        raise APIValueError('email','Email not exist.')
    user = users[0]# 取得用户记录.事实上,就只有一条用户记录,只不过返回的是list

    #把登录密码转化格式并进行摘要算法
    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")

    # 用户登录之后,同样的设置一个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
async def api_register_user(*,name,email,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 and not _RE_SHA1.match(passwd):
        raise APIValueError('password')
    users = await User.findAll(where='email=?', args=[email])# 查询邮箱是否已注册,查看ORM框架源码
    if len(users) > 0:
        raise APIError('register:failed','email','Email is already in use.')

    # 接下来就是注册到数据库上,具体看会ORM框架中的models源码
    # 这里用来注册数据库表id不是使用Use类中的默认id生成,而是调到外部来,原因是后面的密码存储摘要算法时,会把id使用上。
    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()

    #制作cookie返回返回浏览器客户端
    r = web.Response()
    r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
    user.passwd = '******'  # 掩盖passwd
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
async def api_create_blog(request, *, name, summary, content):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'Name cannot be empty.')
    if not summary or not summary.strip():
        raise APIValueError('summary', 'Summary cannot be empty.')
    if not content or not content.strip():
        raise APIValueError('content', 'Content cannot be empty.')
    blog = Blog(user_id = request.__user__.id, user_name = request.__user__.name, user_image = request.__user__.image, name = name.strip(), summary = summary.strip(), content = content.strip())
    await blog.save()
    return blog
async def api_update_blog(id, request, *, name, summary, content):
    check_admin(request)
    blog = await Blog.find(id)
    if not name or not name.strip():
        raise APIValueError('name', 'name cannot be empty.')
    if not summary or not summary.strip():
        raise APIValueError('summary', 'summary cannot be empty.')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty.')
    blog.name = name.strip()
    blog.summary = summary.strip()
    blog.content = content.strip()
    await blog.update()
    return blog
Beispiel #11
0
async def api_create_category(request, *, name):
    if request.__user__ is None or not request.__user__.admin:
        raise APIPermissionError('Only admin can do this!')
    if not name or not name.strip():
        raise APIValueError('name', 'Name can not be empty.')
    cat = Category(name=name.strip())
    await cat.save()
    return cat
Beispiel #12
0
async def api_update_category(id, request, *, name):
    if request.__user__ is None or not request.__user__.admin:
        raise APIPermissionError('Only admin can do this!')
    if not name or not name.strip():
        raise APIValueError('name', 'Name can not be empty.')
    cat = await Category.find(id)
    cat.name = name.strip()
    await cat.update()
    return cat
async def api_create_comment(id, request, *, content):
    user = request.__user__  # 登录再说
    if not user:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty.')
    blog = await Blog.find(id)
    if blog is None:
        raise APIResourceNotfoundError('Blog')
    comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip())
    await comment.save()
    return comment
Beispiel #14
0
async def api_reset_password(*, email):
    # 重置密码
    if not email:
        raise APIValueError('email', 'Invalid email.')
    users = await User.findAll(where='email=?', args=[email])
    if len(users) == 0:
        raise APIValueError('email', 'Email not exist.')
    user = users[0]
    s = '%s:%d' % (user.id, int(time.time() * 1000))
    password0 = hashlib.md5(s.encode('utf-8')).hexdigest()[:10]  # 重置后的密码
    password1 = '%s:%s' % (email, password0)
    password1 = hashlib.sha1(
        password1.encode('utf-8')).hexdigest()  # 模拟客户端用email加密密码
    sha1_password = '******' % (user.id, password1)
    user.password = hashlib.sha1(sha1_password.encode('utf-8')).hexdigest()
    await user.update()

    # 发送email
    from_addr = configs.email.addr
    password = configs.email.password
    to_addr = email
    smtp_server = configs.email.server
    smtp_port = configs.email.port
    msg = MIMEText('您的密码已经重置,请使用新密码登陆网站并尽快修改密码。\n重置后的新密码为: ' + password0,
                   'plain', 'utf-8')
    msg['From'] = _format_addr('管理员 <%s>' % from_addr)
    msg['To'] = _format_addr('%s <%s>' % (user.name, to_addr))
    msg['Subject'] = Header('来自 ' + configs.web_meta.web_name + ' - 重置密码',
                            'utf-8').encode()
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
    return dict(email=email)
Beispiel #15
0
async def api_create_comment(id, request, *, content):
    user = request.__user__
    if user is None or not user.admin:
        raise APIPermissionError('Only admin can do this!')
    if not content or not content.strip():
        raise APIValueError('comment', 'Comment can not be empty.')
    blog = await Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    await comment.save()
    return comment