Exemple #1
0
def insert_user(request):
    user_id = get_params(request, "user_id")
    password = get_params(request, "password")
    m = hashlib.md5()
    m.update(password)
    password = str(m.hexdigest())
    email = get_params(request, "email")
    mobile = get_params(request, "mobile")
    name = get_params(request, "name")
    id_card = get_params(request, "id_card")
    age = get_params(request, "age")
    sex = get_params(request, "sex")
    exist_user = User.objects.filter(user_id=user_id)
    if len(exist_user):
        return JsonResponse({
            "error_no": REQUEST_ERROR,
            "message": USER_EXISTS
        })
    else:
        u = User(user_id=user_id, name=name, mobile=mobile, email=email, sex=sex, age=age, id_card=id_card)
        u.save()
        upf = UserProfile(user=u, password=password)
        upf.save()
    return JsonResponse({
        "error_no": REQUEST_SUCCESS
    })
Exemple #2
0
def callback(request):
    # Get the state saved in session
    expected_state = request.session.pop('auth_state', '')
    # Make the token request
    token = get_token_from_code(request.get_full_path(), expected_state)

    # Get the user's profile
    user = get_user(token)

    try:
        request.user = User.objects.get(email=user['mail'])
    except User.DoesNotExist:
        user_ = User(first_name=user['displayName'],
                     last_name="",
                     email=user['mail'])
        user_.save()
        junta_ = Junta(user=user_, role=VOTER)
        junta_.save()
        request.user = user_

    # Save token and user
    store_token(request, token)
    store_user(request, user)

    try:
        callback_url = request.session['redirect_callback']
    except KeyError:
        callback_url = reverse('portal:index')

    return HttpResponseRedirect(callback_url)
Exemple #3
0
    def test_user_crud(self):
        """
        Test following 5 methods
        - camunda_api.create_user
        - camunda_api.delete_user
        - camunda_api.get_user
        - camunda_api.get_user_list
        - camunda_api.get_user_count
        """
        user = User()
        user.email = '*****@*****.**'
        user.first_name = 'test_first_name'
        user.last_name = 'test_last_name'

        user_count_initial = UserApi.get_count()

        # Test camunda_api.create_user
        response = UserApi.create(user)
        self.assertTrue(
            response.ok,
            "Response should be OK. (status_code = {})\n{}".format(
                response.status_code, response.text))

        # Check user count / Test camunda_api.user_list and camunda_api.user_count
        user_count_after_creation = UserApi.get_count()
        self.assertEqual(user_count_initial + 1, user_count_after_creation)

        # Test camunda_api.get_user
        response = UserApi.get_one(user)
        self.assertTrue(
            response.ok,
            "Response should be OK. (status_code = {})\n{}".format(
                response.status_code, response.text))
        response_json = response.json()
        self.assertEqual(response_json['id'], user.email)
        self.assertEqual(response_json['firstName'], user.first_name)
        self.assertEqual(response_json['lastName'], user.last_name)
        self.assertEqual(response_json['email'], user.email)

        # Test camunda_api.delete_user
        response = UserApi.delete(user)
        self.assertTrue(
            response.ok,
            "Response should be OK. (status_code = {})\n{}".format(
                response.status_code, response.text))

        # Check user count / Test camunda_api.user_list and camunda_api.user_count
        user_count_after_deletion = UserApi.get_count()
        self.assertEqual(user_count_after_creation - 1,
                         user_count_after_deletion)
Exemple #4
0
def register():
    user = User.query.all()
    checkAdmin = 1
    for u in user:
        if u.is_admin == True:
            checkAdmin = 0
            break
    if current_user.is_authenticated:
        return redirect(url_for('check'))
    form = RegistrationForm()
    if form.validate_on_submit():
        if form.username.data == 'test':
            flash('This username cannot be taken', 'danger')
        else:
            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('Wait for admin approval', 'info')
            return redirect(url_for('login'))
    return render_template('register.html',
                           title='Register',
                           form=form,
                           check=checkAdmin)
Exemple #5
0
def admin_register(key):
    if '1800' == key:
        user = User.query.all()
        check = 1
        for u in user:
            if u.is_admin == True:
                check = 0
                break
        if check == 1:
            if current_user.is_authenticated:
                return redirect(url_for('checkUser'))
            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,
                            is_admin=True,
                            is_active=True,
                            is_manager=True)
                db.session.add(user)
                db.session.commit()
                flash('You are now admin.', 'info')
                return redirect(url_for('login'))
            return render_template('register.html',
                                   title='Register',
                                   form=form)
        elif check == 0:
            flash('Admin account already exists', 'info')
            return redirect(url_for('login'))
    else:
        render_template('error.html', error=404)
Exemple #6
0
    def setUp(self):
        self.tenant = Tenant()
        self.tenant.id = 'hogehoge'
        self.tenant.name = 'hogehoge'

        self.user = User()
        self.user.id = '*****@*****.**'
        self.user.email = '*****@*****.**'
        self.user.first_name = '稲葉'
        self.user.last_name = '理晃'
        self.user.tenant = self.tenant
Exemple #7
0
def _create_db_users(users):
    db.session.add_all([
        User(
            project_id=p['project_id'],
            email=p['email'],
            current_portal_user_yn=p['current_portal_user_yn'],
            gv_end_del_log=p['gv_end_del_log'],
            is_imported=p['is_imported'],
        ) for p in users
    ])
    db.session.commit()
Exemple #8
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    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('Akun berhasil dibuat! Silahkan Login', 'is-success')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', title='Register', form=form)
Exemple #9
0
    def test_create_user_member(self):
        """
        Test following 3 methods
        - camunda_api.TenantApi.create_user_member
        - camunda_api.TenantApi.get_list
        - camunda_api.UserApi.get_list
        """
        tenant = Tenant('1', 'Test_Tenant_1')
        tenant.name = 'test_create_user_member_tenant_name'

        user = User()
        user.email = '*****@*****.**'
        user.first_name = 'test_create_user_member_first_name'
        user.last_name = 'test_create_user_member_last_name'
        user.tenant = tenant

        UserApi.create(user)
        TenantApi.create(tenant)
        TenantApi.create_user_member(user)

        tenant_list = TenantApi.get_list(userMember=user.email).json()
        user_list = UserApi.get_list(memberOfTenant=tenant.name).json()

        self.assertEqual(tenant.name, tenant_list[0]['id'])
        self.assertEqual(tenant.name, tenant_list[0]['name'])
        self.assertEqual(user.email, user_list[0]['id'])
        self.assertEqual(user.first_name, user_list[0]['firstName'])
        self.assertEqual(user.last_name, user_list[0]['lastName'])
        self.assertEqual(user.email, user_list[0]['email'])

        UserApi.delete(user)
        TenantApi.delete(tenant)
Exemple #10
0
def add_users():
    form=AddUsersForm()
    if current_user.user_type == 'admin':
        if form.validate_on_submit():
            current_num = len(User.query.filter_by(user_type=form.user_type.data).all())
            log_id = f"{form.user_type.data[0:2]}{current_num+1}"
            password = bcrypt.generate_password_hash('123456').decode('utf-8')
            new_user = User(login_id=log_id, user_type=form.user_type.data, name=form.name.data,
                            email=form.email.data, school=current_user.school, password=password)
            db.session.add(new_user)
            db.session.commit()
            flash(f'{new_user.login_id} is added', 'success')
            return redirect(url_for('add_users'))
    return render_template('add_users.html', form=form, title='Account')
Exemple #11
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('auth.reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Password Anda telah diupdate! silahkan login', 'is-success')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_token.html', title='Reset Password', form=form)
Exemple #12
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    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',
              'is-success')
        return redirect(url_for('admin.login'))
    return render_template('admin/register.html', title='Register', form=form)
Exemple #13
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        current_num = len(User.query.filter_by(user_type='admin').all())
        log_id = f"ad{current_num+1}"
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        admin = User(login_id=log_id,user_type='admin', email=form.email.data,
                         name=form.name.data, school=form.school.data, password=hashed_password)
        db.session.add(admin)
        db.session.commit()
        login_user(admin)
        flash(f'{form.school.data} is registered!', 'success')
        flash(f'Your login id is {admin.login_id}', 'success')
        return redirect(url_for('about'))
    return render_template('register.html', title='Register', form=form)
Exemple #14
0
def import_user():
    current_app.logger.info('Importing user details')

    existing_users = {u.email: u for u in User.query.options(joinedload('practices')).all()}
    practices = {p.code: p for p in Practice.query.all()}

    users = []

    with etl_practice_database() as p_db:
        for email, details in groupby(p_db.execute(user_table.select().order_by(user_table.c.email)), key=lambda x: x['email'].lower()):
            user = existing_users.get(email, None)

            if user is None:
                user = User(email=email)
            
            ds = list(details)

            u = ds[0]
            user.project_id = u['project_id']
            user.current_portal_user_yn = bool(u['current_portal_user_yn'])
            user.gv_end_del_log = parse_date(u['gv_end_del_log'])
            user.last_update_timestamp = u['last_update_timestamp']
            user.is_imported = True
            user.active = bool(u['current_portal_user_yn'])

            user.practices = set([practices[d['practice_code']] for d in ds])

            users.append(user)

    db.session.add_all(users)
    db.session.flush()

    for u in User.query.filter(User.id.notin_([u.id for u in users]), User.is_imported.is_(True)).all():
        db.session.delete(u)

    db.session.commit()
Exemple #15
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('login'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated! You are now able to log in',
              'success')
        return redirect(url_for('login'))
    return render_template('reset_token.html',
                           title='Reset Password',
                           form=form)
def register():
    """User registration route."""
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    if (request.method == 'POST'
            and request.form['submit_button'] == 'register'):
        username = request.form.get("username")
        password = request.form.get("password")
        user = User.query.filter_by(username=username).first()
        if user is not None:
            flash('Username already exists.', 'error')
            return redirect(url_for('register'))
        user = User(username=username, password=password, otp_enabled=False)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('index'))
        # Redirect to page with 2FA QR to scan with FreeOTP or app like it.
        # session['username'] = user.username
        # return redirect(url_for('reg_two_factor_setup'))
    return render_template('register.html')
Exemple #17
0
 def test_user(self):
     assert len(User.query.all()) is 0
     user = User()
     Base.session.add(user)
     Base.session.commit()
     assert len(User.query.all()) is 1