Esempio n. 1
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)
Esempio n. 2
0
 def set_token(token, request, *args, **kwargs):
     logger.debug('set token - user: {}\n'.format(request.user.userId))
     tok = Token(**token)
     tok.userId = request.user.userId
     tok.client_id = request.client.client_id
     tok.save()
     return tok
Esempio n. 3
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)
Esempio n. 4
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))
Esempio n. 5
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))
Esempio n. 6
0
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
Esempio n. 7
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)
Esempio n. 8
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
Esempio n. 9
0
    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
Esempio n. 10
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}')
Esempio n. 11
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
Esempio n. 12
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)
Esempio n. 13
0
def issue_token():
    data = request.get_json()
    User.validate_user_login(data)
    user = User.find_or_404(email=data['email'])
    is_valid = user.check_password(data['password'])

    # Wrong
    if not is_valid:
        message = {"Error": "Invalid login credentials."}
        return make_response(jsonify(message), status.HTTP_401_UNAUTHORIZED)

    token = Token.find_by_user_id(user.id)

    if token:
        token.delete()

    token = Token(user.id)
    token.save()
    return token.generate_jwt_token()
Esempio n. 14
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        psdmd5 = md5(request.form['password'])
        password = psdmd5.hexdigest()
        user = User.query.filter_by(
            username=username
        ).first()
        if user:
            if user.password == password:
                tokenText = md5(password + str(time.time())).hexdigest()
                token = Token(user_id=user.id, token=tokenText)
                token.save()
                return info(tokenText)
            else:
                return custom_info("Password is wrong", 2)
        else:
            return error('user not exist')
    return error('not POST')
Esempio n. 15
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']
Esempio n. 16
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})
Esempio n. 17
0
def get_uid_token(flush=False):
    cmdb_info = Cmdb.objects.filter(username=CMDB2_USER)
    tu = Token.objects.all()
    username, password, uid, token = "", "", "", ""
    for ci in cmdb_info:
        username = ci.username
        password = base64.b64decode(ci.password)
    for one in tu:
        uid, token = one.uid, one.token
    if uid and token and not flush:
        return uid, token
    url = CMDB2_URL + "cmdb/openapi/login/"
    data = {
        "username": username,
        "password": password,
        "sign": "",
        "timestamp": TimeToolkit.local2utctime(datetime.now())
    }
    data_str = json.dumps(data)
    try:
        # Log.logger.info("login data:{}".format(data))
        ret = requests.post(url, data=data_str, timeout=5)
        # Log.logger.info(ret.json())
        if ret.json()["code"] == 0:
            uid, token = ret.json()["data"]["uid"], ret.json()["data"]["token"]
            one = Token.objects.filter(uid=uid)
            if one:
                Token.objects(uid=uid).update_one(
                    token=token,
                    token_date=TimeToolkit.local2utctimestamp(datetime.now()))
            else:
                tu = Token(uid=uid,
                           token=token,
                           token_date=TimeToolkit.local2utctimestamp(
                               datetime.now()))
                tu.save()
    except Exception as exc:
        pass
    return uid, token
Esempio n. 18
0
def users_authenticate():
    SALT = current_app.config.get('SALT')
    payload = request.get_json()
    username = None
    password = None

    if payload:
        if 'username' in payload:
            username = payload['username']
        if 'password' in payload:
            password = payload['password']

    token = None

    to_serialize = {'status': False}
    code = 200
    if username is None or password is None:
        to_serialize['error'] = 'Required parameter is missing'
    else:
        hashed_password = hashlib.sha512(password + SALT + username).hexdigest()
        user = User.objects(hashed_password=hashed_password).first()  ##????
        if user is not None:
            data = {'pk': str(user.pk), 'ip': request.remote_addr}
            token = Token(token=str(uuid.uuid4()), data=json.dumps(data))
            token.save()

    if token is not None:
        to_serialize['status'] = True
        to_serialize['result'] = {'token': token.token}
    # todo make the json_response() better
    response = current_app.response_class(
        response=json.dumps(to_serialize),
        status=code,
        mimetype='application/json'
    )
    return response
Esempio n. 19
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)
Esempio n. 20
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)
Esempio n. 21
0
def register(request):
    '''
    注册
    '''
    params = yield from request.json()
    kw = dict(**params)
    name = kw['userName']
    psd = kw['password']
    repsd = kw['repassword']
    if not name or not name.strip():
        result = dict(code=0, msg="名称不能为空")
    elif not psd:
        result = dict(code=0, msg="密码不能为空")
    elif psd != repsd:
        result = dict(code=0, msg="确认密码不正确")
    else:
        users = yield from User.findAll('name=?', [name])
        if len(users) > 0:
            result = dict(code=0, msg="该名称已经注册过了")
        else:
            uid = next_id()  #生成唯一的id
            shal_psd = '%s:%s' % (uid, psd)  #加密密码
            user = User(id=uid,
                        name=name,
                        nickname='',
                        email='',
                        password=hashlib.sha1(
                            shal_psd.encode('utf-8')).hexdigest(),
                        image='')
            yield from user.save()

            #创建token
            shal = '%s=%s=%s' % ('Token', uid, time.time())
            shal_key = hashlib.sha1(shal.encode('utf-8')).hexdigest()
            token = Token(id=next_id(), uid=uid, token_key=shal_key)
            yield from token.save()
            result = dict(code=1, msg="注册成功")
    return result
Esempio n. 22
0
def forgot_password(request):
    if request.method == 'POST':
        try:
            email = request.POST.get('email', None)
            if email:
                user = User.objects.get(email=email)
                message = 'An email was sent to you.'
                try:
                    token = Token.objects.get(user=user)
                    # send email to user with token
                    send_mail(
                        'iSpark Password Reset',
                        'Click on the following link to reset your password http://www.isparkegypt.com/password_reset/%s' % token.token,
                        '*****@*****.**',
                        ['%s' % user.email],
                        fail_silently=False,
                    )
                except Token.DoesNotExist:
                    token = Token(user=user)
                    token.save()
                    # send email to user with token
                    send_mail(
                        'iSpark Password Reset',
                        'Click on the following link to reset your password http://www.isparkegypt.com/password_reset/%s' % token.token,
                        '*****@*****.**',
                        ['%s' % user.email],
                        fail_silently=False,
                    )
            else:
                message = 'Enter a valid email.'
        except User.DoesNotExist:
            message = 'You are not registered.'
        addresses = Contact.objects.filter(type='AD')
        emails = Contact.objects.filter(type='EM')
        phones = Contact.objects.filter(type='PH')
        try:
            fb = Contact.objects.get(type='FB')
        except Contact.DoesNotExist:
            fb = ''
        try:
            tw = Contact.objects.get(type='TW')
        except Contact.DoesNotExist:
            tw = ''
        try:
            ins = Contact.objects.get(type='IN')
        except Contact.DoesNotExist:
            ins = ''
        try:
            yt = Contact.objects.get(type='YT')
        except Contact.DoesNotExist:
            yt = ''
        return render(request, 'forgot_password.html', {'message': message, 'emails': emails, 'addresses': addresses, 'phones': phones, 'fb': fb, 'tw': tw, 'in': ins, 'yt': yt})
    else:
        addresses = Contact.objects.filter(type='AD')
        emails = Contact.objects.filter(type='EM')
        phones = Contact.objects.filter(type='PH')
        try:
            fb = Contact.objects.get(type='FB')
        except Contact.DoesNotExist:
            fb = ''
        try:
            tw = Contact.objects.get(type='TW')
        except Contact.DoesNotExist:
            tw = ''
        try:
            ins = Contact.objects.get(type='IN')
        except Contact.DoesNotExist:
            ins = ''
        try:
            yt = Contact.objects.get(type='YT')
        except Contact.DoesNotExist:
            yt = ''
        return render(request, 'forgot_password.html', {'emails': emails, 'addresses': addresses, 'phones': phones, 'fb': fb, 'tw': tw, 'in': ins, 'yt': yt})
Esempio n. 23
0
 def get_data(self, **response_kwargs):
     token = Token()
     token.save()
     return token.dict()