Exemple #1
0
 def setUp(self):
     self.client = Client()
     self.user1 = User(username="******",
                       first_name="Fa",
                       password="******")
     self.user1.save()
     self.user2 = User(username="******",
                       first_name="Fa",
                       password="******")
     self.user2.save()
Exemple #2
0
def home():
    print "config.AUTHENTICATE {}".format(config.AUTHENTICATE)
    if config.AUTHENTICATE:
        return render_template('index.html',
                               login_form=LoginForm(),
                               create_form=CreateAccountForm())
    else:
        email = 'default'
        password = '******'
        access_key_id = config.AWS_ID
        secret_access_key = config.AWS_KEY
        aws_bucket_name = config.AWS_BUCKET_NAME
        next_backend_global_host = config.NEXT_BACKEND_GLOBAL_HOST
        if not User.objects(email=email):
            user = User(email=email,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        aws_bucket_name=aws_bucket_name,
                        next_backend_global_host=next_backend_global_host)
            user.set_password(password)
            user.save()
        else:
            user = User.objects(email=email).first()
        login_user(user, remember=True)
        return redirect(url_for('dashboard._dashboard'))
Exemple #3
0
 def saveUser(self, _param):
     """
     保存用户信息
     @param _param: 
     @return: 
     """
     flag_add = True
     user = User.objects.filter(
         pk=_param['id']).first() if _param.get('id', None) else None
     if user:
         flag_add = False
     if user and User.objects.exclude(pk=_param['id']).filter(
             username=_param['username']).count():
         raise ex(u'该用户名已经存在!')
     if not user:
         if _param.get('username', None) and User.objects.filter(
                 username=_param['username']):
             raise ex(u'该用户名已经存在!')
         user = User()
     dic2obj(user, [
         'username', 'truename', 'name', 'email', 'phone', 'department_id',
         'role_id'
     ], _param)
     if _param.get('password', ''):
         user.password = _param['password']
     user.save()
     self.logAtion(ActionLog.ACTION_MODIFY, User, user.id)
Exemple #4
0
def signup():
    vals = dict(request.form)
    for key, val in vals.items():
        vals[key] = val[0]

    email = vals.get('email')
    username = vals.get('username')

    user_db = User.query.filter_by(username=username).first()
    email_db = User.query.filter_by(email=email).first()

    if not user_db and not email_db:
        user = User(email=email,
                    username=username,
                    password=generate_password_hash(vals.get('password')))
        db.session.add(user)
        db.session.commit()
        return json.dumps({
            'status': 'success',
            'msg': 'Sign up successful! Please login now.'
        })
    else:
        response = {'status': 'failed', 'msg': ''}
        if user_db:
            response['msg'] += 'This username already exists. '
        if email_db:
            response['msg'] += 'This email already exists. '
        return json.dumps(response)
Exemple #5
0
def signup():
    user = User()
    form = UserForm()
    if form.validate_on_submit():
        form.populate_obj(user)
        user.save(force_insert=True)
        flash('Your account have been created')
        return redirect(url_for('index'))
    return render_template('index.html', form=form)
Exemple #6
0
def add_user():
    username = request.form["username"]
    if User.query.filter_by(username=username).count() > 0:
        return jsonify(Msg(False, gettext("User exists.")))
    password = request.form["password"]
    user = User(username, password)
    db.session.add(user)
    db.session.commit()
    return jsonify(Msg(True, gettext("User added Successfully.")))
Exemple #7
0
def submit(request):
    try:
        email = request.POST.get('email')
        locale_id = request.POST.get('locale_id')
        user = User(email=email.lower(), locale_id_id=locale_id, active=True)
        user.save()
        return HttpResponseRedirect(reverse('subscription:submitted'))
    except IntegrityError as err:
        log_error(err)
    return HttpResponseRedirect(reverse('subscription:nosubmit'))
Exemple #8
0
    def get(self):
        user = User('Test Name', '*****@*****.**')
        db.session.add(user)

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            app.logger.debug(e)

        return TODOS
Exemple #9
0
    def setUp(self):
        self.db = base.db
        self.db.create_all()
        self.client = self.app.test_client()

        u = User(username='******', email='*****@*****.**', password='******')
        bm = Bookmark(user=u, url="http://www.example.com", tags="one,two,three")
        self.db.session.add(u)
        self.db.session.add(bm)
        self.db.session.commit()

        self.client.post(url_for('auth.login'), data=dict(username='******', password='******'))
Exemple #10
0
    def POST(cls, *args, **kwargs):
        new_user = User()
        form = request.form
        new_user.nickname = form.get('nickname')
        new_user.password_hash = generate_password_hash(form.get('password'))
        new_user.image_url = form.get('image_url')
        new_user.about = form.get('about')
        new_user.footer_text = form.get('footer')
        new_user.email = form.get('email')

        db.session.add(new_user)
        db.session.commit()
        return cls.GET(*args, **kwargs)
Exemple #11
0
def app_add_user():
    try:
        app_add_user = User(**request.form)
        db.session.merge(app_add_user)
        db.session.commit()
        return json.dumps({'success': True}), 200, {
            'ContentType': 'application/json'
        }
    except Exception as e:
        print(e)
        return json.dumps({'success': False}), 400, {
            'ContentType': 'application/json'
        }
Exemple #12
0
    def __init__(self):
        global _player
        if _player is not None:
            raise "Player was initialized!"

        random.seed(time.clock())

        print("Starting player...")
        self.vlcInstance = vlc.Instance(
            "--live-caching=0 --network-caching=0 --norm-buff-size=8")
        self.vlcPlayer = self.vlcInstance.media_player_new()
        self.vlcEvents = self.vlcPlayer.event_manager()
        self.vlcEvents.event_attach(vlc.EventType.MediaPlayerEndReached,
                                    self.songFinished)
        self.vlcEvents.event_attach(vlc.EventType.MediaPlayerEncounteredError,
                                    self.songCorrupted)
        self.vlcEvents.event_attach(vlc.EventType.MediaStateChanged,
                                    self.mediaStateChanged)

        # Import old DJPajton playlist
        if Song.objects.count() == 0 and os.path.isfile('music4you.playlist'):
            with open("music4you.playlist", "r") as f:
                playlist = json.loads(f.read())
                for item in playlist:
                    print("Item: {}".format(item))

                    song = Song()
                    song.id = int(item['id'])
                    song.date = item['addedDate']
                    song.active = (bool(item['deleted']) == False)
                    song.url = item['url']
                    song.title = item['title']

                    try:
                        user = User.objects.get(login=item['addedLogin'])
                    except:
                        user = User()
                        user.active = False
                        user.type = USER_TYPE_SKYPE
                        user.login = item['addedLogin']
                        user.displayName = user.login
                        user.save()

                    song.user = user
                    song.save()

        #self.vlcPlayer.audio_set_volume(100)

        if Song.objects.count() == 0:
            return
Exemple #13
0
    def form_valid(self, form):
        # Create a user, but remember to set inactive!
        user = User()
        user.username = form.cleaned_data['email']
        user.email = form.cleaned_data['email']
        user.is_active = False
        try:
            user.save()
        except IntegrityError:
            form.add_error('email',
                           gettext('Shop with this email already exists.'))
            return super(ShopRegisterView, self).form_invalid(form)

        self.object = form.save(commit=False)
        self.object.postcode = Postcode.objects.get(
            postcode=form.cleaned_data['postcode_special'])
        self.object.user = user
        self.object.save()

        current_site = get_current_site(self.request)
        context = {
            'shopname': self.object.name,
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': account_activation_token.make_token(user),
        }

        html_message = render_to_string('emails/account_activation.html',
                                        context)
        txt_message = render_to_string('emails/account_activation.txt',
                                       context)

        email = EmailMultiAlternatives(gettext('FOODBEE - Confirm email'),
                                       txt_message)
        email.from_email = settings.DEFAULT_FROM_EMAIL
        email.to = [self.object.email]
        email.attach_alternative(html_message, "text/html")
        email.content_subtype = 'html'
        email.mixed_subtype = 'related'

        with open('base/static/base/img/fb_logo.png', mode='rb') as f:
            image = MIMEImage(f.read())
            image.add_header('Content-ID', "<Foodbee_logo_long.png>")
            email.attach(image)

        email.send()

        return super().form_valid(form)
Exemple #14
0
    def test_delete_user(self):
        self.user3 = User(username="******",
                          first_name="Ryan",
                          password="******")
        self.user3.save()
        user_detail = self.client.get('/users/%s/' % self.user3.pk)
        u_json_string = json.loads(user_detail.content.decode('utf-8'))
        self.assertEqual(user_detail.status_code, 200)

        user_delete = self.client.delete('/users/%s/' % self.user3.pk)
        self.assertEqual(user_delete.status_code, 204)

        user_detail = self.client.get('/users/%s/' % self.user3.pk)
        u_json_string = json.loads(user_detail.content.decode('utf-8'))
        self.assertEqual(user_detail.status_code, 404)
Exemple #15
0
def create():
    create_form = CreateAccountForm(request.form)
    if create_form.validate_on_submit():
        print "form data",create_form.new_email.data
        new_email = create_form.new_email.data
        new_password = create_form.new_password.data
        confirm_password = create_form.confirm_password.data
        print User.objects()
        if User.objects(email=new_email).count() == 0:
            if new_password == confirm_password:
                # Set the hashed password on the user.
                user = User(email=new_email)
                user.set_password(new_password)
                user.save()
                login_user(user, remember=True)
                return redirect(url_for('dashboard._dashboard'))
            else:
                flash("Passwords don't match!", "create_error")
                return redirect('#create')    
        else:
            flash("Username exists!", "create_error")
            return redirect('#create')
    # login form is not valid
    return render_template('index.html', login_form=LoginForm(), create_form=create_form)
sb3 = Sublocation(sublocation_name='Haus Khas Village');
sb1.save();
sb2.save();
sb3.save();

t1 = Tag(tag_name='government schools');
t2 = Tag(tag_name='advertising');
t3 = Tag(tag_name='legal');
t4 = Tag(tag_name='community project');

t1.save();
t2.save();
t3.save();
t4.save();

u1 = User(user_email='*****@*****.**');
u1.save();
u2 = User(user_email='*****@*****.**');
u2.save();

sk1 = Skill(skill_name='Information Architecture');
sk2 = Skill(skill_name='Web Development');
sk3 = Skill(skill_name='Photography&Filmography');
sk4 = Skill(skill_name='Brand Management');
sk5 = Skill(skill_name='Content Generation');
sk6 = Skill(skill_name='Stratergy Consulting');

sk1.save();
sk2.save();
sk3.save();
sk4.save();
Exemple #17
0
def init_user():
    if User.query.count() == 0:
        db.session.add(User("admin", "admin", True))
        db.session.commit()
Exemple #18
0
def init_user():
    if User.query.count() == 0:
        db.session.add(User('admin', 'admin'))
        db.session.commit()
Exemple #19
0
def add_user(request):
    '''用户添加'''
    context = {}
    context['add_user'] = True
    if request.method == 'GET':
        #获得职位信息
        positions = Position.objects.all()
        position_list = []
        for position in positions:
            position_list.append({
                'id': position.id,
                'name': position.name,
            })
        #获得部门信息
        departments = Department.objects.all()
        department_list = []
        for department in departments:
            department_list.append({
                'id': department.id,
                'name': department.name,
            })
        if department_list:
            context['department_list'] = department_list
        if position_list:
            context['position_list'] = position_list

    else:
        errorList = []
        username = request.POST['username']
        username_zh = request.POST.get('username_zh', '')
        mobile = request.POST['mobile']
        password = request.POST['password']
        confirm_password = request.POST['confirm_password']
        department = request.POST.get('department', '')
        position = request.POST.get('position', '')
        chief = request.POST.get('chief', '')
        short_phone = request.POST.get('short_phone', '')
        if password != confirm_password:
            errorList.append({'error': u'密码不一致'})
        else:
            user = User()
            if username:
                user.username = username
            if username_zh:
                user.username_zh = username_zh
            if mobile:
                user.mobile = mobile
            if department:
                user.department = Department.objects.get(id=int(department))
            if position:
                user.position = Position.objects.get(id=int(position))
            if short_phone:
                user.short_phone = short_phone
            user.set_password(password)
            try:
                user.full_clean()
                user.save()

            except ValidationError as e:
                # Do something based on the errors contained in e.message_dict.
                # Display them to a user, or handle them programmatically.
                errKeys = e.message_dict.keys()
                for errKey in errKeys:
                    errorList.append({'error': e.message_dict[errKey][0]})
        if errorList:
            context['errorList'] = errorList

    return render(request, 'base/settings.html', context)