Exemple #1
0
 def get(self, **kwargs):
     """GET method handler."""
     user_id = kwargs.get('user_id')
     user = User()
     return Response(json.dumps(UserResponse().dump(
         user.get(user_id)).data),
                     status=200,
                     mimetype='application/json')
Exemple #2
0
 def post(self, **kwargs):
     """POST method handler."""
     user_data = kwargs
     user = User(full_name=user_data.get('full_name'),
                 user_name=user_data.get('user_name'),
                 email_id=user_data.get('email_id'))
     user.add()
     return Response(json.dumps({
         'message':
         'user {0} added successfully'.format(user_data.get('user_name'))
     }),
                     status=200,
                     mimetype='application/json')
    def save_new_user(data):
        user = session.query(User).filter_by(username=data['username']).first()
        if not user:
            new_user = User(
                username=data['username'],
                password=data['password'],
                registered_on=datetime.datetime.utcnow()
            )

            UserService.save_changes(new_user)

            response_object = {
                'status': 'success',
                'message': 'Successfully registered.'
            }

            return response_object, 201

        else:
            response_object = {
                'status': 'fail',
                'message': 'User already exists. Please Log in.',
            }

            return response_object, 409
Exemple #4
0
def user_api():
    # get the auth token
    auth_header = request.headers.get('Authorization')
    if auth_header:
        try:
            auth_token = auth_header.split(" ")[1]
        except IndexError:
            responseObject = {
                'status': 'Fail',
                'message': 'Bearer token malformed.'
            }
            return make_response(jsonify(responseObject)), 401
    if auth_token:
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(user_id=resp).first()
            result = UserSchema().dump(user, many=False)
            return make_response(jsonify(result)), 200
        responseObject = {'status': 'Fail', 'message': resp}
        return make_response(jsonify(responseObject)), 401
    else:
        responseObject = {
            'status': 'Fail',
            'message': 'Provide a valid auth token.'
        }
        return make_response(jsonify(responseObject)), 403
Exemple #5
0
def verify_token(token):
    """ Verify user token """
    resp = User.decode_auth_token(token)
    if not isinstance(resp, str):
        user = User.query.filter_by(user_id=resp).first()
        if user:
            return True
    return False
def login():
    data = json.loads(request.data)
    user = User.objects(username=data['username']).first()

    if user is not None and user.verify_password(data['password']):
        login_user(user)
        return jsonify(success=True)

    return jsonify({'success': False}), 404
Exemple #7
0
def create_user():
    if request.method == 'POST':
        args = request.json
        password = args["password"]
        hashed_password = bcrypt.hashpw(password.encode('utf8'),
                                        bcrypt.gensalt())
        user = User(name=args["name"],
                    email=args["email"],
                    password=hashed_password,
                    role=UserRole.USER)
        UserDao.insert(user)
        return "OK"
def register_api():
    """ Creates new row in User table """
    # get the post data
    post_data = request.get_json()
    # Check if mail address is valid
    if not (validate_email(post_data.get('user_mail'))):
        responseObject = {
            'status': 'Fail',
            'message': "Please enter valid mail adress"
        }
        return make_response(jsonify(responseObject)), 200
    # Database process
    try:
        user_name = User.query.filter_by(
            user_name=post_data.get('user_name')).first()
        user_email = User.query.filter_by(
            email=post_data.get('user_mail')).first()
        # If user name already exits return Fail
        if (user_name or user_email):
            responseObject = {
                'status':
                'Fail',
                'message':
                '{} allready exist'.format(
                    'User name' if user_name else 'Email')
            }
            return make_response(jsonify(responseObject)), 200
        else:
            # create user
            user_name = post_data.get('user_name')
            email = post_data.get('user_mail')
            user_pwd = post_data.get('user_password')
            age = post_data.get('age')
            city = post_data.get('city')
            user = User(user_name, email, user_pwd, age, city)
            # add user to database
            db.session.add(user)
            db.session.commit()
            responseObject = {
                'status': 'Success',
                'message': "New user created"
            }
            return make_response(jsonify(responseObject)), 200
    except Exception as e:
        print(e)
        responseObject = {'status': 'Fail', 'message': 'Database error'}
        return make_response(jsonify(responseObject)), 503
Exemple #9
0
def logout_api():
    auth_header = request.headers.get('Authorization')
    if auth_header:
        try:
            auth_token = auth_header.split(" ")[1]
        except IndexError:
            responseObject = {
                'status': 'Fail',
                'message': 'Bearer token malformed.'
            }
            return make_response(jsonify(responseObject)), 401
    if auth_token:
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(user_id=resp).first()
            # Update login flag
            user.logged_in = False
            db.session.merge(user)
            db.session.commit()
            # mark the token as blacklisted
            blacklist_token = BlacklistToken(token=auth_token)
            try:
                # insert the token
                db.session.add(blacklist_token)
                db.session.commit()
                responseObject = {
                    'status': 'Success',
                    'message': 'Successfully logged out.'
                }
                return make_response(jsonify(responseObject)), 200
            except Exception as e:
                responseObject = {'status': 'Fail', 'message': e}
                return make_response(jsonify(responseObject)), 401
        else:
            responseObject = {'status': 'Fail', 'message': resp}
            return make_response(jsonify(responseObject)), 401
    else:
        responseObject = {
            'status': 'Fail',
            'message': 'Provide a valid auth token.'
        }
        return make_response(jsonify(responseObject)), 403
def update_user():
    """ Updates user related informations """
    # get the auth token
    updated_user = request.get_json()
    auth_header = request.headers.get('Authorization')
    if auth_header:
        try:
            auth_token = auth_header.split(" ")[1]
        except IndexError:
            responseObject = {
                'status': 'Fail',
                'message': 'Bearer token malformed.'
            }
            return make_response(jsonify(responseObject)), 401
    if auth_token:
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(user_id=resp).first()
            user.user_name = updated_user.get('user_name')
            user.email = updated_user.get('email')
            user.age = updated_user.get('age')
            user.city = updated_user.get('city')
            db.session.merge(user)
            db.session.commit()
            result = UserSchema().dump(user, many=False)
            responseObject = {
                'status': 'Success',
                'message': 'Successfully updated!',
                'user': result
            }
            return make_response(jsonify(responseObject)), 200
        responseObject = {
            'status': 'Fail',
            'message': resp
        }
        return make_response(jsonify(responseObject)), 401
    else:
        responseObject = {
            'status': 'Fail',
            'message': 'Provide a valid auth token.'
        }
        return make_response(jsonify(responseObject)), 403
Exemple #11
0
def create_user(db: Session, user: UserSchema):
    db_user = User(email=user.email)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Exemple #12
0
 def load_user(user_id):
     """Loader used by the login manager"""
     return User.objects(uid=user_id).exclude('encrypt_pw').first()