コード例 #1
0
ファイル: views.py プロジェクト: ShadowDancer/django
def register_page(request):
    if request.method == 'POST':
        form = FormularzRejestracji(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
              username=form.cleaned_data['username'],
              password=form.cleaned_data['password1'],
            )
            user.save()
            acc = Account()
            acc.owner = user.username
            acc.balance = 0
            acc.save()
            
            if form.cleaned_data['log_on']:
                user = authenticate(username=form.cleaned_data['username'],password=form.cleaned_data['password1'])
                login(request,user) 
                return HttpResponseRedirect("/blog/") 
            else:    
                template = get_template("registration/register_success.html")
                variables = RequestContext(request,{'username':form.cleaned_data['username']})
                output = template.render(variables)
                return HttpResponse(output)            
    else:
        form = FormularzRejestracji()
    template = get_template("registration/register.html")    
    variables = RequestContext(request,{'form':form})
    output = template.render(variables)
    return HttpResponse(output)
コード例 #2
0
ファイル: app.py プロジェクト: sopnic/ybk
def add_user():
    mobile = request.form.get('mobile')
    username = request.form.get('username')
    password = request.form.get('password')
    u = User({'mobile': mobile, 'username': username,
              'password': password})
    u.upsert()
    i = 0
    lnames = []
    while True:
        login_name = request.form.get('accounts[{}][login_name]'.format(i))
        login_password = request.form.get(
            'accounts[{}][login_password]'.format(i))
        if login_name and login_password:
            a = Account({'user_id': u._id,
                         'login_name': login_name,
                         'login_password': login_password})
            a.upsert()
            lnames.append(login_name)
            i += 1
        else:
            break
    Account.delete_many({'user_id': u._id,
                         'login_name': {'$nin': lnames}})
    return jsonify(status=200)
コード例 #3
0
    def test_get_one_returns_entity(self):
        acc = Account(username=self.username, password=self.password, userid=self.userid)
        acc.put()

        result = Account.get_one()

        self.assertEqual(acc, result)
コード例 #4
0
ファイル: tests.py プロジェクト: tovmeod/anaf
    def test_model_liability(self):
        "Test liability model"
        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        currency = Currency(code="GBP",
                            name="Pounds",
                            symbol="L",
                            is_default=True)
        currency.save()

        account = Account(
            name='test', owner=contact, balance_currency=currency)
        account.save()

        obj = Liability(name='test',
                        source=contact,
                        target=contact,
                        account=account,
                        value=10,
                        value_currency=currency)
        obj.save()
        self.assertEquals('test', obj.name)
        self.assertNotEquals(obj.id, None)
        obj.delete()
コード例 #5
0
ファイル: wallet.py プロジェクト: rnicoll/nodeup-xk-io
def process_tx_initial(tx_obj: Tx):
    found_relevant_address = False
    for out in tx_obj.txs_out:
        address = out.bitcoin_address()
        if address in all_addresses:
            found_relevant_address = True
            break
    if not found_relevant_address:
        logging.info('Found irrelevant tx %s' % hash_to_hex(tx_obj.hash()))
        return

    tx_hash = tx_obj.hash()
    txid = hash_to_hex(tx_hash).decode()
    if tx_hash in known_txs:
        return
    known_txs.add(tx_hash)
    txs[tx_hash] = tx_obj.as_hex()
    for out in tx_obj.txs_out:
        address = out.bitcoin_address()
        if address in all_addresses and address is not None:
            unprocessed_txs.add(tx_hash)
            uid = addr_to_uid[address]
            account = Account(uid)
            account.txs.add(tx_hash)
            account.unconf_minutes.incr(calc_node_minutes(satoshi_amount=out.coin_value, exchange_rate=exchange_rate.get()))
            account.add_msg('Found tx for %.08f, %s' % (out.coin_value / COIN, txid))
            nodes_recently_updated.append(account.uid)
コード例 #6
0
def cw_register(request):
	username = request.POST.get('username', '')
	password = request.POST.get('password', '')
	email = request.POST.get('email', '')
	first_name = request.POST.get('first_name', '')
	last_name = request.POST.get('last_name', '')
	zip_code = request.POST.get('zip', '')
	if User.objects.filter(email=email).exists():
		return HttpResponseBadRequest(reason='An account exists for this email address.')

	if User.objects.filter(username=username).exists():
		return HttpResponseBadRequest(reason='Sorry, this username is taken.')

	try:
		User.objects.create_user(username, email, password)
		user = authenticate(username=username, password=password)
		user.is_active = False
		user.save()
	except Exception as e:
		return HttpResponseServerError(reason=str(e))

	try:
		account = Account(user=user, email=email, first_name=first_name, last_name=last_name, zip_code=zip_code)
		account.save()
		login(request, user)
		return HttpResponse()
	except Exception as e:
		user.delete()
		return HttpResponseServerError(reason=str(e))
コード例 #7
0
ファイル: middleware.py プロジェクト: noio/Cardbox
 def process_request(self, request):
   """ This function sets up the user object
       Depending on the value of require_login, it
       can return None as 'profile'.
   """
   #Get Google user_id
   google_user = users.get_current_user()
   account = None
   is_admin = False
   logging.info(request.META['HTTP_USER_AGENT'])
   if google_user:
       #Check if the user already has a site profile
       user_id = google_user.user_id()
       is_admin = users.is_current_user_admin()
       q = Account.all()
       q.filter('google_user ='******'My Box')
           box.put()
           
   request.user = account
   Account.current_user_account = account
   request.user_is_admin = is_admin
コード例 #8
0
ファイル: tests.py プロジェクト: rogeriofalcone/anaf
    def test_model_liability(self):
        "Test liability model"
        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        currency = Currency(code="GBP",
                            name="Pounds",
                            symbol="L",
                            is_default=True)
        currency.save()

        account = Account(name='test',
                          owner=contact,
                          balance_currency=currency)
        account.save()

        obj = Liability(name='test',
                        source=contact,
                        target=contact,
                        account=account,
                        value=10,
                        value_currency=currency)
        obj.save()
        self.assertEquals('test', obj.name)
        self.assertNotEquals(obj.id, None)
        obj.delete()
コード例 #9
0
ファイル: services.py プロジェクト: Bindambc/segue
 def create_for_email(self, email, commit=False):
     if self.is_email_registered(email): raise EmailAlreadyInUse(email)
     account = Account(email=email)
     account.password = self.hasher.generate()
     db.session.add(account)
     if commit: db.session.commit()
     return account
コード例 #10
0
ファイル: api.py プロジェクト: jzxyouok/kefu_web
def verify_mail():
    """
    """
    account_obj = _get_account_by_email(g._db, request.form.get('email', ''))
    if account_obj:
        raise MainException.ACCOUNT_DUPLICATE

    email = request.form.get('email', '')
    password = request.form.get('password', '')
    password = generate_password_hash(password)
 
    code = random_ascii_string(40)
    account_id = Account.gen_id(g._db)

    send_verify_email(email, code, email_cb=url_for('account.register_valid', code='', _external=True))

    Account.insert_verify_email(g._db, email, code, EmailUsageType.DEVELOPER_VERIFY, account_id)
    Account.create_account(g._db, account_id, email, password, 0, RoleType.DEVELOPER)

    if 'user' not in session:
        session['user'] = {}

    session['user']['id'] = account_id
    session['user']['email'] = email
    session['user']['email_checked'] = 0
    session['user']['role'] = RoleType.DEVELOPER

    account = {
        "id":account_id,
        "email":email,
        "email_checked":0,
        "role":RoleType.DEVELOPER
    }
    return send_response(account)
コード例 #11
0
def account_sync(request):
    """
    API end point to sync the account that signed in via oauth.
    This API is called by [mankey] service. Logic:
    If account exists in database, fetch account + role and return
    if account does not exist, save the email into database as a visitor.
         
    sample request.data:    
    {
    "name": "Tayler",
    "email": "*****@*****.**",
    "token":"AABBCC",
    }
    """

    account = request.data
    email = account.get('email')
    name = account.get('name')

    log.debug(
        ' account_sync get request.data, receive account={0}, type={1}'.format(
            account, type(account)))

    user = {}
    # check account by email
    if account_exists(email):
        user = Account.objects.get(email=email)
    else:
        user = Account(name=name, email=email, status='v')
        user.save()

    serializer = AccountSerializer(user)

    return Response(serializer.data)
コード例 #12
0
def dataset(setup_database):

    session = setup_database

    # Creates user
    john = User(username="******")
    mary = User(username="******")
    session.add(john)
    session.add(mary)
    session.commit()

    # Creates account
    john_account = Account(balance=10.0)
    mary_account = Account(balance=5.0)
    joint_account = Account(balance=20.0)
    john.accounts.append(john_account)
    mary.accounts.append(mary_account)
    john.accounts.append(joint_account)
    mary.accounts.append(joint_account)
    session.add(john_account)
    session.add(mary_account)
    session.add(joint_account)
    session.commit()

    yield session
コード例 #13
0
 def save(self, role=1):
     user = Account(**self.data)
     user.role = role
     user.save()
     stuusr = Student(stuid=user.username, grade="20" + user.username[0:2])
     stuusr.save()
     return user
コード例 #14
0
ファイル: conference.py プロジェクト: bpoole6/Uprojects
 def saveProfile(self, request):
     """Update & return user profile."""
     sandy = Account(username='******',
             userid=123,
             email='*****@*****.**')
     sandy_key = sandy.put()
     return self._doProfile(request)
コード例 #15
0
ファイル: api.py プロジェクト: joseph-bing-han/xiaowei_web
def reset_mail():
    """
    """
    email = request.form.get('email', '')

    if not email:
        raise MainException.ACCOUNT_NOT_FOUND

    account_obj = _get_account_by_email(g._db, email)
    if not account_obj:
        raise MainException.ACCOUNT_NOT_FOUND

    count = Account.get_verify_count(g._db, email)
    if count > 5:
        raise MainException.EMAIL_TOO_OFTEN

    code = random_ascii_string(40)

    send_reset_email(
        email, code,
        url_for('account.password_forget_check',
                mail=email,
                code='',
                _external=True))

    Account.insert_verify_email(g._db, email, code,
                                EmailUsageType.SELLER_RESET_PWD,
                                account_obj['id'])

    return MainException.OK
コード例 #16
0
def cw_register(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    email = request.POST.get('email', '')
    first_name = request.POST.get('first_name', '')
    last_name = request.POST.get('last_name', '')
    zip_code = request.POST.get('zip', '')
    if User.objects.filter(email=email).exists():
        return HttpResponseBadRequest(
            reason='An account exists for this email address.')

    if User.objects.filter(username=username).exists():
        return HttpResponseBadRequest(reason='Sorry, this username is taken.')

    try:
        User.objects.create_user(username, email, password)
        user = authenticate(username=username, password=password)
        user.is_active = False
        user.save()
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

    try:
        account = Account(user=user,
                          email=email,
                          first_name=first_name,
                          last_name=last_name,
                          zip_code=zip_code)
        account.save()
        login(request, user)
        return HttpResponse()
    except Exception as e:
        user.delete()
        return HttpResponseServerError(reason=str(e))
コード例 #17
0
ファイル: views.py プロジェクト: bmander/amaurot
def get_or_init_account(user):
    account = Account.all().filter('user =', user).get()
    if account is None:
        account = Account(user=user)
        account.put()
    
    return account
コード例 #18
0
def get_or_init_account(user):
    account = Account.all().filter('user =', user).get()
    if account is None:
        account = Account(user=user)
        account.put()

    return account
コード例 #19
0
ファイル: utils.py プロジェクト: Scarygami/gde-app-backend
def get_current_account():
    """Retrieve the Account entity associated with the current user."""

    user = endpoints.get_current_user()
    if user is None:
        return None

    email = user.email().lower()

    # Try latest recorded auth_email first
    accounts = Account.query(Account.auth_email == email).fetch(1)
    if len(accounts) > 0:
        return accounts[0]

    # Try the user's default email next
    accounts = Account.query(Account.email == email).fetch(1)
    if len(accounts) > 0:
        # Store auth email for next time
        accounts[0].auth_email = email
        accounts[0].put()
        return accounts[0]

    # Try via the user's Google ID
    user_id = _getUserId()
    accounts = Account.query(Account.gplus_id == user_id).fetch(1)
    if len(accounts) > 0:
        # Store auth email for next time
        accounts[0].auth_email = email
        accounts[0].put()
        return accounts[0]

    return None
コード例 #20
0
    def post(self):
        username = self.request.get('username')
        password = self.request.get('password')
        verify_password = self.request.get('verify')
        email = self.request.get('email')
        error = ""

        if username and password and verify_password:
            if password != verify_password:
                error = "Verify password is not matched"
            elif self.is_username_exist(username):
                error = "Username has already existed"
            else:
                hash_pw = encrypt.make_pw_hash(username, password)
                account = Account(username=username,
                                  password=hash_pw,
                                  email=email)
                account.put()
                account_id = account.key().id()
                cookie_account_id = encrypt.make_secure_cookie(account_id)
                # TODO: What is Path=/?
                self.response.headers.add_header(
                    "Set-Cookie",
                    "user_id={}; Path=/".format(cookie_account_id))
                self.response.headers.add_header(
                    "Set-Cookie", "username={}; Path=/".format(username))
                self.redirect("/welcome")
        else:
            error = "Username, password and verify password is required!"
        self.render("sign_up.html",
                    error=error,
                    username=username,
                    email=email)
コード例 #21
0
ファイル: __init__.py プロジェクト: yshurrab/WDND-Examples
    def create_account():
        body = request.get_json()
        first_name = body.get("first_name", None)
        last_name = body.get("last_name", None)
        init_balance = int(body.get("balance", None))

        res_body = {}

        error = False
        if first_name is None or init_balance is None:
            error = True
            abort(400)
        else:
            try:
                new_account = Account(first_name=first_name,
                                      last_name=last_name,
                                      balance=init_balance)
                new_account.insert()
                res_body['created'] = new_account.id
                res_body['first_name'] = new_account.first_name
                res_body['last_name'] = new_account.last_name
                res_body['balance'] = new_account.balance
                res_body['success'] = True

                return jsonify(res_body)

            except:
                abort(422)
コード例 #22
0
ファイル: monitor_nodes.py プロジェクト: XertroV/nodeup-xk-io
def configure_droplet(id, servers=None):
    # presumably id was just popped from droplets_to_configure
    if servers is None:
        servers = get_servers()
    account = Account(droplet_to_uid[id])
    logging.info('Configuring %s for %s' % (id, account.uid))
    droplet = servers[id]
    logging.info('Got server %s' % repr(droplet))
    ip = droplet['main_ip']
    password = droplet['default_password']
    droplet_ips[id] = ip
    # ssh
    try:
        print('root', password, ip)
        _, stdout, stderr = ssh(ip, 'root', password, create_install_command(account.name.get(), account.client.get(), account.branch.get(), gen_loc(account.dcid.get())))
    except Exception as e:
        print(e)
        logging.error('could not configure server %s due to %s' % (id, repr(e)))
        return
    print(stdout.read(), stderr.read())
    account.add_msg('Started compilation script on server %s -- can take hours as it also bootstraps the blockchain.' % id)
    logging.info('Configuring server %s' % id)
    account.compile_ts.set(int(time.time()))
    droplets_to_configure.remove(id)
    currently_compiling.add(id)
コード例 #23
0
ファイル: views.py プロジェクト: joshma/botsandbans
def callback(request):
    oauth_token = request.GET.get('oauth_token')
    oauth_verifier = request.GET.get('oauth_verifier')
    oauth = OAuth1(settings.CONSUMER_KEY,
        client_secret=settings.CONSUMER_SECRET,
        resource_owner_key = request.session['key'],
        resource_owner_secret = request.session['secret'],
        verifier=oauth_verifier)
    r = requests.post(TWITTER_BASE + 'oauth/access_token', auth=oauth)
    credentials = parse_qs(r.content)
    oauth_token = credentials.get('oauth_token')[0]
    oauth_token_secret = credentials.get('oauth_token_secret')[0]
    user_id = credentials.get('user_id')[0]
    screen_name = credentials.get('screen_name')[0]
    account = Account(
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret,
        user_id=user_id,
        screen_name=screen_name)
    account.save()

    d = {
        'oauth_token': oauth_token,
        'oauth_token_secret': oauth_token_secret,
        'user_id': user_id,
        'screen_name': screen_name,
    }

    return render_to_response('callback.html', d)
コード例 #24
0
ファイル: init_db.py プロジェクト: araikc/sbb
def create_account(rp):
    # Account User
    account = Account(0, 0)
    account.referralProgram = rp
    db.session.add(account)
    #db.session.commit()
    return account
コード例 #25
0
def create_account():
    form = CreateAccountForm()
    if request.method == 'POST':
        ws_cust_id = request.form.get('ws_cust_id')
        ws_acct_type = request.form.get('ws_acct_type')
        ws_amt = request.form.get('ws_amt')

        customer = Customer.query.filter_by(ws_cust_id=ws_cust_id).first()
        if customer:
            account = Account(ws_cust_id=ws_cust_id, ws_acct_type=ws_acct_type)
            account.ws_acct_balance = ws_amt
            account.ws_acct_crdate = datetime.now()
            account.ws_acct_lasttrdate = datetime.now()
            #ws_acct_duration

            db.session.add(account)
            db.session.commit()
            # to update status
            temp_acc = Account.query.order_by(Account.ws_acc_id.desc()).first()
            if temp_acc:
                update_status_account(temp_acc.ws_acc_id, 'created')

            flash("Account creation initiated !", "success")
            return render_template("customer.html",
                                   title="Account created",
                                   create_account=True)
        else:
            flash("Customer Id does not exist !", "danger")

    return render_template("create_account.html",
                           form=form,
                           create_account=True,
                           title='Create Account')
コード例 #26
0
def get_alluser(db, arg):
    listObj = {
        "total": 0,
        "users": [],
    }

    start = arg["paras"].get("start") or 0
    limit = arg["paras"].get("limit") or 100

    cond = "WHERE 1=1 "
    ret = db.select(TB_ACCOUNT, cond=cond, limit=int(limit), offset=int(start))
    if ret == -1:
        ERROR("get user list error")
        return (DB_ERR, None)

    for dur in db.cur:
        obj = dbmysql.row_to_dict(TB_ACCOUNT, dur)
        user = Account(db, dbObj=obj)
        user.loadFromObj()

        listObj["users"].append(user.toObj())

    listObj["total"] = getAccountCount(db)

    return (OCT_SUCCESS, listObj)
コード例 #27
0
    def test_Account_initialization(self):
        try:
            Account().put()
            self.assertEqual(1,2)
        except BadValueError:
            pass
        try:
            Account(username='******').put()
            self.assertEqual(1,2)
        except BadValueError:
            pass
        try:
            Account(email='*****@*****.**').put()
            self.assertEqual(1,2)
        except BadValueError:
            pass

        # test contructor
        Account(username='******', email='*****@*****.**').put()
        self.assertEqual(1, len(Account.query().fetch(2)))

        # test add new user
        request = AccountRequest('First Mate', '*****@*****.**')
        Account.add_new_user(request)
        self.assertEqual(2, len(Account.query().fetch(3)))
コード例 #28
0
ファイル: account.py プロジェクト: ihciah/xk-database
 def save(self, role=1):
     user = Account(**self.data)
     user.role=role
     user.save()
     stuusr=Student(stuid=user.username,grade="20"+user.username[0:2])
     stuusr.save()
     return user
コード例 #29
0
def register():
    errors = []

    if request.method == 'GET':
        if current_user.get_id():
            return redirect(url_for('home'))
        else:
            return render_template('register.html')
    if db.session.query(Account).filter_by(account_name=request.form['account_name']).count() > 1:
        errors.append('Account name is already taken.')
    if not request.form['account_name']:
        errors.append('Please enter a account name.')
    if not request.form['password']:
        errors.append('Please enter a password.')
    if errors:
        return jsonify({"status": "error", 'errors': errors}), 400

    account = Account(
        account_name=request.form['account_name'],
        active_user=True,
    )
    account.set_password(request.form['password'])
    try:
        db.session.add(account)
        db.session.commit()
    except Exception:
        errors.append("Name is already taken")
    if errors:
        return jsonify({"status": "error", 'errors': errors}), 400

    login_user(account, remember=True)
    success_message = "Your account has been created!"
    return jsonify({"status": "success", "value": success_message}), 200
コード例 #30
0
ファイル: functions.py プロジェクト: N0tinuse/senior_project
def basicinfo(user, self):
    if user:
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
        nickname = user.nickname()
        accounts = Account.query(Account.guser == user).fetch()

        if len(accounts) == 0:  # if no Account object exists for user
            new_account = Account(
                guser=user,
                modules_completed=[],
                projects_completed=[]
            )
            new_account.put()
    else:
        url = users.create_login_url(self.request.uri)
        url_linktext = 'Login'
        nickname = None

    template_values = {
        'title': config.SITE_NAME,
        'url': url,
        'url_linktext': url_linktext,
        'nickname': nickname
    }
    return template_values
コード例 #31
0
 def save(self, user):
     cd = self.cleaned_data
     account = Account(number=cd['number'],
                       bank=cd['bank'],
                       balance=cd['balance'],
                       nominal=cd['nominal'],
                       user=user)
     account.save()
コード例 #32
0
ファイル: dataaccess.py プロジェクト: var/dbxcard
def setAccountInfo(info):
	e = Account.get_by_id(info['uid'])
	if e:
		pass
	else:
		account = Account(id = info['uid'], uid = info['uid'], name = info['display_name'], country = info['country'], link = info['referral_link'], 
		quota_normal = info['quota_info']['normal'], quota_shared = info['quota_info']['shared'], quota_quota = info['quota_info']['quota'])
		account.put()
コード例 #33
0
ファイル: commands.py プロジェクト: nickhs/hermes
def new_user(type, custom_options={}):
    service = Service.query.filter(Service.type == type).one()
    account = Account()
    account.fill(service)
    db.session.add(account)
    db.session.commit()

    return custom_action("new_user", service, custom_options, account=account)
コード例 #34
0
 def find_existing(cls, email):
     hash = hashlib.md5(email).hexdigest()
     found = Account.all().filter('hash =', hash).get()
     if not found:
         found = Account.all().filter('hashes =', hash).get()
     if not found:
         found = Email.all().filter('email =', email).get()
     return found
コード例 #35
0
    def test_account_is_stored(self):
        acc = Account(username=self.username, password=self.password, userid=self.userid)
        key = acc.put()
        stored = key.get()

        self.assertEqual(stored.username, self.username)
        self.assertEqual(stored.password, self.password)
        self.assertEqual(stored.userid, self.userid)
コード例 #36
0
ファイル: create.py プロジェクト: ilovax/Pmanager
def save_account(name, password, username, email):
    password, iv = crypt(password)
    account = Account(name=name,
                      password=password,
                      username=username,
                      email=email,
                      iv=iv)
    account.save()
コード例 #37
0
ファイル: test_account.py プロジェクト: so-c/nozomi_miraha
 def test_followings_timeline(self):
     account = Account()
     tweets = account.followings_timeline()
     myid = 43657148
     self.assertTrue(myid in tweets)
     self.assertTrue(len(tweets[myid]) > 0)
     print tweets[myid][0][0]
     print tweets[myid][0][1]
コード例 #38
0
  def test_placeholder(self):

    user = users.User("*****@*****.**")
    account = Account(user=user)
    account.set_hash_and_key()
    account.put()

    self.assertTrue(account.user.email() == "*****@*****.**")
コード例 #39
0
ファイル: test_account.py プロジェクト: so-c/nozomi_miraha
 def test_followings_timeline(self):
     account = Account()
     tweets = account.followings_timeline()
     myid = 43657148
     self.assertTrue(myid in tweets)
     self.assertTrue(len(tweets[myid]) > 0)
     print tweets[myid][0][0]
     print tweets[myid][0][1]
コード例 #40
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def find_existing(cls, email):
     hash = hashlib.md5(email).hexdigest()
     found = Account.all().filter("hash =", hash).get()
     if not found:
         found = Account.all().filter("hashes =", hash).get()
     if not found:
         found = Email.all().filter("email =", email).get()
     return found
コード例 #41
0
def get_user(db, userId):
    user = Account(db, userId)

    if (user.init() != 0):
        ERROR("user %s not exist" % userId)
        return (USER_NOT_EXIST, None)

    return (OCT_SUCCESS, user.toObj())
コード例 #42
0
 def create_account(email, password):
     """No API endpoint calls this method - it's meant to be used via CLI"""
     AuthController.validate_email(email)
     try:
         account = Account(email, password)
         account.save()
     except Exception as e:
         logger.error(e)
         raise Error(FATAL)
コード例 #43
0
 def create_new_account_response():
     new_account = Account(username=username)
     account_key = new_account.put()
     link_header = create_link_header(
         url_for("get_account", account_key=account_key.urlsafe()),
         'account',
         'Account created'
     )
     return '', httplib.CREATED, {'Link': link_header}
コード例 #44
0
def signup(username, password, email, facebook_id):
	user = Account(username=username
		,signup_date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		,email=email, facebook_id=facebook_id)
	user.hash_password(password)
	db.session.add(user)
	db.session.commit()
	send_mail('testing_android', [user.email], {})
	return "Adding successful"
コード例 #45
0
ファイル: views.py プロジェクト: xxh13/anyquant
def register(request):
    """
    用户注册页面
    需要用户填写 email,name,password
    POST请求后插入到数据库中,需要做校验
    成功后跳转到登录首页
    :param request:
    :return:
    """
    if request.method == 'POST':
        email = request.POST.get('email', '')
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        if not captch_http_check(request.POST.get('code', ''), request):
            return render_to_response(
                'account/register.html', {
                    'error': u'验证码输入错误',
                    'email': email,
                    'name': username,
                    'password': password
                })
        # email和name唯一,所以进行校验,如果email已经被注册,需要再次换一个email
        result = Account.objects.filter(Q(email=email) | Q(name=username))
        #生成激活码
        code = md5(username.encode('utf-8') + str(password)).hexdigest()
        if len(result) > 0:
            error = u'邮箱或用户名已经被注册,请换一个'
            return render_to_response(
                'account/register.html', {
                    'error': error,
                    'email': email,
                    'name': username,
                    'password': password
                })

        account = Account(email=email,
                          name=username,
                          password=md5(password).hexdigest(),
                          is_active=False,
                          active_code=code)
        account.save()

        #发送邮件
        return_code = send_register_email(email, code)
        if return_code != 0:
            return render_to_response('account/register.html', {'done': 1})
        else:
            return render_to_response(
                'account/register.html', {
                    'error': u'发送激活邮件失败',
                    'email': email,
                    'name': username,
                    'password': password
                })

    return render_to_response('account/register.html')
コード例 #46
0
 def create_account(email, password):
     """No API endpoint calls this method - it's meant to be used via CLI"""
     AuthController.validate_email(email)
     try:
         account = Account(email, password)
         account.save()
     except Exception as e:
         logger.error(e)
         raise Error(FATAL)
コード例 #47
0
def create_account_menu():
    print("Account creation")
    firstName = input('First Name : ')
    lastName = input('Last Name : ')
    pin = input('PIN : ')

    fullName = firstName + " " + lastName
    newUser = Account(fullName, 0, pin) #Default account number as 0 to indicate a real "new account"
    #Create the account in the database
    print("account created, your account number is: ", newUser.createAccount())
コード例 #48
0
ファイル: main.py プロジェクト: xz565/vote-item
    def checkUser(self, user):
        accounts = Account.all()
        user_ids = []
        for acc in accounts:
            user_ids.append(acc.user_id)

        uid = user.nickname()
        if uid not in user_ids:
            account = Account(key_name=uid, user_id=uid)
            account.put()
コード例 #49
0
ファイル: handlers.py プロジェクト: andreyvit/mockko
def create_account(user):
    """
    This function creates account for new user
    """
    account = Account(user=user, newsletter=True)
    account.put()
    ig = ImageGroup(name="Custom Images", owner=account, priority=0)
    ig.save()
    notify_admins_about_new_user_signup(user)
    return account
コード例 #50
0
ファイル: handlers.py プロジェクト: andreyvit/mockko
def create_account(user):
    """
    This function creates account for new user
    """
    account = Account(user=user, newsletter=True)
    account.put()
    ig = ImageGroup(name='Custom Images', owner=account, priority=0)
    ig.save()
    notify_admins_about_new_user_signup(user)
    return account
コード例 #51
0
ファイル: api.py プロジェクト: Feanorka/notify-io
 def get(self, hash):
   if Account.all().filter('api_key =', self.request.get('api_key')).get():
     if (Account.all().filter('hash =', hash.lower()).get()) or (Account.all().filter('hashes =', hash.lower()).get()):
       self.response.out.write("200 OK")
     else:
       self.error(404)
       self.response.out.write("404 User not found")
   else:
     self.error(403)
     self.response.out.write("403 Missing required parameters")
コード例 #52
0
ファイル: forms.py プロジェクト: belate/money
 def save(self, user):
     cd = self.cleaned_data
     account = Account(
         number=cd['number'],
         bank=cd['bank'],
         balance=cd['balance'],
         nominal=cd['nominal'],
         user=user
     )
     account.save()
コード例 #53
0
ファイル: tests.py プロジェクト: pombredanne/hypertextual
 def setUp(self):
     self.scott = Account.new('scott', 'tiger', '*****@*****.**')
     self.scott_page = Page.new(self.scott, 'Book List')
     self.scott_rev = self.scott_page.save_draft_rev(
         'book list sample text', True)
     self.scott_page.publish_draft_rev()
     self.sally = Account.new('sally', 'secret', '*****@*****.**')
     self.sally_page = Page.new(self.sally, 'Dear Diary')
     self.sally_rev = self.sally_page.save_draft_rev('today i am sad', True)
     self.sally_page.publish_draft_rev()
コード例 #54
0
 def check_fail_cookie(cls):
     for i in Account.select():
         cls(i.nick)
     users = Account.select(
     )  # .where(Account.valid == False)#, Account.apply == True)
     if users:
         msg = '、'.join([user.nick for user in users])
         Smail('登陆失效提醒', '{users}已失效,请尽快重新登陆!'.format(users=msg))
         return False
     return True
コード例 #55
0
ファイル: main.py プロジェクト: VictorAny/sbcremote
    def post(self):
        json_req = self.jsonifyRequestBody()
        data = json_req
        print data
        print "Entering account handler!"
        service_ids = data["service_ids"]
        print service_ids
        for id_ in service_ids.keys():
            # Checks if account exists at all..
            # Means only there cannot be two accounts with the same service_id
            accountExists = self.validateAccount(id_)
            if accountExists:
                print "Account exists"
                continue
            print "Creating account for id " + id_
            acc = Account()

            acc.email = data["email"]
            print "gotten email"
            acc.serviceID = id_
            acc.alias = service_ids[id_]
            print "got service id"
            acc.config = default_config
            print "set default configs"
            acc.key = ndb.Key(Account, id_)
            print "creating key"
            acc.put()
            print "Account sucessfully created"
            logging.info("Account has been put into the datastore")
        #Better flesh out fail state.
        self.writeSucessfulResponse("Account sucessfully created")
コード例 #56
0
ファイル: admin.py プロジェクト: jt-wang/xk-database
    def save(self):
        user = Account(**self.data)
        user.save()
        if self.role.data == 1:
            stuusr = Student(stuid=self.username.data)
            stuusr.save()
        if self.role.data == 3:
            teausr = Teacher(teaid=self.username.data)
            teausr.save()

        return self.username.data, self.role.data
コード例 #57
0
def changeFollow(request):
    name=request.GET['username']
    friend=Account.objects(username=name).first()
    user=Account.objects(username=request.user.username).first()
    if str(friend.id) in user.friends:
        user.friends.remove(str(friend.id))
    else:
        user.friends=user.friends+[str(friend.id)]
    user.save()
    request.user=user
    return HttpResponse("add success")
コード例 #58
0
def login_menu():
    accountNum = input("Account number: ")
    pin = input("PIN: ")
    loginUser = Account("", accountNum, pin)

    testLogin = loginUser.login()

    if testLogin == False:
        print("!! Account Number/PIN # is invalid")
    else:
        loggedIn_menu(testLogin)
コード例 #59
0
ファイル: admin.py プロジェクト: minisin/xk-database
    def save(self):
        user = Account(**self.data)
        user.save()
        if self.role.data == 1:
            stuusr = Student(stuid=self.username.data)
            stuusr.save()
        if self.role.data == 3:
            teausr = Teacher(teaid=self.username.data)
            teausr.save()

        return self.username.data, self.role.data