예제 #1
0
    def post(self):
        args = self.member_post_parser.parse_args()
        email = args.email

        if email is None:
            abort(406, message="needs email")
        if re.match("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", email) is None:
            abort(406, message="email wrong formatted")
        abort_if_member_email_exist(email)

        member = Member(
                email=email,
                nickname=args.nickname
        )
        member.hash_password(args.password)

        if args.profile_img is not None:

            profile_filename = save_json_image('PROFILE_IMAGE_FOLDER', args.profile_img)
            member.profile_filename = profile_filename
            member.profile_url = generate_image_url('profile', profile_filename)

        db.session.add(member)
        db.session.commit()

        # Redis init
        p = youngs_redis.pipeline()
        for each_member in Member.query.all():
            log.info(each_member.email)
            p.set('member:'+each_member.email, {
                'id': each_member.id,
            })
        p.execute()
        return marshal(member, member_fields['normal'], envelope='results')
예제 #2
0
def save_json_image(save_path_config, url_image_raw):
    try:
        up = urllib.parse.urlparse(url_image_raw)
        head, data = up.path.split(',', 1)
        bits = head.split(';')
        mime_type = bits[0] if bits[0] else 'text/plain'
        charset, b64 = 'ASCII', False
        for bit in bits:
            if bit.startswith('charset='):
                charset = bit[8:]
            elif bit == 'base64':
                b64 = True

        image_file = str.encode(data)
        log.info(image_file[:10])

        hash_mod.update(str(ptime.time()).encode('utf-8'))
        image_filename = hash_mod.hexdigest()[:10]
        filedir = current_app.config[save_path_config]
        if not os.path.exists(filedir):
            os.makedirs(filedir)

        ext = 'jpg'
        filename = secure_filename(image_filename) + '.' + ext

        filepath = os.path.join(filedir, filename)
        # not exist
        if not os.path.exists(filepath):
            with open(filepath, "wb") as message_file:
                message_file.write(base64.decodebytes(image_file))

        file_dir, filename = os.path.split(filepath)
        return filename
    except ValueError as e:
        abort(406, message='wrong image')
예제 #3
0
    def post(self):
        args = self.member_post_parser.parse_args()
        email = args.email

        if email is None:
            abort(406, message="needs email")
        if re.match("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$",
                    email) is None:
            abort(406, message="email wrong formatted")
        abort_if_member_email_exist(email)

        member = Member(email=email, nickname=args.nickname)
        member.hash_password(args.password)

        if args.profile_img is not None:

            profile_filename = save_json_image('PROFILE_IMAGE_FOLDER',
                                               args.profile_img)
            member.profile_filename = profile_filename
            member.profile_url = generate_image_url('profile',
                                                    profile_filename)

        db.session.add(member)
        db.session.commit()

        # Redis init
        p = youngs_redis.pipeline()
        for each_member in Member.query.all():
            log.info(each_member.email)
            p.set('member:' + each_member.email, {
                'id': each_member.id,
            })
        p.execute()
        return marshal(member, member_fields['normal'], envelope='results')
예제 #4
0
def after_request(response):
    request_args = {}
    for each_arg in request.args:
        request_args[each_arg] = request.args[each_arg]
    if 'text/html' in response.headers['Content-Type']:
        return response

    diff = datetime.now() - g.start
    try:
        authorization_value = request.headers.get('Authorization')
        if authorization_value is None:
            authorization_value = ''
        token = authorization_value.replace('JWT ', '', 1)
        # userinfo = jwt.decode(token, current_app.config['SECRET_KEY'])
        # print(userinfo)
        request_log = {
            # 'id': current_user.id,
            'request_path': request.path,
            'request_args': request_args,
            'request_method': request.method,
            'response_time': diff,
            'response_status': response.status_code,
        }
    except Exception as e:
        print(e)
        log.error('Logging error')
        return response
    if app.config['LOG_LEVEL'] == 'debug' and 'json' in response.headers['Content-Type']:
        request_log['response_data'] = json.loads(response.data.decode('utf-8'))
    try:
        log.info('request log', extra=request_log)
    except Exception as e:
        log.error('Logging error : %s', e)

    return response
예제 #5
0
def save_json_image(save_path_config, url_image_raw):
    try:
        up = urllib.parse.urlparse(url_image_raw)
        head, data = up.path.split(',', 1)
        bits = head.split(';')
        mime_type = bits[0] if bits[0] else 'text/plain'
        charset, b64 = 'ASCII', False
        for bit in bits:
            if bit.startswith('charset='):
                charset = bit[8:]
            elif bit == 'base64':
                b64 = True

        image_file = str.encode(data)
        log.info(image_file[:10])

        hash_mod.update(str(ptime.time()).encode('utf-8'))
        image_filename = hash_mod.hexdigest()[:10]
        filedir = current_app.config[save_path_config]
        if not os.path.exists(filedir):
            os.makedirs(filedir)

        ext = 'jpg'
        filename = secure_filename(image_filename) + '.' + ext

        filepath = os.path.join(filedir, filename)
        # not exist
        if not os.path.exists(filepath):
            with open(filepath, "wb") as message_file:
                message_file.write(base64.decodebytes(image_file))

        file_dir, filename = os.path.split(filepath)
        return filename
    except ValueError as e:
        abort(406, message='wrong image')
예제 #6
0
def delete_html(folder, content_filename):
    filedir = os.path.join(current_app.config['INROOM_WEBVIEW_FOLDER'], folder)
    if not os.path.exists(filedir):
        os.makedirs(filedir)
    filepath = os.path.join(filedir, content_filename)
    # exist
    if os.path.exists(filepath):
        log.info(os.remove(filepath))
예제 #7
0
def delete_html(folder, content_filename):
    filedir = os.path.join(current_app.config['INROOM_WEBVIEW_FOLDER'], folder)
    if not os.path.exists(filedir):
        os.makedirs(filedir)
    filepath = os.path.join(filedir, content_filename)
    # exist
    if os.path.exists(filepath):
        log.info(os.remove(filepath))
예제 #8
0
 def delete(self):
     """
     :return: logout session, which means delete token and session
     """
     if 'token' in session:
         log.info('session token %s', session['token'])
         youngs_redis.delete('auth:token' + session['token'])
     if 'user_id' in session:
         log.info('cleared session userid %s', session['user_id'])
     logout_user()
     return jsonify({'result': 'success'})
예제 #9
0
 def delete(self):
     """
     :return: logout session, which means delete token and session
     """
     if 'token' in session:
         log.info('session token %s', session['token'])
         youngs_redis.delete('auth:token'+session['token'])
     if 'user_id' in session:
         log.info('cleared session userid %s', session['user_id'])
     logout_user()
     return jsonify({'result': 'success'})
예제 #10
0
def save_html(folder, content):

    hash_mod.update(str(ptime.time()).encode('utf-8'))
    image_filename = hash_mod.hexdigest()[:10]

    ext = 'html'
    filename = secure_filename(image_filename) + '.' + ext
    filedir = os.path.join(current_app.config['INROOM_WEBVIEW_FOLDER'], folder)
    if not os.path.exists(filedir):
        os.makedirs(filedir)
    filepath = os.path.join(filedir, filename)
    if not os.path.exists(filepath):
        with open(filepath, "wb") as html_file:
            log.info(content)
            content = str.encode(content)
            html_file.write(content)
    file_dir, filename = os.path.split(filepath)
    return filename
예제 #11
0
def save_html(folder, content):

    hash_mod.update(str(ptime.time()).encode('utf-8'))
    image_filename = hash_mod.hexdigest()[:10]

    ext = 'html'
    filename = secure_filename(image_filename) + '.' + ext
    filedir = os.path.join(current_app.config['INROOM_WEBVIEW_FOLDER'], folder)
    if not os.path.exists(filedir):
        os.makedirs(filedir)
    filepath = os.path.join(filedir, filename)
    if not os.path.exists(filepath):
        with open(filepath, "wb") as html_file:
            log.info(content)
            content = str.encode(content)
            html_file.write(content)
    file_dir, filename = os.path.split(filepath)
    return filename
예제 #12
0
    def post(self):
        """ login function """

        if 'application/json' in request.headers['Content-Type']:
            args = self.auth_post_parser.parse_args()
            email = args.email
            password = args.password

        else:
            raise abort(406, message='server cannot understand')
        # TODO get device type from headers

        member = Member.query.filter_by(email=email).one()

        if not member.verify_password(password):
            raise abort(401, message='id or pw is invalid')

        login_user(member)

        member.recent_login_timestamp = datetime.utcnow()
        db.session.commit()

        token_payload = {
            'id': member.id,
            'exp': datetime.utcnow() + timedelta(days=7)
        }
        token = jwt.encode(token_payload,
                           current_app.config['SECRET_KEY'],
                           algorithm='HS256').decode('utf-8')
        session_ttl = int(current_app.config['SESSION_ALIVE_MINUTES'] * 60)
        p = youngs_redis.pipeline()
        if youngs_redis.exists('auth:token:' + token) is False:
            p.hmset('auth:token:' + token, {'id': member.id})
        p.expire('auth:token:' + token, session_ttl)
        p.execute()
        session['token'] = token
        member.token = token

        log.info('Login : '******'results')
예제 #13
0
    def decorated_function(*args, **kwargs):
        # print session
        # temp

        token = request.headers.get('Authorization')
        if (token is None) or (len(token) < 7):
            abort(403, message='token invalid')
        token = token[6:]
        if token == '1':
            session['userid'] = 'admin'
            session['id'] = 1
            session['token'] = '1'
        elif youngs_redis.get('token-' + token) is None:
            log.error('token invalid : token [' + token + ']')
            abort(403, message='token invalid')
        else:
            userinfo = ast.literal_eval(youngs_redis.get('token-' + token))
            session['userid'] = userinfo['userid']
            session['id'] = userinfo['id']
            session['token'] = token
        log.info('token valid : user [' + session['userid'] + ']')
        return f(*args, **kwargs)
예제 #14
0
    def decorated_function(*args, **kwargs):
        # print session
        # temp

        token = request.headers.get('Authorization')
        if (token is None) or (len(token) < 7):
            abort(403, message='token invalid')
        token = token[6:]
        if token == '1':
            session['userid'] = 'admin'
            session['id'] = 1
            session['token'] = '1'
        elif youngs_redis.get('token-'+token) is None:
            log.error('token invalid : token [' + token + ']')
            abort(403, message='token invalid')
        else:
            userinfo = ast.literal_eval(youngs_redis.get('token-'+token))
            session['userid'] = userinfo['userid']
            session['id'] = userinfo['id']
            session['token'] = token
        log.info('token valid : user [' + session['userid'] + ']')
        return f(*args, **kwargs)
예제 #15
0
    def post(self):
        """ login function """

        if 'application/json' in request.headers['Content-Type']:
            args = self.auth_post_parser.parse_args()
            email = args.email
            password = args.password

        else:
            raise abort(406, message='server cannot understand')
        # TODO get device type from headers

        member = Member.query.filter_by(email=email).one()

        if not member.verify_password(password):
            raise abort(401, message='id or pw is invalid')

        login_user(member)

        member.recent_login_timestamp = datetime.utcnow()
        db.session.commit()

        token_payload = {
            'id': member.id,
            'exp': datetime.utcnow() + timedelta(days=7)
        }
        token = jwt.encode(token_payload, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
        session_ttl = int(current_app.config['SESSION_ALIVE_MINUTES'] * 60)
        p = youngs_redis.pipeline()
        if youngs_redis.exists('auth:token:'+token) is False:
            p.hmset('auth:token:'+token, {'id': member.id})
        p.expire('auth:token:'+token, session_ttl)
        p.execute()
        session['token'] = token
        member.token = token

        log.info('Login : '******'results')
예제 #16
0
def after_request(response):
    request_args = {}
    for each_arg in request.args:
        request_args[each_arg] = request.args[each_arg]
    if 'text/html' in response.headers['Content-Type']:
        return response

    diff = datetime.now() - g.start
    try:
        authorization_value = request.headers.get('Authorization')
        if authorization_value is None:
            authorization_value = ''
        token = authorization_value.replace('JWT ', '', 1)
        # userinfo = jwt.decode(token, current_app.config['SECRET_KEY'])
        # print(userinfo)
        request_log = {
            # 'id': current_user.id,
            'request_path': request.path,
            'request_args': request_args,
            'request_method': request.method,
            'response_time': diff,
            'response_status': response.status_code,
        }
    except Exception as e:
        print(e)
        log.error('Logging error')
        return response
    if app.config['LOG_LEVEL'] == 'debug' and 'json' in response.headers[
            'Content-Type']:
        request_log['response_data'] = json.loads(
            response.data.decode('utf-8'))
    try:
        log.info('request log', extra=request_log)
    except Exception as e:
        log.error('Logging error : %s', e)

    return response