示例#1
0
    def register_user():

        body = request.get_json()
        check_params(body, 'email', 'password', 'device_token')

        # If user exists and failed to validate his account
        user = (Users.query.filter_by(email=body['email'],
                                      password=sha256(
                                          body['password'])).first())

        if user and user.valid == False:
            data = {'validation_link': validation_link(user.id)}
            send_email(type='email_validation', to=user.email, data=data)

            return jsonify({
                'message':
                'Another email has been sent for email validation'
            })

        elif user and user.valid:
            raise APIException('User already exists', 405)

        user = Users(email=body['email'], password=sha256(body['password']))
        db.session.add(user)
        db.session.add(Devices(token=body['device_token'], user=user))
        db.session.commit()

        user = Users.query.filter_by(email=body['email']).first()

        send_email(type='email_validation',
                   to=user.email,
                   data={'validation_link': validation_link(user.id)})

        return jsonify({'message': 'Please verify your email'}), 200
示例#2
0
def nur():
    Nurses.query.delete()
    db.session.execute("ALTER TABLE userpatient AUTO_INCREMENT = 1")

    nurs = Nurses(
        fullname="Anntonian Brown",
        username="******",
        password=utils.sha256("brown"),
        email="*****@*****.**",
        age="35",
        work_exprience="yes",
        license="yes",
        years_working="10",
    )
    db.session.add(nurs)

    nurs2 = Nurses(
        fullname="Rajae Lindsay",
        username="******",
        password=utils.sha256("bignurselindsay"),
        email="*****@*****.**",
        age="35",
        work_exprience="yes",
        license="yes",
        years_working="20",
    )
    db.session.add(nurs2)
    db.session.commit()
示例#3
0
def make_iso_image():
    setfile('${ISO_DESTDIR}/boot/loader.conf',
            template('${BUILD_CONFIG}/templates/cdrom/loader.conf'))
    setfile('${ISO_DESTDIR}/.mount.conf',
            template('${BUILD_CONFIG}/templates/cdrom/mount.conf'))
    sh('cp ${WORLD_DESTDIR}/boot/loader ${ISO_DESTDIR}/boot/loader')
    sh('cp ${WORLD_DESTDIR}/boot/device.hints ${ISO_DESTDIR}/boot/device.hints'
       )
    sh('cp ${WORLD_DESTDIR}/boot/*.4th ${ISO_DESTDIR}/boot')
    sh('cp ${WORLD_DESTDIR}/boot/loader.rc ${ISO_DESTDIR}/boot/loader.rc')
    sh('cp ${WORLD_DESTDIR}/boot/loader.rc.local ${ISO_DESTDIR}/boot/loader.rc.local'
       )
    sh('cp ${WORLD_DESTDIR}/boot/menu.rc ${ISO_DESTDIR}/boot/menu.rc')
    sh('cp -R ${WORLD_DESTDIR}/boot/defaults ${ISO_DESTDIR}/boot/defaults')

    # New-style isoboot image
    output_nogrub = output.replace('.iso', '-NOGRUB.iso')
    sh('${BUILD_ROOT}/build/tools/make_iso_image.sh ${CDROM_LABEL} ${output_nogrub} ${WORLD_DESTDIR} ${ISO_DESTDIR}'
       )
    sha256(output_nogrub)

    # Old-style GRUB image
    sh('mkdir -p ${ISO_DESTDIR}/boot/grub')
    setfile('${ISO_DESTDIR}/boot/grub/grub.cfg',
            template('${BUILD_CONFIG}/templates/cdrom/grub.cfg'))
    sh('grub-mkrescue --xorriso=${BUILD_ROOT}/build/tools/xorriso.sh -o ${output} ${ISO_DESTDIR} -- -volid ${CDROM_LABEL}'
       )
    sha256(output)
示例#4
0
def make_iso_image():
    setfile('${ISO_DESTDIR}/boot/loader.conf', template('${BUILD_CONFIG}/templates/cdrom/loader.conf'))
    setfile('${ISO_DESTDIR}/boot/grub/grub.cfg', template('${BUILD_CONFIG}/templates/cdrom/grub.cfg'))
    setfile('${ISO_DESTDIR}/.mount.conf', template('${BUILD_CONFIG}/templates/cdrom/mount.conf'))
    sh('cp ${WORLD_DESTDIR}/boot/device.hints ${ISO_DESTDIR}/boot/device.hints')
    sh('grub-mkrescue -o ${output} ${ISO_DESTDIR} -- -volid ${CDROM_LABEL}')
    sha256(output)
示例#5
0
def reset_password(id):

    if id == 'me':
        id = str(get_jwt())['sub']

    if not id.isnumeric():
        raise APIException('Invalid id: ' + id, 400)

    if request.args.get('forgot') == 'true':
        return jsonify({
            'message':
            'A link has been sent to your email to reset the password',
            'link':
            os.environ.get('API_HOST') + '/users/reset_password/' +
            create_jwt({
                'id': id,
                'role': 'password'
            })
        }), 200

    body = request.get_json()
    check_params(body, 'email', 'password', 'new_password')

    user = Users.query.filter_by(id=int(id),
                                 email=body['email'],
                                 password=sha256(body['password'])).first()
    if not user:
        raise APIException('Invalid parameters', 400)

    user.password = sha256(body['new_password'])

    db.session.commit()

    return jsonify({'message': 'Your password has been changed'}), 200
示例#6
0
 def chain(self, receipt, previousJwsString):
     chainingValue = None
     if previousJwsString:
         chainingValue = utils.sha256(previousJwsString.encode("utf-8"))
     else:
         chainingValue = utils.sha256(receipt.registerId.encode("utf-8"))
     return chainingValue[0:8]
def create_package():
    if os.path.exists('/usr/local/bin/pigz'):
        sh('tar -C ${DEBUG_ROOT} -cvf - . | /usr/local/bin/pigz -c > ${output}', log='/dev/null')
    else:
        sh('tar -C ${DEBUG_ROOT} -cvJf ${output} .', log='/dev/null')

    sha256(output)
示例#8
0
def make_iso_image():
    setfile('${ISO_DESTDIR}/boot/loader.conf', template('${BUILD_CONFIG}/templates/cdrom/loader.conf'))
    setfile('${ISO_DESTDIR}/boot/grub/grub.cfg', template('${BUILD_CONFIG}/templates/cdrom/grub.cfg'))
    setfile('${ISO_DESTDIR}/.mount.conf', template('${BUILD_CONFIG}/templates/cdrom/mount.conf'))
    sh('cp ${WORLD_DESTDIR}/boot/device.hints ${ISO_DESTDIR}/boot/device.hints')
    sh('grub-mkrescue -o ${output} ${ISO_DESTDIR} -- -volid ${CDROM_LABEL}')
    sha256(output)
示例#9
0
def create_package():
    info('Creating debug package')
    if os.path.exists('/usr/local/bin/pigz'):
        sh('tar -C ${DEBUG_ROOT} -cvf - . | /usr/local/bin/pigz -c > ${output}', log='/dev/null')
    else:
        sh('tar -C ${DEBUG_ROOT} -cvJf ${output} .', log='/dev/null')

    sha256(output)
示例#10
0
def run():

    Userpatient.query.delete()
    db.session.execute("ALTER TABLE userpatient AUTO_INCREMENT = 1")

    user_patient1 = Userpatient(fullname="antoan",
                                username="******",
                                email='brown12gngemail',
                                password=utils.sha256('password for patient1'),
                                age='35',
                                gender='gender',
                                race='black',
                                home_address='home_address',
                                patient_condition="Aalzheimer",
                                patient_allergies="cats",
                                patient_name="debbie bropwe",
                                patient_medications="patient_medications",
                                patient_age="66",
                                patient_gender="female",
                                patient_race="black")
    db.session.add(user_patient1)

    user_patient2 = Userpatient(fullname="ann cqambple",
                                username="******",
                                email='aanathebestemail',
                                password=utils.sha256('password for patient2'),
                                age='26',
                                gender='female',
                                race='whitee',
                                home_address='home_address',
                                patient_condition="Aalzheimer",
                                patient_allergies="strawberry",
                                patient_name="patr caqmpbewl;",
                                patient_medications="pills",
                                patient_age="48",
                                patient_gender="male",
                                patient_race="white")
    db.session.add(user_patient2)

    user_patient3 = Userpatient(
        fullname="antoan jackson ",
        username="******",
        email='email',
        password=utils.sha256('password'),
        age='age',
        gender='gender',
        race='race',
        home_address='home_addresstyahate i lihe 415 ln',
        patient_condition="Aalzheimer",
        patient_allergies="penut",
        patient_name="manne jackson",
        patient_medications="pills",
        patient_age="15",
        patient_gender="male",
        patient_race="espanic")
    db.session.add(user_patient3)
    db.session.commit()
示例#11
0
 def sync(self):
     database_hash = sha256(database)
     print("Started sync")
     print('-' * 30)
     while True:
         time.sleep(1)
         #Update the GUI only if there's a change to the database
         if sha256(database) != database_hash:
             #if serialize(database) != serialize(previous_database):
             self.update_chats(database['users'])
             self.update_chatbox()
             #previous_database = deepcopy(database)
             database_hash = sha256(database)
示例#12
0
def make_iso_image():
    setfile('${ISO_DESTDIR}/boot/loader.conf',
            template('${BUILD_CONFIG}/templates/cdrom/loader.conf'))
    setfile('${ISO_DESTDIR}/.mount.conf',
            template('${BUILD_CONFIG}/templates/cdrom/mount.conf'))
    sh('cp ${WORLD_DESTDIR}/boot/loader ${ISO_DESTDIR}/boot/loader')
    sh('cp ${WORLD_DESTDIR}/boot/device.hints ${ISO_DESTDIR}/boot/device.hints'
       )
    sh('cp -r ${WORLD_DESTDIR}/boot/lua ${ISO_DESTDIR}/boot/')
    sh('cp -R ${WORLD_DESTDIR}/boot/defaults ${ISO_DESTDIR}/boot/defaults')

    # New-style isoboot image
    sh('${BUILD_ROOT}/build/tools/make_iso_image.sh ${CDROM_LABEL} ${output} ${WORLD_DESTDIR} ${ISO_DESTDIR}'
       )
    sha256(output)
示例#13
0
def login():

    if request.method == 'GET':
        return render_template('login.html', host=os.environ.get('API_HOST'))

    json = request.get_json()
    utils.check_params(json, 'email', 'password')

    user = Users.query.filter_by(email=json['email'],
                                 password=utils.sha256(
                                     json['password'])).first()

    if user is None:
        return jsonify({
            'login': False,
            'message': 'Email and password are incorrect',
        })

    return jsonify({
        'login': True,
        'jwt': create_jwt({
            'id': user.id,
            'role': 'admin'
        })
    })
示例#14
0
    def get_all_users_in_trmnt(id):
        
        r  = request.get_json()

        # Security token check
        if r['api_token'] != utils.sha256( os.environ['POKERSOCIETY_API_TOKEN'] ):
            return jsonify({'error':'API token does not match'})        

        trmnt = Tournaments.query.get( id )
        if trmnt is None:
            return jsonify({'error':'Tournament not found with id: '+str(id)})

        trmnt_data = {
            'tournament name': trmnt.name,
            'casino': trmnt.casino,
            'start date': trmnt.start_at }

        users = [ trmnt_data ]

        for swap in trmnt.swaps:
            user = swap.sender_user
            data = {
                'email': user.user.email,
                'first name': user.first_name,
                'last name': user.last_name,
                'ID (poker society)': user.pokersociety_id }
            if swap.status._value_ == 'agreed':
                if data not in users:
                    users.append(data)


        return jsonify(users)
示例#15
0
文件: base.py 项目: tweetyf/TChatBot
 def countPrivilege(self):
     '''根据预置的秘密计算一个时间相关的随机数,每分钟变一次,用来发布ROM的时候做验证。'''
     secret = config.AUTOPUB_SECRET
     salt = time.strftime("%Y-%m-%d %H:00", time.localtime(time.time()))
     ptoken = utils.sha256(secret + salt)
     print("hasPrivilege: ptoken is:", ptoken)
     return ptoken
示例#16
0
 def resolve_conflict(self):
     base = self.find_same_base(self.rev, self.rev - 1)
     v0, boundaries = read(base)
     v1, _ = read(self.rev - 1)
     v2, _ = read(self.rev)
     user1 = self.vector[self.rev - 1].get_attribute('modifier')
     user2 = self.vector[self.rev].get_attribute('modifier')
     user1 = user1['firstname'] + user1['lastname']
     user2 = user2['firstname'] + user2['lastname']
     ops = operation.conflict_resolution(v0, v1, user1, v2, user2)
     v12 = operation.apply_sequence(v0, ops)
     chunker = ocdc.ocdc(ops, boundaries)
     chunker.mark()
     chunker.recalculate(v12)
     hashs = []
     datas = []
     for i in range(len(chunker.boundaries)):
         start = chunker.boundaries[i]
         if i == len(chunker.boundaries) - 1:
             end = len(v12)
         else:
             end = chunker.boundaries[i + 1]
         data = v12[start:end]
         datas.append(data)
         hashs.append(utils.sha256(data))
     node = vnode.vnode({}, hashs)
     node.set_attribute('size', len(v12))
     node.set_attribute('base_rev', base)
     node.set_attribute('modifier', config.server_user)
     node.set_attribute('modified_time', int(time.time() * 1000))
     self.add_vnode(node, True)
     return hashs, datas
示例#17
0
    def login_admin():

        if request.method == 'GET':
            return render_template('login.html',
                                   host=os.environ.get('API_HOST'))

        json = request.get_json()
        utils.check_params(json, 'email', 'password')

        user = Users.query.filter_by(email=json['email'],
                                     password=utils.sha256(
                                         json['password'])).first()

        if user is None:
            return jsonify({
                'login': False,
                'message': 'Email and password are incorrect',
            })

        identity = {'id': user.id, 'role': 'admin', 'sub': user.id}

        return jsonify({
            'login':
            True,
            'jwt':
            jwt.encode(identity,
                       os.environ['JWT_SECRET_KEY'],
                       algorithm='HS256')
        })
示例#18
0
 def post(self):
     a = self.get_argument("a","")
     uname = self.get_argument("uname","")
     urole = self.get_argument("urole","developer")
     upwd1 = self.get_argument("upassword","")
     upwd2 = self.get_argument("upassword2","")
     picname = self.get_argument("upicname",config.DEFAULT_HEAD)
     uavatar = list(self.request.files.items())
     udscpt = self.get_argument("udescription","")
     if not (self.accessSelf(uname) or self.accessAdmin()):
         ##不是自己操作或者不是管理员则返回
         self.permissionDenied()
         return
     if (a =='add'):
         if (not (upwd1 == upwd2)) or (upwd1==""):
             self.write("密码输入不一致")
             return
         mtime = int(time.time())
         if (len(uavatar)>0):
             (field, mpic) = uavatar[0]
             for picfile in mpic:
                 picname ="/static/images/"+ (picfile["filename"])
                 #1, 保存新应用的图标
                 utils.saveBin("."+picname, picfile["body"])
         # 确保只有管理员可以改变用户角色
         if not self.accessAdmin():
             urole = "developer"
         #3, 保存在数据库里
         self.logI(u"保存开发者信息:%s:%s"%(uname,urole))
         model.add_new_user(uname, utils.sha256(upwd1), urole, picname, udscpt, mtime)
     self.seeother("/publish")
示例#19
0
    def decryptTurnoverCounter(self, receipt, encTurnoverCounter, key):
        iv = utils.sha256(
            receipt.registerId.encode("utf-8") +
            receipt.receiptId.encode("utf-8"))[0:16]
        decCtr = utils.aes256ctr(iv, key, encTurnoverCounter)

        return int.from_bytes(decCtr, byteorder='big', signed=True)
示例#20
0
def swapprofit_user():

    json = request.get_json()
    utils.check_params(json, 'api_token', 'email', 'password', 'first_name',
                       'last_name')

    if json['api_token'] != utils.sha256(os.environ['API_TOKEN']):
        raise APIException('Invalid api token', 400)

    # Find user in db
    user = Users.query.filter_by(email=json['email']).first()

    # If no user found, create one
    if user is None:
        print('user is None', end='\n')
        user = Users(email=json['email'],
                     password=json['password'],
                     first_name=json['first_name'],
                     last_name=json['last_name'],
                     nickname=json.get('nickname'),
                     hendon_url=json.get('hendon_url'),
                     status='valid')
        db.session.add(user)
        db.session.commit()

    return jsonify({'pokersociety_id': user.id})
    def login():

        req = request.get_json()
        check_params(req, 'email', 'password', 'device_token')

        user = Users.query.filter_by(email=req['email'],
                                     password=sha256(req['password'])).first()

        if user is None:
            raise APIException('Sorry you entered the wrong email or password',
                               404)
        if user.status._value_ == 'invalid':
            raise APIException('Email not validated', 405)
        if user.status._value_ == 'suspended':
            raise APIException('Your account is suspended', 405)

        is_token_registered = \
            Devices.query.filter_by( token=req['device_token'] ).first() is not None
        profile_exists = Profiles.query.get(user.id) is not None

        if profile_exists and not is_token_registered:
            db.session.add(Devices(user_id=user.id, token=req['device_token']))
            db.session.commit()

        return jsonify({
            'jwt':
            create_jwt({
                'id': user.id,
                'role': 'user',
                'exp': req.get('exp', 15)
            })
        }), 200
示例#22
0
    def upload(self, filepath):
        """
            Function to upload a file
        """

        sha256_file = utils.sha256(filepath)
        url = '%s/apks/%s/get_upload_url' % (BASE_URL, sha256_file)
        response = requests.get(url=url, headers=self.headers,
                                verify=REQUESTS_CA_BUNDLE)
        if response.status_code == 200:
            json_data = response.json()
            # print json_data.get('upload_url', None)
            files = {'file': open(filepath, 'rb')}

            response = requests.post(url=json_data.get("upload_url"),
                                     files=files,
                                     verify=REQUESTS_CA_BUNDLE)
            while response.status_code == 404:  # Workaround server problem sometimes
                time.sleep(1)
                response = requests.post(url=json_data.get("upload_url"),
                                         files=files,
                                         verify=REQUESTS_CA_BUNDLE)
            return sha256_file
        elif response.status_code == 409:
            raise Exception("APK already exists")
        else:
            raise Exception("Unknown error: %s" % response.text)
示例#23
0
def handle_login():

    body = request.get_json()

    user = users.query.filter_by(email=body['email'],
                                 password=sha256(body['password'])).first()

    if not user:
        return 'User not found', 404

    return jsonify({
        #   'token': create_jwt(identity=1),
        'id': user.id,
        'email': user.email,
        'firstname': user.firstname,
        'lastname': user.lastname,
        'avatar': user.avatar,
        'wallet': user.wallet,
        'birthdate': user.birthdate,
        'gender': user.gender,
        'address': user.address,
        'city': user.city,
        'state': user.state,
        'zipCode': user.zipCode,
        'phone': user.phone,
        'admin': user.admin
    })
示例#24
0
def handle_register():

    body = request.get_json()

    if body is None:
        raise APIException(
            "You need to specify the request body as a json object",
            status_code=400)
    if 'firstname' not in body and 'lastname' not in body:
        raise APIException("You need to specify the first name and last name",
                           status_code=400)
    if 'password' not in body and 'email' not in body:
        raise APIException("You need to specify the password and email",
                           status_code=400)
    if 'firstname' not in body:
        raise APIException('You need to specify the first name',
                           status_code=400)
    if 'lastname' not in body:
        raise APIException('You need to specify the last name',
                           status_code=400)
    if 'password' not in body:
        raise APIException('You need to specify the password', status_code=400)
    if 'email' not in body:
        raise APIException('You need to specify the email', status_code=400)

    db.session.add(
        users(email=body['email'],
              firstname=body['firstname'],
              lastname=body['lastname'],
              password=sha256(body['password']),
              admin=0))
    db.session.commit()

    return jsonify({'register': 'success', 'msg': 'Successfully Registered'})
示例#25
0
    def html_reset_password(token):

        jwt_data = decode_jwt(token)

        if request.method == 'GET':
            user = Users.query.filter_by(id=jwt_data['sub'],
                                         email=jwt_data['role']).first()
            if user is None:
                raise APIException('User not found', 404)

            return render_template('reset_password.html',
                                   host=os.environ.get('API_HOST'),
                                   token=token,
                                   email=jwt_data['role'])

        # request.method == 'PUT'
        req = request.get_json()
        utils.check_params(req, 'email', 'password')

        if len(req['password']) < 6:
            raise APIException('Password must be at least 6 characters long')

        user = Users.query.filter_by(id=jwt_data['sub'], email=req['email'])
        if user is None:
            raise APIException('User not found', 404)

        user.password = utils.sha256(req['password'])

        db.session.commit()

        return jsonify({'message': 'Your password has been updated'}), 200
示例#26
0
    def upload(self, filepath):
        """
            Function to upload a file
        """

        sha256_file = utils.sha256(filepath)
        url = '%s/apks/%s/get_upload_url' % (BASE_URL, sha256_file)
        response = requests.get(url=url,
                                headers=self.headers,
                                verify=REQUESTS_CA_BUNDLE)
        if response.status_code == 200:
            json_data = response.json()
            # print json_data.get('upload_url', None)
            files = {'file': open(filepath, 'rb')}

            response = requests.post(url=json_data.get("upload_url"),
                                     files=files,
                                     verify=REQUESTS_CA_BUNDLE)
            while response.status_code == 404:  # Workaround server problem sometimes
                time.sleep(1)
                response = requests.post(url=json_data.get("upload_url"),
                                         files=files,
                                         verify=REQUESTS_CA_BUNDLE)
            return sha256_file
        elif response.status_code == 409:
            raise Exception("APK already exists")
        else:
            raise Exception("Unknown error: %s" % response.text)
def handle_register():

    json = request.get_json()

    property_check = [
        'first_name', 'last_name', 'username', 'password', 'email'
    ]
    missing_props = []
    empty_props = []
    for prop in property_check:
        if prop not in json:
            missing_props.append(prop)
    if len(missing_props) > 0:
        raise APIException(
            f'Missing {", ".join(missing_props)} property in json')

    for prop in property_check:
        if json[prop] == "":
            empty_props.append(prop)
    if len(empty_props) > 0:
        raise APIException(f'Missing {", ".join(empty_props)} data in json')

    db.session.add(
        Users(first_name=json['first_name'],
              last_name=json['last_name'],
              username=json['username'],
              password=utils.sha256(json['password']),
              date_of_birth=json.get('date_of_birth'),
              email=json['email']))
    db.session.commit()
    return jsonify(json)
示例#28
0
    def update_email(user_id):

        req = request.get_json()
        utils.check_params(req, 'email', 'password', 'new_email')

        if req['email'] == req['new_email']:
            return jsonify(
                {'message': 'Your email is already ' + req['new_email']})

        user = Users.query.filter_by(id=user_id,
                                     email=req['email'],
                                     password=utils.sha256(
                                         req['password'])).first()

        if user is None:
            raise APIException('User not found', 404)

        user.status = 'invalid'
        user.email = req['new_email']

        db.session.commit()

        send_email(template='email_validation',
                   emails=user.email,
                   data={
                       'validation_link':
                       utils.jwt_link(user.id, role='email_change')
                   })

        return jsonify({'message': 'Please verify your new email'}), 200
示例#29
0
def html_reset_password(token):

    jwt_data = decode_jwt(token)
    if jwt_data['role'] != 'password':
        raise APIException('Access denied', 401)

    if request.method == 'GET':
        return render_template('reset_password.html',
                               data={
                                   'host': os.environ.get('API_HOST'),
                                   'token': token
                               })

    # request.method == 'PUT'
    body = request.get_json()
    check_params(body, 'email', 'password')

    user = Users.query.filter_by(id=jwt_data['sub'],
                                 email=body['email']).first()
    if not user:
        raise APIException('User not found', 404)

    user.password = sha256(body['password'])

    db.session.commit()

    return jsonify({'message': 'Your password has been updated'}), 200
示例#30
0
def update_email(id):

    if id == 'me':
        id = str(get_jwt()['sub'])

    if not id.isnumeric():
        raise APIException('Invalid id: ' + id, 400)

    body = request.get_json()
    check_params(body, 'email', 'password', 'new_email')

    user = Users.query.filter_by(id=int(id),
                                 email=body['email'],
                                 password=sha256(body['password'])).first()
    if not user:
        raise APIException('Invalid parameters', 400)

    user.valid = False
    user.email = body['new_email']

    db.session.commit()

    return jsonify({
        'message': 'Please verify your new email',
        'validation_link': validation_link(user.id)
    }), 200
示例#31
0
 def countPrivilege(self):
     '''根据预置的秘密计算一个时间相关的随机数,每分钟变一次,用来发布ROM的时候做验证。'''
     secret = config.AUTOPUB_SECRET
     salt = time.strftime("%Y-%m-%d %H:00",time.localtime(time.time()))
     ptoken = utils.sha256(secret+salt)
     print("hasPrivilege: ptoken is:",ptoken)
     return ptoken
示例#32
0
    def encryptTurnoverCounter(self, receipt, turnoverCounter, key, size):
        iv = utils.sha256(
            receipt.registerId.encode("utf-8") +
            receipt.receiptId.encode("utf-8"))[0:16]

        pt = turnoverCounter.to_bytes(size, byteorder='big', signed=True)

        return utils.aes256ctr(iv, key, pt)
示例#33
0
    def get_queued_tx_hash(self):
        hashes = bytearray()
        if not self.tx_queue:
            hashes = b'\x00' * 32
        else:
            for tx in self.tx_queue:
                hashes.extend(tx.hash())

        return sha256(hashes)
示例#34
0
	def canonical_request(self):
		# body is hashed here TODO
		req = self.method + "\n" + self.path + "\n\n"
		for hk in sorted(self.signed_headers):
			hv = self.header[hk]
			req += hk.lower()+":"+hv+"\n"
		req += "\n" + ";".join(self.signed_headers) + "\n"
		req += utils.sha256(self.body)
		return req
示例#35
0
    def reset_password():

        req = request.get_json()
        utils.check_params(req, 'email')

        # User forgot their password
        if request.args.get('forgot') == 'true':
            user = Users.query.filter_by(email=req['email']).first()
            if user is None:
                raise APIException('This email is not registered', 400)

            send_email('reset_password_link',
                       emails=req['email'],
                       data={
                           'link':
                           utils.jwt_link(user.id, 'users/reset_password/',
                                          req['email'])
                       })
            return jsonify({
                'message':
                'A link has been sent to your email to reset the password'
            }), 200

        # User knows their password
        utils.check_params(req, 'password', 'new_password')

        if req['password'] == req['new_password']:
            raise APIException(
                'Your new password is the same as the old password')
        if len(req['new_password']) < 6:
            raise APIException(
                'Your new password must be at least 6 characters long')

        user = Users.query.filter_by(email=req['email'],
                                     password=utils.sha256(
                                         req['password'])).first()
        if user is None:
            raise APIException('User not found', 404)

        user.password = utils.sha256(req['new_password'])

        db.session.commit()

        return jsonify({'message': 'Your password has been changed'}), 200
示例#36
0
def create_member(sid, name, password, department, level):
    result = conn.insert(
        "member", {
            "sid": sid,
            "name": name,
            "password": sha256(password),
            "department": department,
            "level": level
        })
    return result.inserted_id
示例#37
0
 def login_post(self, username,password):
     '''验证网站管理员登录'''
     user = model.get_user_by_uname(username)
     if (user is None):
         return False
     usr = user["u_name"]
     pwd = user["u_password"]
     j1 = (username == usr)
     j2 = (pwd ==  utils.sha256(password))
     return j1 and j2
示例#38
0
	def canonical_request(self):
		# body is hashed here TODO
		req = self.method + "\n" + self.path + "\n\n"
		for hk in sorted(self.signed_headers):
			hv = self.header[hk]
			req += hk.lower()+":"+hv+"\n"
		req += "\n" + ";".join(self.signed_headers) + "\n"
		if not self.header.get("x-amz-content-sha256"):
			req += utils.sha256(self.body)
		else:
			req += self.header["x-amz-content-sha256"]
		return req
示例#39
0
	def __init__(self,inp):
		# Within Amazon Glacier files use their names and get ID labels.
		# If you want to keep the interface the same it should take
		# either a file name or an ID within Glacier.
		# That's why the input is undefinied at first.

		# As stated here (http://docs.amazonwebservices.com/amazonglacier/
		# latest/dev/working-with-archives.html) archive IDs are 138 bytes long.
		# If there is the coincidence that the file name is 138 bytes long
		# the result will still be interpreted as file if it exists.
		if len(inp) == 138 and not os.path.isfile(inp):
			self.id = inp
		else:
			try:
				self.file = open(inp,"r").read()
				self.path = inp
				self.size = len(self.file)
				self.hash = utils.sha256(self.file)
				self.treehash = self.get_tree_hash()
			except IOError:
				raise IOError("file " + inp + " does not exist.")
示例#40
0
    def __init__(self, inp):
        """
            Creates an archive instance
            
            Archives can either represent a local file instance or
			a remote id. As soon as the archive gets uploaded the 
			instance will transform.
            
			:param inp: local file name or archive id
            :type inp: string

		"""

        # Within Amazon Glacier files use their names and get ID labels.
        # If you want to keep the interface the same it should take
        # either a file name or an ID within Glacier.
        # That's why the input is undefinied at first.

        # As stated here (http://docs.amazonwebservices.com/amazonglacier/
        # latest/dev/working-with-archives.html) archive IDs are 138 bytes long.
        # If there is the coincidence that the file name is 138 bytes long
        # the result will still be interpreted as file if it exists.

        # If you run into trouble opening files on Mac: If you drag and drop
        # files into the editor/terminal the escaped strings wil look like
        # this: "\ ". This doesn't work for Python. Remove each backslash
        # and you will running again.

        if len(inp) == 138 and not os.path.isfile(inp):
            self.id = inp
        else:
            try:
                self.file = open(inp, "r")
                self.path = inp
                self.size = os.fstat(self.file.fileno()).st_size
                self.hash = utils.sha256(self.file)
                self.treehash = self.get_tree_hash()
            except IOError:
                raise IOError("file " + inp + " does not exist.")
示例#41
0
	def string_to_sign(self,canonical_request):	
		return "\n".join(["AWS4-HMAC-SHA256",self.header["x-amz-date"],
		"%(time)s/%(region)s/glacier/aws4_request" % \
		{"time":utils.time("%Y%m%d"),"region": self.region},
		utils.sha256(canonical_request)])
示例#42
0
	def part_hash(self, part):
		"""
            Returns the sha256 hashof the requested part
		"""
		return utils.sha256(self.read_part(part))
示例#43
0
	def get_hash(self):
		if not self._hash:
			self._hash = utils.sha256(self.file)
		return self._hash
示例#44
0
文件: request.py 项目: yhager/glacier
	def string_to_sign(self,canonical_request):	
		return "\n".join(["AWS4-HMAC-SHA256",self.header["x-amz-date"],
		utils.time("%Y%m%d")+"/us-east-1/glacier/aws4_request",
		utils.sha256(canonical_request)])