Beispiel #1
0
def forward_token(request, token_str=None, **kwargs):
    kwargs['extra_context'] = {}
    error = None
    token = get_object_or_404(Token, token=token_str)
    user_tokens = get_tokens_from_cookie(request)
    if not token.can_forward:
        error = _("Apologies! This token can not be forwarded.")
    else:
        if request.user.is_staff:
            pass
        elif not token.token in user_tokens:
            error = _("Apologies! You are not allowed to forward this token.")
    kwargs['extra_context']['token'] = token
    kwargs['extra_context']['error'] = error
    if not error:
        if request.method == 'POST':
            form = ForwardProtectedURLForm(token, request.POST)
            if form.is_valid():
                if token.forward_count:
                    token.forward_count = token.forward_count - len(form.cleaned_data['emails'])
                    token.save()
                for email in form.cleaned_data['emails']:
                    forwarded_token = Token( url=token.url, valid_until=token.valid_until, forward_count=0, email=email )
                    forwarded_token.save()
                    forwarded_token.send_token_email()
                return HttpResponseRedirect(reverse('token_list'))
        else:
            form = ForwardProtectedURLForm(token)
        kwargs['extra_context']['form'] = form
    return direct_to_template(request, template='token_auth/forward_token.html', **kwargs)
def save_token(token, request, *args, **kwargs):
    user = request.user
    toks = Token.objects(
        client_id=request.client.client_id,
        user_id=user.id
    )
    # make sure that every client has only one token connected to a user
    for t in toks:
        t.delete()

    expires_in = token.pop('expires_in')
    expires = datetime.utcnow() + timedelta(seconds=expires_in)

    tok = Token(
        access_token=token['access_token'],
        refresh_token=token['refresh_token'],
        token_type=token['token_type'],
        _scopes=token['scope'],
        expires=expires,
        client_id=request.client.client_id,
        user_id=user.id,
        user=user
    )
    tok.save()
    return tok
Beispiel #3
0
def initialize_redis():
    global redis
    redis = None

    # Get the crdentials from the Bluemix environment
    if 'VCAP_SERVICES' in os.environ:
        app.logger.info("Using VCAP_SERVICES...")
        VCAP_SERVICES = os.environ['VCAP_SERVICES']
        services = json.loads(VCAP_SERVICES)
        creds = services['rediscloud'][0]['credentials']
        app.logger.info("Conecting to Redis on host %s port %s" % (creds['hostname'], creds['port']))
        redis = connect_to_redis(creds['hostname'], creds['port'], creds['password'])
    else:
        app.logger.info("VCAP_SERVICES not found, checking localhost for Redis")
        redis = connect_to_redis('127.0.0.1', 6379, None)
        if not redis:
            app.logger.info("No Redis on localhost, using: redis")
            redis = connect_to_redis('redis', 6379, None)
    if not redis:
        # if you end up here, redis instance is down.
        app.logger.error('*** FATAL ERROR: Could not connect to the Redis Service')

    User.use_db(redis)
    Client.use_db(redis)
    Token.use_db(redis)
Beispiel #4
0
 def get_token(access_token=None, refresh_token=None):
     if access_token:
         logger.debug('get token - access_token: {}\n'.format(access_token))
         return next(Token.query(access_token=access_token))
     if refresh_token:
         return next(Token.query(refresh_token=refresh_token))
     return None
Beispiel #5
0
 def post(self):
     user = self.current_user
     desc = self.get_argument("description")
     value = "%040x" % random.randrange(16**40)
     # TODO: Retry on duplicate token value (peewee.IntegrityError)?
     Token.create(user=user, value=value, desc=desc)
     self.redirect(self.reverse_url("web:settings"))
Beispiel #6
0
 def post(self):
     user = self.current_user
     desc = self.get_argument("description")
     value = "%040x" % random.randrange(16 ** 40)
     # TODO: Retry on duplicate token value (peewee.IntegrityError)?
     Token.create(user=user, value=value, desc=desc)
     self.redirect(self.reverse_url("web:settings"))
Beispiel #7
0
def consumer_create(request):
    if request.method == "POST":
        form = ConsumerCreateForm(request.POST)
        if form.is_valid():
            consumer = Consumer()
            consumer.name = form.cleaned_data['name']
            consumer.description = form.cleaned_data['description']
            consumer.user_id = request.user.username
            consumer.refresh_key_secret()
            consumer.save()
            
            token = Token()
            token.key = Token.generate_token()
            token.secret = Token.generate_token()
            token.consumer = consumer
            token.user = request.user.username
            token.type = 'A'
            token.save()
            
            return HttpResponseRedirect('/accounts/profile')
    else: 
        form = ConsumerCreateForm()    

    params = {'form': form}
    return render_to_response('oauth/consumer_form.tpl', params,
                              context_instance=RequestContext(request))
def create_token(request, url_id=None, **kwargs):
    kwargs['extra_context'] = {}
    if request.method == 'POST':
        form = TokenAddForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            token = Token(
                url=form.cleaned_data['url'],
                valid_until=form.cleaned_data['valid_until'],
                forward_count=form.cleaned_data['forward_count'],
                email=email,
                name=form.cleaned_data['name'],
            )
            token.save()
            messages.add_message(
                request, messages.SUCCESS,
                'Token successfully created for %s.' % token.email)
            return HttpResponseRedirect(reverse('token_list'))
    else:
        initial_data = None
        if not url_id is None:
            url = ProtectedURL.objects.get(id=url_id)
            initial_data = {
                'url': url.url,
            }
        form = TokenAddForm(initial=initial_data)
    kwargs['extra_context']['form'] = form
    return direct_to_template(request,
                              template='token_auth/create_token.html',
                              **kwargs)
    def get(self):
        apid = self.request.get("apid")
        email = self.request.get("email",'').lower()
        version = int(self.request.get("version", "0"))
        q = Token.query(Token.email == email)
        token = q.get()
        if token:
            token.apid = apid
            token.email = email
            token.version = version
        else:
            q = Token.query(Token.apid == apid)
            token = q.get()
            if token:
                token.apid = apid
                token.email = email
                token.version=version
            else:token = Token(apid=apid, email=email, version=version)
        token.put()

        cb = self.request.get('callback')
        self.response.headers['Content-Type'] = 'application/json'
        if cb:
            self.response.out.write(cb+'(' + json.dumps({}) +');')
        else:
            self.response.out.write(json.dumps({}))
Beispiel #10
0
def load_token(access_token=None, refresh_token=None):
    if access_token:
        current_access_token = Token.query(
            Token.access_token == access_token).fetch(1)
        if current_access_token:
            return current_access_token[0]
    elif refresh_token:
        return Token.query(Token.refresh_token == refresh_token).fetch(1)[0]
Beispiel #11
0
def push_to_all(text, count):

    ios_tokens = Token.query(Token.os!='android').fetch()
    and_tokens = Token.query(Token.os=='android').fetch()

    for token in ios_tokens:
        push_to_apns(token.token, text, count)

    push_to_gcm(list(token.token for token in and_tokens), text, count)
Beispiel #12
0
def generate_token():
    global token
    auth = ''.join(
        random.choice(string.ascii_uppercase + string.digits +
                      string.ascii_lowercase) for _ in range(15))
    token = Token(auth)

    with open('token.json', 'w') as f:
        f.flush()
        f.write(token.toJSON())
Beispiel #13
0
    def regist_token(self, request):
        if Token.query(Token.token==request.token).fetch():
          return RegistTokenResult(result="DUP")

        token = Token(token=request.token, os='ios');
        token.put();

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
Beispiel #14
0
def create_token(uid):
    '''
    生成token
    '''
    shal = '%s=%s=%s' % ('Token', uid, time.time())
    shal_uid = hashlib.sha1(shal.encode('utf-8')).hexdigest()

    token = Token(id=next_id(), uid=uid, key=shal_uid)
    yield from token.save()
    return token['key']
Beispiel #15
0
    def regist_token(self, request):
        if Token.query(Token.token == request.token).fetch():
            return RegistTokenResult(result="DUP")

        token = Token(token=request.token, os='ios')
        token.put()

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
Beispiel #16
0
 def save_token(self, session, user):
     uid = user.username
     try:
         token = Token.objects.get(uid=uid, user=user)
     except Exception:
         token = Token(uid=uid, user=user)
     token.access_token = session.access_token
     token.expires = session.expires
     token.save()
     
     return token
Beispiel #17
0
def email_key(user):
    token = Token(key=registration_key(),
                email=user.email)
    g = Global.objects()[0]
    g.n_tokens += 1
    g.save()
    token.save()

    body = "Hey! Create an account by clicking on the link below:"
    body += "localhost:5000/createAccount?accountEmail={0}&signupToken={1}".format(user.email, token.key)
    send_email("Lsten.fm, all the music.", body, user.email)
Beispiel #18
0
    def regist_token(self, request):
        if Token.query(Token.token==request.token).fetch():
          return RegistTokenResult(result="DUP")

        token = urllib.unquote(request.token)
        token = Token(token=request.token, os=request.os, width=request.width, height=request.height);
        token.put();

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
    def _make_token_with_timestamp(self, user, timestamp):

        from django.utils.hashcompat import sha_constructor
        hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +
            user.password +
            unicode(timestamp)).hexdigest()[::2]

        self.delete_token(user)

        token = Token(user = user, hash = hash)
        token.save()
        return hash
Beispiel #20
0
def debug_resetdb():
    to_serialize = {'status': 'success'}
    User.drop_collection()
    Token.drop_collection()
    Diary.drop_collection()
    code = 200
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
Beispiel #21
0
def change_token(uid):
    '''
    修改token
    '''
    tokens = yield from Token.findAll('uid=?', [uid])
    shal = '%s=%s=%s' % ('Token', uid, time.time())
    shal_uid = hashlib.sha1(shal.encode('utf-8')).hexdigest()

    token = Token(id=tokens[0].id,
                  uid=uid,
                  token_key=shal_uid,
                  last_time=time.time())
    yield from token.update()
    return token.token_key
Beispiel #22
0
def monitor_token():
    """
    监听 kafka 日志数据,出现新数据时,过滤出 transfer 函数对应的日志,从 web3 获取 token
    :return:
    """
    if not config.get('kafka', 'log_topic', fallback=None):
        logger_err.error('config.ini 中没有 log_topic 参数,退出 monitor_token 任务')
        return
    elif not config.get('kafka', 'token_topic', fallback=None):
        logger_err.error('config.ini 中没有 token_topic 参数,退出 monitor_token 任务')
        return
    consumer = kafka_consumer(config.get('kafka', 'log_topic'), group_id='monitor_token')
    last_block_height = None
    tx_cnt = 0  # 已处理的交易数
    for msg in consumer:
        logs = msg.value

        block_number = logs[0]['block_number']
        if last_block_height != block_number:
            logger.info(f'区块 {last_block_height} 共处理交易 {tx_cnt} 笔')
            logger.info(f'开始处理区块高度 {block_number} 下各交易的 receipt')
            last_block_height = block_number
            tx_cnt = 1
        else:
            tx_cnt += 1

        # 筛选出 token 地址
        addresses = set()
        for log in logs:
            if log['topics'].startswith(TOPIC_TRANSFER):
                addresses.add(log['address'])

        # 获取 token
        for address in addresses:
            # 如果是已经处理过的地址,则直接处理
            if address in valid_token_cache:
                valid_token_cache[address].save()
                continue
            elif address in invalid_token_cache:
                invalid_token_cache[address] = 1
                continue

            try:
                contract = w3.eth.contract(address, abi=ERC20_ABI)
                token = Token(data=address, contract=contract, block_number=block_number)
                token.save()
                valid_token_cache[address] = token
            except InvalidAddress:
                invalid_token_cache[address] = 1
                logger_err.debug(f'无法处理 token 合约地址 {address}')
Beispiel #23
0
    def regist_token(self, request):
        if Token.query(Token.token == request.token).fetch():
            return RegistTokenResult(result="DUP")

        token = urllib.unquote(request.token)
        token = Token(token=request.token,
                      os=request.os,
                      width=request.width,
                      height=request.height)
        token.put()

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
def store_tokens_notification_relation_in_db(tokens, notification_id):
    stored_tokens = Token.query.all()
    stored_tokens = [_token.token for _token in stored_tokens]
    for token in tokens:
        if token not in stored_tokens:
            newToken = Token(token=token)
            newToken.insert()
            token_id = newToken.id
        else:
            existing_token = Token.query.filter_by(token=token).first()
            token_id = existing_token.id
        token_notification_entry = TokenNotification(
            token_id=token_id, notification_id=notification_id)
        token_notification_entry.insert()
Beispiel #25
0
def generate_token(db: Session = Depends(get_db)):
    """
    This Api Route will Generate a Random Token on Every Request
    """
    release_token_in_sixty_sec(db)
    delete_token_five_min(db)
    token = uuid.uuid4()
    token_obj = Token(token_name=str(token), is_assigned=False)
    db.add(token_obj)
    db.commit()
    token_obj.token_name = f'{token}---{token_obj.id}'
    db.add(token_obj)
    db.commit()
    db.refresh(token_obj)
    return token_obj
Beispiel #26
0
def generate_token():

    token = ''.join(random.choice(string.ascii_uppercase + string.digits)
                    for x in range(32))

    insertToken = Token(
        name='first_token',
        token=token
    )

    session.add(insertToken)
    session.commit()
    
    try:
        newToken = session.query(Token).filter_by(token=token).one()
        return make_response(
            jsonify(
                status=200,
                result = {
                    'token': newToken.token
                }
            ), 200
        )
    except Exception:
        return make_response(
            jsonify(
                status=500,
                result = {
                    'message': 'Something went wrong'
                }
            ), 500
        )
Beispiel #27
0
def create_transaction():
    # Get the token in the parameters
    params = request.get_json()
    paramsToken = params.get('token')
    paramsAmount = params.get('amount')
    paramsBank = params.get('bank')

    # Check if the token exist
    try:
        token = Token.get(Token.token == paramsToken)
        if time.time() < token.expiration_date:
            transaction = Transaction.create(user_id=token.user_id,
                                             amount=paramsAmount,
                                             bank=paramsBank)
            transaction.save()
            transactionData = model_to_dict(transaction)
            return jsonify({
                'response': 'Transaction well created',
                'transaction': transactionData
            }), 201
        else:
            return str(
                'Your token is expired. Please update it by login again on: /tokens/update/<id>.'
            )
    except Exception as identifier:
        return jsonify({
            'error':
            'Token not found {message}'.format(message=identifier.message)
        }), 404
Beispiel #28
0
def create_token():
    # Get the parameters
    params = request.get_json()
    paramsCode = params.get('code')
    try:
        code = MobileCode.get(MobileCode.mobile_code == paramsCode)
        if code.mobile_code == paramsCode:
            generatedToken = binascii.b2a_hex(os.urandom(16))
            currentTime = int(time.time())
            expirationDate = currentTime + 3600
            token = Token.create(token=generatedToken,
                                 user_id=code.user_id,
                                 created_at=currentTime,
                                 updated_at=currentTime,
                                 expiration_date=expirationDate)
            token.save()
            isDeleted = code.delete_instance()
            tokenData = model_to_dict(token)
            return jsonify({
                'response':
                'Token well created for our user, and code well deleted',
                'token': tokenData,
                'code_deleted': isDeleted
            }), 201
        return str('Code given did not match to code generated')
    except Exception as identifier:
        return jsonify({
            'error':
            'Code not found {message}'.format(message=identifier.message)
        }), 404
Beispiel #29
0
def fs_request_token_ready(request):
  """
  OAuth dance for Foursquare, callback URL
  """
  CONSUMER_KEY = FS_CONSUMER_KEY
  CONSUMER_SECRET = FS_CONSUMER_SECRET
  token = Token.gql( "WHERE user = :1", str(request.user) ).get()
  request_values = token.fs_request_token.split("&")
  env = os.environ['QUERY_STRING'].split("&")
  for e in env:
      request_values.append(e)
  values = {}
  for rv in request_values:
      (key, value) = rv.split("=")
      values[key] = value
  oauth_token = oauth.OAuthToken.from_string( token.fs_request_token )
  oauth_verifier = values['oauth_verifier']
  request_token_key = oauth_token
  request_token_secret = values['oauth_token_secret']
  credentials = foursquare.OAuthCredentials(CONSUMER_KEY, CONSUMER_SECRET)
  fs = foursquare.Foursquare(credentials)
  user_token = fs.access_token(token=request_token_key, oauth_verifier=oauth_verifier)
  credentials.set_access_token(user_token)
  fs_token = "oauth_token_secret=%s&oauth_token=%s" % (request_token_secret, str(user_token))
  token.fs_token = fs_token
  token.fs_user_token = str(user_token)
  token.put()
  return redirect( "/" )
    def post(self):
        isajax = self.request.get('isajax')
        phone = self.request.get('phone')
        msg = self.request.get('msg')
        contact_name = self.request.get('contact_name')

        user = users.get_current_user()
        email = user.email().lower()
        q = Token.query(Token.email == email)
        token = q.get()
        status = 100
        hist=''
        logging.debug(email + ' ' + phone + ' ' + msg + ' ' + contact_name)
        if token:
            status = 101
            if len(phone) and len(msg):
                status = 200
                hist = History(email=email, msg=msg, phone=phone, contact_name = contact_name)
                hist.put()
                airship.push({
                    "android": {
                         "extra": {"msgid": str(hist.key.id()), "phone": phone, "msg":msg}
                    }
                }, apids=[token.apid])
                id = hist.key.id()
                hist = hist.to_dict()
                hist['created']=hist['created'].isoformat();
                hist['id'] = id
                hist['type'] = 'sms'        
        self.response.out.write(json.dumps({'status':status, 'msg':hist}))
    def get(self):
        user = users.get_current_user()
        if user:
            q = Token.query(Token.email == user.email().lower())
            token = q.get()
            if token and token.version:
                template = jinja_environment.get_template('templates/index_with_contact.html')
            else:
                template = jinja_environment.get_template('templates/index.html')
            status = 100
            if token:status = 200
            chat_token = self.request.cookies.get('token2', None)
            if not chat_token:
                chat_token = channel.create_channel(user.email().lower(), 1440)
                expires = time.time() + 86400
                self.response.headers.add_header(
                    'Set-Cookie', 
                    'token2=%s; expires=%s' \
                      % (chat_token, time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime(expires))))

            self.response.out.write(template.render({'status':status, 
                'logout':users.create_logout_url("/"), 'token':chat_token}))
        else:
            template = jinja_environment.get_template('templates/landing.html')
            self.response.out.write(template.render({"path": users.create_login_url("/")}))
Beispiel #32
0
 def post(self, id):
     try:
         token = Token.get((Token.user == self.current_user) & (Token.id == id))
         token.delete_instance()
         self.redirect(self.reverse_url("web:settings"))
     except:
         raise HTTPError(404)
Beispiel #33
0
    def fetch_request_token(self, oauth_consumer, oauth_callback):
        logger.warning("!!! In MockOAuthDataStore.fetch_request_token  args: %s"%locals())
        
        if oauth_consumer.key != self.consumer.key:
            raise OAuthError('Consumer key does not match.')
            
        # OAuth 1.0a: if there is a callback, check its validity
        callback = None
        callback_confirmed = False
        if oauth_callback:
            if oauth_callback != OUT_OF_BAND:
                if check_valid_callback(oauth_callback):
                    callback = oauth_callback
                    callback_confirmed = True
                else:
                    raise oauth.OAuthError('Invalid callback URL.')

        #not going to implement scope just yet-so just hard code this for now
        resource = Resource.all().filter("name =","default")[0]
        
        #try:
        #    resource = Resource.objects.get(name=self.scope)
        #except:
        #    raise OAuthError('Resource %s does not exist.' % escape(self.scope))
        
        self.request_token = Token.create_token(consumer=self.consumer,
                                                        token_type=Token.REQUEST,
                                                        timestamp=self.timestamp,
                                                        resource=resource,
                                                        callback=callback,
                                                        callback_confirmed=callback_confirmed)
        
        return self.request_token
Beispiel #34
0
    def _tokensetter(self, token, req, *args, **kwargs):
        from models import Token
        from flask import current_app as app
        session = app.db.session
        if req.user:
            toks = req.user and Token.query.filter_by(
                client_id=req.client.client_id,
                user_id=req.user.id) or Token.query.filter_by(
                    client_id=req.client.client_id)
            # make sure that every client has only one token connected to a user
            for t in toks:
                session.delete(t)

        expires_in = token.get('expires_in')
        expires = datetime.utcnow() + timedelta(seconds=expires_in)

        tok = Token(
            access_token=token['access_token'],
            refresh_token=token['refresh_token'],
            token_type=token['token_type'],
            _scopes=token['scope'],
            expires=expires,
            client_id=req.client.client_id,
            user_id=req.user and req.user.id or None,
        )
        session.add(tok)
        session.commit()
        return tok
Beispiel #35
0
def db_test():
    try:
        DBHelper.connect()
        DBHelper.create_db_tables()
        return str(Token.select().count())
    finally:
        DBHelper.close()
Beispiel #36
0
def list_token():

    # Build query to get all tokens as dictionaries
    query = Token.select().dicts()

    # Get tokens dictionary and send JSON list to browser
    return jsonify({ 'list_token': list(query) }), 200
Beispiel #37
0
async def get_token(form_data: OAuth2PasswordRequestForm = Depends()):
    """
    Used for getting the jwt token,
    takes a form data with {"username": ... , "password": ...}
    but username is email in our case
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Incorrect username or password",
        headers={"WWW-Authenticate": "Bearer"},
    )
    # checks if the username is in the db
    user = await User.get(email=form_data.username
                          ).values_list("email", "password_hash")
    if not user:
        raise credentials_exception
    # list of tuples
    user_email = user[0][0]
    user_hash = user[0][1]

    # checks if password matches
    if not verify_password(user_hash, form_data.password):
        raise credentials_exception

    access_token = create_access_token(data={"sub": user_email})

    return Token(access_token=access_token, token_type="bearer")
Beispiel #38
0
def create_code(id):
    # Get the parameters
    params = request.get_json()
    paramsName = params.get('name')
    hashedParamsPassword = hashlib.md5(params.get('password')).hexdigest()
    # Check if there is already a token created
    try:
        tokenAlreadyCreated = Token.get(Token.user_id == id)
        return str('The ID given already match with a token')
    except:
        # Then check if there is an user with the ID given
        try:
            user = User.get(User.id == id)
            if user.name == paramsName and user.password == hashedParamsPassword:
                generatedMobileCode = binascii.b2a_hex(os.urandom(2))
                client.send_message({
                    'from': 'Token - Python TP',
                    'to': user.phone_number,
                    'text': generatedMobileCode,
                })
                code = MobileCode.create(user_id=user.id,
                                         mobile_code=generatedMobileCode)
                code.save()
                codeData = model_to_dict(code)
                return jsonify({
                    'response': 'Code well send for user:'******'code': codeData
                }), 201
            return str('Params given did not match to user ID')
        except Exception as identifier:
            return jsonify({
                'error':
                'User not found {message}'.format(message=identifier.message)
            }), 404
Beispiel #39
0
def lexer(input: str, skip_whitespace: bool = True) -> [Token]:
    tokens = []
    pos = 0
    while pos <= len(input):
        if skip_whitespace:
            match = re_ws_skip.search(input, pos)

            if match:
                pos = match.start()
            else:
                return tokens

        matches = [re.match(input, pos) for re, _ in rules]

        try:
            match = [(match, rules[idx][1])
                     for idx, match in enumerate(matches) if match][0]
        except IndexError as e:
            print(input[pos])
            raise LexerError(pos)

        if match[1] is not 'COMMENT':
            tokens.append(Token(match[1], match[0].group(0)))
        pos = match[0].end()

    return tokens
Beispiel #40
0
def users():
    to_serialize = {'status': False}
    payload = request.get_json()
    if payload and 'token' in payload:
        token_str = payload['token']
    code = 200
    if not is_token_valid(token_str):
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        token = Token.objects(token=token_str).first()
        data = json.loads(token.data)
        pk = data['pk']
        user = User.objects(pk=ObjectId(pk)).first()
        result = {'username': user.username, 'fullname': user.fullname, 'age': user.age}
        to_serialize['status'] = True
        to_serialize['result'] = json.dumps(result)

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
Beispiel #41
0
    def save_token(token, request, *args, **kwargs):
        client_id = request.client.client_id
        user_id = request.user.id

        # Make sure there is only one grant token for every (client, user)
        mongo.db.tokens.remove({'client_id': client_id, 'user_id': user_id})

        expires_in = token.pop('expires_in')
        expires = datetime.utcnow() + timedelta(seconds=expires_in)

        token = Token(
            client_id=request.client.client_id,
            user_id=user_id,
            token_type=token['token_type'],
            access_token=token['access_token'],
            refresh_token=token['refresh_token'],
            expires=expires,
        )

        # Add the access token to the Redis cache and set it to
        # expire at the appropriate time.
        redis.setex(token.access_token, expires_in, user_id)

        spec = {'user_id': user_id, 'client_id': client_id}

        # Replace token if it exists already, insert otherwise.
        mongo.db.tokens.update(spec, _to_json(token), upsert=True)
Beispiel #42
0
def save_snippet(node, page):

    snippet = Snippet.create(
        page=page,
        text_above=extract_text_above(node),
        text_below=extract_text_below(node),
        header=extract_header_above(node),
        code=extract_code(node),
        line_count=len(node.text.split('\n')),
    )

    for tok_str in extract_tokens(node):
        token, _ = Token.get_or_create(string=tok_str)
        SnippetToken.create(
            snippet=snippet,
            token=token,
        )

    for comment_str in extract_comments(node):
        comment, _ = Comment.get_or_create(string=comment_str)
        SnippetComment.create(
            snippet=snippet,
            comment=comment,
        )

    return snippet
Beispiel #43
0
def diary_post():
    to_serialize = {'status': False}
    payload = request.get_json()
    if payload:
        token_str = payload['token']
    else:
        token_str = payload
    code = 200
    if is_token_valid(token_str) == False:
        to_serialize['status'] = False
        to_serialize['error'] = 'Invalid authentication token.'
    else:
        token = Token.objects(token=token_str).first()
        data = json.loads(token.data)
        pk = data['pk']
        user = User.objects(pk=ObjectId(pk)).first()
        username = user.username
        results = Diary.objects(username=username)
        result = []
        if results is not None:
            for oneresult in results:
                diary = {'id': oneresult.id, 'title': oneresult.title, 'author': oneresult.username,
                         'publish_date': oneresult.published_time, 'public': oneresult.public, 'text': oneresult.text}
                result.append(json.dumps(diary))
        to_serialize['status'] = True
        to_serialize['result'] = result

    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
Beispiel #44
0
def forgot_password():
    content = request.get_json(silent=True)

    with db.connect() as session:
        user = (session.query(User).filter_by(
            username=content["username"]).first())

        if user and content["email"] == user.email:

            data = user.get_data()
            data["uuid"] = str(uuid4())

            # Store token in database
            expiry_date = datetime.utcnow() + timedelta(seconds=600)
            token = Token(token=data["uuid"],
                          token_expire=expiry_date,
                          token_type="PW_RESET",
                          blacklisted=False)
            session.add(token)

            # Create and send email
            token = encode_email_token(data)
            url = url_for("reset_password", token=token, _external=True)

            send_forgot_email(url, content["email"])

            return {"succes": True, "message": "Reset request sent."}

        return {"success": False, "message": "Nope. Didn't work! :("}
Beispiel #45
0
def delete_transaction(id):
    # Get the token in the parameters
    params = request.get_json()
    paramsToken = params.get('token')

    # Check if the token exist
    try:
        token = Token.get(Token.token == paramsToken)
        if time.time() < token.expiration_date:
            transaction = Transaction.get(Transaction.id == id)
            if transaction.user_id == token.user_id:
                is_deleted = transaction.delete_instance()
                return str(is_deleted)
            else:
                return str(
                    'The token is not matching with the user_id of the specific transaction'
                )
        else:
            return str(
                'Your token is expired. Please delete this one, and create another one.'
            )
    except Exception as identifier:
        return jsonify({
            'error':
            'Token not found {message}'.format(message=identifier.message)
        }), 404
Beispiel #46
0
def create_user():
    i = ctx.request.input(phone='',password='',code='')
    phone = i.phone.strip()
    password = i.password.strip()
    code = i.code.strip()
    verify = VerifyCode.find_first('where num=?', phone)
    logging.info('the code %s and verify %s' %(code,verify))
    if not verify or verify.code!=code:
        raise APIError('register:failed','verify code','verify code is not correct.','-1')
    if time.time() - verify.created_at > 90:
        raise APIValueError('code',errcode='-3')
    
    if not phone or not _RE_PHONE.match(phone):
        raise APIValueError('phone',errcode='-1')
    if not password:
        raise APIValueError('password', errcode='-1')

    verify.delete()
    user = User.find_first('where phone=?',phone)
    if user and user.valid==True:
        raise APIError('register:failed','phone','phone is already in use.')

    if user:
        token = Token.find_first('where id=?', user.id)
        if not token:
            token_string = next_id()
            token = Token(id = user.id, token1=token_string, token2 = token_string)
            token.insert()
        else:
            token.token1 = next_id()
            logging.info('the update token is %s' % token.token1)
            token.update()
        user.password = password
        user.update()
        user.token = token.token1
    else:
        user = User(phone=phone, valid=False, password=password)
        user.insert()
        token_string = next_id()
        token = Token(id = user.id, token1=token_string, token2 = token_string)
        token.insert()
        user.token = token.token1
    user.pop('id')
    user.pop('password')
    user.pop('created_at')
    user.errcode='0'
    return user
Beispiel #47
0
def createProject(request):

  pd = ocpcaproj.OCPCAProjectsDB()  

  if request.method == 'POST':
    if 'createproject' in request.POST:

      form = ProjectForm(request.POST)
      
# RBRM I think this is not right.  Omit and delete by 8/1.   6/9/15
#      # restrict datasets to user visible fields
#      form.fields['dataset'].queryset = Dataset.objects.filter(user_id=request.user.id) | Dataset.objects.filter(public=1)

      if form.is_valid():
        new_project=form.save(commit=False)
        new_project.user_id=request.user.id
        if request.POST.get('legacy') == 'yes':
          new_project.ocp_version='0.0'
        else:
          new_project.ocp_version=OCP_VERSION
        new_project.schema_version=SCHEMA_VERSION
        new_project.save()
        try:
          # create a database when not linking to an existing databases
          if not request.POST.get('nocreate') == 'on':
            pd.newOCPCAProject( new_project.project_name )
          if 'token' in request.POST:
            tk = Token ( token_name = new_project.project_name, token_description = 'Default token for public project', project_id=new_project, user_id=request.user.id, public=new_project.public ) 
            tk.save()

          ## RBTODO create a default channel

        except Exception, e:
          logger.error("Failed to create project.  Error {}".format(e))
          messages.error(request,"Failed to create project Error {}".format(e))

        return HttpResponseRedirect(get_script_prefix()+'ocpuser/projects/')
      else:
        context = {'form': form}
        return render_to_response('createproject.html',context,context_instance=RequestContext(request))

    else:
      #default
      return redirect(getProjects)
Beispiel #48
0
def save_token(token, request, *args, **kwargs):
    # app.logger.debug('save_token')
    #toks = db.session.query(Token).filter_by(client_id=request.client.client_id,
    #                             user_id=request.user.id).all()
    #app.logger.debug('client_id={client_id}, user_id={user_id}'.format(client_id=request.client.client_id, user_id=request.user.id))
    #app.logger.debug(toks)
    ## make sure that every client has only one token connected to a user
    #db.session.delete(toks)

    expires_in = token.pop('expires_in')
    expires = datetime.utcnow() + timedelta(seconds=expires_in)

    # app.logger.debug(token)

    #from pprint import pprint
    # import pprint
    # from inspect import getmembers
    #
    # pp = pprint.PrettyPrinter(indent=4)
    #
    # app.logger.debug('=' * 80)
    # app.logger.debug(pp.pformat(getmembers(request)))
    # app.logger.debug('=' * 80)
    # app.logger.debug(pp.pformat(getmembers(current_user)))
    # app.logger.debug('=' * 80)
    #app.logger.debug(current_user.dir())
    tok = Token(**token)
    tok.expires = expires
    tok.client_id = request.client.client_id

    if not request.user:
        tok.user_id = current_user.id
    else:
        tok.user_id = request.user.id

        #if hasattr(request, 'user'):
        #tok.user_id = request.user.id
        #elif current_user.id:
        #tok.user_id = current_user.id
    #tok.user_id = current_user.id
    db.session.add(tok)
    db.session.commit()
    return tok
Beispiel #49
0
def render_index(request, template):
    """
    Render the single landing page we have in FireCheckIn. Fill in information on the state
    of the connections to Fire Eagle and Foursquare and see if the user is logged in.
    """
    fireeagle_connected = False
    foursquare_connected = False
    if request.user.is_anonymous():
        return render_to_response(template,  { 'fireeagle_connected': fireeagle_connected,
                                                 'foursquare_connected': foursquare_connected})
    else:
        if ( Token.gql( "WHERE user = :1", str(request.user) ).get() != None ):
              token = Token.gql( "WHERE user = :1", str(request.user) ).get()
              if ( token.fe_token ):
                  fireeagle_connected = True
              if ( token.fs_token ):
                  foursquare_connected = True
        return render_to_response(template,  { 'fireeagle_connected': fireeagle_connected,
                                                 'foursquare_connected': foursquare_connected})
Beispiel #50
0
def register(request):
    info = ''
    if request.method == 'POST':
        form = CustomerRegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            if Customer.objects.filter(email= email).count() == 0:
                customer = form.save()
                customer.save()
                token = Token(token = utility.generate_token(), customer = customer)
                token.save()
                content = '''<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>Guo Hao Hotel注册验证</title></head><body><a href='http://10.131.255.124/account/%s/'>激活</a></body></html>'''
                utility.send_mail(customer.email, 'GuoHaoHotel', content % token.token)
                info = '已经发送一封邮件至%s,请点击链接激活账户' % customer.email
            else:
                info = '邮箱已经注册!'
    elif request.method == 'GET':
        form = CustomerRegisterForm()
    return render(request, 'register.html', {'form' : form, 'info' : info})
Beispiel #51
0
def syncworker(request):
    """
    Okay, this is the real stuff. It's the worker process for the task queue.
    Gets a user name as a parameter.
    Calls Foursquare, Fire Eagle. Compares times of last check-in. If the Foursquare check-in
    is more recent, updates Fire Eagle.
    We catch all kinds of exceptions, so users with messed up OAuth permissions won't stop
    the worker.
    """
    user = request.args.get('user')
    logging.warning('user is: %s' % str(user))
    t = Token.gql( "WHERE user = :1", str(user) ).get()
    lat = 0
    lon = 0
    try:
        token = oauth.OAuthToken.from_string( t.fe_token )
        fe = FireEagle( FE_CONSUMER_KEY, FE_CONSUMER_SECRET )
        user = fe.user( token )
        date_time = user[0]['location'][0]['located_at']
        """
        For some reasons that only Yahoo! knows, Fire Eagle logs its time and dates
        in local Californian time (including Daylight Saving Time), so we have to
        convert the thing to UTC. Crazy, huh? 
        Share my frustration at http://blog.johl.io/post/393494632/what-time-is-it
        """
        current_datetime = datetime.datetime.now(ustimezones.pacific()) # What time is it in Cali?
        fe_delta = str(current_datetime.replace(tzinfo=None) - date_time)
        credentials = foursquare.OAuthCredentials( FS_CONSUMER_KEY, FS_CONSUMER_SECRET )
        fs = foursquare.Foursquare( credentials )
        token = oauth.OAuthToken.from_string( t.fs_user_token )
        credentials.set_access_token(token)
        history = fs.history()
        date_time = history['checkins'][0]['created']
        lat = history['checkins'][0]['venue']['geolat']
        lon = history['checkins'][0]['venue']['geolong']
        current_datetime = datetime.datetime.now()
        date_time = datetime.datetime.fromtimestamp(time.mktime(rfc822.parsedate(date_time)))
        fs_delta = str(current_datetime.replace(tzinfo=None) - date_time)
    except:
        """
        So yeah, something went wrong. Let's assume we should update Fire Eagle.
        """
        logging.warning('Application error occurred with user %s', str(t.user))
        fs_delta = 0
        fe_delta = -1
    if (fs_delta < fe_delta):
      try:
        fe.update( lat=lat, lon=lon, token=oauth.OAuthToken.from_string( t.fe_token ) )
      except:
        """
        Can't update Fire Eagle. Whatever.
        """
        logging.warning('Application error occurred with user %s', str(t.user))
    return render_to_response('firecheckin/index.html')
Beispiel #52
0
def deleteme(request):
    """
    Remove the currently logged in user from our database and log them out. 
    Privacy, you know? Don't request this casually :)
    """
    if (not (request.user.is_anonymous())):
        logout = users.create_logout_url( "/" )
        db.delete(Token.gql( "WHERE user = :1", str(request.user) ).get())
        return redirect( logout )
    else:
        return redirect( "/" )
Beispiel #53
0
 def post(self):
     user = users.get_current_user()
     q = Token.query(Token.email == user.email())
     token = q.get()
     
     airship.push({
         "android": {
              "extra": {"phone": self.request.get('phone'), "msg":self.request.get('msg')}
         }
     }, apids=[token.apid])
     template = jinja_environment.get_template('templates/index.html')
     self.response.out.write(template.render({}))
Beispiel #54
0
def sync(request):
  """
  It's the cron job that gets run every 2 minutes (or on request). Iterates over users and
  queues tasks to sync. Will only 'iterate' over the current user
  if called by a logged in user.
  """
  tokens = []
  if (request.user.is_anonymous()):
      tokens = Token.all().fetch(1000)
  else:
      tokens.append(Token.gql( "WHERE user = :1", str(request.user) ).get())
  for t in tokens:
      taskqueue.add(url='/syncworker/?user=%s' % str(t.user), method='GET')
  """
  We cannot return a redirect when called anonymously as a cron job.
  Google App Engine will complain about 'Too many continues.'
  """
  if (request.user.is_anonymous()):
      return render_to_response('firecheckin/index.html')
  else:
      return redirect( "/" )
Beispiel #55
0
def CreateToken (house_id, protocol='http://', idp=''):
    try:
	video = Video.objects.get(house_id=house_id)
    except:
	return ''
    
    token = Token()
    token.protocol      = protocol
    token.idp_code      = idp
    token.expiration 	= datetime.now() + timedelta(0,7200)
    token.token      	= _get_md5_hash(house_id)
    token.video		= video
    token.save()
    return token.token
Beispiel #56
0
	def get(self, username=None, password=None):

		try:
			if (username is not None) and (password is not None):

				# Verification du user.
				user = User.query(ndb.AND(User.str_username==username,User.str_password==password)).get()

				if user is None:
					self.error(404)
					return

				# Voir s'il y a deja un token, si oui, on le recréé.
				token = Token.query(Token.key_user==user.key).get()

				if token is not None:
					token.key.delete()

				token = Token(id=GetTimeInt(),
					key_user=user.key,
					b_valide=True)

				token.urlsafe_key = token.key.urlsafe()

				token.put()

				self.response.headers['Content-Type'] = ('text/plain')
				self.response.write(token.key.urlsafe())
				self.response.set_status(200)

		except (db.BadValueError, ValueError, KeyError):
			logging.error('%s', traceback.format_exc())
			self.error(400)

		except Exception:
			logging.error('%s', traceback.format_exc())
			self.error(500)
Beispiel #57
0
def create_token(request, url_id=None, **kwargs):
    kwargs['extra_context'] = {}
    if request.method == 'POST':
        form = TokenAddForm(request.POST)
        if form.is_valid():
            email=form.cleaned_data['email']
            token = Token(
                url=form.cleaned_data['url'],
                valid_until=form.cleaned_data['valid_until'],
                forward_count=form.cleaned_data['forward_count'],
                email=email,
                name=form.cleaned_data['name'],
            )
            token.save()
            messages.add_message(request, messages.SUCCESS, 'Token successfully created for %s.' % token.email)
            return HttpResponseRedirect(reverse('token_list'))
    else:
        initial_data = None
        if not url_id is None:
            url = ProtectedURL.objects.get(id=url_id)
            initial_data = {'url': url.url, }
        form = TokenAddForm( initial=initial_data )
    kwargs['extra_context']['form'] = form
    return direct_to_template(request, template='token_auth/create_token.html', **kwargs)
Beispiel #58
0
    def token_or_redirect(**kwargs):
        token = kwargs.get('token', '')
        msg, umi, user = Token.convert_token(token)
        if user is None:
            # TODO where to redirect?
            return redirect(url_for_with_prefix('app_router.reset_token'))
        else:
            if msg is not None:
                if msg.is_already_sent() and viewfunc.__name__ is not 'message_sent':
                    return redirect(url_for_with_prefix('app_router.message_sent', token=token))
                elif not msg.is_already_sent() and user.default_info.accept_tos and viewfunc.__name__ not in ['confirm_reps', 'message_sent']:
                    return redirect(url_for_with_prefix('app_router.confirm_reps', token=token))

            kwargs.update({'msg': msg, 'umi': umi, 'user': user})
            return viewfunc(**kwargs)