示例#1
0
async def post(request):
    # print(await request.text())
    req = (await request.post()) or (await request.json())
    code = req.get('code')
    output_format = req.get('format').lower()
    client_name = req.get('client_name', 'unnamed')
    density = req.get('density', 200)
    quality = req.get('quality', 85)
    if False \
            or not isinstance(code, str) \
            or not isinstance(output_format, str) \
            or not isinstance(density, int) \
            or not isinstance(quality, int) \
            or not (1 <= density <= 2000) \
            or not (1 <= quality <= 100):
        raise aiohttp.web.json_response({'error': 'bad input formats'})
    if output_format not in ('pdf', 'png', 'jpg'):
        return aiohttp.web.json_response({'error': 'invalid output format'})
    job_id = random_string(64)
    logs.info('Job {} started'.format(job_id))
    reply = await jobs.render_latex(job_id, output_format, code, density,
                                    quality)
    if reply['status'] == 'success':
        reply['filename'] = job_id + '.' + output_format
        logs.info('Job success : {}'.format(job_id))
        stats.track_event('api2', 'success', client=client_name)
    else:
        logs.info('Job failed : {}'.format(job_id))
        stats.track_event('api2', 'failure', client=client_name)
    return aiohttp.web.json_response(reply)
示例#2
0
文件: ed.py 项目: tampakrap/edpwd
def encrypt(key, password):
    """
    Encrypt the password in Blowfish encryption
    The password is saved in the form: ${NUMBER}${PASSWORD}${GARBAGE}
    ${LENGTH} is the length of the password, used from the decrypt()
    function to separate it from the garbage.
    If the password is multiple of 8, then no ${GARBAGE} is appended
    """
    if not key or type(key) != str:
        raise Exception("Please provide a valid secret key")
    if not password or type(password) != str:
        raise Exception("Please provide a valid password")
    obj = Blowfish.new(key)
    length = str(len(password))
    if len(password) <= 9:
        # In case the length of the password is less than 10, then
        # add a zero in the front (eg 06), so we can produce a hash that
        # is always a multiple of 8
        length = '0' + length
    new_password = length + password
    if len(new_password) % 8 != 0:
        # Append random strings to satisfy Blowfish
        new_password += random_string(-len(new_password) % 8)
    hash_password = base64.b64encode(obj.encrypt(new_password))
    return hash_password
示例#3
0
文件: ed.py 项目: mgorny/edpwd
def encrypt(key, password):
    """
    Encrypt the password in Blowfish encryption
    The password is saved in the form: ${NUMBER}${PASSWORD}${GARBAGE}
    ${LENGTH} is the length of the password, used from the decrypt()
    function to separate it from the garbage.
    If the password is multiple of 8, then no ${GARBAGE} is appended
    """
    if not key or type(key) != str:
        raise Exception("Please provide a valid secret key")
    if not password or type(password) != str:
        raise Exception("Please provide a valid password")
    obj = Blowfish.new(key)
    length = str(len(password))
    if len(password) <= 9:
        # In case the length of the password is less than 10, then
        # add a zero in the front (eg 06), so we can produce a hash that
        # is always a multiple of 8
        length = '0' + length
    new_password = length + password
    if len(new_password) % 8 != 0:
        # Append random strings to satisfy Blowfish
        new_password += random_string(-len(new_password) % 8)
    hash_password = base64.b64encode(obj.encrypt(new_password))
    return hash_password
示例#4
0
def authenticate_email(email, password):
    try:
        password = hashlib.sha512(str(password).encode("utf-8")).hexdigest()
        sql = f"SELECT users.userID, users.email, users.fullName, users.token, users.domain, users.rollNo, users.department, users.bloodType, users.phone, users.emergencyContact, users.emergencyContactName, users.emergencyContactRelation, users.lastSignInTimeStamp, users.signUpTimeStamp, domains.organizationName, domains.email, domains.phone, domains.address FROM users, domains WHERE users.domain = domains.domain AND users.email = '{email}' AND users.password = '******'"
        cnx = mysql.connect()
        cursor = cnx.cursor()
        cursor.execute(sql)
        for row in cursor:
            cursor.close()
            token = random_string(100)
            sql = f"UPDATE users set token = '{token}' WHERE email = '{email}'"
            cursor = cnx.cursor()
            cursor.execute(sql)
            cnx.commit()
            cnx.close()

            if cursor.rowcount == 1:
                row["token"] = token
                return row
            else:
                return False
        return False
    except Exception as e:
        print(e)
        return False
示例#5
0
def POST_endpoint_function():
    try:
        uid = request.form['uid']
        password = request.form['password']
        pager_id = request.form['pager_id']
        name = request.form['name']
        designation = request.form['designation']
        organization = request.form['organization']
        picture = request.form['picture']

        if uid and password and pager_id and name and designation and organization and picture and request.method == 'POST':
            # Generate 28 char API key
            api_key = random_string(28)

            # Hash password to SHA512
            password = hashlib.sha512(password)

            # TODO: Save picture and return picture_url
            picture_url = 'https://vmlinuz.pattarai.in/images/logo_large.png'

            # TODO: Dynamically create bot and get bot_id
            pager_api_key = '1671540030:AAEAMUBDjfS4-w4_DSkct0HQmb23lozGyxo'

            # insert record in database
            try:
                cnx = mysql.connect()
                sql = f"INSERT INTO `nxtstep`.`users` (`uid`, `password`, `api_key`, `pager_id`, `pager_api_key`, `name`, `designation`, `organization`, `picture_url`) VALUES ('{uid}', '{password}', '{api_key}', '{pager_id}', '{pager_api_key}', '{name}', '{designation}', '{organization}', '{picture_url}')"
                cursor = cnx.cursor()
                cursor.execute(sql)
                cursor.close()
                cnx.commit()
                cnx.close()
                json_dict = {"status": "success"}
                res = jsonify(json_dict)
                res.status_code = 200
                return res
            except Exception as e:
                return internal_server_error()
        else:
            return forbidden()

    except Exception as e:
        print(e)
        return internal_server_error()
示例#6
0
文件: tests.py 项目: mgorny/edpwd
 def test_random_string(self):
     self.assertRegexpMatches(random_string(40), '^[a-zA-Z0-9]{40}$')
示例#7
0
from random_string import random_string
from datetime import date
import os
from random_sum import random_sum

a = random_string()

print('Задача 5_1')
print(a[8:])
print(a[:len(a) // 2 - 2] + a[len(a) // 2 + 2:])
print(a[:-5])

print('\nЗадача 5_2')
print(a[-1::-1])

print('\nЗадача 5_3')
print(a[::2])

print('\nЗадача 5_4')
print(a[::2] + a[1::2])

print('\nЗадача 5_5')
today = str(date.today()).replace('-', '/')
print(today[-2:len(today)] + today[4:-2] + today[:4])

print('\nЗадача 5_6')
for path in os.path.abspath(__file__).split('\\'):
    print(path)

print('\nЗадача 5_7')
string_num = random_sum()
示例#8
0
 def test_random_string(self):
     self.assertRegexpMatches(random_string(40), '^[a-zA-Z0-9]{40}$')