def post(self):
     # insert into db
     json_data = request.get_json(force=True)
     if not json_data:
         return {
             'status': 'error',
             'message': 'No input data provided'
         }, 400
     # Validate and deserialize input
     data, errors = user_schema.load(json_data)
     if errors:
         return errors, 422
     user = User.query.filter_by(email=data['email']).first()
     if user:
         return {
             'status': 'error',
             'message': 'Oops! Email address already exists.'
         }, 400
     passw = bcrypt.generate_password_hash(
         json_data['password']).decode('utf-8')
     user = User(username=json_data['username'],
                 email=json_data['email'],
                 password=passw)
     db.session.add(user)
     db.session.commit()
     resp = user_schema.dump(user).data
     return {"status": 'success', 'data': resp}, 201
Exemple #2
0
    def put(self, username):
        user = get_jwt_identity()

        password = request.json['password']
        allowed_fields = ('username', 'email', 'admin', 'password')

        if UserModel.objects(username=user).first().admin:
            user = UserModel.objects(username=username).first_or_404()

            for field in allowed_fields:
                fieldValue = request.json.get(field)
                if fieldValue is not None:
                    if field == 'password':
                        if password is not None:
                            setattr(
                                user, field,
                                str(
                                    bcrypt.generate_password_hash(
                                        password).decode('utf-8')))
                            user.save()
                    else:
                        setattr(user, field, fieldValue)
                    user.save()

            return make_response(
                jsonify({
                    "status": "success",
                    "message": "resource updated successfully"
                }), 200)

        return Response.insufficient_permissions()
Exemple #3
0
def new_user(data):

    first_name = data['first_name']
    last_name = data['last_name']
    username = data['username']
    password = data['password']
    email = data['email']
    public_id = str(uuid4())
    
    hashed_password = bcrypt.generate_password_hash(password)
    new_user = User(first_name = first_name, last_name = last_name, username = username, \
        password = hashed_password, email = email, public_id = public_id, is_logged_in = True)
    try:
        db.session.add(new_user)
        db.session.commit()

        access_token = generate_access_token(public_id)
        refresh_token = generate_refresh_token(public_id)
        res = make_response({ 'message' : 'New user created!' })
        res.set_cookie('x-access-token', value = access_token, httponly = True, samesite = \
            None, expires = datetime.utcnow() + timedelta(minutes = 30))
        res.set_cookie('x-refresh-token', value = refresh_token, httponly = True, samesite = \
            None, expires = datetime.utcnow() + timedelta(weeks = 2), path = '/user/login/')
        return res, 201
    except:
        return { 'message' : 'There was an issue creating a new user!' }, 400
Exemple #4
0
def add_lawyer_judge(json_obj):
    try:
        y = json_obj
        user_type = y['usr_type']
        username = y["username"]
        name = y["name"]
        passw = y["password"]
        address = y['usr_addr']
        hashed_password = bcrypt.generate_password_hash(passw).decode('utf-8')
        usr = User.query.filter_by(username=username).first()
        if(usr):
            return json.dumps({"add_status": "0", "err_msg": "Username Already Exists"})
        user = User(username=username, address=address, name=name,
                    password=hashed_password, user_type=user_type)

        db.session.add(user)
        db.session.commit()
        ret_val = {}
        ret_val['add_status'] = "1"
        ret_val['err_msg'] = "The account of has been created successfully!!"
        ret_json = json.dumps(ret_val)
        return ret_json

    except:
        db.session.rollback()
        ret_val = {}
        ret_val['add_status'] = "0"
        ret_val['err_msg'] = "Sorry!!We were unable to create the account!! The username probably exists !!"
        ret_json = json.dumps(ret_val)
        return ret_json
Exemple #5
0
    def post(self):
        args = parser.parse_args()

        user = User.objects(username__iexact=args['username']).first()
        if user:
            abort(409, message="Username already exists.")

        user = User(username=args['username'])
        user.password = bcrypt.generate_password_hash(args['password'])

        if args['type'] == 'individual':
            user.user_type = args['type']
            user.user_profile = Individual()
        elif args['type'] == 'group':
            user.user_type = args['type']
            user.user_profile = Group()

        user.save()

        response = {
            'username': user.username,
            'email': user.email,
            'type': user.user_type,
            'created_at': str(user.created_at),
            'updated_at': str(user.updated_at)
        }

        return response
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    user_table = op.create_table(
        'user', sa.Column('_id', sa.Integer(), nullable=False),
        sa.Column('email', sa.String(length=300), nullable=False),
        sa.Column('name', sa.String(length=300), nullable=False),
        sa.Column('password', sa.String(), nullable=False),
        sa.Column('authenticated', sa.Boolean(), nullable=True),
        sa.PrimaryKeyConstraint('_id'))
    op.create_table(
        'event', sa.Column('_id', sa.Integer(), nullable=False),
        sa.Column('user_id', sa.Integer(), nullable=False),
        sa.Column('timestamp_begin', sa.DateTime(), nullable=True),
        sa.Column('timestamp_end', sa.DateTime(), nullable=True),
        sa.Column('title', sa.String(length=300), nullable=True),
        sa.Column('description', sa.String(length=300), nullable=True),
        sa.ForeignKeyConstraint(
            ['user_id'],
            ['user._id'],
        ), sa.PrimaryKeyConstraint('_id'))
    # ### end Alembic commands ###
    op.bulk_insert(
        user_table,
        [{
            '_id': 1,
            'email': '*****@*****.**',
            'name': 'admin',
            'password': bcrypt.generate_password_hash('admin').decode('utf-8'),
        }])
Exemple #7
0
    def post(self):
        keys = ('username', 'password', 'email')

        rjson = request.json
        if rjson is None: return Response.missing_parameters()
        if all(elem in rjson for elem in keys):
            if '' in rjson.values():
                return Response.invalid_arguments()

            if User.objects(username=rjson['username']):
                return Response.user_exists()
            if User.objects(email=rjson['email']):
                return Response.email_taken()

            User(password=bcrypt.generate_password_hash(rjson['password']),
                 username=rjson['username'],
                 email=rjson['email']).save()

            return make_response(
                jsonify({
                    "status": "success",
                    "message": "user successful created"
                }), 201)

        else:
            return Response.missing_parameters()
        return Response.unexpected_error()
def register():
    """POST users/register

    Desc: Registers a new user
          Validates email and password used to register
          Ensures new accounts are not duplicates

    Returns:
        201: authentication token
        401: validation error, unauthorized access
        409: duplicate account, conflict with database
    """
    req = request.get_json()
    is_valid, errors = valid_registration(req)
    if not is_valid:
        return errors, 401

    user = User.objects(email=req['email']).first()
    if user:
        return {
            'email': 'Account could not be created. User already exists.',
            'password': ''
        }, 409

    new_user = User(**req)
    pw_hash = bcrypt.generate_password_hash(new_user.password).decode('utf-8')
    new_user.password = str(pw_hash)
    new_user.save()

    access_token = create_access_token(identity=new_user)
    return {'token': access_token}, 201
Exemple #9
0
    def post(self):
        json_data = load_json()

        # get the email and password
        try:
            email = json_data['email']
            password = json_data['password']
            confirmed_password = json_data['confirmed_password']
        except KeyError:
            return {'message': 'request must include email, password, and confirmed_password'}, 422

        # check if the user exists
        test_user = UserModel.query.filter_by(email=email).first()
        if test_user:
            return {'message': f"There is already an account associated with {email}."}, 403

        # check if the passwords match
        if password != confirmed_password:
            return {'message': 'Passwords do not match.'}, 409

        # hash the password
        hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')

        # create a user and add it to the database
        new_user = UserModel(email=email, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()

        return {'status': 'success'}, 201
Exemple #10
0
 def __init__(self, username, email, is_admin, password):
     self.username = username
     self.email = email
     self.is_admin = is_admin
     self.password = bcrypt.generate_password_hash(
         password, app.config.get('BCRYPT_LOG_ROUNDS')
     ).decode()
Exemple #11
0
 def __init__(self, email, username, password, admin=False):
     self.email = email
     self.username = username
     self.password = bcrypt.generate_password_hash(
         password, app.config.get('BCRYPT_LOG_ROUNDS')
     ).decode()
     self.registered_on = datetime.datetime.now()
     self.admin = admin
 def change_password(old_password, new_password):
     """
     reset old_password to new_password
     """
     new_password = bcrypt.generate_password_hash(
         new_password, app.config.get('BCRYPT_LOG_ROUNDS')).decode('UTF-8')
     old_password = new_password
     return old_password
Exemple #13
0
def signup():
    data = request.get_json()
    hashed_password = bcrypt.generate_password_hash(data["password"]).decode("utf-8")
    new_user = User(username=data["username"], email=data["email"],
                    password=hashed_password)
    db.session.add(new_user)
    db.session.commit()

    return jsonify({"Message" : "A new user has been created!"})
 def __init__(self, public_id, email, password, first_name, last_name):
     '''initialize with email'''
     self.public_id = public_id
     self.email = email
     self.password = bcrypt.generate_password_hash(
         password, app.config.get('BCRYPT_LOG_ROUNDS')).decode('UTF-8')
     self.first_name = first_name
     self.last_name = last_name
     self.registered_on = datetime.datetime.now()
Exemple #15
0
 def __init__(self, first_name, last_name, email, phone, password, active):
     self.uuid = str(uuid.uuid4())
     self.first_name = first_name
     self.last_name = last_name
     self.email = email
     self.phone = phone
     self.password = bcrypt.generate_password_hash(
         password, current_app.config["BCRYPT_LOG_ROUNDS"]).decode()
     self.active = active
Exemple #16
0
 def __init__(self, username, email, password, currency, isadmin=False):
     self.username = username
     self.email = email
     self.password = bcrypt.generate_password_hash(password).decode("utf8")
     self.main_currency = currency
     if self.role is None:
         if isadmin:
             self.role = Role.query.filter_by(name="Admin").first()
         else:
             self.role = Role.query.filter_by(default=True).first()
Exemple #17
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('set_entry'))
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user = User(username=form.username.data, email=form.email.data, password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created! You are now able to log in', 'success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Exemple #18
0
def update_user(id):
    try:
        nuevo_usuario = jloads(request.data)
        nuevo_usuario["contrasena"] = bcrypt.generate_password_hash(
            nuevo_usuario["contrasena"])
        examiner = helpers.Examiner(id=id,
                                    model=Usuario,
                                    schema=usuario_schema,
                                    unwanted_columns=['id'],
                                    json_data=nuevo_usuario)
        return helpers.update_row(examiner)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
Exemple #19
0
def register():
    form = RegistrationForm()
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    if form.validate_on_submit():
        password_hash = bcrypt.generate_password_hash(form.password.data)
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=password_hash)
        db.session.add(user)
        db.session.commit()
        flash('You account has been created successfully', 'success')
        return redirect(url_for('user.login'))
    return render_template("register.html", title="Register", form=form)
Exemple #20
0
def register_user():

    # Get data from request (user's details)
    data = request.get_json()

    # Encrypt the user's password
    hash_password = bcrypt.generate_password_hash(data['password'])

    # Create public id for the user
    public_user_id = str(uuid.uuid4())

    # Check to see if the email has been already used by another user
    email_exists = db.session.query(
        User.email).filter_by(email=data['email']).scalar()

    # Check for invalid email
    if check_email(data['email']) == False:
        return jsonify({'message': 'Invalid email!'})
    else:
        #  Check to see if the email provied is not used by another user
        if not email_exists:

            # Create user object
            new_user = User(public_id=public_user_id,
                            first_name=data['first_name'],
                            last_name=data['last_name'],
                            email=data['email'],
                            password=hash_password)

            # Add the user to database
            db.session.add(new_user)
            db.session.commit()

            # Create a token for the registered user
            token = jwt.encode({'public_id': new_user.public_id},
                               app.config['SECRET KEY'])

            # Return the created token and public id to the user
            # Note: All users must use their public id and token to access and use this api
            return jsonify({
                'message': 'Acount has been created!',
                'public_id': new_user.public_id,
                'api-token': token.decode('UTF-8')
            })
        else:
            return jsonify({
                'message':
                'This email: ' + data['email'] + ' is already registered'
            })
Exemple #21
0
def create_user():

    data = request.get_json()
    hashed_password = bcrypt.generate_password_hash(
        data['password']).decode('utf-8')

    new_user = User(public_id=secrets.token_hex(16),
                    name=data['name'],
                    password=hashed_password,
                    admin=False)

    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': 'New user created!'})
Exemple #22
0
 def setUp(self):
     basedir = os.path.abspath(os.path.dirname(__file__))
     app.config['TESTING'] = True
     app.config['WTF_CSRF_ENABLED'] = False
     app.config['DEBUG'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
         os.path.join(basedir, 'test.db')
     self.username = '******'
     self.password = self.confirm = 'test_password'
     self.test_key = 'test_key'
     self.test_key_2 = 'test_key_2'
     self.test_value = 'test_value'
     self.hashed_password = bcrypt.generate_password_hash(
         self.password).decode('utf-8')
     self.app = app.test_client()
     db.create_all()
def login():
    username = request.json["username"]
    password = request.json["password"]
    hashed_password = bcrypt.generate_password_hash(password).decode("utf-8")
    user = User(username=username, password=hashed_password)

    token = secrets.token_hex(20)
    resp = {
        "token": token,
        "user": user.serialize
    }

    if user:
        return jsonify(resp)
    else:
        return abort(404)
def create_user():
    data = request.get_json()
    user = User.query.filter_by(email=data['email']).first()
    if user:
        return {'message': 'Email already registered'}, 400

    temp_pass = data['password']
    hashed_password = bcrypt.generate_password_hash(temp_pass).decode(
        'utf-8')  ## Look into switching this hashing to bcrypt

    new_user = User(public_id=str(uuid.uuid4()),
                    email=data['email'].lower(),
                    password=hashed_password)
    db.session.add(new_user)
    db.session.commit()

    return {'message': 'New user created!'}
Exemple #25
0
 def post(self):
     registerData = {
         'username': request.json['username'],
         'password': request.json['password'],
         'email': request.json['email']
     }
     if not registerData['username'] or not registerData[
             'password'] or not registerData['email']:
         return jsonify(message='Missing parameters')
     if User.objects(username=registerData['username']).first():
         return jsonify(message='This user already exist!')
     if User.objects(email=registerData['email']).first():
         return jsonify(
             message='This email address is already used, please use other')
     User(password=bcrypt.generate_password_hash(registerData['password']),
          username=registerData['username'],
          email=registerData['email']).save()
     return jsonify(message='User successful created!')
Exemple #26
0
def register():
	name = request.json.get('name')
	password = request.json.get('password')
	if not name or not password:
		return jsonify(error="Missing name/password")

	user = User.query.filter_by(name=name).first()
	if user:
		return jsonify(error=f'Sorry, the name {name} has been taken.')
	
	hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
	user = User(name=name, password=hashed_password)
	db.session.add(user)
	db.session.commit()

	token = jwt.encode({'name': name, 'password': password, 'exp': datetime.datetime.utcnow()
		+ datetime.timedelta(days=session_days)}, current_app.config['SECRET_KEY'])
	return jsonify(token=token.decode('utf-8'))
Exemple #27
0
def test_login_incorrect_password(client):
    user_data = {
        "first_name": "TestFirstName",
        "last_name": "TestLastName",
        "email": "*****@*****.**",
        "password": "******"
    }
    pw_hash = bcrypt.generate_password_hash(
        user_data["password"]).decode('utf-8')
    new_user = User(**user_data)
    new_user.password = str(pw_hash)
    new_user.save()
    res = client.post('/users/login',
                      json={
                          "email": user_data["email"],
                          "password": user_data["password"] + "!"
                      })
    assert res.status_code == 401
Exemple #28
0
    def test_user_login(self, username=None, password=None):
        """ Tests the authentication endpoint for users """
        if not username and not password:
            user_creds = copy.copy(self.user_creds)
            user_creds["password"] = bcrypt.generate_password_hash(
                self.user_creds["password"]).decode("utf-8")
            user = User.create(**user_creds)

        url = "/auth/login"
        r = self.client.post(url,
                             json={
                                 "username":
                                 username or self.user_creds["username"],
                                 "password":
                                 password or self.user_creds["password"]
                             })
        self.assertEqual(r.status_code, 200)

        return r.json
Exemple #29
0
def new_user(data):

    first_name = data['first_name']
    last_name = data['last_name']
    username = data['username']
    password = data['password']
    email = data['email']
    public_id = str(uuid4())
    
    hashed_password = bcrypt.generate_password_hash(password)
    new_user = User(first_name = first_name, last_name = last_name, username = username, \
        password = hashed_password, email = email, public_id = public_id, is_logged_in = True)
    try:
        db.session.add(new_user)
        db.session.commit()
        access_token = generate_access_token(public_id)
        return { 'token' : access_token }, 201
    except:
        return { 'message' : 'There was an issue creating a new user!' }, 400
    def post(self):
        args = parser.parse_args()
        individual = Individual.objects(id_no=args['id_no']).first()
        if individual:
            abort(409, message="An individual with that id number already exists.")

        individual = Individual(id_no=args['id_no'], name=args['name'])
        individual.password = bcrypt.generate_password_hash(args['password'])

        if args['image'] and validate_file(args['image'].filename):
            individual.image.put(args['image'], content_type=args['image'].content_type)

        individual.save()

        response = {
            'id_no': individual.id_no,
            'name': individual.name,
            'image': str(individual.image.grid_id) if individual.image.grid_id else None
        }

        return response, 201
Exemple #31
0
    def put(self):
        json_data = load_json()

        # get relevant data
        try:
            email = json_data['email']
            old_password = json_data['old_password']
            new_password = json_data['new_password']
        except KeyError:
            return {'message', 'email, old_password, and new_password are required'}, 422

        validated, user, code = validate_user(email, old_password)

        if not validated:
            return user, code

        # change the password
        user.password = bcrypt.generate_password_hash(new_password).decode('utf-8')
        db.session.commit()

        return {'status': 'success'}, 201
Exemple #32
0
    def post(self):
        args = parser.parse_args()
        group = Group.objects(name__iexact=args['name']).first()
        if group:
            abort(409, message="A group with that name already exist.")

        group = Group(name=args['name'], full_name=args['full_name'])
        group.password = bcrypt.generate_password_hash(args['password'])

        if args['image'] and validate_file(args['image'].filename):
            group.image.put(args['image'], content_type=args['image'].content_type)

        group.save()

        response = {
            'name': group.name,
            'full_name': group.full_name,
            'image': str(group.image.grid_id) if group.image.grid_id else None
        }

        return response, 201
Exemple #33
0
    def put(self, username):
        if not username:
            abort(404, message="A username is required.")

        args = auth_parser.parse_args()
        user = User.objects(username__iexact=username).first()

        if not user:
            abort(404, message="Username does not exist.")

        user.password = bcrypt.generate_password_hash(args['password'])

        user.save()

        response = {
            'username': user.username,
            'email': user.email,
            'type': user.user_type,
            'created_at': str(user.created_at),
            'updated_at': str(user.updated_at)
        }

        return response
Exemple #34
0
    def test_team_role_creation(self):
        """ Tests the Team Role post endpoint (for creating/updating user
            roles)
        """
        logged_in = self.test_user_login()
        user, token = logged_in["user"]["id"], logged_in["token"]
        team = Team.create(name="Test Team")
        edge = UserAssignedToCoreVertex.create(user=user,
                                               team=team.id,
                                               role="admin")

        second_user_pass = "******"
        second_user_pass_hash = bcrypt.generate_password_hash(
            second_user_pass).decode("utf-8")
        second_user = User.create(username="******",
                                  email="test",
                                  password=second_user_pass_hash,
                                  fullName="test")

        url = f"/team/{team.id}/roles"

        # No roles to lead test (by admin) - success
        r = self.client.post(url + f"?user={second_user.id}",
                             json={"role": "lead"},
                             headers={"Authorization": "Bearer %s" % token})
        self.assertEqual(r.status_code, 200, r.json)
        self.assertEqual(r.json["role"], "lead", r.json)

        # Lead to admin test (by lead) - fail
        logged_in = self.test_user_login(username=second_user.username,
                                         password=second_user_pass)
        user, token = logged_in["user"]["id"], logged_in["token"]
        r = self.client.post(url,
                             json={"role": "admin"},
                             headers={"Authorization": "Bearer %s" % token})
        self.assertEqual(r.status_code, 403, r.json)
Exemple #35
0
 def hash_password(self, password):
     self.password_hash = bcrypt.generate_password_hash(password)