def login_user_auth(data):
    '''
    Login generate token by user_id 
    '''
    try:
        email = data.get('email')
        password = data.get('password')
        user = User.query.filter_by(email=email).first()

        if not user:
            error_respon = {'status': 'fail', 'message': 'user does not exist'}
            return error_respon, 404
        check_password = bcrypt.check_password_hash(user.password, password)
        if not check_password:
            error_respon = {
                'status': 'fail',
                'message': 'email or password does not match'
            }
            return error_respon, 401
        # user exist and email&password math
        login_user(user)  # login by flask-login
        auth_token = User.auth_encode_token(user.id)
        if auth_token:
            success_respon = {
                'status': 'success',
                'message': 'You Successfully Login',
                'token': auth_token.decode('utf-8')
            }
            return success_respon, 200

    except Exception as e:
        error_respon = {'status': 'fail', 'message': e}
        return error_respon, 500
def logout_user_auth(request):
    '''Logout'''
    dev_token = request.headers.get('DEV-API-KEY')
    pro_token = request.headers.get('Authorization')
    auth_token = None
    if pro_token:
        auth_token = pro_token.split(" ")[1]
    if dev_token:
        auth_token = dev_token
    if auth_token:
        result = User.auth_decode_token(auth_token)
        if isinstance(result, str):
            # token invalid or expired
            error_respon = {'status': 'fail', 'message': result}
            return error_respon, 401
        # token isvalid ,correct logout
        logout_user()  # logout by flask-login
        success_respon = {
            'status': 'success',
            'message': 'You Successfully Logout'
        }
        return success_respon, 200
    else:
        error_respon = {'status': 'fail', 'message': 'token does not exist'}
        return error_respon, 403
 def post(self):
     '''Create a new user'''
     data = user_api.payload
     username = data.get('username')
     email = data.get('email')
     password = data.get('password')
     is_exist_email = User.query.filter_by(email=email).first()
     is_exist_username = User.query.filter_by(username=username).first()
     if is_exist_email:
         error_respon = {
             'status': 'fail',
             'message': 'User by email already exists, Please reset'
         }
         return error_respon, 409
     if is_exist_username:
         error_respon = {
             'status': 'fail',
             'message': 'User by username already exists, Please rename'
         }
         print(1)
         return error_respon, 409
     password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
     new_user = User(public_id=str(uuid.uuid4()),
                     email=email,
                     username=username,
                     password=password_hash)
     db.session.add(new_user)
     db.session.commit()
     success_respon = {
         'status': 'success',
         'message': 'User signup success, Please login'
     }
     return success_respon, 201
def populte():
    print('drop database')
    db.drop_all()
    print('drop done')
    print('create database')
    db.create_all()
    print('create database done')
    print('creating......')
    for user in users:
        hash_password = bcrypt.generate_password_hash(
            user.get('password')).decode('utf-8')
        create_user = User(public_id=str(uuid.uuid4()),
                           username=user.get('username'),
                           email=user.get('email'),
                           password=hash_password,
                           admin=True)
        db.session.add(create_user)
        print('create user success')
    print('create users done')
    admin = User.query.filter_by(username='******').first()

    per_c = int(len(posts) / len(categorys))
    mod_post = len(posts) % len(categorys)
    print(per_c)
    print(mod_post)
    rm_list = []
    if mod_post != 0:
        for i in range(mod_post):
            rm_index = random.randint(0, len(posts) - 1)
            rm_obj = posts.pop(rm_index)
            rm_list.append(rm_obj)
    if rm_list:
        null_category = Category(name='null')
        db.session.add(null_category)
        for post in rm_list:
            create_post = Post(title=post,
                               body=post * 3,
                               category=null_category)
            db.session.add(create_post)
    cp = cut_post(posts, per_c)
    cc = yield_category()
    for cut_posts in cp:
        print(cut_posts)
        for c_name in cc:
            print(c_name)
            create_category = Category(name=c_name)
            db.session.add(create_category)
            for post in cut_posts:
                create_post = Post(title=post,
                                   body=post * 3,
                                   category=create_category,
                                   author=admin)
                db.session.add(create_post)
                print('create post success')
            break
    db.session.commit()
    print('done')
예제 #5
0
파일: users.py 프로젝트: akosourov/blog_api
def create_user():
    user_raw = request.get_json(force=True)
    user_cleaned, error = parse_validate_user_raw(user_raw)
    if error:
        return error_response(HTTP_400_BAD_REQUEST, error)
    user = User(username=user_cleaned['username'])
    db.session.add(user)
    try:
        db.session.commit()
        db.session.flush()
    except IntegrityError:
        return error_response(HTTP_400_BAD_REQUEST, 'User already exists')

    return success_response(HTTP_201_CREATED, {
        'id': user.id,
        'username': user.username
    })
예제 #6
0
def create_user(user):
    if not user.get('username') or not user.get(
            'email') or not user.get('password'):
        return {'error': 'invalid input', 'success': False}, 400
    new_user = User(username=user.get('username'),
                    email=user.get('email'),
                    password=user.get('password'))
    db.session.add(new_user)
    try:
        db.session.commit()
        created_user = {'username': new_user.username,
                        'email': new_user.email,
                        'image_file': new_user.image_file,
                        'id': new_user.id}
        return {'error': None, 'success': True,
                'result': created_user}, 201
    except Exception as e:
        print(e)
        return server_error_response()
def dev_check_token(request):
    '''
    For development
    If some methods login required  
    This function would check auth_token before when run login-required methods  
    '''
    auth_token = request.headers.get('DEV-API-KEY')
    if auth_token:
        result = User.auth_decode_token(auth_token)
        if isinstance(result, str):
            # token invalid or expired
            error_respon = {'status': 'fail', 'message': result}
            return error_respon, 401
        # token isvalid , get user info
        try:
            user = User.query.get(int(result))
            success_respon = {
                'status': 'success',
                'data': {
                    'user_id': user.id,
                    'username': user.username,
                    'active': user.active,
                    'admin': user.admin,
                    'created': user.created_time
                }
            }
            return success_respon, 200
        except Exception as e:
            # get user occur error
            error_respon = {'status': 'fail', 'message': e}
            return error_respon, 401
    else:
        # auth_token does noe exist
        error_respon = {
            'status': 'fail',
            'message': 'token does no exist , please login'
        }
        return error_respon, 401