Пример #1
0
def register():
    form = RegisterForm()

    if form.validate_on_submit():
        logout_session_clear()
        user = User(email=form.email.data)

        user.hash_password(form.password.data)
        user.activity.created = utc_now()
        verification_code = uuid.uuid4()

        user.activity.payment_reference = user.uid

        user.activity.email_verification = EmailVerification(
            verification_code=str(verification_code))
        user.activity.activity_audit.append(
            ActivityAudit(uid=user.uid,
                          created=utc_now(),
                          code="USER CREATED",
                          text="User created",
                          headers={
                              "REMOTE_ADDR": request.environ["REMOTE_ADDR"],
                              "HTTP_USER_AGENT":
                              request.environ["HTTP_USER_AGENT"],
                              "REMOTE_PORT": request.environ["REMOTE_PORT"],
                          }).save())

        user.save()

        user_registered_email(user.email, user.uid, verification_code)

        return render_template('auth/user_registered.html')
    return render_template('auth/register.html', form=form)
Пример #2
0
def create_user():
    """Create a new user."""
    # get form info
    data = request.json or {}
    # check info
    error = []
    if 'username' not in data:
        error.append('username')
    if 'password' not in data:
        error.append('password')
    if 'email' not in data:
        error.append('email')
    if len(error) > 0:
        return jsonify({'message':
                        'Require {}.'.format(' and '.join(error))}), 400
    # check if user existed
    if User.filter_by(username=data['username'].strip()).first():
        return jsonify({'message': 'Username already exists.'}), 409
    # check if email existed
    if User.filter_by(email=data['email'].strip()).first():
        return jsonify({'message': 'Email has been registered.'}), 409
    # create User
    user = User(public_id=str(uuid.uuid1()),
                username=data['username'].strip(),
                email=data['email'].strip())
    # password hash
    user.set_password(data['password'].strip())
    # db commit
    user.save()

    return jsonify({'message': 'Created a new user.'}), 201
Пример #3
0
    def test_default(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        self.assertTrue(user.is_active is False)
        self.assertTrue(user.is_admin is False)
        self.assertTrue(isinstance(user.create_at, datetime.datetime) is True)
Пример #4
0
def make_user():
    email = request.json.get('email')
    password = request.json.get('password')
    if email is None or password is None:
        response = jsonify({'status': 'Fail', 'message': 'Missing parameters'})
        response.status_code = 400
        return response

    if User.objects.filter(email=email).first() is not None:
        response = jsonify({'status': 'Fail', 'message': 'User already exists'})
        response.status_code = 400
        return response

    user = User(email=email)
    user.hash_password(password)
    user.activity.created = now()
    verification_code = uuid.uuid4()
    user.activity.verification_code = str(verification_code)
    user.save()

    user_registered_email(email, verification_code)

    response = jsonify({'status': 'Success', 'message': 'User created'})
    response.status_code = 201
    return response
Пример #5
0
    def post(self):
        # get data from json request
        data = request.get_json()

        # spliting the data from request
        username = data['username']
        password = data['password']  # clear data
        # checking if the collect data exists
        print(user_exists(username))
        if user_exists(username):
            error = {
                'status': 301,
                'msg': 'Invalid Credentials'
            }
            return jsonify(error)
        # user checked , time to hash the password
        hashpass = generate_password_hash(password, method='sha256')
        own = 0.0
        debt = 0.0
        # username and passw already done, is time do add to db
        user = User(username=username, password=hashpass, own=own, debt=debt)
        user.save()

        # data stored in db, confirmation return

        success = {
            'status': 200,
            'msg': "Success! You have Signup to yoBank!"
        }

        return jsonify(success)
Пример #6
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('public.index'))
    form = RegisterForm()
    error = None
    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        password = form.password.data
        # Comprobamos que no hay ya un usuario con ese email
        user = User.get_by_email(email)
        if user is not None:
            flash(
                'El email {} ya está siendo utilizado por otro usuario'.format(
                    email))
        else:
            # Creamos el usuario y lo guardamos
            user = User(name=username, email=email)
            user.set_password(password)
            user.save()
            # Creo el rol del nuevo usuaricio
            usuario_nuevo = User.get_by_email(email)
            rol = Role(rolename="user", user_id=usuario_nuevo.id)
            rol.save()
            # Dejamos al usuario logueado
            login_user(user, remember=True)
            return redirect(url_for('public.index'))
    return render_template("register.html", form=form)
Пример #7
0
    def test_delete_user(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        lxgui = User.query.filter_by(username='******').first()
        lxgui.delete()

        self.assertTrue(User.query.filter_by(username='******').first() is None)
Пример #8
0
    def test_token(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        token = user.generate_confirmation_token()
        user.confirm(token)

        self.assertTrue(user.is_active is True)
Пример #9
0
def login():
    """Simulate the standard login flow."""
    user = User.find_by_email('*****@*****.**')
    if user is None:
        user = User('Dave')
        user.email = '*****@*****.**'
        user.save()
    login_user(user)
    return redirect(url_for('main.home'))
Пример #10
0
    def test_user_login(self):
        user = User(username='******',
                    email='*****@*****.**',
                    password='******',
                    is_active=True)
        user.save()

        form = LoginForm(username=user.username, password='******')
        self.assertTrue(form.validate() is True)
Пример #11
0
    def test_email_exist(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        form = RegisterForm(username='******',
                            email='*****@*****.**',
                            password='******',
                            confirm='123')
        self.assertFalse(form.validate() is True)
Пример #12
0
 def create_customer(username, password, name, surname, nif, email):
     user = User(username=username, user_type=1)
     user.set_password(password)
     user.save()
     customer = Customer(nif=nif,
                         name=name,
                         surname=surname,
                         email=email,
                         user_id=user.id)
     customer.save()
Пример #13
0
 def post(self, args):
     data = request.json
     if name_has_numbers(data):
         response = {
             "messages": {
                 "errors": {
                     "name:": ["field cannot contain numbers"]
                 }
             }
         }
         return make_response(jsonify(response), 400)
     if is_valid(data['first_name']) or is_valid(data['last_name']):
         response = {
             "messages": {
                 "errors": {
                     "name": ["field contains special characters"]
                 }
             }
         }
         return make_response(jsonify(response), 400)
     if not validate_email(strip_clean(data['email'])):
         response = {"messages": {"email": ["Invalid email format!"]}}
         return make_response(jsonify(response), 400)
     user = User.query.filter_by(email=strip_clean(data['email'])).first()
     if not user:
         new_user = User(email=strip_clean(data['email']),
                         password=bcrypt.generate_password_hash(
                             strip_clean(data['password'])).decode('utf-8'),
                         first_name=strip_clean(data['first_name']),
                         last_name=strip_clean(data['last_name']),
                         location=strip_clean(data['location']),
                         gender=strip_clean(data['gender']))
         new_user.save()
         user = User.query.filter_by(
             email=strip_clean(data['email'])).first()
         token = create_auth_token(user.id, strip_clean(data['email']),
                                   strip_clean(data['first_name']),
                                   strip_clean(data['last_name']))
         response = {
             "messages": {
                 "message": ["User account created"],
                 "token": [token]
             }
         }
         return make_response(jsonify(response), 201)
     else:
         response = {
             "messages": {
                 "errors": {
                     "user": ["User with that email already exists"]
                 }
             }
         }
         return make_response(jsonify(response), 409)
Пример #14
0
def register():
    form = RegisterForm()
    if request.method == 'POST':
        if form.validate():
            existing_user = User.objects(username=form.username.data).first()
            if existing_user is None:
                username = form.username.data
                debt = 0.0
                own = 0.0
                hashpass = generate_password_hash(form.password.data, method='sha256')
                user = User(username=username, password=hashpass, own=own, debt=debt)
                user.save()
                login_user(user)
                return redirect(url_for('auth.dashboard'))
    return render_template('auth/register.html', form=form)
Пример #15
0
 def test_already_registered_user(self):
     """Test for user registration with already registered email"""
     new_user = User(email="*****@*****.**",
                     password="******",
                     first_name="firstname",
                     last_name="lastname",
                     location="Nairobi",
                     gender="Male")
     new_user.save()
     with self.client:
         response = self.register_user("*****@*****.**", "password",
                                       "firstname", "lastname", "Nairobi",
                                       "Male")
         self.assertEqual(response.status_code, 409)
         self.assertIn("User with that email already exists",
                       str(response.data))
Пример #16
0
 def post(self):
     args = self.reqparse()
     row = UserModel(args.name, args.email,
                     generate_password_hash(args.password))
     err = row.save()
     if err != None:
         return rp(message=str(err)), 500
     return rp(success=True, payload=row.serialize()), 201
Пример #17
0
def handle_authorize(remote, token, user_info):
    current_app.logger.info("remote: {}".format(remote))
    current_app.logger.info("token: {!r}".format(token))
    current_app.logger.info("user_info: {!r}".format(user_info))

    if user_info:

        # Note: Here's where to do team membership or whitelist/blacklist tests

        user = User.find_by_email(user_info['email'])
        if user is None:
            user = User(user_info['preferred_username'])
            user.email = user_info['email']
            # Note: in real life we wouldn't discard the rest
            user.save()
        login_user(user)

    else:
        # Authorization failed.
        # In real code, we'd provided feedback (e.g., flash a message)
        pass

    return redirect(url_for('main.home'))
Пример #18
0
 def test_auth_model_save_normal(self):
     """ Example: send correct payload """
     user = User(self.data)
     instance = user.save()
     assert instance.get('email') == self.data.get('email')
 def create_user(name, email, password, is_admin):
     user = User(name, email)
     user.set_password(password)
     user.is_admin = is_admin
     user.save()
     return user
Пример #20
0
    def test_password_hash(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        jx = User.query.filter_by(username='******').first()
        self.assertTrue(jx.verify_password('123'))
Пример #21
0
def save_user(email, name, password):
    user = User(email, name, password)
    user.save()
Пример #22
0
    def test_create_user(self):
        user = User(username='******', email='*****@*****.**', password='******')
        user.save()

        me = User.query.filter_by(username='******').first()
        self.assertTrue(user == me)