Exemplo n.º 1
0
def register_vip(username, firstname, surname, password, department = "floor1", address="Nowhere", phone=102):
    if len(firstname) > 24 or len(surname) > 24:
        return None
    if department not in VipDepartmentList:
        return None

    # Instantiate connection
    client, conn = instantiate_connection()

    # Check if user already exists
    FILTER = f'(cn={sanitize(username)})'
    response = conn.search(LDAPBASE_DN , 2, FILTER)
    conn.close()
    nb_results = len(response)
    if nb_results >= 1:
        return None

    else:
        # Generate Key Pair
        (private_key, public_key) = generateKeyPair()
        enc_address = encodeUsingKey(public_key, str.encode(address)).hex()

        hash_pass = hash_password(password)

        # Connect using admin account
        server, conn = instantiate_connection()
        # Build user DN
        USER_DN = f'cn={username},ou=people,{LDAPBASE_DN}'

        # Build user entry
        user = LDAPEntry(USER_DN)
        user['objectClass'] = ['person', 'inetOrgPerson', 'ldapPublicKey']
        user['givenName'] = firstname
        user['sn'] = surname
        user['homePostalAddress'] = enc_address
        user['telephoneNumber'] = int(phone)
        user['departmentNumber'] = department
        user['userPassword'] = hash_pass
        # Handle intern keys and non intern keys
        user['sshPublicKey'] = public_key.public_bytes(
                                encoding=serialization.Encoding.PEM,
                                format=serialization.PublicFormat.SubjectPublicKeyInfo)

        print_priv = private_key.private_bytes(
                        encoding=serialization.Encoding.PEM,
                        format=serialization.PrivateFormat.TraditionalOpenSSL,
                        encryption_algorithm=serialization.NoEncryption())

        add_sucess = conn.add(user)
        conn.close()
        if (add_sucess):
            return print_priv
        else:
            return None
Exemplo n.º 2
0
def register(username, firstname, surname, password, department = "floor1", address="Nowhere", phone=102):

    # Register checks, still some to implement
    if len(firstname) > 24 or len(surname) > 24:
        return None
    if department not in departmentList:
        return None

    # Instantiate connection
    client, conn = instantiate_connection()

    # Check if user already exists
    FILTER = f'(cn={sanitize(username)})'
    response = conn.search(LDAPBASE_DN , 2, FILTER)
    conn.close()
    nb_results = len(response)
    if nb_results >= 1:
        return None

    else:
        hash_pass = hash_password(password)

        # Connect using admin account
        server, conn = instantiate_connection()
        # Build user DN
        USER_DN = f'cn={username},ou=people,{LDAPBASE_DN}'

        # Build user entry
        user = LDAPEntry(USER_DN)
        user['objectClass'] = ['person', 'inetOrgPerson', 'ldapPublicKey']
        user['givenName'] = firstname
        user['sn'] = surname
        # Non VIP user doesn't enjoy encryption for data
        user['homePostalAddress'] = address
        # Telephone number
        try :
            user['telephoneNumber'] = int(phone)
        except:
            user['telephoneNumber'] = 123456

        user['departmentNumber'] = department
        user['userPassword'] = hash_pass
        # Handle intern keys and non intern keys
        user['sshPublicKey'] = b'No key for non VIP user'
        print_priv = b'No key for non VIP user'

        add_sucess = conn.add(user)
        conn.close()
        if (add_sucess):
            return print_priv
        else:
            return None
Exemplo n.º 3
0
    def insert_token(self, user_id):
        token = crypto.get_new_token()
        hashed_token = crypto.hash_password(token)

        self.cursor.execute(
            '''
            INSERT INTO tokens (user_id, token)
            VALUES (%s, %s)
            RETURNING id;
        ''', (user_id, hashed_token))
        self.conn.commit()

        token_id = self.cursor.fetchone()[0]

        return token_id, token
Exemplo n.º 4
0
    def insert_user(self, username, password):
        hashed_password = crypto.hash_password(password)

        try:
            self.cursor.execute(
                '''
            INSERT INTO users (username, password)
            VALUES (%s, %s)
            RETURNING id;
            ''', (username, hashed_password))
        except psycopg2.errors.UniqueViolation:
            self.conn.rollback()
            return

        self.conn.commit()

        user_id = self.cursor.fetchone()[0]

        return user_id
Exemplo n.º 5
0
async def register_user(user: UserIn):
    """
    Registers a user,
    takes a user_in model which is just {"email": ..., "password": ...}
    """
    if not valid_password(user.password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=
            "Password must have uppercase and lowercase letter,be at least 8 characters long and contain at least a number and an uppercase character",
        )

    user = user.dict()

    # hash the user's password
    user["password_hash"] = hash_password(user["password"])
    # remove the normal password, os only password_hash remains
    user.pop("password")

    # Create the user in the database
    user_obj = await User.create(**user)

    return {"detail": "User created"}
Exemplo n.º 6
0
def update_user(repo: Repository, item_id: int, data: dict) -> models.User:
    sanitized = clean_empty_keys(data)
    if "password" in sanitized:
        data["password"] = crypto.hash_password(data["password"])
    return repo.update(item_id, sanitized)
Exemplo n.º 7
0
def create_user(repo: Repository, user: schemas.UserCreate) -> models.User:
    user.password = crypto.hash_password(user.password)
    user_model = convert_to_model(user)
    return repo.add(user_model)
Exemplo n.º 8
0
 def register(cls, username, password, email=None):
     pw_hash, salt = crypto.hash_password(username, password)
     return User(username=username,
                 passwhash=pw_hash,
                 passwsalt=salt,
                 email=db.Email(email if email else 'None'))
Exemplo n.º 9
0
def test_hash_password():
    passwd = "test"
    hashed = hash_password(passwd)
    assert is_correct_password(passwd, hashed)