예제 #1
0
    def setPassword(person_id, password):
        # TODO: verify user has access to update password...
        if password is not None:
            if is_number(person_id):
                find_str = "ID(p)={person_id}"
            else:
                find_str = "p.password_reset_key = {person_id}"

            db_password_hash = ''
            # check if password matches person_id
            result = db.run("MATCH (p:Person) WHERE " + find_str + " RETURN p.password AS password",
                            {"person_id": person_id})
            for p in result:
                db_password_hash = p['password']

            if db_password_hash != '':
                # hash new password and update DB
                new_pass_hash = sha256_crypt.hash(password)

                if db_password_hash == new_pass_hash:
                    return True

                result = db.run("MATCH (p:Person) WHERE " + find_str + " SET p.password = {new_pass_hash}, p.password_reset_key = '' RETURN p",
                                {"person_id": person_id, "new_pass_hash": new_pass_hash})

                # Check we updated something
                summary = result.consume()
                if summary.counters.properties_set >= 1:
                    return True
                return False

            else:
                raise FindError("No user found")

        else:
            raise AuthError("Password is empty")
예제 #2
0
 def encode_api_key(self):
     self.api_key = sha256_crypt.hash(self.username + str(datetime.utcnow))
예제 #3
0
#!/usr/bin/python3
import sys

from passlib.hash import sha256_crypt

password = sys.argv[1]
password_hash = sha256_crypt.hash(password)
print("password = "******"password hash = " + password_hash)
예제 #4
0
    query_result = db.Column(db.Text, nullable=True)
    time = db.Column(db.DateTime, nullable=False)
    user = db.relationship(User)


@login_manager.user_loader
def load_user(id):
    existing_user = User.query.filter_by(uname=id).first()
    return existing_user


with app.app_context():
    db.init_app(app)
    db.create_all()
    if not load_user('admin'):
        adminUser = User('admin', sha256_crypt.hash('Administrator@1'),
                         '12345678901')
        adminUser.isAdmin = True
        db.session.add(adminUser)
        db.session.commit()


class UserForm(FlaskForm):
    uname = StringField('User Name:', validators=[DataRequired()])
    pword = StringField('Password: '******'2FA Token:', validators=[], id='2fa')


def addUser(uname, pword, twofa):
    user = User(uname, sha256_crypt.hash(pword), twofa)
    user.isAdmin = False
예제 #5
0
 def hash_password(self, password):
     self.password = sha256_crypt.hash(password)
예제 #6
0
파일: app.py 프로젝트: lee00670/ACCM7
def profile():
    # Check if user is loggedin
    if 'loggedin' in session:

        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        category = session['category']
        if (category == 'professor'):
            cursor.execute(
                'select distinct id, fname, lname, email, pw, name from professor inner join teach using(profid) inner join coursemap using(mapid) inner join program using(pid) where id=%s and pw=%s',
                ([session['id']], [session['pw']]))
        elif (category == 'coordinator'):
            cursor.execute(
                'SELECT * FROM coordinator inner join program using(pid) WHERE id = %s AND pw = %s',
                ([session['id']], [session['pw']]))
        elif (category == 'secretary'):
            cursor.execute(
                'select id, fname, lname, pw, email, name from secretary inner join program_secretary using (secid) inner join program using(pid) where id=%s and pw=%s',
                ([session['id']], [session['pw']]))
        elif (category == 'student'):
            cursor.execute(
                'select student_num as id, fname, lname, pw, email, name from student inner join enrollment using (sid) inner join  program using (pid) where student_num=%s and pw=%s',
                ([session['id']], [session['pw']]))

        account = cursor.fetchone()

        if request.method == 'POST' and 'password' in request.form:

            #if password is right, show the profile info
            if (sha256_crypt.verify(request.form['password'], session['pw'])):
                return render_template('profile.html',
                                       account=account,
                                       category=session['category'],
                                       msg="s")
            else:
                return render_template('profile.html',
                                       account=account,
                                       category=session['category'],
                                       msg="The password is wrong.")

        # if user requests to change password
        elif request.method == 'POST' and 'newPassword' in request.form and 'newPassword2' in request.form:
            if (request.form['newPassword'] == request.form['newPassword2']):
                try:
                    category = session['category']

                    #make hash using new password user inputs
                    pw = sha256_crypt.hash(request.form['newPassword'])

                    #update password
                    if (category == 'professor'):
                        cursor.execute(
                            'update professor set pw = %s WHERE id = %s',
                            (pw, [session['id']]))
                    elif (category == 'coordinator'):
                        cursor.execute(
                            ' update coordinator set pw = %s where id= %s',
                            (pw, [session['id']]))
                    elif (category == 'secretary'):
                        cursor.execute(
                            'update secretary set pw = %s WHERE id = %s',
                            (pw, [session['id']]))
                    elif (category == 'student'):
                        cursor.execute(
                            'update student set pw = %s WHERE student_num = %s',
                            (pw, [session['id']]))
                    mysql.connection.commit()
                    cursor.close()
                    #save new hash to session
                    session['pw'] = pw
                    return render_template('profile.html',
                                           account=account,
                                           category=session['category'],
                                           msg="New password is updated.")
                except (MySQLdb.Error, MySQLdb.Warning) as e:
                    print(e)
                    cursor.close()
                    return render_template('profile.html',
                                           account=account,
                                           category=session['category'],
                                           msg="New password is not changed.")
            else:
                cursor.close()
                return render_template('profile.html',
                                       account=account,
                                       category=session['category'],
                                       msg="New password is not changed.")
        cursor.close()
        return render_template('profile.html',
                               account=account,
                               category=session['category'])
    # User is not loggedin redirect to login page
    return redirect(url_for('login'))
예제 #7
0
def hash_password(password):
    return sha256_crypt.hash(password)
예제 #8
0
def newprofile():
	adminflag=False
	pnameok=False
	while pnameok==False:	
		threadqueues.secureoutput.put("please enter profile name")
		pname=wait_for_secure_input()
		print(9)
		fstring="/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/"+pname+".txt"
		try:
			f = open(fstring,"r")
			f.close()
			return("PROFILE NAME ALREADY IN USE. PLEASE TRY AGAIN.")
		except FileNotFoundError:
			pnameok=True
	pscheckexit=0
	print("here")
	while(pscheckexit==0):
		threadqueues.secureoutput.put("PROFILE NAME: "+pname+". Please enter profile password")
		print(455)
		pps=wait_for_secure_input()
		print("here2")
		threadqueues.secureoutput.put("please confirm password")
		ppscheck=wait_for_secure_input()
		print("j")
		if(ppscheck==pps):
			pscheckexit=1
		else:
			threadqueues.secureoutput.put("ERROR. PASSWORDS DON'T MATCH. PLEASE TRY AGAIN.")
	threadqueues.secureoutput.put("Do you wish this to be an admistrative account? Y/N")
	if(wait_for_secure_input())=="Y":
		exit=1
		while(exit==1):
			threadqueues.secureoutput.put("PLEASE INPUT MASTER PASSWORD NOW")
			mspscheck=wait_for_secure_input()
			if(passwordcheck(mspscheck,"masteradmin")==True):
				threadqueues.secureoutput.put("MASTER PASSWORD ACCEPTED.")
				adminflag=True
				exit=0
			else:
				threadqueues.secureoutput.put("incorrect password please try again (Y) or make ordinary profile instead (N).")
				rexit=1
				while(rexit==1):
					response=wait_for_secure_input()
					if(response=="Y"):rexit=0
					if(response=="N"):
						rexit=0
						exit=0
					else:threadqueues.secureoutput.put("invalid input. please input Y/N.")
	print(1234)
	threadqueues.secureoutput.put("please enter default location (this can be changed later)")
	loc=wait_for_secure_input()
	storedpassword=sha256_crypt.hash(pps)
	passwordfile = open("/media/sf_share/samaritan-VA/current_code/front_end/backend/security/keymanagement/pswds.txt", "a")
	passwordfile.write("\n"+pname+":"+storedpassword)
	passwordfile.close()
	profilelistfile=open("/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/profilelist.txt","a")
	if adminflag==True:privs="1011010"
	if adminflag==False:privs="0000000"
	profilelistfile.write("\n"+pname+":"+privs)
	fstring="/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/"+pname+".txt"
	f=open(fstring,"wb")
	profilestringlist=[pname,privs,loc]
	profilestring=""
	for i in profilestringlist:
		profilestring+=(":"+i)
	salt=get_random_bytes(32)
	filekey= PBKDF2(pps, salt, dkLen=32)
	data = bytes(profilestring,"utf-8")
	cipher = AES.new(filekey, AES.MODE_CBC) # Create a AES cipher object with the key using the mode CBC
	ciphered_data = cipher.encrypt(pad(data, AES.block_size)) # Pad the input data and then encrypt
	f.write(salt)
	f.write(cipher.iv)
	f.write(ciphered_data)
	f.close()
	print("profile created")
	return "nptest"
예제 #9
0
import csv
import sys
from passlib.hash import sha256_crypt
import os

users = [
    {
        'username': '',
        'password': ''
    },
]

do_header = False
if not os.path.isfile('users.csv'):
    do_header = True

with open('users.csv', 'a') as csvfile:
    fieldnames = ['username', 'password']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    # Add header the first time the file is created
    if do_header:
        writer.writeheader()

    for u in users:
        # Generate new salt, hash password
        password_hash = sha256_crypt.hash(u['password'])

        writer.writerow({'username': u['username'], 'password': password_hash})
예제 #10
0
파일: hash.py 프로젝트: daffamiftahul/Hash
def enc():
    awal()
    putih = "\033[97m"
    dfv = raw_input(W + "[" + B + "+" + W + "] Your Text     " + B + ": " + G)
    asw = raw_input(W + "[" + B + "+" + W + "] Your Password " + B + ": " + G)
    print W + "\n* Generate Hash . . . . Please Wait !!!"
    time.sleep(1)
    print(W + '  ------------------------------------------------')
    #md5
    daf1 = hashlib.md5(dfv.encode("utf -8")).hexdigest()
    print W + "[" + B + "+" + W + "] Md5    " + B + ":" + W, daf1
    time.sleep(0.1)
    #sha256
    daf2 = hashlib.sha256(dfv.encode()).hexdigest()
    print W + "[" + B + "+" + W + "] Sha256 " + B + ":" + W, daf2
    time.sleep(0.1)
    #sha224
    daf4 = hashlib.sha224(dfv.encode()).hexdigest()
    print W + "[" + B + "+" + W + "] Sha224 " + B + ":" + W, daf4
    time.sleep(0.1)
    #sha512
    daf5 = hashlib.sha512(dfv.encode()).hexdigest()
    print W + "[" + B + "+" + W + "] Sha512 " + B + ":" + W, daf5
    time.sleep(0.1)
    #sha384
    daf6 = hashlib.sha384(dfv.encode()).hexdigest()
    print W + "[" + B + "+" + W + "] Sha384 " + B + ":" + W, daf6
    time.sleep(0.1)
    #sha1
    daf11 = hashlib.sha1(dfv.encode()).hexdigest()
    print W + "[" + B + "+" + W + "] Sha1   " + B + ":" + W, daf11
    time.sleep(0.1)
    #pbkdf2_sha1
    daf12 = pbkdf2_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Pbkdf2_sha1   " + B + ":" + W, daf12
    time.sleep(0.1)
    #pbkdf2_sha256
    daf13 = pbkdf2_sha256.hash(dfv)
    print W + "[" + B + "+" + W + "] Pbkdf2_sha256 " + B + ":" + W, daf13
    time.sleep(0.1)
    #pbkdf2_sha512
    daf14 = pbkdf2_sha512.hash(dfv)
    print W + "[" + B + "+" + W + "] Pbkdf2_sha512 " + B + ":" + W, daf14
    time.sleep(0.1)
    #sha256_crypt
    daf15 = sha256_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Sha256_crypt  " + B + ":" + W, daf15
    time.sleep(0.1)
    #sha512_crypt
    daf16 = sha512_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Sha512_crypt  " + B + ":" + W, daf16
    time.sleep(0.1)
    #md5_crypt
    daf17 = md5_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Md5_crypt  " + B + ":" + W, daf17
    time.sleep(0.1)
    #sha1_crypt
    daf18 = sha1_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Sha_crypt  " + B + ":" + W, daf18
    time.sleep(0.1)
    #sha1_crypt
    daf18 = sha1_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Sha_crypt  " + B + ":" + W, daf18
    time.sleep(0.1)
    #sun_md5_crypt
    daf19 = sun_md5_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Sun_md5_crypt " + B + ":" + W, daf19
    time.sleep(0)
    #des_crypt
    daf20 = des_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Des_crypt  " + B + ":" + W, daf20
    time.sleep(0.1)
    #bsdi_crypt
    daf21 = bsdi_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Bsdi_crypt " + B + ":" + W, daf21
    time.sleep(0.1)
    #bigcrypt
    daf22 = bigcrypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Bigcrypt   " + B + ":" + W, daf22
    time.sleep(0.1)
    #crypt16
    daf23 = crypt16.hash(dfv)
    print W + "[" + B + "+" + W + "] Crypt16 " + B + ":" + W, daf23
    time.sleep(0.1)
    #phpass
    daf24 = phpass.hash(dfv)
    print W + "[" + B + "+" + W + "] Phpass  " + B + ":" + W, daf24
    time.sleep(0.1)
    #scram
    daf25 = scram.hash(dfv)
    print W + "[" + B + "+" + W + "] Scram   " + B + ":" + W, daf25
    time.sleep(0.1)
    #apr_md5_crypt
    daf27 = apr_md5_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Apr_Md5_Crypt    " + B + ":" + W, daf27
    time.sleep(0.1)
    #cta_pbkdf2
    daf28 = cta_pbkdf2_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Cta_pbkdf2_sha1  " + B + ":" + W, daf28
    time.sleep(0.1)
    #dlitz_pbdf2_sha1
    daf29 = dlitz_pbkdf2_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Dlitz_pbkdf_sha1 " + B + ":" + W, daf29
    time.sleep(0.1)
    #ldap_md5_crypt
    daf30 = ldap_md5_crypt.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_Md5_Crypt   " + B + ":" + W, daf30
    time.sleep(0.1)
    #ldap_hex_md5
    daf31 = ldap_hex_md5.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_Hex_Md5   " + B + ":" + W, daf31
    time.sleep(0.1)
    #ldao_hex_sha1
    daf32 = ldap_hex_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_Hex_Sha1  " + B + ":" + W, daf32
    time.sleep(0.1)
    #ldap_pbkdf2_sha1
    daf33 = ldap_pbkdf2_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_pbkdf2_sha1  " + B + ":" + W, daf33
    time.sleep(0.1)
    #ldap_pbkdf2_sha256
    daf34 = ldap_pbkdf2_sha256.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_pbkdf2_sha256  " + B + ":" + W, daf34
    time.sleep(0.1)
    #ldap_pbkdf2_sha512
    daf35 = ldap_pbkdf2_sha512.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_pbdf2_sha512   " + B + ":" + W, daf35
    time.sleep(0.1)
    #atlassian_pbkdf2_sha1
    daf36 = atlassian_pbkdf2_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Atlassian_pbkdf2_sha1  " + B + ":" + W, daf36
    time.sleep(0.1)
    #fshp
    daf37 = fshp.hash(dfv)
    print W + "[" + B + "+" + W + "] Fshp  " + B + ":" + W, daf37
    time.sleep(0.1)
    #mysql323
    daf38 = mysql323.hash(dfv)
    print W + "[" + B + "+" + W + "] Mysql323 " + B + ":" + W, daf38
    time.sleep(0.1)
    #mysql41
    daf39 = mysql41.hash(dfv)
    print W + "[" + B + "+" + W + "] Mysql41  " + B + ":" + W, daf39
    time.sleep(0.1)
    #postgres_md5
    daf40 = postgres_md5.hash(dfv, user=asw)
    print W + "[" + B + "+" + W + "] Postgres_md5 " + B + ":" + W, daf40
    time.sleep(0.1)
    #oracle10
    daf41 = oracle10.hash(dfv, user=asw)
    print W + "[" + B + "+" + W + "] Oracle10 " + B + ":" + W, daf41
    time.sleep(0.1)
    #oracle11
    daf42 = oracle11.hash(dfv)
    print W + "[" + B + "+" + W + "] Oracle11 " + B + ":" + W, daf42
    time.sleep(0.1)
    #lmhash
    daf43 = lmhash.hash(dfv)
    print W + "[" + B + "+" + W + "] Lmhash  " + B + ":" + W, daf43
    time.sleep(0.1)
    #nthash
    daf44 = nthash.hash(dfv)
    print W + "[" + B + "+" + W + "] Nthash  " + B + ":" + W, daf44
    time.sleep(0.1)
    #msdcc
    daf45 = msdcc.hash(dfv, user=asw)
    print W + "[" + B + "+" + W + "] Msdcc   " + B + ":" + W, daf45
    time.sleep(0.1)
    #msdcc2
    daf46 = msdcc2.hash(dfv, user=asw)
    print W + "[" + B + "+" + W + "] Msdcc2  " + B + ":" + W, daf46
    time.sleep(0.1)
    #cisco_type7
    daf47 = cisco_type7.hash(dfv)
    print W + "[" + B + "+" + W + "] Cisco_type7  " + B + ":" + W, daf47
    time.sleep(0.1)
    #grub_pbkdf2_sha512
    daf48 = grub_pbkdf2_sha512.hash(dfv)
    print W + "[" + B + "+" + W + "] Grub_pbkdf2_sha512  " + B + ":" + W, daf48
    time.sleep(0.1)
    #hex_sha1
    daf49 = hex_sha1.hash(dfv)
    print W + "[" + B + "+" + W + "] Hex_Sha1   " + B + ":" + W, daf49
    time.sleep(0.1)
    #pwd
    daf50 = pwd.genword()
    print W + "[" + B + "+" + W + "] Pwd  " + B + ":" + W, daf50
    time.sleep(0.1)
    #mssql2005
    daf51 = cuk.hash(dfv)
    print W + "[" + B + "+" + W + "] Mssql2005  " + B + ":" + W, daf51
    time.sleep(0.1)
    #Mssql2000
    daf52 = cak.hash(dfv)
    print W + "[" + B + "+" + W + "] Mssql2000  " + B + ":" + W, daf52
    time.sleep(0.1)
    #ldap_salted_md5
    daf52 = cik.hash(dfv)
    print W + "[" + B + "+" + W + "] Ldap_salted_md5  " + B + ":" + W, daf52
    time.sleep(0.1)
예제 #11
0
def prepare_the(meat):
    meat = sha256_crypt.hash(meat)
    return meat
예제 #12
0
#Concaténation de l'adresse
df['adresse'] = df['adresse_rue'] + ', ' + df['ville'] + ' ' + df['code_postal']
df.drop(['adresse_rue', 'ville', 'code_postal'], axis=1, inplace=True)

# Création des adresses courriels à partir des nom et prénom des clients
df = df.assign(courriel=df['prenom'] + '.' + df['nom'])
df['courriel'] = df['courriel'].apply(lambda x: uni.unidecode(x.lower(
)) + '@gmail.com')  #création du courriel sans accents et en minuscule

#Création de la colonne mdp

#Peuplement de la table Client
peupler(df, 'Client')

df_u = df[['courriel']].copy()
df_u = df_u.assign(mdp=[sha256_crypt.hash(gen_MP()) for x in range(len(df_u))])
peupler(df_u, 'Utilisateur')
"""
Création et peuplement de la table Artiste
"""
# création du dataframe Artiste
df_a = df[['courriel']].iloc[0:100].copy()
df_a = df_a.assign(
    nom=df['prenom'].apply(lambda x: x[0:3]) +
    df['nom'].apply(lambda x: x[0:3])
)  #nomArtiste : concat des 3 premières lettres du prenom et nom
df_a['nom'] = df_a['nom'].apply(lambda x: x.lower())

#Peuplement de la table
peupler(df_a, 'Artiste')
"""
#         'nonce': nonce,
#     })
#     singed_trn = web3.eth.account.sign_transaction(trxn, private_key=key)
#     web3.eth.sendRawTransaction(singed_trn.rawTransaction)

doc_privatekeys = [
    '936b9a4a782b66182e48d7d61ae36942847f06dbc04e9ff39ed6b99b1afeffc7',
    '28903f4c7b0ad2f22790de3b035c2f8700f815597bf55f490e538e19fb5eea38',
    '3c055897e9045855e8a4e9631913504beedf445bc67116c79971dd203326507b'
]
doc_names = ['Abdul', 'Ubaid', 'Saad']

for i, key in enumerate(doc_privatekeys):
    password = '******'
    account = web3.eth.account.encrypt(key, password)
    password = sha256_crypt.hash(password)
    pub_key = web3.toChecksumAddress(account['address'])
    User(name=pat_names[i],
         email=f'doc{i}@doc.com',
         password=password,
         data=account,
         publickey=pub_key,
         type='doctor').save()
    nonce = web3.eth.getTransactionCount(pub_key)
    trxn = HealthContract.functions.addDoctor(
        pat_names[i], 'aadhar_number').buildTransaction({
            'chainId':
            chain_id,
            'gas':
            700000,
            'gasPrice':
예제 #14
0
파일: models.py 프로젝트: gtamba/flask-vote
 def __init__(self, email, password, is_privileged=False):
     self.email = email
     self.password = sha256_crypt.hash(password)
     self.is_privileged = is_privileged
예제 #15
0
    query_result = db.Column(db.Text, nullable=True)
    time = db.Column(db.DateTime, nullable=False)
    user = db.relationship(User)


@login_manager.user_loader
def load_user(id):
    existing_user = User.query.filter_by(uname=id).first()
    return existing_user


with app.app_context():
    db.init_app(app)
    db.create_all()
    if not load_user('admin'):
        adminUser = User('admin', sha256_crypt.hash(admin_password), admin_2fa)
        adminUser.isAdmin = True
        db.session.add(adminUser)
        db.session.commit()


class UserForm(FlaskForm):
    uname = StringField('User Name:', validators=[DataRequired()])
    pword = StringField('Password: '******'2FA Token:', validators=[], id='2fa')


def addUser(uname, pword, twofa):
    user = User(uname, sha256_crypt.hash(pword), twofa)
    user.isAdmin = False
    db.session.add(user)
def edit_users_page(id):
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        password = sha256_crypt.hash(request.form.get('password'))
        status = request.form.get('status')
        orgid = request.form.get('orgid')
        lastlogin = time
        createddate = time
        if id == '0':
            postvalidate = Users.query.filter_by(email=email).first()
            if (postvalidate == None):
                post = Users(name=name,
                             email=email,
                             password=password,
                             status=status,
                             orgid=orgid,
                             lastlogin=lastlogin,
                             createddate=createddate)
                db.session.add(post)
                db.session.commit()
                subject = "Welcome aboard " + name + "!"
                content1 = '''<!DOCTYPE html><html lang="en" ><head><meta charset="UTF-8"><title>Register CGV</title></head><body><table cellspacing="0" cellpadding="0" border="0" style="color:#333;background:#fff;padding:0;margin:0;width:100%;font:15px/1.25em 'Helvetica Neue',Arial,Helvetica"><tbody><tr width="100%"><td valign="top" align="left" style="background:#eef0f1;font:15px/1.25em 'Helvetica Neue',Arial,Helvetica"><table style="border:none;padding:0 18px;margin:50px auto;width:500px"><tbody><tr width="100%" height="60"><td valign="top" align="left" style="border-top-left-radius:4px;border-top-right-radius:4px;background: white; padding:10px 18px;text-align:center"> <img height="75" width="75" src="https://cdn.discordapp.com/attachments/708550144827719811/792008916451328010/android-chrome-512x512.png" title="CGV" style="font-weight:bold;font-size:18px;color:#fff;vertical-align:top" class="CToWUd"></td></tr><tr width="100%"><td valign="top" align="left" style="background:#fff;padding:18px"><h1 style="font-size:20px;margin:16px 0;color:#333;text-align:center">India’s Largest Online Verification Network</h1><p style="font:15px/1.25em 'Helvetica Neue',Arial,Helvetica;color:#333;text-align:center">Hey, ''' + str(
                    name
                ) + '''</p><div style="background:#f6f7f8;border-radius:3px"> <br><p style="font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;">Now contact your organization head for your account activation. Once activated click on link below to login.</p><p style="font:15px/1.25em 'Helvetica Neue',Arial,Helvetica;margin-bottom:0;text-align:center"> <a href="'''
                content2 = json[
                    "site_url"] + '''/login" style="border-radius:3px;background:#3aa54c;color:#fff;display:block;font-weight:700;font-size:16px;line-height:1.25em;margin:24px auto 6px;padding:10px 18px;text-decoration:none;width:180px" target="_blank">Login Now!</a></p> <br><br></div><p style="font:14px/1.25em 'Helvetica Neue',Arial,Helvetica;color:#333"> <strong>What's CGV?</strong> We generate and verify certificates online which also includes a backend dashboard. Click to know more. <a href="https://cgvcertify.herokuapp.com" style="color:#306f9c;text-decoration:none;font-weight:bold" target="_blank">Learn more »</a></p></td></tr></tbody></table></td></tr></tbody></table></body></html>'''
                content = content1 + content2
                message = Mail(from_email=('*****@*****.**',
                                           'Register Bot CGV'),
                               to_emails=email,
                               subject=subject,
                               html_content=content)
                try:
                    sg = SendGridAPIClient(json['sendgridapi'])
                    response = sg.send(message)
                except Exception as e:
                    print("Error!")
                    flash("Error while sending mail!", "danger")
                flash("User added successfully!", "success")
            else:
                flash("User exist!", "danger")
        else:
            post = Users.query.filter_by(id=id).first()
            if (post.email == json['admin_email']):
                flash("You can't edit admin user details!", "danger")
                return redirect('/view/users')
            else:
                post.name = name
                post.email = email
                post.password = password
                post.status = status
                post.orgid = orgid
                post.lasylogin = time
                db.session.commit()
                flash("User edited successfully!", "success")
                return redirect('/edit/users/' + id)
    posto = Organization.query.filter_by().all()
    post = Users.query.filter_by(id=id).first()
    return render_template('add_edit_users.html',
                           json=json,
                           id=id,
                           post=post,
                           posto=posto,
                           c_user_name=current_user.name)
예제 #17
0
 def from_plaintext(cls, plaintext):
     password = cls()
     password.cyphertext = sha256_crypt.hash(plaintext, rounds=HASH_ROUNDS)
     return password
 def set_password(self, password):
     self.password_hash = sha256_crypt.hash(password)
예제 #19
0
 def _make_password_hash(raw_password: str) -> str:
     return sha256_crypt.hash(raw_password)
예제 #20
0
 def encode_password(self, password):
     self.password = sha256_crypt.hash(password)
     return self.password
예제 #21
0
from passlib.hash import md5_crypt, sha1_crypt, sha256_crypt, sha512_crypt, des_crypt

var = "Hello"

salt = "ZDzPE45C"
desSalt = "e4"

md5 = md5_crypt.hash(var, salt=salt)
sha1 = sha1_crypt.hash(var, salt=salt)
sha256 = sha256_crypt.hash(var, salt=salt)
sha512 = sha512_crypt.hash(var, salt=salt)
des = des_crypt.hash(var, salt=desSalt)

print("MD5 Hash of {}: {}...    Length = {}".format(var, md5[12:18], len(md5)))
print("SHA1 Hash of {}: {}...    Length = {}".format(var, sha1[13:19],
                                                     len(sha1)))
print("SHA256 Hash of {}: {}...    Length = {}".format(var, sha256[26:32],
                                                       len(sha256)))
print("SHA512 Hash of {}: {}...    Length = {}".format(var, sha512[26:32],
                                                       len(sha512)))
print("Des hash of {}: {}...    Length = {}".format(var, des, len(des)))
예제 #22
0
 def __init__(self, email, password):
     self.email = email
     self.password = sha256_crypt.hash(password)
예제 #23
0
def register_page():
    # check if form has been submitted i.e., user has tried to register
    if request.method == "POST":
        # get the data in name, email, and password fields
        name = request.form.get("name")
        email = request.form.get("email")
        profile_image = avatar(email, 128)
        # Validate email address
        if not validate(EMAIL_VALIDATION, email):
            flash("Invalid Email Address!", "danger")
            return render_template("register.html", favTitle=favTitle)

        password = request.form.get("password")

        # Validate password
        if not validate(PASSWORD_VALIDATION, password):
            flash("Invalid Password. Please enter a valid password!", "danger")
            return render_template("register.html", favTitle=favTitle)

        password2 = request.form.get("password2")
        # check if passwords match
        if password != password2:
            # if not, flash an error msg
            flash("Password unmatched!", "danger")
            return render_template("register.html", favTitle=favTitle)
        else:
            # generate the hashed password
            password = sha256_crypt.hash(password)
            response = User.query.filter_by(email=email).first()
            # check if the email already exists in the db
            if not response:
                # add the user to the db using the details entered and flash a msg
                entry = User(
                    name=name,
                    email=email,
                    password=password,
                    date=time,
                    profile_image=profile_image,
                    status=0,
                    is_staff=True,
                )
                db.session.add(entry)
                db.session.commit()

                # Generate email verification token
                verification_token = generate_token(email)
                print(
                    url_for("verify_email",
                            token=verification_token,
                            email=email))
                # generate the welcome email to be sent to the user

                message = Mail(
                    from_email=("*****@*****.**",
                                "Register Bot | Bulk Mailer"),
                    to_emails=email,
                    subject="Welcome aboard " + name + "!",
                    html_content=render_template("emails/register.html",
                                                 token=verification_token,
                                                 email=email),
                )

                # If any error occurs, the response will be equal to False
                if isinstance(send_mail(message), bool) and not response:
                    flash("Error while sending mail!", "danger")
                else:
                    flash(
                        "Now verify your email address for activating your account.",
                        "success",
                    )

                return redirect(url_for("login"))
            else:
                # user exists so flash an error
                flash("User exists!", "danger")
                return render_template("register.html", favTitle=favTitle)
    return render_template("register.html", favTitle=favTitle)
예제 #24
0
 def __init__(self, username, email, password, dashboard):
     self.username = username
     self.email = email
     self.password = sha256_crypt.hash(password)
     self.dashboards.append(dashboard)
예제 #25
0
def google_login_callback():
    # Get authorization code Google sent back to us
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow us to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code,
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json_lib.dumps(token_response.json()))

    # Now that we have tokens, let's find and hit the URL
    # from Google that gives us the user's profile information,
    # including their Google profile image and email
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # You want to make sure their email is verified.
    # The user authenticated with Google, authorized your
    # app, and now we've verified their email through Google!
    if userinfo_response.json().get("email_verified"):
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["name"]
    else:
        abort(401)
    pwd = new_password
    password = sha256_crypt.hash(pwd)
    # Create a user in your db with the information provided
    # by Google

    # Doesn't exist? Add it to the database.
    if not User.query.filter_by(email=users_email).first():
        entry = User(
            name=users_name,
            email=users_email,
            password=password,
            date=time,
            profile_image=picture,
            status=1,
            is_staff=False,
        )
        db.session.add(entry)
        db.session.commit()

    # Begin user session by logging the user in

    user = User.query.filter_by(email=users_email).first()
    login_user(user)

    # Send user back to homepage
    return redirect(url_for("dash_page"))
예제 #26
0
def addUser(uname, pword, twofa):
    user = User(uname, sha256_crypt.hash(pword), twofa)
    user.isAdmin = False
    db.session.add(user)
    db.session.commit()
예제 #27
0
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db, models, forms
from passlib.hash import sha256_crypt
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))
admin = models.User(username="******",
                    email="*****@*****.**",
                    hashed_password=sha256_crypt.hash("password"),
                    admin=True,
                    last_name="smith",
                    first_name="john")
db.session.add(admin)
db.session.commit()
예제 #28
0
def create_user():
    # check if request is json
    try:
        if request.is_json:
            data = request.get_json()
            # check for username key if existing
            required = [
                'username', 'password', 'firstName', 'lastName', 'email',
                'balance', 'phone'
            ]
            incomplete = False
            error = {"invalid_fields": []}
            for r in required:
                if r not in data.keys():
                    error["invalid_fields"].append({
                        "field":
                        r,
                        "reason":
                        r + " is a required property"
                    })
                    incomplete = True

            if incomplete:
                error_str = json.dumps(error)
                response = make_response(error_str, 400)
                response.headers['Content-Type'] = 'application/json'
                response.headers['Access-Control-Allow-Origin'] = '*'
                response.headers['Connection'] = 'close'
                return response

            else:
                # check password if in pattern, return 400 response error if not match, else continue
                error = {"invalid_fields": []}
                incomplete = False
                password_pattern = re.compile(
                    "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\\w\\s]).{8,}$"
                )
                email_pattern = re.compile(
                    "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
                username_pattern = re.compile("([a-z]+[_]+[a-z]*)")

                if not username_pattern.match(data['username']):
                    error["invalid_fields"].append({
                        "field":
                        'username',
                        "reason":
                        "usernames must only have lowercase letters and underscore. Example: john_doe"
                    })
                    incomplete = True
                if not password_pattern.match(data['password']):
                    error["invalid_fields"].append({
                        "field":
                        'password',
                        "reason":
                        "password does not match '^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\\\\w\\\\s]).{8,}$'"
                    })
                    incomplete = True
                if not email_pattern.match(data['email']):
                    error["invalid_fields"].append({
                        "field":
                        'email',
                        "reason":
                        "email does not match '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'"
                    })
                    incomplete = True
                try:
                    if data['password'] != data['confirm_password']:
                        error["invalid_fields"].append({
                            "field":
                            'password',
                            "reason":
                            "password and confirm password does not match"
                        })
                        incomplete = True
                except:
                    error["invalid_fields"].append({
                        "field":
                        'password',
                        "reason":
                        "passwords and confirm password does not match"
                    })
                    incomplete = True
                if data['balance'] == "":
                    data['balance'] = 0.0
                else:
                    data['balance'] = float(data['balance'])
                if incomplete:
                    error_str = json.dumps(error)
                    response = make_response(error_str, 400)
                    response.headers['Content-Type'] = 'application/json'
                    response.headers['Access-Control-Allow-Origin'] = '*'
                    response.headers['Connection'] = 'close'
                    return response

            # Insert database section
            # Encrypt password
            hashed_password = sha256_crypt.hash(data['password'])
            data['password'] = hashed_password

            # check for existing user
            accounts = mongo.db.accounts
            q = accounts.find_one({'username': data['username']})
            if q:
                error = {
                    "invalid_fields": [{
                        "field":
                        'username',
                        "reason":
                        "User " + data['username'] + " already existed"
                    }]
                }
                error_str = json.dumps(error)
                response = make_response(error_str, 400)
                response.headers['Content-Type'] = 'application/json'
                response.headers['Access-Control-Allow-Origin'] = '*'
                response.headers['Connection'] = 'close'
                return response
            else:
                data.update({'categories': [], 'records': []})
                del data['confirm_password']
                if mongo.db.accounts.insert(data):
                    # Return response
                    return_data = {
                        "balance": data['balance'],
                        "email": data['email'],
                        "phone": data['phone'],
                        "username": data['username']
                    }
                    return_data_str = json.dumps(return_data)
                    response = make_response(return_data_str, 200)
                    response.headers['Content-Type'] = 'application/json'
                    response.headers['Access-Control-Allow-Origin'] = '*'
                    response.headers['Connection'] = 'close'
                    return response
                else:
                    error = {
                        'message':
                        "there's something wrong when inserting the data"
                    }
                    error_str = json.dumps(error)
                    response = make_response(error_str, 400)
                    response.headers['Content-Type'] = 'application/json'
                    response.headers['Access-Control-Allow-Origin'] = '*'
                    response.headers['Connection'] = 'close'
                    return response
        # return error of not a json request
        else:
            error = {
                "detail":
                "Invalid Content-type (application/json), expected JSON data",
                "status": 415,
                "title": "Unsupported Media Type",
                "type": "about:blank"
            }
            error_str = json.dumps(error)
            response = make_response(error_str, 415)
            response.headers['Content-Type'] = 'application/json'
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Connection'] = 'close'
            return response
    except Exception as e:
        error = {
            "detail":
            "Invalid Content-type (application/json), expected JSON data",
            "status": 415,
            "title": "Unsupported Media Type",
            "type": "about:blank"
        }
        error_str = json.dumps(error)
        response = make_response(error_str, 415)
        response.headers['Content-Type'] = 'application/json'
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Connection'] = 'close'
        return response
예제 #29
0
def user_new():
    # check if all args are provided
    if 'name' not in request.args or \
            'email' not in request.args or \
            'password' not in request.args or \
            'device_puid' not in request.args:
        return jsonify({'status': ERROR['missing_args']})

    # only required length of args no extra. prevents bulky reqs
    if len(request.args) > 4:
        return jsonify({'status': ERROR['too_many_args']})

    # check none of the args are empty
    if check_is_args_empty(request):
        return jsonify({'status': ERROR['empty_args']})

    # store args in vars for later use
    name = request.args['name']
    email = request.args['email']
    password = request.args['password']
    device_puid = request.args['device_puid']

    # check if email is not blocked i.e. someone else's blocked due to spam
    err, is_email_blocked = check_is_email_blocked(email, Blockedemail)
    if err is not None:
        return jsonify({'status': ERROR[err['key']]})

    # is email valid?
    if not validate_email(email):
        return jsonify({'status': ERROR['invalid_email']})
    # try:
    #     v = validate_email(email) # validate and get info
    #     print(v)
    #     email = v["email"] # replace with normalized form
    # except EmailNotValidError as e:
    #     # email is not valid, exception message is human-readable
    #     print(str(e))
    #     return jsonify({
    #         'status': ERROR['invalid_email']
    #     })

    # check if device_puid is genuine
    err, is_device_genuine = check_is_device_genuine(device_puid, Device)
    if err is not None:
        return jsonify({'status': ERROR[err['key']]})

    # check if device is not registered to another user
    err, is_device_available = check_is_device_available(
        device_puid, Device, User)
    if err is not None:
        return jsonify({'status': ERROR[err['key']]})

    # fetch user to see if user exists and is verified or not
    err, is_new_user = check_is_new_user(email, User)
    if err is not None:
        return jsonify({'status': ERROR[err['key']]})
        # run scheduler so that non verified users get cleared after time

    # generate verification token
    email_verification_token = \
        URL_TOKENIZER.dumps(email, salt=app.config['SECRET_KEY'])

    # add user to db
    new_user = None
    try:
        new_user = User(name=name, email=email,
                        password=sha256_crypt.hash(password),
                        verification_token=email_verification_token,
                        is_verified=False,
                        registered_on=datetime.datetime.utcnow(),
                        device_uid=Device.query \
                            .filter_by(physical_uid=device_puid) \
                            .first().uid)
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({'status': ERROR['database_error']})

    # send verification email
    try:
        mailer.send_message(
            subject='From SmartKitchen - Please Verify Your Email',
            html="""
                <h3>SmartKitchen - Signup</h3>
                <br/>
                <p>
                    Please click the following link to verify your email.
                    <br/>
                    <a href="{}" target="_blank">{}</a>
                </p>
                <br/>
                <p>
                    If this was not you then 
                    <a href="{}" target="_blank">{}</a>
                    to block any future emails.
                </p>
                <br/>
                <p><small>
                    *** This is a computer generated Email. 
                     Reply to this Email will not be entertained. Thank You! ***
                </small></p>
            """.format(
                url_for('confirm_email',
                        token=email_verification_token,
                        _external=True),
                url_for('confirm_email',
                        token=email_verification_token,
                        _external=True),
                url_for('block_email',
                        token=email_verification_token,
                        _external=True), 'Click Here'),
            sender=app.config['MAIL_USERNAME'],
            recipients=[email])
    except Exception as e:
        print(e)
        try:
            if new_user is not None:
                db.session.delete(new_user)
                db.session.commit()
        except:
            pass
        return jsonify({'status': ERROR['mailing_error']})

    # notify user to verify email
    return jsonify({
        'status': SUCCESS['verification_email_sent'],
        'data': {
            'name': new_user.name,
            'email': new_user.email,
        }
    })
예제 #30
0
 def _encrypt(self, clearvalue, salt=None):
     rounds = param_tools.get_global_parameter("rounds_number")
     sha256_crypt.using(rounds=rounds)
     return sha256_crypt.hash(clearvalue)
예제 #31
0
 def secure_password(self):
     self.password = sha256_crypt.hash(self.password)
예제 #32
0
  def addPerson(forename, surname, location, email, nyunetid, url, tagline, password):
    if validate_email(email, verify=False) is False:
      raise SaveError(message="Email address is invalid", context="People.addPerson")
    if email_domain_is_allowed(email) is False:
      raise SaveError(message="You cannot register with this email address", context="People.addPerson")

    # TODO - Enforce password more complex password requirements?
    if password is not None and (len(password) >= 6):
      password_hash = sha256_crypt.hash(password)

      ts = time.time()
      created_on = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

      try:
        result = db.run("MATCH (n:Person{email: {email}}) RETURN ID(n) as id, n.surname as surname, n.forename AS forename, n.email as email, n.nyunetid as nyunetid", {"email": email}).peek()
      except Exception as e:
        raise DbError(message="Could not look up user", context="People.addPerson", dberror=e.message)

      if result:
        raise SaveError(message="User already exists with this email address", context="People.addPerson")
        # return {
        #   "exists": True,
        #   "user_id": result['id'],
        #   "surname": result['surname'],
        #   "forename": result['forename'],
        #   "name": str(result['forename']) + " " + str(result['surname']),
        #   "email": result['email'],
        #   "nyunetid": result['nyunetid']
        # }
      else:
        try:
          result = db.run(
            "CREATE (n:Person {url: {url}, surname: {surname}, forename: {forename}, email: {email}, location: {location}, tagline: {tagline}, nyunetid: {nyunetid}, is_disabled: 0, is_admin: 0," +
            "password: {password_hash}, created_on: {created_on}, prefs: ''})" +
            " RETURN n.forename AS forename, n.surname AS surname, n.location AS location, n.email AS email, n.url AS url, n.tagline AS tagline, n.nyunetid as nyunetid, ID(n) AS user_id",
            {"url": url, "surname": surname, "forename" : forename, "email": email, "location": location, "tagline": tagline, "nyunetid": nyunetid,
             "password_hash": password_hash, "created_on": created_on})
        except Exception as e:
          raise DbError(message="Could not create user", context="People.addPerson", dberror=e.message)

        if result:
          person = {}
          for p in result:
            person['surname'] = p['surname']
            person['forename'] = p['forename']
            person['name'] = str(p['forename']) + " " +  str(p['surname'])
            person['location'] = p['location']
            person['email'] = p['email']
            person['nyunetid'] = p['nyunetid']
            person['url'] = p['url']
            person['tagline'] = p['tagline']
            person['user_id'] = p['user_id']

            send_mail(p['email'], None, "Registration notification", "registration",
                      {"email": p['email'],
                       "login_url": app_config["base_url"]})
            return person

        else:
          raise SaveError(message="Could not add person", context="People.addPerson")

    raise SaveError(message="Password must be at least six characters in length", context="People.addPerson")
예제 #33
0
 def create_new(login: str, password: str):
     user = User()
     user.login = login
     user.password_hash = sha256_crypt.hash(password)
     return user