コード例 #1
0
    def test_errors(self):
        with self.assertRaises(ValueError):
            passgen(length=-2)

        with self.assertRaises(ValueError):
            passgen(case="spam")

        with self.assertRaises(ValueError):
            passgen(digits=False, letters=False)
コード例 #2
0
ファイル: service.py プロジェクト: StevenHessing/byoda-python
    async def create_service_ca(self,
                                network_services_ca: NetworkServicesCaSecret = None,
                                local: bool = False) -> None:
        '''
        Create the service CA using a generated password for the private key. This
        password is different then the passwords for the other secrets as the
        Service CA should have additional security implemented and should be stored
        off-line

        :param local: should the CSR be signed by a local key or using a
        request to the directory server of the network
        :raises: ValueError if the service ca already exists
        '''

        private_key_password = passgen.passgen(length=48)

        if local:
            self.service_ca = await self._create_secret(
                ServiceCaSecret, network_services_ca,
                private_key_password=private_key_password
            )
        else:
            self.service_ca = await self._create_secret(
                ServiceCaSecret, None, private_key_password=private_key_password
            )
        _LOGGER.info(
            '!!! Private key password for the off-line Service CA: '
            f'{private_key_password}'
        )
コード例 #3
0
ファイル: rails_compose.py プロジェクト: HE-Arc/webapp-server
def main(argv):
    students = argv[1]
    destination = argv[2]
    nginx_conf = argv[3]

    users = []
    counter = 0

    with open(students, "r", encoding="utf-8", newline="") as f:
        reader = csv.reader(f, delimiter="\t")
        # skip headers
        next(reader)
        for student in map(StudentRecord._make, reader):
            if len(student.email) < 5:
                continue

            groupname = student.email.replace('.', '_')
            users.append(
                User(
                    machine=groupname,
                    groupname=groupname,
                    hostname=student.email,
                    password=passgen(punctuation=False),
                    github=student.github,
                    ssh=2200 + counter,
                    http=8000 + counter,
                    jupyter=8800 + counter))
            counter += 1

    with open(destination, 'w', encoding='utf-8') as f:
        f.write(template.render(users=users))
    with open(nginx_conf, 'w', encoding='utf-8') as f:
        f.write(nginx.render(users=users))
コード例 #4
0
	def create_pass(self, button):
		"""Creates the password and displays it."""
	
		# Retrieve password length from SpinButton
		length = int(self.spinbutton1.get_value_as_int())
		
		# Configure character selection based on checkboxes
		num, lower, upper, punc = False, False, False, False
		if self.check_num.get_active():
			num=True
		
		if self.check_lower.get_active():
			lower=True
			
		if self.check_upper.get_active():
			upper=True
	
		if self.check_punc.get_active():
			punc=True
		
		blacklist = self.blacklist.get_text().replace(" ", "")

		if "," in blacklist:
			blacklist = "".join(blacklist.split(","))
		
		
		password = passgen.passgen(length, num, lower, upper, punc, blacklist)
		self.pass_display.set_text(password)
コード例 #5
0
def generate_one_time_password():
    """passgen modules used to generate one time password"""
    value = passgen(length=6,
                    case='both',
                    digits=True,
                    letters=True,
                    punctuation=False)
    return value
コード例 #6
0
ファイル: models.py プロジェクト: aperezdc/tacitum
 def __init__(self, username, password=None, name=None, totp_key=None, groups=()):
     if name is None:
         name = username
     if password is None:
         password = passgen.passgen()
     if totp_key is None:
         totp_key = pyotp.random_base32()
     super(User, self).__init__(username=username, password=password,
             name=name, totp_key=totp_key, groups=groups)
コード例 #7
0
 def test_limit_punctuation(self):
     pl = '.'
     password = passgen(letters=True,
                        digits=False,
                        length=6,
                        punctuation=True,
                        limit_punctuation=pl)
     password = re.sub(r"[a-zA-Z.]", "", password)
     self.assertTrue(password == '')
コード例 #8
0
def generateOneTimePassword():

    # return generate_password_hash(str(random.random()))[20:26]
    value = passgen(length=6,
                    case='both',
                    digits=True,
                    letters=True,
                    punctuation=False)
    return value
コード例 #9
0
 def test_class_always_occurs(self):
     # Generating 4-char password with all classes
     for i in range(1, 100):
         password = passgen(punctuation=True, case='both', length=4)
         password = re.sub(r"[0-9]", "", password)
         self.assertTrue(len(password) == 3)
         password = re.sub(r"[a-z]", "", password)
         self.assertTrue(len(password) == 2)
         password = re.sub(r"[A-Z]", "", password)
         self.assertTrue(len(password) == 1)
def get_password():
    try:
        if "iam_password" in config:
            return config["iam_password"]
        else:
            password = passgen.passgen()
            return password

    except Exception as error:
        print(error)
コード例 #11
0
ファイル: test_passgen.py プロジェクト: soslan/passgen
    def test_errors(self):
        with self.assertRaises(ValueError):
            passgen(length=-2)

        with self.assertRaises(ValueError):
            passgen(case="spam")

        with self.assertRaises(ValueError):
            passgen(digits=False, letters=False)
コード例 #12
0
ファイル: api.py プロジェクト: heatdream/simple-flask-api
def send_reset_mail(email):
    senderEmail = "" #Email from youre EMail Account
    empfangsEmail = email
    msg = MIMEMultipart()
    msg['From'] = senderEmail
    msg['To'] = empfangsEmail
    msg['Subject'] = "Reset youre Password"
    code = passgen(length=6, punctuation=False, digits=True, letters=False, case='both')
    emailText = f"Use this code to reset youre Password: {code}"
    msg.attach(MIMEText(emailText, 'html'))

    server = smtplib.SMTP('smtp.gmail.com', 587)  # The Server Datas
    server.starttls()
    server.login(senderEmail, "")  # The Password
    text = msg.as_string()
    server.sendmail(senderEmail, empfangsEmail, text)
    server.quit()
    collection.update_one({'email': f'{email}'}, {'$set': {'code': int(code)}})
コード例 #13
0
def githubauthorize():
    token = github.authorize_access_token()
    resp = github.get('user', token=token)
    resp.raise_for_status()
    user_info = resp.json()
    # do something with the token and profile
    email = user_info['email']
    password = passgen(20)
    name = user_info['name']
    user = User.query.filter_by(email=email).first()
    if user is not None:
        login_user(user, remember=True)
    else:
        user = User(name=name,
                    email=email,
                    password=generate_password_hash(password))
        db.session.add(user)
        db.session.commit()
        login_user(user, remember=True)
    return redirect(url_for('display.show_post'))
コード例 #14
0
ファイル: models.py プロジェクト: sofDji/SmartPoll
    def partage_cle(self):

        sk, pk, fk = c.generer_cles()
        # Les stocker dans un fichier qui a comme nom: nomQuiz_spécialité_section_public/private_key.pem
        name = self.name + "_" + self.subject.specialite + "_" + self.subject.section
        passwd = passgen(length=11,
                         punctuation=False,
                         digits=True,
                         letters=True,
                         case='both')
        c.store_keys(sk, pk, fk, name, passwd.encode())

        #shamir
        shamir = sss.SSS(passwd.encode())
        #recup les partages
        shares = shamir.get_Shares()

        #partage des minis secrets sur les 2 parties: p1= responsable, p2= délégué
        #inserer les mini secrets dans la table secret
        share1 = json.dumps(shares[0])
        chkey = c.sym_crypter_msg(share1, fk)
        #insérer le mini secret du responsable
        p1 = Secret.objects.create(partie=self.owner,
                                   key1=chkey,
                                   ref_quiz=self)
        p1.save()

        #insérer le mini secret du délégué
        #avoir le délégué
        quiz_specialité = self.subject
        q = Student.objects.filter(interests=quiz_specialité).filter(
            is_deleguer=True).values_list('user_id', flat=True)
        dlg = User.objects.filter(id=q[0])

        share2 = json.dumps(shares[1])
        chkey = c.sym_crypter_msg(share2, fk)
        p2 = Secret.objects.create(partie=dlg[0], key1=chkey, ref_quiz=self)
        p2.save()
コード例 #15
0
def main():
    parser = argparse.ArgumentParser(description="docker-compose.yml builder")
    parser.add_argument("team", type=str, help="team name")

    args = parser.parse_args()

    teams = {}

    reader = csv.reader(sys.stdin, delimiter="\t")
    # skip headers
    next(reader)
    for student in map(StudentRecord._make, reader):
        # groupname
        groupname = None
        if (args.team in (student.team1, student.team2)
                or student.classname == admin):
            groupname = args.team.lower()

        # imagename
        image = None
        if args.team == student.team1:
            image = student.image1
        elif args.team == student.team2:
            image = student.image2

        if groupname:
            # XXX admin group must be after the others
            if groupname not in teams:
                teams[groupname] = Team(image=image.lower(),
                                        machine=groupname,
                                        groupname=groupname,
                                        hostname=groupname,
                                        password=passgen(punctuation=False),
                                        ssh_keys={student.github})
            else:
                teams[groupname].ssh_keys.add(student.github)

    print(template.render(teams=teams.values(), domainname=domainname))
コード例 #16
0
    def handle(self, *args, **options):
        max_turk_num = 0
        for user in User.objects.filter(username__regex=r'^mturk(\d+)'):
            turk_num = int(re.search(r'^mturk(\d+)', str(user)).group(1))
            if turk_num > max_turk_num:
                max_turk_num = turk_num

        max_turk_num += 1

        output_csv_string = 'Username,Password\n'
        for i in range(max_turk_num, max_turk_num + options['num_turkers'][0]):
            username = '******' + str(i)
            password = passgen(length=12,
                               punctuation=False,
                               digits=True,
                               case='both')
            user = User.objects.create(username=username)
            user.set_password(password)
            user.save()
            output_csv_string += username + ',' + password + '\n'

        with open(options['filename'], 'a') as f:
            f.write(output_csv_string)
コード例 #17
0
ファイル: network.py プロジェクト: StevenHessing/byoda-python
    async def create(network_name: str, root_dir: str, password: str):
        '''
        Factory for creating a new Byoda network and its secrets.

        Create the secrets for a network, unless they already exist:
        - Network Root CA
        - Accounts CA
        - Services CA
        - Network Data secret (for sending signed messages)

        A network directory server does not need a TLS secret signed
        by its CA chain as it uses a Let's Encrypt TLS certificate.

        :returns: Network insance
        :raises: ValueError, PermissionError
        '''

        paths = Paths(network=network_name, root_directory=root_dir)

        if not await paths.network_directory_exists():
            await paths.create_network_directory()

        if not await paths.secrets_directory_exists():
            await paths.create_secrets_directory()

        # Create root CA
        root_ca = NetworkRootCaSecret(paths=paths)

        if await root_ca.cert_file_exists():
            await root_ca.load(with_private_key=True, password=password)
        else:
            root_ca.create(expire=100*365)
            root_ca_password = passgen.passgen(length=48)
            await root_ca.save(password=root_ca_password)
            _LOGGER.info(
                f'!!! Saving root CA using password {root_ca_password}'
            )

        network_data = {
            'network': network_name, 'root_dir': root_dir,
            'private_key_password': password, 'roles': ['test']
        }
        network = Network(network_data, network_data)
        await network.load_network_secrets(root_ca)

        # Root CA, signs Accounts CA, Services CA and
        # Network Data Secret. We don't need a 'Network.ServiceSecret'
        # as we use the Let's Encrypt cert for TLS termination
        if not network.data_secret or not network.data_secret.cert:
            network.data_secret = await Network._create_secret(
                network.name, NetworkDataSecret, root_ca, paths, password
            )

        network.accounts_ca = await Network._create_secret(
            network.name, NetworkAccountsCaSecret, root_ca, paths, password
        )

        network.services_ca = await Network._create_secret(
            network.name, NetworkServicesCaSecret, root_ca, paths, password
        )

        # Create the services directory to enable the directory server to start
        os.makedirs(paths.get(Paths.SERVICES_DIR), exist_ok=True)

        return network
コード例 #18
0
# Get the set of current users from Cognito by repeatedly
# through list user calls until all pages are fetched
existing_usernames = set()
params = {'UserPoolId': user_pool_id, 'AttributesToGet': []}
while True:
    response = cognito_idp.list_users(**params)
    existing_usernames.update(u['Username'] for u in response['Users'])
    if 'PaginationToken' in response:
        params['PaginationToken'] = response['PaginationToken']
    else:
        break

# Determine a delta of new system identifiers that need to be added; note that
# the identifiers not in the local systems.txt file are retained (in other
# words this process is purely additive in order to prevent accidental deletion)
usernames_to_add = new_usernames - existing_usernames

# Create a new Cognito user for each new system identifier, generate a
# randomized password for each one, and then set that password permanently
print('Adding system identifiers to {0}'.format(user_pool_id))
for username in usernames_to_add:
    params = {'UserPoolId': user_pool_id, 'Username': username}
    cognito_idp.admin_create_user(**params)
    params['Password'] = passgen.passgen(32,
                                         True,
                                         limit_punctuation='!@#$%^&*()')
    params['Permanent'] = True
    cognito_idp.admin_set_user_password(**params)
    print('Added user: {0} // {1}'.format(username, params['Password']))
コード例 #19
0
    def test_length(self):
        password = passgen(length=10)
        self.assertEqual(len(password), 10)

        password = passgen(length=15, case='upper', digits=False)
        self.assertEqual(len(password), 15)
コード例 #20
0
	def _generate_password(self):
		return passgen(length=12, punctuation=False, digits=True, letters=True, case='both')
コード例 #21
0
ファイル: simplevault.py プロジェクト: hrisant/ops-cli
    def __init__(self,
                 path,
                 key='value',
                 policy={},
                 vault_user=None,
                 vault_addr=None,
                 vault_token=None,
                 auto_prompt=True):
        self.__DEFAULT_POLICY__ = {'engine': 'passgen', 'length': 24}
        self.current_data = {}
        self.already_initialized = False
        self.actual_policy = self.__DEFAULT_POLICY__.copy()
        self.key = key
        if isinstance(policy, int):
            self.actual_policy.update({'length': policy})
        elif isinstance(policy, dict):
            self.actual_policy.update(policy)
        else:
            raise Exception(
                "Incorrect policy specified. Use a number if unsure.")
        if path:
            self.vault_path = path
        else:
            raise Exception("Invalid path for secret")
        self.policy = policy
        if ManagedVaultSecret.p_sv and ManagedVaultSecret.p_sv.is_authenticated(
        ):
            self.sv = ManagedVaultSecret.p_sv
        else:
            try:
                self.sv = SimpleVault(vault_user=None,
                                      vault_addr=None,
                                      vault_token=None,
                                      auto_prompt=True)
                ManagedVaultSecret.p_sv = self.sv
            except Exception as e:
                display(
                    'MANAGED-SECRET: could not obtain a proper Vault connection.\n{}'
                    .format(e.message))
                raise e
        try:
            self.current_data = self.sv.get(path=path,
                                            fetch_all=True,
                                            raise_exceptions=True)
        except Exception as e:
            display(
                'MANAGED-SECRET: could not confirm if secret at path {} does or not already exist. '
                'Exception was:\n{}'.format(path, e.message))
            raise e
        if self.current_data.get(key):
            #something exists on that path, we assume the secret already exists and do nothing more
            pass
        else:
            #secret does not exist, we will generate it right now according to the desired policy
            generator_args = self.actual_policy.copy()
            engine = generator_args.pop('engine', None)
            if self.actual_policy['engine'] == 'passgen':
                try:
                    import passgen
                except ImportErrori as e:
                    display(
                        'MANAGED-SECRET: You need passgen python module in order to use the passgen engine.'
                    )
                    raise e
                try:
                    #generating and storing the new secret

                    self.new_data = self.current_data.copy()
                    self.new_data[key] = passgen.passgen(**generator_args)
                    self.sv.put(path, self.new_data)
                    self.already_initialized = True
                    self.current_data = self.new_data
                except Exception as e:
                    display(
                        'MANAGED-SECRET: could not create new managed secret')
                    raise e
            else:
                raise Exception("Unsupported password generation engine.")
コード例 #22
0
import csv
from django.contrib.auth.models import User
from passgen import passgen

with open('user_passwords.csv', 'w') as f:
    dw = csv.DictWriter(f, fieldnames=('username', 'password'))
    dw.writeheader()

    for user in User.objects.filter(is_superuser=False):
        print("Creating password for user {0}.".format(user.username))
        password = passgen(length=12)
        user.set_password(password)
        user.save()
        dw.writerow(dict(username=user.username, password=password))
コード例 #23
0
ファイル: models.py プロジェクト: symonline/myvest
def identifier(string_length):
    random_string = passgen(length=string_length, punctuation=False,
                            digits=True, letters=True, case='upper')
    return random_string
コード例 #24
0
ファイル: app.py プロジェクト: aperezdc/tacitum
#
# Copyright © 2016 Adrian Perez <*****@*****.**>
#
# Distributed under terms of the MIT license.

import muffin
import models, lasso
from passgen import passgen
from store import TacitumStore
from os import path as P

app = muffin.Application(
    "tacitum",
    PLUGINS=("muffin_session", "muffin_pystache"),
    SESSION_LOGIN_URL="/login",
    SESSION_SECRET=passgen(),
    STATIC_FOLDERS=P.join(P.dirname(__file__), "static"),
    PYSTACHE_PATH=P.join(P.dirname(__file__), "templates"),
    PYSTACHE_LAYOUT="layout",
)

store = TacitumStore("data")


@app.ps.session.user_loader
def get_user(uid):
    return store.get("/user/" + uid)


@app.register("/login", methods="GET")
def login(request):
コード例 #25
0
ファイル: test_passgen.py プロジェクト: soslan/passgen
    def test_case(self):
        password = passgen(case='upper')
        self.assertEqual(password, password.upper())

        password = passgen(case='lower')
        self.assertEqual(password, password.lower())
コード例 #26
0
import csv
import passgen
from cs50 import SQL
from flask_bcrypt import Bcrypt

bcrypt = Bcrypt()
rdb = SQL("sqlite:///JC.db")
db = SQL("sqlite:///project.db")

with open('JC.csv', "r") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        for ID in row:
            loginID = ID
            password = passgen.passgen(length=15,
                                       punctuation=False,
                                       digits=True,
                                       letters=True,
                                       case='both')
            hash = bcrypt.generate_password_hash(password)
            rdb.execute(
                "INSERT INTO JCcredentials (loginID, password) VALUES(:login_ID, :pwd)",
                login_ID=loginID,
                pwd=password)
            db.execute(
                "INSERT INTO JCID (loginID, password) VALUES(:login_ID, :pwd_hash)",
                login_ID=loginID,
                pwd_hash=hash)
コード例 #27
0
	def _generate_password():
		"""Generates a random password."""
		return passgen.passgen(punctuation=True)
コード例 #28
0
    def post(self):
        # Checks for proper authorization
        if current_user.authentication_level is 3:

            # Create class jurisdiction string
            departments = json.load(open("configs/departments.json"))

            class_jurisdiction = ""

            for i in range(len(departments["departments"])):
                if self.args["department"] == departments["departments"][i][
                        "catsweb_val"]:
                    for j in range(
                            len(departments["departments"][i]
                                ["jurisdiction"])):
                        if j == len(departments["departments"][i]
                                    ["jurisdiction"]) - 1:
                            class_jurisdiction = class_jurisdiction + departments[
                                "departments"][i]["jurisdiction"][j]
                        else:
                            class_jurisdiction = class_jurisdiction + departments[
                                "departments"][i]["jurisdiction"][j] + ","
                    break

            try:
                new_user = UserModel(
                    id=self.args["netID"],
                    firstname=self.args["firstname"],
                    lastname=self.args["lastname"],
                    email=self.args["netID"] + '@txstate.edu',
                    department=self.args["department"],
                    authentication_level=self.args["authorization_level"],
                    class_jurisdiction=class_jurisdiction)

                # Creates a random password for the new user's account and then adds user to database
                new_password = passgen(length=12,
                                       punctuation=False,
                                       digits=True,
                                       letters=True,
                                       case='both')
                new_user.set_password(new_password)
                db.session.add(new_user)
                db.session.commit()

                # Send the new user an email with their new password
                send_email(self.args["netID"] + '@txstate.edu',
                           self.args["firstname"], new_password)

                return {
                    "status":
                    True,
                    "message":
                    "User " + self.args["netID"] +
                    " successfully created! Please reload the page. "
                }
            except Exception as e:
                db.session.delete(new_user)
                db.session.commit()
                return {"status": False, "message": "Error!"}
        else:
            return {
                "status":
                False,
                "message":
                "You do not have the proper credentials to create a user"
            }
コード例 #29
0
def password_create():
    return passgen.passgen()
コード例 #30
0
	def _generate_password(self):
		return passgen(length=12, punctuation=False, digits=True, letters=True, case='both')
コード例 #31
0
 def test_only_digits(self):
     password = passgen(letters=False, digits=True)
     password = re.sub(r"[0-9]", "", password)
     self.assertTrue(password == '')
コード例 #32
0
def create_user(uname, num):
    uid = BASE_UID + num
    try:
        pwd.getpwuid(uid)
        newpass = None
    except KeyError:
        newpass = passgen.passgen()
    if (newpass is not None):
        if (on_master()):
            homedirflag = "-m"
        else:
            homedirflag = "-M"
        gname = grp.getgrgid(pwd.getpwnam("hpc").pw_gid).gr_name
        homedir = os.path.join(
            os.path.split(pwd.getpwnam("hpc").pw_dir)[0], uname)
        subprocess.Popen([
            "/usr/sbin/useradd", "-c", "Training user {num}".format(num=num),
            "-g", gname, "-d", homedir, "-s", "/bin/bash", homedirflag, "-u",
            str(uid), uname
        ]).wait()
        p = subprocess.Popen(["/usr/bin/passwd", uname], stdin=subprocess.PIPE)
        tmp = newpass + "\n"
        p.stdin.write(tmp.encode("utf-8"))
        p.stdin.write(tmp.encode("utf-8"))
        p.communicate()
        p.wait()
        if (on_master()):
            keyfile = os.path.join(homedir, ".ssh", "id_rsa")
            subprocess.Popen(
                'sudo -u {uname} ssh-keygen -t rsa -f {keyfile} -q -P "" '.
                format(uname=uname, keyfile=keyfile),
                shell=True).wait()
            with open(keyfile + ".pub", "r") as inf:
                with open(os.path.join(homedir, ".ssh", "authorized_keys"),
                          "a") as ouf:
                    for line in inf:
                        ouf.write(line)
            subprocess.Popen('chown ' + uname + ':' + gname + ' ' +
                             os.path.join(homedir, ".ssh", "authorized_keys"),
                             shell=True)
            subprocess.Popen(
                'mkdir /share/data/{uname}; chown {uname}.{gname} /share/data/{uname}'
                .format(uname=uname, gname=gname),
                shell=True).wait()
            subprocess.Popen(
                'sudo --user {uname} --login python3 -m bash_kernel.install --user'
                .format(uname=uname),
                shell=True).wait()
            subprocess.Popen(
                'sudo --user {uname} --login jupyter notebook --generate-config'
                .format(uname=uname),
                shell=True).wait()
            longcommand = '''echo 'c.NotebookApp.contents_manager_class = "notedown.NotedownContentsManager"'
                                >> ${HOME}/.jupyter/jupyter_notebook_config.py &&
                           echo 'c.NotebookApp.server_extensions.append("ipyparallel.nbextension")'
                                >> ${HOME}/.jupyter/jupyter_notebook_config.py &&
                           ipython3 profile create --parallel --profile=mpi && 
                           echo 'c.IPClusterEngines.engine_launcher_class = "MPI"'
                                >> ${HOME}/.ipython/profile_mpi/ipcluster_config.py &&
                           echo 'c.BaseParallelApplication.cluster_id = "training_cluster_0"'
                                >> ${HOME}/.ipython/profile_mpi/ipcluster_config.py'''
            subprocess.Popen(
                ["sudo", "--login", "--user", uname, "sh", "-c",
                 longcommand]).wait()
            with open(os.path.join(homedir, ".gitconfig"), "w") as f:
                f.write(
                    "[user]\nname = Training user {uid}\nemail = {uname}@training_cluster.nonexistent.azure.com\n"
                    .format(uid=num, uname=uname))

    return newpass
コード例 #33
0
ファイル: main.py プロジェクト: playerdefault/littlethings
import passgen

if __name__ == '__main__':
    passgen.passgen()
コード例 #34
0
ファイル: test_passgen.py プロジェクト: soslan/passgen
    def test_length(self):
        password = passgen(length=10)
        self.assertEqual(len(password), 10)

        password = passgen(length=15, case='upper', digits=False)
        self.assertEqual(len(password), 15)
コード例 #35
0
def AES256_create():
    return passgen.passgen(length=43, letters=True, case='both') + "="
コード例 #36
0
ファイル: app.py プロジェクト: aperezdc/tacitum
#
# Copyright © 2016 Adrian Perez <*****@*****.**>
#
# Distributed under terms of the MIT license.

import muffin
import models, lasso
from passgen import passgen
from store import TacitumStore
from os import path as P


app = muffin.Application("tacitum",
        PLUGINS = ("muffin_session", "muffin_pystache"),
        SESSION_LOGIN_URL = "/login",
        SESSION_SECRET = passgen(),
        STATIC_FOLDERS = P.join(P.dirname(__file__), "static"),
        PYSTACHE_PATH = P.join(P.dirname(__file__), "templates"),
        PYSTACHE_LAYOUT = "layout",
    )

store = TacitumStore("data")


@app.ps.session.user_loader
def get_user(uid):
    return store.get("/user/" + uid)


@app.register("/login", methods="GET")
def login(request):