示例#1
0
async def api_user_authenticate(request):
    """
    用户登录验证API函数
    :param request: 请求对象
    :return: 回响消息, 并且设置COOKIE
    """
    request_data = RequestData(request)
    if not await request_data.json_load():
        return data_error(u'非法数据格式, 请使用JSON格式')

    email = request_data.email
    password = request_data.password
    if not email:
        return data_error(u'非法邮箱账号')
    if not password:
        return data_error(u'非法密码')

    users = await UserAuth.find_all(where='email=?', args=[email])
    if len(users) == 0:
        return data_error(u'账号不存在')

    user = users[0]
    sha1_password = generate_sha1_password(user['id'], password)
    if user['password'] != sha1_password:
        return data_error(u'密码有误')

    cookie_name = configs.user_cookie.name
    cookie_secret = configs.user_cookie.secret
    cookie_str = user_cookie_generate(user['id'], 86400, cookie_secret)
    r = web.Response()
    r.set_cookie(cookie_name, cookie_str, 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
示例#2
0
async def api_user_authenticate(request):
    """
    用户登录验证API函数
    :param request: 请求对象
    :return: 回响消息, 并且设置COOKIE
    """
    ct = request.content_type.lower()
    if ct.startswith('application/json'):
        params = await request.json()
        if not isinstance(params, dict):
            return data_error()
    else:
        return data_error()

    email = None
    if 'email' in params:
        email = params['email']
    password = None
    if 'password' in params:
        password = params['password']

    if not email:
        return data_error(u'非法邮箱账号')
    if not password:
        return data_error(u'非法密码')

    users = await UserAuth.find_all(where='email=?', args=[email])
    if len(users) == 0:
        return data_error(u'账号不存在')

    user = users[0]
    sha1_password = generate_sha1_password(user['id'], password)
    if user['password'] != sha1_password:
        return data_error(u'密码有误')

    cookie_name = configs.user_cookie.name
    cookie_secret = configs.user_cookie.secret
    cookie_str = user_cookie_generate(user['id'], 86400, cookie_secret)
    r = web.Response()
    r.set_cookie(cookie_name, cookie_str, 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
示例#3
0
async def api_weibo_login(request):
    """
    微博登录API函数
    :param request:
    :return:
    """

    request_data = RequestData(request)
    if not await request_data.json_load():
        return data_error(u'非法数据格式, 请使用JSON格式')

    # 取出用户id和访问令牌
    uid = request_data.uid
    if not uid:
        return data_error()
    access_token = request_data.access_token
    if not access_token or not access_token.strip():
        return data_error()

    # 获取用户数据
    url = 'https://api.weibo.com/2/users/show.json?access_token='
    url += access_token
    url += '&uid='
    url += str(uid)
    async with ClientSession() as session:
        async with session.get(url) as response:
            user_data = await response.json()
            logging.info(user_data)
            if not isinstance(user_data, dict):
                return data_error()

    user_name = None
    if 'screen_name' in user_data:
        user_name = user_data['screen_name']
    if not user_name:
        return data_error()
    user_image = None
    if 'avatar_hd' in user_data:
        user_image = user_data['avatar_hd']
    if not user_image:
        return data_error()

    # 更新或者保存用户信息
    user = await UserInfo.find(str(uid))
    logging.info(user)
    if not user:
        user = UserInfo(id=uid, name=user_name, image=user_image)
        await user.save()
    else:
        user.name = user_name
        user.image = user_image
        await user.update()

    # 生成用户COOKIE
    cookie_name = configs.user_cookie.name
    cookie_secret = configs.user_cookie.secret
    cookie_str = user_cookie_generate(str(uid), 86400, cookie_secret)
    r = web.Response()
    r.set_cookie(cookie_name, cookie_str, max_age=86400, httponly=True)
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
示例#4
0
async def api_user_register(request):
    """
    用户注册API函数
    :param request: 请求对象
    :return: 注册成功则设置COOKIE,返回响应消息
    """
    _RE_EMAIL = re.compile(
        r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
    _RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')

    request_data = RequestData(request)
    if not await request_data.json_load():
        return data_error(u'非法数据格式, 请使用JSON格式')

    name = request_data.name
    email = request_data.email
    password = request_data.password
    verify = request_data.verify

    # 检查验证码是否输入正确
    if not verify or not verify.strip():
        return data_error(u'非法验证码')
    verify_cookie_name = configs.verify_image_cookie.name
    cookie_secret = configs.verify_image_cookie.secret
    cookie_str = request.cookies.get(verify_cookie_name)
    cookie_str_input = verify_image_cookie_generate(verify.upper(),
                                                    cookie_secret)
    if not cookie_str == cookie_str_input:
        return data_error(u'验证码错误')

    # 检查用户数据是否合法
    if not name or not name.strip():
        return data_error(u'非法用户名')
    if not email or not _RE_EMAIL.match(email):
        return data_error(u'非法邮箱账号')
    if not password or not _RE_SHA1.match(password):
        return data_error(u'非法密码')

    # 检查用户邮箱是否已经被注册
    users = await UserAuth.find_all(where='email=?', args=[email])
    if len(users) > 0:
        return data_error(u'邮箱已经被使用')

    # 生成用户ID, 并且混合用户ID和密码进行SHA1加密
    uid = generate_id()
    sha1_password = generate_sha1_password(uid, password)

    # 将新用户数据保存到数据库中
    user = UserAuth(id=uid, email=email, password=sha1_password)
    await user.save()

    # 生成头像图片URL
    head_img_url = configs.domain_name
    head_img_url += '/static/img/head_%s.jpg' % random.randint(1, 15)
    user_info = UserInfo(id=uid, name=name.strip(), image=head_img_url)
    await user_info.save()

    # 生成COOKIE
    cookie_str = user_cookie_generate(user['id'], 86400,
                                      configs.user_cookie.secret)
    cookie_name = configs.user_cookie.name

    # 生成响应消息
    r = web.Response()
    # 删除用于验证验证码的COOKIE
    r.set_cookie(verify_cookie_name, '-deleted-', max_age=0, httponly=True)
    r.set_cookie(cookie_name, cookie_str, 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
示例#5
0
async def api_github_login(request):
    """
    GitHub登录API函数
    :param request:
    :return:
    """
    qs_parser = QueryStringParser(request.query_string)
    github_code = qs_parser.code
    last_url = qs_parser.state
    if not github_code:
        return data_error('GitHub Code Lost')

    # 获取用户令牌
    access_token_url = 'https://github.com/login/oauth/access_token?client_id='
    access_token_url += configs.github.client_id
    access_token_url += '&client_secret='
    access_token_url += configs.github.client_secret
    access_token_url += '&redirect_uri='
    access_token_url += configs.github.redirect_uri
    access_token_url += '&code='
    access_token_url += github_code
    async with ClientSession() as session:
        async with session.post(access_token_url) as response:
            response_data = await response.text()

    data_parser = QueryStringParser(response_data)
    access_token = data_parser.access_token
    if not access_token:
        return data_error()

    user_url = 'https://api.github.com/user?access_token='
    user_url += access_token
    async with ClientSession() as session:
        async with session.get(user_url) as response:
            user_data = await response.json()

    user_id = None
    if 'id' in user_data:
        user_id = user_data['id']
    if not user_id:
        return data_error()

    user_name = None
    if 'login' in user_data:
        user_name = user_data['login']
    if not user_name:
        return data_error()
    user_image = None
    if 'avatar_url' in user_data:
        user_image = user_data['avatar_url']
    if not user_image:
        return data_error()

    # 更新或者保存用户信息
    user = await UserInfo.find(str(user_id))
    logging.info(user)
    if not user:
        user = UserInfo(id=user_id, name=user_name, image=user_image)
        await user.save()
    else:
        user.name = user_name
        user.image = user_image
        await user.update()

    # 生成用户COOKIE
    cookie_name = configs.user_cookie.name
    cookie_secret = configs.user_cookie.secret
    cookie_str = user_cookie_generate(str(user_id), 86400, cookie_secret)

    r = web.HTTPFound(last_url)
    r.set_cookie(cookie_name, cookie_str, max_age=86400, httponly=True)
    return r