summaryrefslogtreecommitdiffstats
path: root/testing/mozharness/mozharness/lib/python/authentication.py
blob: 5d7330e357dd1acaab55dc9c57fbb0616a46db8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****

"""module for http authentication operations"""
import getpass
import os

CREDENTIALS_PATH = os.path.expanduser("~/.mozilla/credentials.cfg")
DIRNAME = os.path.dirname(CREDENTIALS_PATH)
LDAP_PASSWORD = None


def get_credentials():
    """Returns http credentials.

    The user's email address is stored on disk (for convenience in the future)
    while the password is requested from the user on first invocation.
    """
    global LDAP_PASSWORD
    if not os.path.exists(DIRNAME):
        os.makedirs(DIRNAME)

    if os.path.isfile(CREDENTIALS_PATH):
        with open(CREDENTIALS_PATH, "r") as file_handler:
            content = file_handler.read().splitlines()

        https_username = content[0].strip()

        if len(content) > 1:
            # We want to remove files which contain the password
            os.remove(CREDENTIALS_PATH)
    else:
        try:
            # pylint: disable=W1609
            input_method = raw_input
        except NameError:
            input_method = input

        https_username = input_method("Please enter your full LDAP email address: ")

        with open(CREDENTIALS_PATH, "w+") as file_handler:
            file_handler.write("%s\n" % https_username)

        os.chmod(CREDENTIALS_PATH, 0o600)

    if not LDAP_PASSWORD:
        print("Please enter your LDAP password (we won't store it):")
        LDAP_PASSWORD = getpass.getpass()

    return https_username, LDAP_PASSWORD


def get_credentials_path():
    if os.path.isfile(CREDENTIALS_PATH):
        get_credentials()

    return CREDENTIALS_PATH