Exemple #1
0
def register(request):
	try:
		# register a new user
		sys_time = str(datetime.datetime.now())
		hash_md5 = hashlib.md5(sys_time)		
		hash_pwd = hashlib.md5(request.POST['password'])

		user_id = hash_md5.hexdigest()
		username = request.POST['username']
		email = request.POST['email']		
		encoded_pwd = hash_pwd.hexdigest()
		
		user = User(user_id = user_id, name = username, email = email, password = encoded_pwd)
		user.save()
		cust_id = user.id		
		print "auto customer id: %d" % cust_id

	except KeyError:
		render(request, 'demo/user.html', {
			'error_message': "Username has already existed!"
			})

	# redirect back to businesses page
	else:
		# reverse to business page 1
		return HttpResponseRedirect(reverse('demo:business', args = (1, cust_id,)))
Exemple #2
0
 def mutate(self, info, **kwargs):
     user = UserModel()
     user.from_dict(kwargs, new_user=True)
     db.session.add(user)
     db.session.commit()
     return SignUp(user=user,
                   auth_token=user.encode_auth_token(user.id).decode())
Exemple #3
0
def register(request):
    if not 'user' in request.session:
        return render(request, 'index.html', {
            'page': 'index',
            'message': 'Please login first'
        })
    elif request.method == 'GET':
        return render(request, 'register.html', {
            'page': 'register',
            'message': ''
        })
    else:
        name = request.POST['username']
        users = User.objects.filter(username__exact=name)
        if users.count() > 0:
            return render(request, 'register.html', {
                'page': 'register',
                'message': 'Username is not available'
            })
        else:
            b = User(username=name,
                     fullname=request.POST['fullname'],
                     password=request.POST['password'])
            b.save()
            return render(
                request, 'content.html', {
                    'page': 'content',
                    'message':
                    'New user registered: ' + request.POST['fullname']
                })
def store(request):
    data = {
        'name': request.POST.get('name'),
        'email': request.POST.get('email')
    }
    p = User(name=request.POST.get('name'), email=request.POST.get('email'))
    p.save()
    return render(request, "show.html", data)
Exemple #5
0
def reg(request):
    if request.method == "POST":
        uf = UserForm(request.POST, request.FILES)
        if uf.is_valid():
            username = uf.cleaned_data["username"]
            uploadImg = uf.cleaned_data["uploadImg"]
            user = User()
            user.username = username
            user.uploadImg = uploadImg
            user.save()
            return HttpResponse("upload ok!")
    else:
        uf = UserForm()
    return render_to_response("reg.html", {"uf": uf})
Exemple #6
0
async def profile_validation(request):
    """Simple email validation"""
    data = await request.json(loads=ujson.loads)
    user = User(data)

    try:
        user.validate()
    except ModelValidationError as e:
        logger.debug(e.messages['email'].messages)
        return Response({
            'valid': False,
            'errors': e.messages,
        },
                        status=status.HTTP_409_CONFLICT)

    return Response({'valid': True})
def add_user(name, email, username, password, avatar_path):
    '''

    :param name: tên của khách hàng đăng ký
    :param email: email của khách hàng
    :param username: tên đăng nhập
    :param password: mật khẩu của người dùng được băm md5
    :param avatar_path: đường dẩn ảnh của người dùng
    :return: nếu thành công sẽ add vào database còn nếu lỗi thì xuất ra lỗi.

    '''
    password = str(hashlib.md5(password.encode('utf-8')).hexdigest())
    U = User(name=name,
             email=email,
             username=username,
             password=password,
             avatar=avatar_path)

    try:
        db.session.add(U)
        db.session.commit()
        return True
    except Exception as ex:
        print(ex)
        return False
Exemple #8
0
 def get(self):
     result = db.session.query(User.id).order_by(User.id.desc()).first()
     if not result:
         url = url_for('.add')
         return redirect(url)
     user_id, = result
     user = User.get(user_id)
     return render_template('index.html', user=user)
Exemple #9
0
 def post(self, user_id):
     user = User.get_or_404(user_id)
     form = UserForm()
     if form.validate():
         u = form.save(user)
         return str(u)
     else:
         return jsonify(errors=form.errors)
 def construct_new_user(new_user):
     if UserService.valid_user(new_user):
         __username = new_user.get('username')
         __sex = new_user.get('sex')
         new_y_m_d__date = datetime.strptime(new_user.get('birthday'),
                                             '%y-%m-%d').date()
         __birthday = new_y_m_d__date
         return User(username=__username, sex=__sex, birthday=__birthday)
     else:
         log.warn("invalid user {}".format(new_user))
    def post(self, request, *args, **kwargs):
        name = request.POST.get('name')
        imei = request.POST.get('imei')
        enabled = request.POST.get('enabled')
        administrator = request.POST.get('administrator')

        auth = 0
        admin = 0
        if enabled:
            auth = 1

        if administrator:
            admin = 1
            mydevice = MyDevice(name=name, dev_id=imei)
            mydevice.save()

        insert = User(name=name, imei=imei, auth=auth, admin=admin)
        insert.save()
        return redirect('/demo/users')
Exemple #12
0
def user_list(request, db=0):
    """
    List all users under db, or create a new user.
    """
    if request.method == 'GET':
        users = User.objects.using(db).all()
        serializer = UserSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        print("post....")
        data = JSONParser().parse(request)
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            user = User(name=data['name'])
            user.save()
            # serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Exemple #13
0
async def get_user(request):
    user_id = request.match_info.get('id', None)
    logger.debug(user_id)

    pool = request.app['pool']
    # Take a connection from the pool.
    async with pool.acquire() as connection:
        # # Open a transaction.
        # async with connection.transaction(readonly=True):
        # Run the query passing the request argument.
        result = await connection.fetchrow(
            'SELECT * FROM accounts_user WHERE id=$1', user_id)

        if result:
            logger.debug(result)
            user = User(dict(result.items()))
            return Response(user.to_primitive())

    return Response(status=status.HTTP_404_NOT_FOUND)
    def post(self, request, *args, **kwargs):
        name = request.POST.get('name')
        imei = request.POST.get('imei')
        enabled = request.POST.get('enabled')
        administrator = request.POST.get('administrator')

        auth = 0
        admin = 0
        if enabled:
            auth = 1

        if administrator:
            admin = 1
            mydevice = MyDevice(name=name, dev_id=imei)
            mydevice.save()

        insert = User(name=name, imei=imei, auth=auth, admin=admin)
        insert.save()
        return redirect('/demo/users')
Exemple #15
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data.lower(),
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        # send confirmation email
        token = user.generate_confirmation_token()
        send_email(
            to=user.email,
            subject='Confirmation Your Account',
            template='auth/email/confirm',
            username=user.username,
            token=token
        )
        flash('Signed Up. Confirmation Email Sent')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)
 def post(self, request, format=None):
     # delete mappings
     all_mappings = Mapping.objects.all().delete()
     # re-initialize mapping
     sharded_model.init_mapping()
     # delete all objects
     customized_models = importlib.import_module(settings.CUSTOMIZED_MODEL_MODULE)
     shardable_models = settings.SHARDABLE_MODELS.split(',')
     for model in shardable_models:
         for db in settings.DATABASES.keys():
             model_to_del = getattr(customized_models, model)
             model_to_del.objects.using(db).all().delete()
     for i in ['Jack', 'Mengyang', 'Ziyao', 'Shelly', 'Bob', 'Alice']:
         u = User(name=i)
         u.save()
         comment_list = ['Yeah!', 'Sure.', 'OK', 'Wow!', 'Hey!', 'Now?', 'What?', 'Apple', 'Banana', 'Orange', 'Peach', 'No!', 'Yooooo']
         for i in range(5):
             p = Post(shard_key=u, content=random.choice(comment_list))
             p.save()
     return Response(status=status.HTTP_202_ACCEPTED)
Exemple #17
0
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        if User.reset_password(token, form.password.data):
            db.session.commit()
            flash('Your password has been updated.')
            return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)
Exemple #18
0
def register_user(name, email, username, password, avatar):
    password = str(hashlib.md5(password.strip().encode('utf-8')).hexdigest())
    u = User(name=name,
             email=email,
             username=username,
             password=password,
             avatar=avatar,
             user_role=UserRole.KH)
    try:
        db.session.add(u)
        db.session.commit()
        return True
    except:
        return False
Exemple #19
0
def post_list(request, fk):
    """
    List all posts for a user, or create a new post.
    """
    if request.method == 'GET':
        # TODO: need Shelly to debug post get method
        user = User(name=fk)
        posts = Post.objects.get(shard_key=user)
        serializer = PostSerializer(posts, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        try:
            print("post post....")
            data = JSONParser().parse(request)
            print(data)
            user = User.objects.get(name=data['shard_key'])
            user.save()
            post = Post(shard_key=user, content=data['content'])
            post.save()
            return JsonResponse(data, status=201)
        except:
            return JsonResponse('Error when creating post', status=400)
Exemple #20
0
def register():
    # 表单处理
    if request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        check_password = request.form['check_password']

        if(password != check_password):
            flash("两次密码输入不同")
            redirect(url_for('register'))
        
        user_num = User.query.filter_by(username=username).count()
        if user_num == 0:
            user = User(username=username)
            user.set_password(password)
            db.session.add(user)
            db.session.commit()
            redirect(url_for('login'))
        else:
            flash("用户已存在")
            redirect(url_for('register'))

    return render_template('register.html')
Exemple #21
0
    def save(self, user=None):
        if not user:
            user = User()
        user.name = self.name.data

        user.save()
        db.session.commit()
        user = User.get(user.id)
        return user
Exemple #22
0
def registerdone(request):
        user = User(
            username=request.POST.get( 'ID', False ),
            last_name=request.POST.get( 'NAME', False ),
            email=request.POST.get( 'EMAIL', False )
        )
        user.set_password(request.POST.get('PWD',False))
        user.save()
        return render(request,'demo/registerdone.html')
Exemple #23
0
def oauth_callback(provider):
    """Callback route, saves token in session and extract user information
    """
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    oauth = provider_class_map[provider]()
    email, username = oauth.callback()
    # if user with email already exists, then don't create new user 
    user = User.query.filter_by(email=email).first()
    if not user:
        user = User(email=email, username=username, confirmed=True)
        db.session.add(user)
        db.session.commit()
    login_user(user, remember=True)
    return redirect(url_for('main.index'))
Exemple #24
0
def verify_password(email_or_token, password):
    """authentication verification with either login credentials or tokens
    """
    if email_or_token == '':
        return False
    if password == '':
        # verify token
        g.current_user = User.verify_auth_token(email_or_token)
        g.token_used = True
        return g.current_user is not None
    # verify email
    user = User.query.filter_by(email=email_or_token).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password)
Exemple #25
0
def users(count=100):
    fake = Faker()
    i = 0
    while i < count:
        u = User(email=fake.email(),
                 username=fake.user_name(),
                 password='******',
                 confirmed=True,
                 name=fake.name(),
                 location=fake.city(),
                 about_me=fake.text(),
                 member_since=fake.past_date())
        db.session.add(u)
        try:
            db.session.commit()
            i += 1
        except IntegrityError:
            db.session.rollback()
            raise IntegrityError
Exemple #26
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        password2 = request.form["password2"]

        if not username or not password and password != password2:
            flash('输入有误')
            return redirect(url_for('register'))
        user = User.query.first()
        if username == user.username and user.validate_password(password):
              user = User(username=request.form['username'], password=request.form['password'])
            db.session.add(user)
            db.session.commit()
            
            flash('注册成功')
            return redirect(url_for('login'))
        flash('验证失败')
        return redirect(url_for('register'))
Exemple #27
0
 def create(self, validated_data):
     user = User(email=validated_data['email'])
     user.set_password(validated_data['password'])
     user.save()
     return user
Exemple #28
0
def test():
    user = User()
    user.time = datetime.datetime.now()
    user.save()
    print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
Exemple #29
0
def register_page(request):
    result = '请输入用户名、密码'
    register_username = request.POST.get('register_username')
    register_password = request.POST.get('register_password')
    register_email = request.POST.get('register_email')
    exist_user = User.objects.filter(username=register_username)
    if exist_user:
        result = '用户名已存在'
        return render(request, 'register.html', {'result': result})

    if register_username != '':
        if 6 <= len(str(register_username)) <= 16 and 6 <= len(
                str(register_username)) <= 16:
            for i in register_username:
                if 48 <= ord(i) <= 57 or 65 <= ord(i) <= 90 or ord(
                        i) == 95 or 97 <= ord(i) <= 122:
                    pass
                else:
                    result = "存在不合法字符"
            for i in register_password:
                if 48 <= ord(i) <= 57 or 65 <= ord(i) <= 90 or ord(
                        i) == 95 or 97 <= ord(i) <= 122:
                    pass
                else:
                    result = "存在不合法字符"
            if result != "存在不合法字符":
                u = User()
                u.username = register_username
                u.password = register_password
                u.email = register_email
                u.gendle = request.POST.get('gendle')
                u.birth_place = request.POST.get('birth_place')
                u.university = request.POST.get('university')
                u.age = request.POST.get('age')
                u.weigth = request.POST.get('weigth')
                u.heigth = request.POST.get('heigth')
                u.language = request.POST.get('language')
                u.birthday = request.POST.get('birthday')
                u.question1 = request.POST.get('question1')
                u.answer1 = request.POST.get('answer1')
                u.question2 = request.POST.get('question2')
                u.answer2 = request.POST.get('answer2')
                u.question3 = request.POST.get('question3')
                u.answer3 = request.POST.get('answer3')
                u.save()
                result = '注册成功'
                return redirect('demo:demo_login')
        else:
            result = '请输入6-16位用户名、密码'
    else:
        result = '请输入用户名、密码'
    return render(request, 'register.html', {'result': result})
Exemple #30
0
 def wrapper(self, *args, **kwargs):
     auth_resp = UserModel.decode_auth_token(args[0].context)
     if not isinstance(auth_resp, str):
         kwargs['user'] = UserModel.query.filter_by(id=auth_resp).first()
         return method(self, *args, **kwargs)
     raise GraphQLError(auth_resp)
Exemple #31
0
 def get(self, user_id):
     """编辑页面"""
     user = User.get_or_404(user_id)
     form = UserForm(obj=user)
     return render_template('user-edit.html', form=form, user=user)
Exemple #32
0
def stripe_webhook():
    print('WEBHOOK CALLED')

    if request.content_length > 1024 * 1024:
        print('REQUEST TOO BIG')
        abort(400)
    payload = request.get_data()
    sig_header = request.environ.get('HTTP_STRIPE_SIGNATURE')
    endpoint_secret = current_app.config['STRIPE_WEBHOOK_SECRET']
    event = None

    try:
        event = stripe.Webhook.construct_event(payload, sig_header,
                                               endpoint_secret)
    except ValueError as e:
        # Invalid payload
        print('INVALID PAYLOAD')
        return {}, 400
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        print('INVALID SIGNATURE')
        return {}, 400

    # Handle the checkout.session.completed event
    if event['type'] == 'checkout.session.completed':
        data = event['data']['object']
        parsed_info = {
            'user_id': data['client_reference_id'],
            'stripe_customer_id': data['customer'],
        }
        # first link the stripe customer to the user
        User.parse_event_checkout_completed(parsed_info)

        # then create the subscription object
        subscription_data = stripe.Subscription.retrieve(data['subscription'])

        subscription = Subscription(user_id=data['client_reference_id'],
                                    plan=subscription_data['plan']['id'])
        db.session.add(subscription)
        db.session.commit()

    # Handle invoice.paid event
    if event['type'] == 'invoice.paid':
        data = event['data']['object']

        plan_info = data['lines']['data'][0]['plan']

        period_start_on = datetime.datetime.utcfromtimestamp(
            data['lines']['data'][0]['period']['start']).date()
        period_end_on = datetime.datetime.utcfromtimestamp(
            data['lines']['data'][0]['period']['end']).date()

        parsed_info = {
            'payment_id': data['customer'],
            'plan': plan_info['id'],
            'receipt_number': data['receipt_number'],
            'description': plan_info['nickname'],
            'period_start_on': period_start_on,
            'period_end_on': period_end_on,
            'currency': data['currency'],
            'tax': data['tax'],
            'tax_percent': data['tax_percent'],
            'total': data['total'],
        }

        Invoice.parse_event_save_invoice(parsed_info)

    return {}