Esempio n. 1
0
def user():
    ''' route read user '''
    if request.method == 'GET':
        query = request.args
        data = db.users.find_one({'email': query['email']}, {"_id": 0})
        if bool(data):
            user = {}
            # for i in data:
            user['name'] = data['name']
            user['email'] = data['email']
            # data = list(db.users.find())
        # data = {'data': data}

            return jsonify({'ok': True, 'data': user}), 200
        else:
            return jsonify({'ok': False, 'message': 'No user exist with this mail'}), 400

    data = request.get_json()
    if request.method == 'DELETE':
        if data.get('email', None) is not None:
            db_response = db.users.delete_one({'email': data['email']})
            if db_response.deleted_count == 1:
                response = {'ok': True, 'message': 'record deleted'}
            else:
                response = {'ok': True, 'message': 'no record found'}
            return jsonify(response), 200
        else:
            return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400

    if request.method == 'PATCH':
        # if data.get('query', {}) != {}:
        data = request.get_json()

        user = db.users.find_one({'email': data['email']}, {"_id": 0})

        if 'password' in data.keys() and 'name' in data.keys():
            data['password'] = flask_bcrypt.generate_password_hash(
                data['password'])
            newvalues = {
                "$set": {"name": data['name'], "password": data['password']}}
        else:
            if 'password' in data.keys():
                data['password'] = flask_bcrypt.generate_password_hash(
                    data['password'])
                newvalues = {"$set": {"password": data['password']}}
            if 'name' in data.keys():
                newvalues = {"$set": {"name": data['name']}}

        if bool(user):
            db.users.update_one(user, newvalues)
            return jsonify({'ok': True, 'message': 'User updated successfully!'}), 200
        else:
            response = {'ok': True, 'message': 'no record found'}
            return jsonify(response)
    else:
        return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 2
0
def register():
    
    form = RegisterForm(request.form)
    current_app.logger.info(request.form)

    if request.method == "POST" and form.validate() == False:
        current_app.logger.info(form.errors)
        return "Registration Error"

    elif request.method == "POST" and form.validate():
        email = request.form['email']
        username = request.form['username']

        # generate password hash
        password_hash = flask_bcrypt.generate_password_hash(request.form['password'])
        
        user = User(email, password_hash, True, username)

        try:
            user.save()
            if login_user(user, remember="no"):
                flash("Logged in!")
                return redirect(request.args.get('next') or '/jobs')
            else:
                flash("Unable to log you in")
        except:
            flash("Unable to register with that email address")
            current_app.logger.error("Error on registration - possible duplicate emails")

    return render_template('forms/register.html', form = form)
Esempio n. 3
0
def register():
    register_form = forms.SignupForm(request.form)
    current_app.logger.info(request.form)
    if request.method == 'POST' and not register_form.validate():
        current_app.logger.info(register_form.errors)
        return '注册失败!'
    elif request.method == 'POST' and register_form.validate():
        email = request.form['email']
        password_hash = flask_bcrypt.generate_password_hash(
            request.form['password'],
        )
        # Prepare User with register info from form
        user = User(email, password_hash)

        try:
            user.save()
            if login_user(user, remember='no'):
                flash('登录成功!')
                return redirect('/game')
            else:
                flash('登录失败!')
        except:
            flash('无法注册此电子邮箱地址!')
            current_app.logger.error(
                'Error on Registration - possible duplicate emails.'
            )

    # Prepare registration form
    template_data = {'form': register_form}
    return render_template('/auth/register.html', **template_data)
Esempio n. 4
0
def signup_user():
    from app.data.user_roles import get_role_by_code
    rolecode = request.values.get('rolecode')
    user_role = get_role_by_code(rolecode)

    if (user_role[0]):  #check if its a valid code
        username = request.values.get('username').lower()
        password = request.values.get('password')
        password_hash = flask_bcrypt.generate_password_hash(password)

        new_id = User.query[-1].id + 1

        u = User(username=username,
                 password_hash=password_hash,
                 id=new_id,
                 role=user_role[1])

        try:
            db_session_login.add(u)
            db_session_login.commit()
        except:
            return ('That username seems to already exist.')
        return ('success')
    else:
        return ('Failed: Invalid code')
Esempio n. 5
0
def register():
    form = SignupForm()
    if form.validate_on_submit():
        email = request.form['email']
        password = request.form['password']

        # create password hash
        password_hash = flask_bcrypt.generate_password_hash(password)

        # prepare user
        user = Users(email=email, password=password_hash)

        try:
            db.session.add(user)
            db.session.commit()
            if login_user(user, remember='no'):
                flash('Account Created & Logged in')
                return redirect('/')
            else:
                flash('Unable to login')
        except:
            flash('Unable to register with given email address')
            current_app.logger.error('Error on registeration - possible duplicate emails')

    return render_template('/auth/register.html', form=form)
Esempio n. 6
0
def register():
	register_form = forms.SignupForm(request.form)
	current_app.logger.info(request.form)
	error = ''
	if request.method == 'POST' and False == register_form.validate():
		error = "Registration error"

	elif request.method == 'POST' and register_form.validate():
		email = request.form['email']

		if u'CREATOR' in request.form['user_role']:
			isAdmin = True
		else:
			isAdmin = False

		password_hash = flask_bcrypt.generate_password_hash(request.form['password'])

		user = User(email=email, password=password_hash, admin=isAdmin)

		try:
			user.save()
			if login_user(user, remember=False):
				return redirect('/')
			else:
				error = "Unable to log in"
		except:
			error = "Error on registration - possible duplicate emails"

	data = {
		'form': register_form,
		'error': error
	}

	return render_template("/auth/register.html", **data)
Esempio n. 7
0
def register():
    register_form = forms.SignupForm(request.form)
    current_app.logger.info(request.form)
    error = ''
    if request.method == 'POST' and not register_form.validate():
        error = "Registration error"

    elif request.method == 'POST' and register_form.validate():
        username = request.form['username']

        if u'CREATOR' in request.form['user_role']:
            isAdmin = True
        else:
            isAdmin = False

        password_hash = flask_bcrypt.generate_password_hash(
            request.form['password'])

        user = User(username=username, password=password_hash, admin=isAdmin)

        try:
            user.save()
            if login_user(user, remember=False):
                return redirect('/')
            else:
                error = "Unable to log in"
        except:
            error = "Error on registration - possible duplicate logins"

    data = {'form': register_form, 'error': error}

    return render_template("auth/register.html", **data)
Esempio n. 8
0
def register():
    first_name = request.get_json()['first_name']
    last_name = request.get_json()['last_name']
    email = request.get_json()['email']
    password = flask_bcrypt.generate_password_hash(
        request.get_json()['password']).decode('utf-8')
    created = datetime.utcnow()

    user = Users.query.filter_by(email=email).first()
    if not user:
        data_user = Users(first_name=first_name,
                          last_name=last_name,
                          email=email,
                          password=password,
                          created=created)
        db.session.add(data_user)
        db.session.commit()

    user = Users.query.filter_by(email=email).first()
    result = {
        'first_name': user.first_name,
        'last_name': user.last_name,
        'email': user.email,
        'password': user.password,
        'created': user.created
    }

    return jsonify({'result': result})
Esempio n. 9
0
def register():
    data = validate_user(request.get_json())
    if data['ok']:
        data = data['data']
        data['password'] = flask_bcrypt.generate_password_hash(
            data['password']).decode('utf-8')
        user = Users(login=data['login'],
                     email=data['email'],
                     password=data['password'],
                     role=data['role'])
        db.session.add(user)
        db.session.commit()
        access_token = create_access_token(identity=user.json())
        refresh_token = create_refresh_token(
            identity=user.json())  # Why it set
        return jsonify({
            'ok': True,
            'access_token': access_token,
            'refresh_token': refresh_token,
            'user': user.json()
        }), 200
    else:
        return jsonify({
            'ok':
            False,
            'message':
            'Bad request parameters: {}'.format(data['message'])
        }), 400
Esempio n. 10
0
def register():
    ''' register user endpoint '''
    data = request.get_json()
    if 'password' in data:
        data['password'] = flask_bcrypt.generate_password_hash(
            data['password']).decode('utf-8')
        del data['netId']
        if db.put(data):
            return jsonify({
                'ok': True,
                'message': 'User created successfully!'
            }), 200
        else:
            return jsonify({
                'ok':
                False,
                'message':
                'Bad request parameters: {}'.format(data['message'])
            }), 400
    else:
        return jsonify({
            'ok':
            False,
            'message':
            'Bad request parameters: {}'.format(data['message'])
        }), 400
Esempio n. 11
0
def register():
    ''' register user endpoint '''
    data = validate_user(request.get_json())
    if data['ok']:
        data = data['data']
        password = data['password']
        data['password'] = flask_bcrypt.generate_password_hash(
            data['password'])
        user = db.users.find_one({'email': data['email']}, {"_id": 0})
        # LOG.debug(user)
        if bool(user):
            return jsonify({'ok': False, 'message': 'User already exist with same email'}), 400
        else:
            db.users.insert_one(data)
            user = {}
            user['name'] = data['name']
            del data['name']
            del data['_id']
            data['password'] = password
            access_token = create_access_token(identity=data)
            refresh_token = create_refresh_token(identity=data)
            data['token'] = access_token
            data['refresh'] = refresh_token
            del data['password']
            data['name'] = user['name']
            # LOG.debug(data)
            return jsonify({'ok': True, 'data': data, 'message': 'User created successfully!'}), 200
    else:
        return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 12
0
 def __init__(self, email, first_name, last_name, password, admin=False):
     self.email = email
     self.first_name = first_name
     self.last_name = last_name
     self.password = flask_bcrypt.generate_password_hash(password).decode(
         'utf-8')
     self.registered_on = datetime.datetime.now()
     self.admin = admin
Esempio n. 13
0
def register():
    data = validate_user(request.get_json())
    if data['ok']:
        data = data['data']
        data['password'] = flask_bcrypt.generate_password_hash(
            data['password'])
        mongo.db.users.insert_one(data)
        return jsonify({'ok': True, 'message': 'User created successfully!'}), 200
    else:
        return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 14
0
def register():
    register_form = forms.SignupForm(request.form)
    current_app.logger.debug(request.form)
    error_message = ''
    if request.method == 'POST':
        if not register_form.validate():
            current_app.logger.debug(register_form.errors)
            error_message = '密码不一致'
            current_app.logger.debug('密码不一致!')
        else:
            #if not recaptchaCheck(request.form['g-recaptcha-response']):
            #return '请点击人机身份验证!'
            # Prepare User with register info from form
            access_code_obj = AccessCode.from_access_code(
                request.form['access_code'], )
            if access_code_obj is None:
                error_message = '邀请码不正确'
                current_app.logger.debug('邀请码不正确!')
                current_app.logger.debug('wrong access code!')
            else:
                # If we get access code correctly
                reg_timestamp = datetime.datetime.now()
                user = User(
                    user_id=str(uuid.uuid4()),  # generate unique user id
                    email=request.form['email'],
                    username=request.form['username'],
                    password=flask_bcrypt.generate_password_hash(
                        request.form['password'], ),
                    role=access_code_obj.role,
                    register_t=reg_timestamp,
                    expire_t=reg_timestamp +
                    datetime.timedelta(days=access_code_obj.expiration, ),
                    last_active_t=reg_timestamp,
                )
                current_app.logger.debug('Try to save and login!')
                #try:
                user.save_register()
                current_app.logger.debug('Save new user completed!')
                if login_user(user, remember=True):
                    current_app.logger.debug('Login successful!')
                    current_app.logger.debug('user %s' % user.user_id)
                    return redirect('/userGameStatuses')
                else:
                    error_message = '登录失败'
                    current_app.logger.debug('Login successful!')
                    current_app.logger.debug('登录失败!')
            #except:
            #    current_app.logger.error(
            #        'Error on Registration - possible duplicate emails.'
            #    )

    # Prepare registration form
    template_data = {'form': register_form, 'error_message': error_message}
    return render_template('/auth/register.html', **template_data)
Esempio n. 15
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("main.index"))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        sample_password = flask_bcrypt.generate_password_hash(b"aaaa")
        if user is None:
            user = User(password_hash=sample_password)
        if not user.check_password(form.password.data):
            flash(_("Invalid username or password"))
            return redirect(url_for("auth.login"))
        user_otp = OTP.query.filter_by(user_id=user.did).first()
        remember_me = form.remember_me.data

        webauthn = Webauthn.query.filter_by(user_id=user.did).first()
        if webauthn and webauthn.is_enabled is True:
            token = user.set_valid_credentials(remember_me)
            response = make_response(
                render_template("webauthn/login_with_webauthn.html")
            )
            response.set_cookie(
                "token",
                value=token,
                max_age=90,
                secure=Config.HTTPS_ENABLED,
                httponly=True,
                samesite="Strict",
            )
            return response
        if user_otp and user_otp.is_valid == 1:
            user_otp.remaining_attempts = 3
            db.session.add(user_otp)

            form = CheckOTPCode()
            token = user.set_valid_credentials(remember_me)
            response = make_response(
                render_template("twofa/login_with_twofa.html", form=form)
            )
            response.set_cookie(
                "token",
                value=token,
                max_age=90,
                secure=Config.HTTPS_ENABLED,
                httponly=True,
                samesite="Strict",
            )
            db.session.commit()
            return response
        login_user(user, remember=form.remember_me.data)
        next_page = get_next_page(request.args.get("next"))
        return redirect(next_page)
    return render_template("auth/login.html", title=_("Sign In"), form=form)
Esempio n. 16
0
 def setUp(self):
     self.app_context = app.app_context()
     self.app_context.push()
     self.app = app.test_client()
     self.email = '*****@*****.**'
     self.password = '******'
     pwhash = flask_bcrypt.generate_password_hash(self.password)
     u = User(email=self.email,
             password=pwhash
         )
     db.session.add(u)
     db.session.commit()
Esempio n. 17
0
 def create_user(email, password, first_name, last_name):
     """
     Create an user in the database
     :param email: String, user email. Ie, "*****@*****.**"
     :param password: String, user's password. Ie, "my-password"
     :param first_name: String, user's first name. Ie, "Andres"
     :param last_name: String, user's last name. Ie, "Andres"
     """
     user = User(
         email=email,
         password=flask_bcrypt.generate_password_hash(password),
         first_name=first_name,
         last_name=last_name
     )
     user.save()
Esempio n. 18
0
def change_password():
    error = None
    old_password = request.form['oldPassword']
    new_password = flask_bcrypt.generate_password_hash(request.form['newPassword'], rounds=12)
    #Retrieve logged-in doctor document, to populate his profile page
    doctor_doc = Users.objects.get(id=current_user.get_id())
    if not flask_bcrypt.check_password_hash(doctor_doc["password"], old_password):
        error = 'Fjalekalimi gabim! Kerkesa juaj per ndryshim te fjalekalimit nuk u ekzekutua.'
        return render_template('doc_profile/doc_profile.html', message=error,type="error", doctor_doc=doctor_doc)
    elif request.form['newPassword'] != request.form['passwordConfirm']:
        error = 'Fjalekalimet nuk jane te njejta! Kerkesa juaj per ndryshim te fjalekalimit nuk u ekzekutua.'
        return render_template('doc_profile/doc_profile.html', message=error, type="error", doctor_doc=doctor_doc)
    else:
        doctor_doc.update(password=new_password)
        success = "Ndryshimi fjalekalimit u krye me sukses!"
        return render_template('doc_profile/doc_profile.html', message=success, type="success", doctor_doc=doctor_doc)
Esempio n. 19
0
 def put(self):
     """Method to handle user data update"""
     user_update_data = request.get_json(force=True)
     user_data = UserSchema(
         dump_only=['id']).load_object_into_schema(user_update_data)
     if user_data.get('password'):
         hashed_password = BCrypt.generate_password_hash(
             user_data.get('password')).decode('utf-8')
         user_data.update(password=hashed_password)
     exact_user = UserModel.query.filter_by(
         id=get_jwt_identity().get('id')).first()
     updated_user_object = exact_user.update(**user_data)
     return success_response(
         data=UserSchema(exclude=['password']).dump(
             updated_user_object),
         message='Profile Updated Successfully')
Esempio n. 20
0
def register():
    ''' register user endpoint '''
    data = validate_user(request.get_json())
    if data['ok']:
        data = data['data']
        data['password'] = flask_bcrypt.generate_password_hash(
                            data['password'])
        user_id = mongo.db.user.insert_one(data).inserted_id
        closet_id = create_closet(user_id)
        wishlist_id = create_wishlist(user_id)
        mongo.db.user.find_one_and_update({"_id": user_id},
                                 {"$set": {"closet": closet_id, "wishlist": wishlist_id}})
        LOG.info('Registered user: {}'.format(user_id))
        return jsonify({'ok': True, 'message': 'User created successfully!'}), 200
    else:
        return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 21
0
def register():
    data = validate_user(request.get_json())
    if not data['ok']:
        return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400

    data = data['data']
    data['user'] = data['user'].upper()
    user = mongo.db.users.find_one({'user': data['user']})
    if user:
        return jsonify({'ok': False, 'message': 'El usuario {} ya existe'.format(data['user'])}), 400
    
    data['password'] = flask_bcrypt.generate_password_hash(data['password'])
    data['role'] = 'USER_ROLE'
    data['active'] = True
    mongo.db.users.insert_one(data)
    return jsonify({'ok': True, 'message': 'Usuario creado exitosamente!'}), 201
Esempio n. 22
0
def handle_registration():
    if not current_user.moderator:
        return redirect(url_for(".root"))

    email = request.form["email"]
    password = request.form["password"]

    # Change this to: current user's group
    organization = current_user.organization

    pw_hashed = flask_bcrypt.generate_password_hash(password)
    new_user = User(email=email, password=pw_hashed, organization=organization)

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

    return redirect(url_for(".root"))
Esempio n. 23
0
def handle_registration():
    if not current_user.moderator:
        return redirect(url_for('.root'))

    email = request.form['email']
    password = request.form['password']

    # Change this to: current user's group
    organization = current_user.organization

    pw_hashed = flask_bcrypt.generate_password_hash(password)
    new_user = User(email=email, password=pw_hashed, organization=organization)

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

    return redirect(url_for('.root'))
Esempio n. 24
0
def reset_password():
    reset_request_id = request.args.get('id')
    reset_code = request.args.get('reset_code')

    reset_request = PasswordResetRequest.objects.get_or_404(id=reset_request_id)

    if not reset_request:
        flash("You do not have access to that page.", "danger")
        return redirect(url_for('index'))

    if not reset_request.validate_reset_code(reset_code):
        flash("You do not have access to that page", "danger")
        return redirect(url_for('index'))

    if not reset_request.validate_timestamp():
        flash("Password reset has expired", "danger")
        return redirect(url_for('index'))

    if request.method == "POST":
        password = request.form.get('password').strip()
        confirm = request.form.get('confirm').strip()

        has_errors = False
        if len(password) < MIN_PASSWORD_LENGTH:
            flash("Password must be at least {0} "
                  "characters".format(MIN_PASSWORD_LENGTH), "danger")
            has_errors = True
        if password != confirm:
            flash("Password and confirmation do not match", "danger")
            has_errors = True

        if not has_errors:
            userObj = User()
            password_hash = flask_bcrypt.generate_password_hash(password)
            try:
                userObj.reset_password(reset_request.user_id, password_hash)
                reset_request.delete()
                session.pop(reset_request.user_id, None)
                flash("You have successfully reset your password!", "success")
                return redirect(url_for('auth_login.login'))
            except:
                flash("Unable to reset password", "danger")
                current_app.logger.error("Error on registration - possible duplicate emails")               

    form = ResetPassForm(request.form)
    return render_template('forms/reset_password.html', form = form)
Esempio n. 25
0
def generate_password_reset_link(user_id):
    # Clear out all old requests for this member
    for r in PasswordResetRequest.objects(user_id=user_id):
        session.pop(r.user_id, None)

    # Generate new password reset request
    reset_code = uuid4()
    reset_code_hash = flask_bcrypt.generate_password_hash(reset_code)
    reset_request = PasswordResetRequest(reset_code_hash=reset_code_hash,
                                         user_id=user_id,
                                         timestamp=datetime.now())
    reset_request.save()

    session.update({user_id : reset_code})

    # Return the reset password link
    return url_for('auth_login.reset_password', _external=True,
                   id=reset_request.id, reset_code=reset_code)
Esempio n. 26
0
def user(id):
    
    #print("id",id)
    #print("args",request.args)

    if request.method == 'GET':
        query = request.args
        data = mongo.db.users.find_one({"_id":ObjectId(id)})
        #print("data",data)       
        #print("len",len(data))
        
        """
        check = checkSimpleForeign("users",id)
        if check != True:
            return check
        """

        return jsonify(data), 200
    
    if request.method == 'DELETE':
        db_response = mongo.db.users.delete_one({"_id":ObjectId(id)})
        if db_response.deleted_count == 1:
            response = {'message': 'record deleted'}
        else:
            response = {'message': 'no record found'}
        return jsonify(response), 200

    if request.method == 'PUT':
        #data = request.get_json()
        data = validate_user(request.get_json())
        if data['ok']:
            data = data['data']
            if 'password' in data:            
                data['password'] = flask_bcrypt.generate_password_hash(
                    data['password'])
            data["updatedAT"] = datetime.datetime.utcnow()        
            db_response = mongo.db.users.update_one({"_id":ObjectId(id)}, {'$set':data})
            #print("response",db_response.matched_count)
            if db_response.matched_count > 0:            
                return jsonify({'message': 'record updated'}), 200
            else:
                return jsonify({'message': 'error on record updated'}), 400   
        else:
            return jsonify({'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 27
0
def register():
    form = SignupForm(request.form)
    if request.method == 'POST':
        if form.validate():
            user_obj = User()
            email = form.email.data
            password = flask_bcrypt.generate_password_hash(form.password.data)
            user_obj.email = email
            user_obj.password = password
            user_id = user_obj.save() # user_id will be none if email has already been registered
            if not user_id:
                flash('Email has already been registered!')
                return redirect('/register')
            logging.debug('Register-- {} registered'.format(email))
            return redirect('/login')
        else:
            logging.debug('Register-- validate check failed')
            flash("Information input error, please input again!")
    return render_template('register.html', form=form)
Esempio n. 28
0
def register():
    ''' register user endpoint '''
    users = len(json.loads(dumps(mongo.db.users.find())))
    if len == 0:
        data = validate_user(request.get_json())
        if data['ok']:
            
            data = data['data']
            
            if data['password'] != None: 
                data['password'] = flask_bcrypt.generate_password_hash(
                    data['password'])
            data["createdAT"] = datetime.datetime.utcnow()            
            mongo.db.users.insert_one(data)
            return jsonify({'message': 'User created successfully!'}), 200
        else:
            return jsonify({'message': 'Bad request parameters: {}'.format(data['message'])}), 400
    else:
        return jsonify({'message': 'can not created first user'}), 400
Esempio n. 29
0
 def create_user(self, payload):
     hashed_password = flask_bcrypt.generate_password_hash(
         payload["password"]).decode("utf-8")
     exception_map = {}
     user = self.get_user_by_email(payload["email"])
     if not user:
         user = User(
             email=payload["email"],
             first_name=payload["first_name"].lower().capitalize(),
             last_name=payload["last_name"].lower().capitalize(),
             password_hash=hashed_password,
             uuid=str(uuid.uuid4()),
             admin=True,
         )
         db.session.add(user)
         db.session.commit()
     else:
         exception_map[
             "user_already_exists"] = f'user with email \'{payload["email"]}\' already exists'
     return user, exception_map
Esempio n. 30
0
def register():
	
	registerForm = forms.SignupForm(request.form)
	current_app.logger.info(request.form)

	if request.method == 'POST' and registerForm.validate() == False:
		current_app.logger.info(registerForm.errors)
		return "uhoh registration error"

	elif request.method == 'POST' and registerForm.validate():
		email = request.form['email']
		first_name = request.form['first_name']
		last_name = request.form['last_name']
		
		# generate password hash
		password_hash = flask_bcrypt.generate_password_hash(request.form['password'])

		# prepare User
		user = User(email,password_hash,first_name,last_name)
		print user

		try:
			user.save()
			if login_user(user, remember="no"):
				flash("Logged in!")
				return redirect('/')
			else:
				flash("unable to log you in")

		except:
			flash("unable to register with that email address")
			current_app.logger.error("Error on registration - possible duplicate emails")

	# prepare registration form			
	# registerForm = RegisterForm(csrf_enabled=True)
	templateData = {

		'form' : registerForm
	}

	return render_template("/auth/register.html", **templateData)
Esempio n. 31
0
def register():
	
	registerForm = forms.SignupForm(request.form)
	current_app.logger.info(request.form)

	if request.method == 'POST' and registerForm.validate() == False:
		current_app.logger.info(registerForm.errors)
		return "uhoh registration error"

	elif request.method == 'POST' and registerForm.validate():
		email = request.form['email']
		if email.find("creighton.edu") == -1: #checks to see if creighton email
			return "Must be a creigthon email!"
		# generate password hash
		password_hash = flask_bcrypt.generate_password_hash(request.form['password'])

		# prepare User
		user = User(email,password_hash)
		print user

		try:
			user.save()
			# user.search_form = SearchForm()
			if login_user(user, remember="yes"):
				flash("Logged in!")
				return redirect('/home')
			else:
				flash("unable to log you in")

		except:
			flash("unable to register with that email address")
			current_app.logger.error("Error on registration - possible duplicate emails")

	# prepare registration form			
	# registerForm = RegisterForm(csrf_enabled=True)
	templateData = {
		'form' : registerForm
	}

	return render_template("/auth/register.html", **templateData)
def on_put_init_object():

    item = request.get_json()

    # preserve existing object if desired
    if item.get('__preserve') == True:
        preserve_id = item.get('id')
        if not preserve_id:
            return "object without ID cannot be preserved\n", 400
        existing_object = mongo.db.objects.find_one({"id": preserve_id})
        if existing_object:
            return f"object with ID {preserve_id} already existing, preserved\n", 200
        del item['__preserve']
    else:
        # mark object as created automatically
        item['autocreated'] = True

    # automatically created users also need a password hash,
    # using a password, which is passed as a field and removed afterwards
    if item.get('type') == 'user' and 'fields' in item:
        user_id = item['fields'].get('email')
        password = item['fields'].get('password')
        if user_id and password:
            passwordhash = flask_bcrypt.generate_password_hash(
                password).decode()
            del item['fields']['password']
            mongo.db.passwords.replace_one({'userid': user_id}, {
                'userid': user_id,
                'passwordhash': passwordhash
            },
                                           upsert=True)

    # save object and return a text message instead of a JSON result
    json, code = save_object(item, get_jwt_identity())
    if code == 200:
        return "OK\n", 200
    else:
        return (json.get('message')
                or "error saving object") + "\n", code or 500
Esempio n. 33
0
def register():
    data = validate_user(request.get_json())
    if data['ok']:
        data = data['data']
        data['password'] = flask_bcrypt.generate_password_hash(
            data['password']).decode('utf-8')
        user = User(name=data['name'],
                    email=data['email'],
                    password=data['password'])
        db.session.add(user)
        db.session.commit()
        return jsonify({
            'ok': True,
            'message': 'User created successfully'
        }), 200
    else:
        return jsonify({
            'ok':
            False,
            'message':
            'Bad request parameters: {}'.format(data['message'])
        }), 400
Esempio n. 34
0
def users():
    ''' example to get extra data from annotation '''
    #print("extraData",request.extraData)
    ''' route read user '''
    if request.method == 'GET':
        query = request.args
        data = json.loads(dumps(mongo.db.users.aggregate([{'$addFields': {"_id": { '$toString':'$_id'}}}])))
        print("data",data)
        #print("len",len(data))
        return jsonify(data), 200
    if request.method == 'POST':
        data = validate_user(request.get_json())
        if data['ok']:
            data = data['data']
            if 'password' in data:
                data['password'] = flask_bcrypt.generate_password_hash(
                    data['password'])
            data["createdAT"] = datetime.datetime.utcnow()
            mongo.db.users.insert_one(data)
            return jsonify({'message': 'User created successfully!'}), 200
        else:
            return jsonify({'message': 'Bad request parameters: {}'.format(data['message'])}), 400
Esempio n. 35
0
def register():

    registerForm = forms.SignupForm(request.form)
    current_app.logger.info(request.form)

    if request.method == 'POST' and registerForm.validate() == False:
        current_app.logger.info(registerForm.errors)
        return "uhoh registration error"

    elif request.method == 'POST' and registerForm.validate():
        email = request.form['email']

        # generate password hash
        password_hash = flask_bcrypt.generate_password_hash(
            request.form['password'])

        # prepare User
        user = User(email, password_hash)
        print user

        try:
            user.save()
            if login_user(user, remember="no"):
                flash("Logged in!")
                return redirect('/')
            else:
                flash("unable to log you in")

        except:
            flash("unable to register with that email address")
            current_app.logger.error(
                "Error on registration - possible duplicate emails")

    # prepare registration form
    # registerForm = RegisterForm(csrf_enabled=True)
    templateData = {'form': registerForm}

    return render_template("/auth/register.html", **templateData)
Esempio n. 36
0
def register():
    form = SignupForm(request.form)
    if form.validate():

        user = User()
        form.populate_obj(user)
        user_exist = User.query.filter_by(email=form.email.data).first()
        if user_exist:
            # form.email.error.append('Email already in use.')
            return redirect(url_for('authentication.register'))

        else:

            user.password = flask_bcrypt.generate_password_hash(
                form.password.data, 15).decode('utf-8')
            user.active = True

            db.session.add(user)
            db.session.commit()
            return redirect(url_for('views.index'))
    return render_template('register.html',
                           form=SignupForm(),
                           login_form=SigninForm())
Esempio n. 37
0
def register():
    registerForm = forms.SignupForm(request.form)
#    current_app.logger.info(request.form)
    if request.method == 'POST' and registerForm.validate() == False:
        current_app.logger.info(registerForm.errors)
        return "uhoh registration error"

    elif request.method == 'POST' and registerForm.validate():
        username = request.form['username']
        password_hash = flask_bcrypt.generate_password_hash(request.form['password'])
        user = User(username,password_hash,key='')
        
        try:
            user.save()
            if login_user(user,remember="no"):
                flash("Logged in !") 
                return render_template("logined.html")
            else:
                flash("unable to log you in")  
        except Exception as e:
            print(e.message)
            flash("unable to register with that username address") 
    templateData = {'form':registerForm}
    return render_template('/register.html',**templateData)
Esempio n. 38
0
 def __init__(self, username, password):
     self.username = username
     self.password = flask_bcrypt.generate_password_hash(password)
Esempio n. 39
0
 def password(self, password):
     """Encrypt the password on assignment."""
     self._password = flask_bcrypt.generate_password_hash(password)
Esempio n. 40
0
 def __init__(self, email, password):
     self.email = email
     self.password = flask_bcrypt.generate_password_hash(password)
Esempio n. 41
0
from app import db, flask_bcrypt
db.create_all()

from app import User, Organization
from app.config import admin_username, admin_password

focus = Organization('Focus Africa', 'focus-africa.co.za')
admin_group = Organization('admins')

admin_pw_hash = flask_bcrypt.generate_password_hash(admin_password)
admin = User(admin_username, admin_pw_hash, organization=admin_group,
             moderator=True, admin=True)

db.session.add(focus)
db.session.add(admin_group)
db.session.add(admin)
db.session.commit()
Esempio n. 42
0
 def password(self, password):
     self.password_hash = flask_bcrypt.generate_password_hash(
         password).decode('utf-8')
Esempio n. 43
0
 def add_user(self):
     pwhash = flask_bcrypt.generate_password_hash(self.args['<password>'])
     u = User(email=self.args['<email>'], password=pwhash)
     db.session.add(u)
     db.session.commit()
     print('User added')
Esempio n. 44
0
 def on_model_change(self, form, model, is_created=False):
     ''' If the password exists, hash it, otherwise leave it alone '''
     if len(form.new_password.data):
         model.password = flask_bcrypt.generate_password_hash(form.new_password.data)
Esempio n. 45
0
def register_post():

    tid, ip = setup_log_vars()
    lggr = setup_local_logger(tid, ip)

    MAM = MainModel(tid=tid, ip=ip)

    invite_organization = request.form.get('h')
    invite_team = request.form.get('t')
    invite_token = request.form.get('k')
    #invite_email = request.form.get('e')

    #if e and email are not the same that is ok.

    username = request.form.get('username').lower().replace(' ', '')
    email = request.form.get('email').lower().replace(' ', '')

    # generate password hash
    password_hash = flask_bcrypt.generate_password_hash(
        request.form.get('password'))

    # prepare User
    user = User(username=username,
                email=email,
                passhash=password_hash,
                tid=tid,
                ip=ip)
    lggr.info(user)

    try:
        if user.set_user():
            lggr.info('User created')
            user_created = True
        else:
            lggr.info('User NOT created')
            user_created = False

    except:
        lggr.error(
            traceback.format_exception(sys.exc_info()[0],
                                       sys.exc_info()[1],
                                       sys.exc_info()[2]))

        flash("unable to register with that email address", 'UI')
        mpp = {
            'status': 'KO',
            'msg': 'Unable to register with that email address'
        }
        flash({'f': 'track', 'v': '_register', 'p': mpp}, 'MP')
        lggr.error("Error on registration ")
        return redirect(
            url_for('avispa_auth.register_get',
                    _external=True,
                    _scheme=URL_SCHEME))

    if True:
        #try:

        if user_created:

            if invite_organization and invite_team and invite_token and email:

                # Aquire org.invitations document
                result = MAM.select_user_doc_view('orgs/invitations',
                                                  invite_organization)

                # Verify if this is a valid invitation
                for i in result['invitations']:

                    if i['token'] == invite_token and i['email'] == email:
                        lggr.info('Invitation valid')

                        valid_invite = True
                        break
                    else:
                        lggr.info('Invitation invalid')
                        valid_invite = False

                if valid_invite:

                    people = {}
                    people['added'] = str(datetime.now())
                    people['handle'] = username
                    people['addedby'] = i['author']
                    # Add the user to the organization people
                    MAM.append_to_user_field(invite_organization, 'people',
                                             people)
                    lggr.info('User appended to org: %s' %
                              (invite_organization))

                    # Add the user to the team
                    MAM.append_to_user_field(invite_organization,
                                             'teams',
                                             people,
                                             sublist='members',
                                             wherefield='teamname',
                                             wherefieldvalue=invite_team)

                    lggr.info('User added to team: %s' % (invite_team))

                # Set its onLogin hook to <invite_organization>/<invite_team>
                u = {}
                u['id'] = username
                u['onlogin'] = '******' + invite_organization + '/_home'
                MAM.update_user(u)

            lggr.info('User created, now log in the user')
            #Go through regular login process
            userObj = User(email=email, tid=tid, ip=ip)
            userview = userObj.get_user()
            lggr.info(userObj)

            mpp = {'status': 'OK'}
            flash({'f': 'track', 'v': '_register', 'p': mpp}, 'MP')
            flash({'f': 'alias', 'v': username}, 'MP')

            if login_user(userObj, remember="no"):
                flash("Logged in. Welcome to MyRing!", 'UI')

                mpp = {'status': 'OK', 'msg': 'Automatic'}
                flash({'f': 'track', 'v': '_login', 'p': mpp}, 'MP')
                #flash({'track':'_login OK, Automatic'},'MP')
                if invite_organization:
                    #return redirect(absolute_url('/'+invite_organization+'/_home'))
                    return redirect(
                        url_for('avispa_rest.home',
                                handle=invite_organization,
                                _external=True,
                                _scheme=URL_SCHEME))
                else:
                    #return redirect(absolute_url('/'+userview.id+'/_home'))
                    return redirect(
                        url_for('avispa_rest.home',
                                handle=userview.id,
                                _external=True,
                                _scheme=URL_SCHEME))
            else:
                flash("Please enter your credentials ", 'UI')

                mpp = {'status': 'KO', 'msg': 'Automatic'}
                flash({'f': 'track', 'v': '_login', 'p': mpp}, 'MP')
                #flash({'track':'_login KO, Automatic'},'MP')

                #return redirect(absolute_url('/_login'))
                return redirect(
                    url_for('avispa_auth.login',
                            _external=True,
                            _scheme=URL_SCHEME))

        else:

            lggr.info('User could not be created')
            mpp = {'status': 'KO', 'msg': 'User could not be created'}
            flash({'f': 'track', 'v': '_register', 'p': mpp}, 'MP')
            flash({'f': 'alias', 'v': username}, 'MP')
            #return redirect(absolute_url('/_register'))
            return redirect(
                url_for('avispa_auth.register_get',
                        _external=True,
                        _scheme=URL_SCHEME))

    else:
        #except:

        flash("Please enter your credentials. [E12] ", 'UI')
        mpp = {'status': 'KO', 'msg': 'Automatic'}
        flash({'f': 'track', 'v': '_login', 'p': mpp}, 'MP')

        #return redirect(absolute_url('/_login'))
        return redirect(
            url_for('avispa_auth.login', _external=True, _scheme=URL_SCHEME))
Esempio n. 46
0
 def password(self, password):
     self._password = flask_bcrypt.generate_password_hash(password)
Esempio n. 47
0
def forgot():

    tid, ip = setup_log_vars()
    lggr = setup_local_logger(tid, ip)

    MAM = MainModel(tid=tid, ip=ip)

    if request.method == 'POST' and request.form.get('email'):

        email = request.form.get('email')
        userObj = User(email=email, tid=tid, ip=ip)
        user = userObj.get_user()
        lggr.info(user)

        if user and user.is_active():

            try:

                o = urlparse.urlparse(request.url)
                host_url = urlparse.urlunparse(
                    (URL_SCHEME, o.netloc, '', '', '', ''))

                #save the token in the database
                key = flask_bcrypt.generate_password_hash(
                    request.form.get('email') + str(random.randint(0, 9999)))
                #key = 'qwerty1234'
                lggr.info("key:" + key)
                userObj.set_password_key(key)

                to = user.email
                subject = "Password Recovery Email for: " + user.email
                content = "Click here " + host_url + "/_forgot?k=" + key + "&e=" + email

                EMO = EmailModel()
                if EMO.send_one_email(to, subject, content):
                    lggr.info("Sending password recovery email to: " +
                              user.email)
                    flash(
                        "Please check your mail's inbox for the password recovery instructions.",
                        'UI')

                    mpp = {'status': 'OK', 'msg': 'Sent recovery email'}
                    flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
                    #flash({'track':'_forgot OK, sent recovery email'},'MP')
                else:
                    lggr.info(
                        "Something went wrong with sending the email but no error was raised"
                    )
                '''

                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()

                #Next, log in to the server
                server.login(FROMEMAIL, FROMPASS)

                #Send the mail
                msg = "\r\n".join([
                  "From:"+FROMEMAIL,
                  "To: "+user.email,
                  "Subject: Password Recovery Email for: "+user.email,
                  "",
                  "Click here "+host_url+"/_forgot?k="+key+"&e="+email
                  ])
                #msg = "\nHello!" # The /n separates the message from the headers
                server.sendmail(FROMEMAIL, user.email, msg)
                server.quit()

                '''

            except:
                lggr.error(
                    traceback.format_exception(sys.exc_info()[0],
                                               sys.exc_info()[1],
                                               sys.exc_info()[2]))
                lggr.error("Error sending password revovery email")
                flash(
                    "There was an error sending the password recovery instructions"
                )
                flash({'track': '_forgot KO, error sending recovery email'},
                      'MP')
                pass

        else:
            flash("Could not find this email", 'UI')

            mpp = {'status': 'KO', 'msg': 'Could not find email'}
            flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
            #flash({'track':'_forgot KO, could not find email'},'MP')

    elif request.method == 'GET' and request.args.get(
            'k') and request.args.get('e'):
        data = {}
        data['key'] = request.args.get('k')
        data['email'] = request.args.get('e')
        userObj = User(tid=tid, ip=ip)
        if userObj.is_valid_password_key(data['email'], data['key']):
            lggr.info('Token authorized')
            mpp = {'status': 'OK', 'msg': 'Token authorized'}
            flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
            #flash({'track':'_forgot OK, Token authorized'},'MP')
            return render_template("/auth/new_password.html", data=data)
        else:
            lggr.info('Token Rejected')
            mpp = {'status': 'KO', 'msg': 'Token not authorized'}
            flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
            #flash({'track':'_forgot KO, Token not authorized'},'MP')

    elif (request.method == 'POST' and request.form.get('e')
          and request.form.get('k') and request.form.get('password')
          and request.form.get('confirm')):

        userObj = User(email=request.form.get('e'), tid=tid, ip=ip)
        user = userObj.get_user()

        if request.form.get('password') == request.form.get('confirm'):
            if userObj.is_valid_password_key(request.form.get('e'),
                                             request.form.get('k')):
                lggr.info('Token authorized')
                # generate password hash
                passhash = flask_bcrypt.generate_password_hash(
                    request.form.get('password'))
                userObj.set_password(passhash)
                flash('Password changed', 'UI')
                mpp = {'status': 'OK', 'msg': 'Password changed'}
                flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
                #flash({'track':'_forgot OK, Password changed'},'MP')
                #return redirect(absolute_url('_login'))
                return redirect(
                    url_for('avispa_auth.login',
                            _external=True,
                            _scheme=URL_SCHEME))

            else:
                flash('Token Rejected', 'UI')
                mpp = {'status': 'KO', 'msg': 'Token rejected'}
                flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
                #flash({'track':'_forgot KO, Token rejected'},'MP')
                #return redirect(absolute_url('_login'))
                return redirect(
                    url_for('avispa_auth.login',
                            _external=True,
                            _scheme=URL_SCHEME))
        else:
            flash('Both passwords need to match', 'UI')
            mpp = {'status': 'KO', 'msg': 'Password do not match'}
            flash({'f': 'track', 'v': '_forgot', 'p': mpp}, 'MP')
            #flash({'track':'_forgot KO, passwords do not match'},'MP')
            q = 'k=' + request.form.get('k') + '&e=' + request.form.get('e')
            #return redirect(absolute_url('/_forgot',query=q))
            return redirect(
                url_for('avispa_auth.forgot',
                        k=request.form.get('k'),
                        e=request.form.get('e'),
                        _external=True,
                        _scheme=URL_SCHEME))

    data = {}
    data['method'] = '_forgot'

    return render_template("/auth/forgot.html", data=data)