Exemple #1
0
def validate_password(form, password_field):
    username = form.username.data
    password = password_field.data
    if not username:
        return None

    config.reload()
    if not (config.config.has_section("auth")
            and config.config.has_option("auth", username)
            and config.config.get("auth", username) == hash_pwd(password)):
        raise ValidationError("Wrong username or password")
Exemple #2
0
def transact(sourceWID, srcPwd, targetWID, amount, conn):

    result = "{0}TRANSACTION:{1} | {2:>6} | -> | {3:>6} | {4:8.2f}"\
            .format(utils.colors.BRIGHTCYAN.value,
                    utils.colors.END.value, sourceWID, targetWID, amount)

    c = conn.cursor()
    c.execute('SELECT * FROM wallets WHERE walletID=?', (sourceWID, ))
    sourceWallet = c.fetchone()

    if not sourceWallet:
        raise utils.NotFoundError('Source')

    if utils.hash_pwd(srcPwd) != sourceWallet[2]:
        raise utils.PasswordMismatchError()

    c.execute('SELECT * FROM wallets WHERE walletID=?', (targetWID, ))
    targetWallet = c.fetchone()

    if not targetWallet:
        raise utils.NotFoundError('Target')

    if amount > sourceWallet[3]:
        raise utils.InsufficientFundsError()

    sourceId = sourceWallet[0]
    targetId = targetWallet[0]

    newSourceWalletAmt = sourceWallet[3] - amount
    newTargetWalletAmt = targetWallet[3] + amount

    # Raised in case the final balance exceeds the limit.
    try:
        c.execute('UPDATE wallets SET balance = ? WHERE id = ?', (
            newSourceWalletAmt,
            sourceId,
        ))
        c.execute('UPDATE wallets SET balance = ? WHERE id = ?', (
            newTargetWalletAmt,
            targetId,
        ))
        c.execute('INSERT INTO transactions VALUES(NULL, ?,?,?)', (
            sourceId,
            targetId,
            amount,
        ))
        conn.commit()
    except sqlite3.Error as e:
        raise utils.TransactionError(e.args[0])
Exemple #3
0
    def _setup_config(self):
        self.general__ticket_limit = "3000"
        self.general__min_class_occur = "30"

        self.defaults__schedule = "0 0 * * *"

        self.svm__coefficient = "240.0"
        self.svm__cache_size = "2000"

        self.jira__default_resolutions = "Fixed"
        self.jira__default_statuses = "Resolved,Closed"

        self.auth__admin = hash_pwd("admin")

        self.save()
Exemple #4
0
    def _setup_config(self):
        self.general__ticket_limit = "3000"
        self.general__min_class_occur = "30"

        self.defaults__schedule = "0 0 * * *"

        self.svm__coefficient = "240.0"
        self.svm__cache_size = "2000"

        self.jira__default_resolutions = "Fixed"
        self.jira__default_statuses = "Resolved,Closed"

        self.auth__admin = hash_pwd("admin")

        self.save()
Exemple #5
0
 def register(self):
     data = request_json()
     # recaptcha
     errorMsg = validate_recaptcha(data['recaptcha'])
     if errorMsg:
         return failed(errorMsg)
     #
     schema = {
         'email': rules['email'],
         'first_name': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'last_name': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'password': rules['password'],
         'user_type': {
             'required': True,
             'type': 'string',
             'allowed': ['school', 'student']
         },
     }
     v = make_validator(schema)
     if not v.validate(data):
         return failed('Invalid input', {'error': v.errors})
     if data.get('user_type') != 'student':
         return failed('Invalid user_type')
     user = self.model.objects.filter(email=data['email']).first()
     if user:
         return failed('An account with this email already exists')
     data['password'] = hash_pwd(data['password'])
     try:
         user = store(self.model, data)
         profileData = dict_pluck(data, ['first_name', 'last_name'])
         profileData['user_id'] = user.id
         profile = store(models.student_profile, profileData)
         self.do_send_confirmation_email(user.email, user.id)
     except Exception as e:
         print(e)
         errorMsg = str(e)
     if errorMsg:
         return failed(errorMsg)
     login_user(user)
     return success()
Exemple #6
0
def settings():
    form = ConfigurationForm(obj=config)

    if form.validate_on_submit():
        # auth__admin is special, because it needs to be hashed before being
        # passed to the config and saved
        auth__admin = form.auth__admin.data
        form.auth__admin.data = None
        form.populate_obj(config)
        if auth__admin:
            config.auth__admin = hash_pwd(auth__admin)

        config.save()
        flash("Settings successfully updated")
        return redirect(url_for("settings"))

    # No need to present a hash digest to the user :)
    form.auth__admin.data = None

    return render_template("settings.html", form=form)
Exemple #7
0
def settings():
    form = ConfigurationForm(obj=config)

    if form.validate_on_submit():
        # auth__admin is special, because it needs to be hashed before being
        # passed to the config and saved
        auth__admin = form.auth__admin.data
        form.auth__admin.data = None
        form.populate_obj(config)
        if auth__admin:
            config.auth__admin = hash_pwd(auth__admin)

        config.save()
        flash("Settings successfully updated")
        return redirect(url_for("settings"))

    # No need to present a hash digest to the user :)
    form.auth__admin.data = None

    return render_template("settings.html", form=form)
Exemple #8
0
 def reset_password(self):
     data = request_json()
     # recaptcha
     errorMsg = validate_recaptcha(data['recaptcha'])
     if errorMsg:
         return failed(errorMsg)
     # validate
     schema = {
         'user_id': {
             'required': True,
             'type': 'string'
         },
         'token': {
             'required': True,
             'type': 'string'
         },
         'password': rules['password'],
     }
     v = make_validator(schema)
     if not v.validate(data):
         return failed('Invalid input', {'error': v.errors})
     #
     record = models.reset_password_email.objects.filter(
         token=data['token']).first()
     user = self.model.objects.filter(id=data['user_id']).first()
     if not record or not user or record.email != user.email:
         return failed('Illegal request')
     #
     expired = (datetime.now() - record.updated_at).seconds > 3600 * 1
     if expired:
         return failed('Link expired')
     user.password = hash_pwd(data['password'])
     user.email_confirmed = True
     user.save()
     record.delete()
     return success()
Exemple #9
0
from plugins.seeder import fake, pop
import utils as ut
import models
from plugins.ResourceController import store, update
import random

# student
emails = ['*****@*****.**', '*****@*****.**']
passwords = ['123456', '123456']
for i in range(5):
    data = {
        'email': pop(emails) or fake.email(),
        'password': ut.hash_pwd(pop(passwords) or fake.password()),
        'user_type': 'student',
        'email_confirmed': True,
    }
    user = store(models.user, data)
    data = {
        'user_id': user.id,
        'avatar': fake.img(),
        'first_name': fake.fstname(),
        'middle_name': fake.mdname(),
        'last_name' : fake.lstname(),
        'gender' : fake.gender(),
        'birthday': fake.ts(),
        'nationality' : fake.country_code(),
        'country_of_residence' : fake.country_code(),
        'phone' : fake.phone(),
        'passport_info' : {"number":fake.randstr(),"issued_country":fake.country_code(),"expiry_date":fake.ts()},
        'emergency_contact_persons' : [{"name":fake.name(),"relationship":"father","tel":fake.phone()},{"name":None,"relationship":None,"tel":None}],
    }
Exemple #10
0
    },
    {
        'w_id': 'w4',
        'pwd': 'pwd4',
        'balance': 190.0
    },
]

limit = 200
walletTableSql = f'''CREATE TABLE wallets(id INTEGER PRIMARY KEY AUTOINCREMENT,
                    walletID TEXT UNIQUE, passwordHash TEXT, balance REAL
                    CHECK(balance >= 0 and balance <={limit}))'''

conn = sqlite3.connect('ewallet.db')
c = conn.cursor()
c.execute(walletTableSql)

c.execute('''
    CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT,
    sourceWID INTEGER, targetWID INTEGER, amount REAL,
    FOREIGN KEY(sourceWID) REFERENCES wallets(id),
    FOREIGN KEY(targetWID) REFERENCES wallets(id))''')

for wallet in wallet_spec:
    pwdHash = utils.hash_pwd(wallet['pwd'])
    wallet_data = (wallet['w_id'], pwdHash, wallet['balance'])
    c.execute("INSERT INTO wallets VALUES(NULL, ?, ?, ?)", wallet_data)

conn.commit()
conn.close()
Exemple #11
0
 def register(self):
     data = request_json()
     # recaptcha
     errorMsg = validate_recaptcha(data['recaptcha'])
     if errorMsg:
         return failed(errorMsg)
     #
     schema = {
         'name': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'address': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'city': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'country': {
             'required': True,
             'type': 'string',
             'maxlength': 255
         },
         'email': rules['email'],
         'introduction': {
             'required': True,
             'type': 'string',
             'maxlength': 1000
         },
         'website': {
             'required': True,
             'type': 'string',
             'maxlength': 1000
         },
         'contact_persons': {
             'required': True,
             'maxlength': 1000
         },
         'registration_document': {
             'required': True,
             'maxlength': 1000
         },
     }
     v = make_validator(schema)
     if not v.validate(data):
         return failed('Invalid input', {'error': v.errors})
     try:
         t = data['contact_persons']
         keys = ['last_name', 'first_name', 'title', 'email', 'tel']
         if not keys_match(t[0], keys) or not keys_match(t[1], keys):
             return failed('Invalid input')
         for k, v in t[0].items():
             if not v:
                 return failed('The %s is required.' %
                               (k.replace('_', ' ')))
     except Exception as e:
         app.logger.debug(e)
         return failed('Invalid input')
     #
     user = self.model.objects.filter(email=data['email']).first()
     if user:
         return failed('An account with this email already exists')
     userData = {
         'email': data['email'],
         'password': hash_pwd(str_rand(16)),
         'user_type': 'school',
     }
     try:
         user = store(self.model, userData)
         data['user_id'] = user.id
         data['status'] = 'pending'
         profile = store(models.school_profile, data)
     except Exception as e:
         app.logger.debug(e)
         return failed(str(e))
     return success()