def create_user_from_email(email):
    username, _ = email.split("@")
    user = User(username=username, email=email)
    user.save()
    password = generate_random_password()
    user.set_password(password)
    user.profile.email = email
    user.profile.save()
    return user
Пример #2
0
def edit():
    if current_user.permission_lvl < 4:
        flash('You have no permission to do this action.')
        return redirect(url_for('req.index'))

    identifier = request.args.get('staff_id')

    if identifier:
        user_to_edit = User.query.filter_by(staff_id=identifier).first()

        if user_to_edit.permission_lvl == 4:
            flash('To prevent disaster, you cannot edit an Administrator account')
            return redirect(url_for('admin.admin'))

        form = AccountManagerForm(obj=user_to_edit)
        del form.staff_id  # Cannot edit a staff ID
    else:
        form = AccountManagerForm()

    if form.validate_on_submit():
        if not identifier:  # This is an add operation
            to_add = User(staff_id=form.staff_id.data,
                          staff_name=form.staff_name.data,
                          staff_designation=form.staff_designation.data,
                          permission_lvl=int(form.permission_lvl.data),
                          team=form.team.data)
            db.session.add(to_add)
            to_add.set_password('test')  # This is the default password of a newly created account

            db.session.commit()
            flash('User successfully added.')
            return redirect(url_for('admin.admin'))

        else:
            to_edit = User.query.filter_by(staff_id=identifier).first()

            if to_edit.staff_name == form.staff_name.data and \
                    to_edit.staff_designation == form.staff_designation.data and \
                    to_edit.permission_lvl == int(form.permission_lvl.data) and \
                    to_edit.team == form.team.data:
                flash('No change was made to the database.')
                return redirect(url_for('admin.admin'))

            to_edit.staff_name = form.staff_name.data
            to_edit.staff_designation = form.staff_designation.data
            to_edit.permission_lvl = int(form.permission_lvl.data)
            to_edit.team = form.team.data

            db.session.commit()
            flash('User successfully edited.')
            return redirect(url_for('admin.admin'))

    return render_template('admin/edit.html', title='User Manager', form=form)
Пример #3
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Registration successful.')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Пример #4
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    form = RegisterForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data.lower()
        username = form.username.data
        password = form.password.data
        user = User(name=name, email=email, username=username)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        flash('已成功注册', 'info')
        return redirect(url_for('login'))
    return render_template('register.html', form=form, bs=bs)
Пример #5
0
def user_signup(request):
    context = {

    }
    if request.is_ajax():
        response_data = {}

        data = json.loads(request.body.decode('utf-8'))
        postEmail = data.get('email')
        postUsername = data.get('username')
        postPassword = data.get('password')

        user = User(email=postEmail, username=postUsername)
        user.set_password(postPassword)
        try:
            user.save()

        except IntegrityError as e:
            response_data['status'] = False
            response_data['msg'] = 'Sorry! This email is already signed up.'
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json"
                                )
        response_data['status'] = True
        response_data['msg'] = 'Success!'

        return HttpResponse(
                    json.dumps(response_data),
                    content_type="application/json"
                )


    else:
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                form.save()

        else:
            form = UserCreationForm()

        context.update({'form': form})
        return render(request, 'main/pages/signup.html', context)
Пример #6
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index.index'))
    form = RegisterForm()
    if form.validate_on_submit():
        email = request.form['email'].lower()
        user = User.query.filter_by(email=email).first()
        print(user)
        if user is not None:
            flash('The email is already registered, please log in.')
            return redirect(url_for('auth.login'))
        nickname = request.form['nickname']
        password = request.form['password1']
        user = User(email=email, nickname=nickname)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        flash('Registered successful, please log in.')
        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form)
def initdb(drop):
   if drop:
      click.confirm('你想删除全部数据吗?', abort=True)
      db.drop_all()
      click.echo('已删除')
   db.create_all()
   admin = User.query.filter_by(is_admin=True).first()
   if admin:
      password = os.getenv("ADMIN_PASSWORD")
      username = os.getenv("ADMIN_USERNAME")
      admin.username = username
      admin.set_password(password)
   else:
      password = os.getenv("ADMIN_PASSWORD")
      username = os.getenv("ADMIN_USERNAME")
      name = os.getenv("ADMIN_NAME")
      email = os.getenv("ADMIN_EMAIL")
      admin = User(username=username,name=name,email=email,Intellectual_disability=0,is_admin=True)
      admin.set_password(password)
      db.session.add(admin)
   db.session.commit()
   click.echo('已完成')
Пример #8
0
def user_signup(request):
    context = {}
    if request.is_ajax():
        response_data = {}

        data = json.loads(request.body.decode('utf-8'))
        postEmail = data.get('email')
        postUsername = data.get('username')
        postPassword = data.get('password')

        user = User(email=postEmail, username=postUsername)
        user.set_password(postPassword)
        try:
            user.save()

        except IntegrityError as e:
            response_data['status'] = False
            response_data['msg'] = 'Sorry! This email is already signed up.'
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")
        response_data['status'] = True
        response_data['msg'] = 'Success!'

        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")

    else:
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                form.save()

        else:
            form = UserCreationForm()

        context.update({'form': form})
        return render(request, 'main/pages/signup.html', context)
Пример #9
0
    def post(self,
             request,
             method,
             phone_number,
             password,
             validation_code,
             invitation_code=None,
             icon=DEFAULT_ICON_URL,
             wechatid=None,
             nickname=None,
             gender=0,
             province=None,
             city=None):
        """注册,若成功返回用户令牌"""

        if method == 'phone':
            if User.objects.filter(phone_number=phone_number).count() > 0:
                abort(403, '用户已经注册')
                return
        elif method == 'wechat':
            if wechatid is None or nickname is None:
                abort(400, 'wechatid 或昵称不能为空')
                return
            # 防止绑定过微信的用户重复绑定
            if User.objects.filter(wechat_id=wechatid).count() > 0:
                abort(403, '用户已经注册')
                return
            user = User.objects.filter(phone_number=phone_number).first()
            if user is not None:
                # 绑定已经使用手机号注册的账户
                User.objects.filter(phone_number=phone_number).update(
                    wechat_id=wechatid)
                return JsonResponse({'token': user.token})
        else:
            abort(400)
            return
        if not UserValidationCode.verify(phone_number, validation_code):
            abort(400, '验证码错误')

        with transaction.atomic():
            try:
                user = User(phone_number=phone_number,
                            wechat_id=wechatid,
                            city=city,
                            province=province,
                            gender=gender,
                            icon=icon)
                user.set_password(password)
                user.generate_info(phone_number)
                user.save()
                code, desc = register_to_huanxin(phone_number, user.password,
                                                 user.name)
                if code != 200:
                    raise RuntimeError(desc)
                if invitation_code:
                    self.__add_invited_users(request.user,
                                             invitation_code.split(','))
                # 加积分
                user.score += get_score_stage(3)
                user.score_records.create(score=get_score_stage(3),
                                          type="初始数据",
                                          description="首次手机号注册")
                return JsonResponse({'token': user.token})
            except RuntimeError as e:
                print(e)
                abort(403, str(e) or '创建用户失败')
Пример #10
0
class BaseConfiguration(TestCase):

    ZAKAZSCHIK1_LOGIN = '******'
    ZAKAZSCHIK2_LOGIN = '******'
    ZAKUPSCHIK_LOGIN = '******'
    ADMINISTRATOR_LOGIN = '******'
    PASSWORD = '******'

    def setUp(self) -> None:
        birth_date = date(1960, 10, 23)

        self.zakazschik1 = User(
            email=self.ZAKAZSCHIK1_LOGIN,
            phone='+7-999-23-12',
            delivery_address='Test Address 111',
            birth_date=birth_date,
            role=Roles.ZAKAZSCHIK,
        )
        self.zakazschik1.set_password(self.PASSWORD)
        self.zakazschik1.save()

        self.zakazschik2 = User(
            email=self.ZAKAZSCHIK2_LOGIN,
            phone='+7-999-23-55',
            delivery_address='Test Address 222',
            birth_date=birth_date - timedelta(weeks=100),
            role=Roles.ZAKAZSCHIK,
        )
        self.zakazschik2.set_password(self.PASSWORD)
        self.zakazschik2.save()

        self.zakupschik = User(
            email=self.ZAKUPSCHIK_LOGIN,
            phone='+7-555-11-22',
            delivery_address='Test Address 333',
            birth_date=birth_date + timedelta(weeks=55),
            role=Roles.ZAKUPSCHIK,
        )
        self.zakupschik.set_password(self.PASSWORD)
        self.zakupschik.save()

        self.administrator = User(
            email=self.ADMINISTRATOR_LOGIN,
            phone='+7-333-44-55',
            delivery_address='Test Address 444',
            birth_date=birth_date - timedelta(weeks=200),
            role=Roles.ADMINISTRATOR,
        )
        self.administrator.set_password(self.PASSWORD)
        self.administrator.save()

        SettingOptionHandler('extra_charge').value = 10  # 10%
        self.extra_charge = SettingOptionHandler('extra_charge').value

        self.client = Client()

    def tearDown(self) -> None:
        Order.objects.all().delete()
        OrderItem.objects.all().delete()
        Product.objects.all().delete()
        SettingOption.objects.all().delete()
        SettingOptionImages.objects.all().delete()

    @staticmethod
    def get_image_file(name='test.png',
                       ext='png',
                       size=(50, 50),
                       color=(256, 0, 0)):
        file_obj = BytesIO()
        image = Image.new("RGBA", size=size, color=color)
        image.save(file_obj, ext)
        file_obj.seek(0)
        return File(file_obj, name=name)

    def check_for_created_objects(self, orders=0, order_items=0, products=0):
        self.assertEqual(Order.objects.count(), orders)
        self.assertEqual(OrderItem.objects.count(), order_items)
        self.assertEqual(Product.objects.count(), products)
Пример #11
0
 def test_password_hashing(self):
     u = User(username='******')
     u.set_password('cat')
     self.assertFalse(u.check_password('dog'))
     self.assertTrue(u.check_password('cat'))
Пример #12
0
    def forge(message):
        """Generate fake data."""
        import random, json
        from sqlalchemy.exc import IntegrityError

        from faker import Faker

        fake = Faker(locale='en_GB')

        click.echo('Initializing the database...')
        db.drop_all()
        db.create_all()

        click.echo('Forging the data...')
        admin = User(nickname='Fanco', email='*****@*****.**')
        admin.set_password('123456')
        db.session.add(admin)
        db.session.commit()
        
        click.echo('Generating users...')
        for i in range(30):
            user = User(
                nickname=fake.name(),
                email=fake.email())
            db.session.add(user)
        db.session.commit()

        click.echo('Generating rooms...')
        for i in range(7):
            leader = User.query.get(random.randint(1, User.query.count()))
            room = Room(
                name=fake.word(),
                leader=leader.nickname
            )
            room.users.append(leader)
            print(room.name, room.leader)
            users_list = [User.query.get(random.randint(1, User.query.count())) for i in range(1,random.randrange(4,6))]
            for user in users_list:
                room.users.append(user)
            print("room:",room, ";members:",room.users)
            db.session.add(room)
        db.session.commit()

        # click.echo('Generating users...')
        # for i in range(30):
        #     user = User(
        #         nickname=fake.name(),
        #         email=fake.email(),
        #         room=Room.query.get(random.randint(1, Room.query.count())),
        #                 )
        #     db.session.add(user)
        #     try:
        #         db.session.commit()
        #     except IntegrityError:
        #         db.session.rollback()

        click.echo('Generating messages...')
        for i in range(message):
            set_room = Room.query.get(random.randint(1, Room.query.count()))
            set_user = random.choice(set_room.users)
            message = Message(
                user=set_user,
                body=fake.sentence(),
                timestamp=fake.date_time_between('-30d', '-2d'),
                room=set_room
            )
            db.session.add(message)

        db.session.commit()

        click.echo('Generating words...')
        file = os.path.join(os.path.split(os.path.dirname(__file__))[0], 'topic.json')
        with open(file, 'r') as f:
            questions = json.load(f)
        print(questions)
        print(type(questions))
        for category in questions:
            for word in questions[category]:
                new_instance = Word(name=word, category=category)
                db.session.add(new_instance)
                print(word)
        try:
            db.session.commit()

        except IntegrityError:
            db.session.rollback()

        click.echo('Done.')