コード例 #1
0
ファイル: controller1.py プロジェクト: twintechlabs/flaskdash
def create_or_edit_user_page():
    form = UserProfileForm(request.form, obj=current_user)
    roles = Role.query.all()
    user_id = request.args.get('user_id')
    user = User()

    if user_id:
        user = User.query.filter(User.id == user_id).first()

    if request.method == 'POST':
        if user.id is None:
            user = User.query.filter(
                User.email == request.form['email']).first()
            if not user:
                user = User(email=request.form['email'],
                            full_name=request.form['full_name'],
                            password=current_app.user_manager.hash_password(
                                request.form['password']),
                            active=True,
                            email_confirmed_at=datetime.datetime.utcnow())
                db.session.add(user)
                db.session.commit()
            return redirect(url_for('main.user_admin_page'))
        else:
            user.email = request.form['email']
            user.full_name = request.form['full_name']
            if request.form['password'] is not None and request.form[
                    'password'] is not "":
                user.password = current_app.user_manager.hash_password(
                    request.form['password'])
            db.session.commit()
    return render_template('views/admin/edit_user.html',
                           form=form,
                           roles=roles,
                           user=user)
コード例 #2
0
def find_or_create_user(first_name,
                        last_name,
                        email,
                        password,
                        phonenumber,
                        dob,
                        hostel_location,
                        role=None):
    """ Find existing user or create new user """
    user = User.query.filter(User.email == email).first()
    if not user:
        user = User(
            email=email,
            first_name=first_name,
            last_name=last_name,
            password=current_app.user_manager.password_manager.hash_password(
                password),
            active=True,
            phonenumber=phonenumber,
            dob=dob,
            hostel_location=hostel_location,
            email_confirmed_at=datetime.datetime.utcnow())
        if role:
            user.roles.append(role)
        db.session.add(user)
    return user
コード例 #3
0
ファイル: init_db.py プロジェクト: LexPanov/2ch
def create_user(username, password, roleid = 0):
    user = User(username=username,
                password=current_app.user_manager.hash_password(password),
                active=True,
                role=roleid)
    db.session.add(user)
    return user
コード例 #4
0
def create_user_page():
    if current_app.config.get('USER_LDAP', False):
        abort(400)

    form = UserProfileForm()
    roles = Role.query.all()
    form.roles.choices = [(x.id, x.name) for x in roles]

    if form.validate():
        user = User.query.filter(User.email == request.form['email']).first()
        if not user:
            user = User(email=form.email.data,
                        first_name=form.first_name.data,
                        last_name=form.last_name.data,
                        password=current_app.user_manager.hash_password(
                            form.password.data),
                        active=True,
                        email_confirmed_at=datetime.datetime.utcnow())
            db.session.add(user)
            db.session.commit()
            allowed_roles = form.roles.data
            for role in roles:
                if role.id not in allowed_roles:
                    if role in user.roles:
                        user.roles.remove(role)
                else:
                    if role not in user.roles:
                        user.roles.append(role)
            db.session.commit()
            flash('You successfully created the new user.', 'success')
            return redirect(url_for('main.user_admin_page'))
        flash('A user with that email address already exists', 'error')
    return render_template('pages/admin/create_user.html', form=form)
コード例 #5
0
def create_user_page():
    user_id = request.args.get('user_id')
    # Initialize form
    user = User()
    if user_id is not None:
        user = User.query.filter_by(id=user_id).first()
    form = UserProfileForm(request.form, obj=user)

    if request.method == 'POST':
        form.populate_obj(user)
        role = Role.query.filter(Role.name == "admin").first()
        if user.id is None:
            user = User(email=request.form['email'],
                        first_name=request.form['first_name'],
                        last_name=request.form['last_name'],
                        password=current_app.user_manager.hash_password(
                            request.form['password']),
                        active=True,
                        email_confirmed_at=datetime.datetime.utcnow())
            if str(request.form['role']) == "admin":
                user.roles.append(role)
            else:
                user.roles = []
            db.session.add(user)
            db.session.commit()
        else:
            user.email = request.form['email']
            user.first_name = request.form['first_name']
            user.last_name = request.form['last_name']
            if request.form['password'] is not None and request.form[
                    'password'] is not "":
                user.password = current_app.user_manager.hash_password(
                    request.form['password'])
            if str(request.form['role']) == "admin":
                user.roles.append(role)
            else:
                user.roles = []
            db.session.commit()
        flash('You successfully updated your user!', 'success')
        return redirect(url_for('main.user_admin_page'))
    return render_template('pages/admin/create_user.html',
                           user=user,
                           form=form)
コード例 #6
0
def starter_user():
    user = User.query.filter(User.name == 'starter').first()

    if not user:
        user = User()
        user.name = 'starter'
        db.session.add(user)
        db.session.commit()

    return user
コード例 #7
0
def user():
    if request.method == 'POST':
        if 'id' not in request.json or 'email' not in request.json:
            return jsonify(request.json), 403
        user_posted = User(id=request.json['id'], email=request.json['email'])
        db.session.add(user_posted)
        db.session.commit()
        return UserSchema().dump(user_posted)
    if request.method == 'GET':
        users = User.query.all()
        result = UserSchema(many=True).dump(users)
        return jsonify(result)
コード例 #8
0
def find_or_create_user(email, password, role=None):
    """ Find existing user or create new user """
    user = User.query.filter(User.email == email).first()
    if not user:
        user = User(email=email,
                    password=current_app.user_manager.hash_password(password),
                    active=True,
                    confirmed_at=datetime.datetime.utcnow())
        if role:
            user.roles.append(role)
        db.session.add(user)
    return user
コード例 #9
0
def find_or_create_user(first_name, last_name, username, password, role=None):
    """ Find existing user or create new user """
    user = User.query.filter(User.username == username).first()
    if not user:
        user = User(username=username,
                    first_name=first_name,
                    last_name=last_name,
                    password=app.user_manager.hash_password(password),
                    active=True)
        if role:
            user.roles.append(role)
        db.session.add(user)
    return user
コード例 #10
0
def register():
    if current_user.is_authenticated:
        return redirect('index')
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(smu_id=form.smu_id.data,
                    email=form.email.data,
                    full_name=form.full_name.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash(u'Congratulations, you are now a registered user!', 'success')
        return redirect('login')
    return render_template('register.html', title='Register', form=form)
コード例 #11
0
def new_user():
    """
    Add new user
    """
    form = request.form
    first_name = form["first_name"]
    last_name = form["last_name"]
    email = form["email"]
    password = form["password"]

    user = User(first_name=first_name, last_name=last_name, email=email, password=password, active=True)
    db.session.add(user)
    db.session.commit()

    return redirect(request.referrer)
コード例 #12
0
def register_user():
    """Create user"""
    try:
        firstname = request.json['firstname']
        lastname = request.json['lastname']
        email = request.json['email']
        password = generate_password_hash(request.json['password'],
                                          method='sha256')
        phonenumber = request.json['phonenumber']
        username = request.json['username']
        othername = request.json['othername']
    except KeyError:
        return jsonify({'message': 'some fields are missing'}), 400
    return User().register_user(firstname, lastname, email, phonenumber,
                                username, othername, password)
コード例 #13
0
def create_user_page():
    form = UserProfileForm(request.form, obj=current_user)

    if request.method == 'POST':
        user = User.query.filter(User.email == request.form['email']).first()
        if not user:
            user = User(email=request.form['email'],
                        full_name=request.form['full_name'],
                        password=current_app.user_manager.hash_password(
                            request.form['password']),
                        active=True,
                        email_confirmed_at=datetime.datetime.utcnow())
            db.session.add(user)
            db.session.commit()
        return redirect(url_for('main.user_admin_page'))
    return render_template('views/admin/create_user.html', form=form)
コード例 #14
0
def register():
    """
    Register a user
    """
    try:
        email = request.json.get('email', None)
        username = request.json.get('username', None)
        password = request.json.get('password', None)

        user = User(email=email, username=username, password=password)
        db.session.add(user)
        db.session.commit()

        return 'Success', 200

    except AttributeError:
        return 'Provide a Username and Password in JSON format in the request body', 400
コード例 #15
0
def find_or_create_user(first_name, last_name, username, email, password, role=None, bio=''):
    """ Find existing user or create new user """
    user = User.query.filter(User.email == email).first()
    if not user:
        user = User(username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                    password=current_app.user_manager.password_manager.hash_password(password),
                    active=True,
                    email_confirmed_at=datetime.datetime.utcnow())
        if role:
            user.roles.append(role)
        if bio:
            user.bio=bio
        db.session.add(user)
    return user
コード例 #16
0
def parse_authorized_response(resp):

    global uandus_client

    if resp is None:
        flash('Authentication failed.')
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    if isinstance(resp, dict):
        session['access_token'] = (resp['access_token'], '')
        session['refresh_token'] = (resp['refresh_token'], '')
        uandus_client.set_auth(access_token=session['access_token'][0],
                               refresh_token=session['refresh_token'][0])

    elif isinstance(resp, OAuthResponse):
        print(resp.status)
        if resp.status != 200:
            session['access_token'] = None
            session['refresh_token'] = None
            # session['uandus_client'] = None
            return redirect(url_for('index'))
        else:
            session['access_token'] = (resp.data['access_token'], '')
            session['refresh_token'] = (resp.data['refresh_token'], '')
            uandus_client.set_auth(access_token=session['access_token'][0],
                                   refresh_token=session['refresh_token'][0])
    else:
        raise Exception()

    user_info = uandus_client.user_me()

    user = User.query.filter(User.username == user_info['username']).first()
    if not user:
        user = User(username=user_info['username'],
                    first_name=user_info['first_name'],
                    last_name=user_info['last_name'],
                    email=user_info['email'])
        db.session.add(user)
        db.session.commit()
    elif user:
        user.first_name = user_info['first_name']
        user.last_name = user_info['last_name']
        user.email = user_info['email']
        db.session.commit()
    login_user(user, True)
    return user
コード例 #17
0
ファイル: user_service.py プロジェクト: wflin/yanyanbiji
def register(telephone, password):
    """
    手机验证码注册
    :param telephone:
    :param password:
    :return:
    """
    session = g.session
    result = session.query(User).filter(User.username == telephone).one_or_none()
    if result:
        return False, msg.A_EXIST
    model = User(telephone=telephone, password=password)
    session.add(model)
    session.flush()
    model_id = model.id
    session.commit()
    return True, model_id
コード例 #18
0
def create_user(first_name, last_name, email, password, roles=None):

    user = User(email=email,
                first_name=first_name,
                last_name=last_name,
                password=password,
                active=True)

    if roles:
        user.roles.extend(roles)
    else:
        user_role = Role.query.filter(Role.name == 'user').first()
        if user_role is not None:
            user.roles.append(user_role)

    db.session.add(user)
    db.session.commit()

    return user
コード例 #19
0
ファイル: main_views.py プロジェクト: tejasrivastav/gta
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    lastname = request.json.get('lastname')
    firstname = request.json.get('firstname')
    if username is None or password is None:
        abort(400)  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # existing user
    user = User(username=username, lastname=lastname, firstname=firstname)
    user.hash_password(password)
    db.session.add(user)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        raise
    finally:
        db.session.close()
    return (jsonify({'username': user.username}), 201, {
        'Location': url_for('main.get_user', id=user.id, _external=True)
    })
コード例 #20
0
ファイル: init_db.py プロジェクト: souvikmaji/healthcare
def find_or_create_user(first_name, last_name, ph_no, email, password,
                        medicine_name):
    """ Find existing user or create new user """
    user = User.query.filter(User.email == email).first()
    if not user:
        morning = MedicineSchedule(time=datetime(2018, 12, 25, 7, 0))
        noon = MedicineSchedule(time=datetime(2018, 1, 1, 12, 0))
        night = MedicineSchedule(time=datetime(2019, 5, 2, 17, 0))

        medicine = UserMedicine(medicine_name=medicine_name,
                                schedule=[morning, noon, night])
        user = User(email=email,
                    first_name=first_name,
                    last_name=last_name,
                    ph_no=ph_no,
                    password=current_app.user_manager.hash_password(password),
                    active=True,
                    confirmed_at=datetime.utcnow(),
                    medicines=[medicine])

        db.session.add(medicine)
        db.session.add(user)
    return user
コード例 #21
0
def get_users():
    """Get all users"""
    return User().get_users()
コード例 #22
0
def admin_create_tutor():

    form = TutorCustomForm()
    # this next line needed for a validation in the user model class
    form.id = -1

    # adding the full set of select options to the select list
    addTutorFormChoices(form)
    if form.add_time.data:
        form.dates.append_entry()
        return render_template('admin/admin_create_edit_tutor.html',
                               form=form,
                               time_state='manage_time',
                               state='Create')

    if form.remove_time.data:
        removeTime(form)
        return render_template('admin/admin_create_edit_tutor.html',
                               form=form,
                               time_state='manage_time',
                               state='Create')

    if form.validate_on_submit():
        user = User()
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        user.email = form.email.data
        user.roles = []
        for role_id in form.roles.data:
            roleObj = Role.query.filter(Role.id == role_id).first()
            user.roles.append(roleObj)

        user.password = current_app.user_manager.password_manager.hash_password(
            form.password.data)

        tutor = Tutor()
        tutor.tutor_phone = form.phone.data
        tutor.display_in_sched = form.display_in_sched.data

        tutor.languages = []
        for lang in form.languages:
            if lang.checked is True:
                langObj = Language.query.filter(
                    Language.id == lang.data).first()
                tutor.languages.append(langObj)

        tutor.courses = []
        for course in form.courses:
            if course.checked is True:
                courseObj = Course.query.filter(
                    Course.id == course.data).first()
                tutor.courses.append(courseObj)

        for date_group in form.dates:
            time = Time()
            time.time_day = date_group['time_day'].data
            time.time_start = date_group['time_start'].data
            time.time_end = date_group['time_end'].data
            tutor.dates.append(time)

        user.tutor = tutor
        db.session.add(user)
        db.session.commit()

        flash('User Created!!', 'success')
        return redirect(url_for('admin.admin_list_users'))
    return render_template('admin/admin_create_edit_tutor.html',
                           form=form,
                           state='Create')