Exemplo n.º 1
0
Arquivo: auth.py Projeto: tdi/alerta
def create_token(user, name, login, provider=None, customer=None, role='user'):
    payload = {
        'iss': request.url_root,
        'sub': user,
        'iat': datetime.utcnow(),
        'aud': app.config['OAUTH2_CLIENT_ID'] or request.url_root,
        'exp':
        datetime.utcnow() + timedelta(days=app.config['TOKEN_EXPIRE_DAYS']),
        'name': name,
        'login': login,
        'provider': provider
    }

    if app.config['ADMIN_USERS']:
        payload['role'] = role

    if app.config['CUSTOMER_VIEWS']:
        payload['customer'] = customer

    if provider == 'basic':
        payload['email_verified'] = db.is_email_verified(login)

    token = jwt.encode(payload,
                       key=app.config['SECRET_KEY'],
                       json_encoder=DateEncoder)
    return token.decode('unicode_escape')
Exemplo n.º 2
0
def login():
    try:
        email = request.json["email"]
        domain = email.split("@")[1]
        password = request.json["password"]
    except KeyError:
        return (
            jsonify(status="error", message="Must supply 'email' and 'password'"),
            401,
            {"WWW-Authenticate": 'Basic realm="%s"' % BASIC_AUTH_REALM},
        )

    if app.config["AUTH_REQUIRED"] and not db.is_user_valid(login=email):
        return (
            jsonify(status="error", message="User or password not valid"),
            401,
            {"WWW-Authenticate": 'Basic realm="%s"' % BASIC_AUTH_REALM},
        )
    elif not db.is_user_valid(login=email):
        return (
            jsonify(status="error", message="User %s does not exist" % email),
            401,
            {"WWW-Authenticate": 'Basic realm="%s"' % BASIC_AUTH_REALM},
        )
    else:
        user = db.get_users(query={"login": email}, password=True)[0]

    if not bcrypt.hashpw(password.encode("utf-8"), user["password"].encode("utf-8")) == user["password"].encode(
        "utf-8"
    ):
        return (
            jsonify(status="error", message="User or password not valid"),
            401,
            {"WWW-Authenticate": 'Basic realm="%s"' % BASIC_AUTH_REALM},
        )

    if app.config["EMAIL_VERIFICATION"] and not db.is_email_verified(email):
        return jsonify(status="error", message="email address %s has not been verified" % email), 401

    if app.config["AUTH_REQUIRED"] and not (
        "*" in app.config["ALLOWED_EMAIL_DOMAINS"] or domain in app.config["ALLOWED_EMAIL_DOMAINS"]
    ):
        return jsonify(status="error", message="Login for user domain %s not allowed" % domain), 403

    if app.config["CUSTOMER_VIEWS"]:
        try:
            customer = customer_match(email, groups=[domain])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user domain %s" % domain), 403
    else:
        customer = None

    token = create_token(user["id"], user["name"], email, provider="basic", customer=customer, role=role(email))
    return jsonify(token=token)
Exemplo n.º 3
0
def login():
    try:
        email = request.json['email']
        domain = email.split('@')[1]
        password = request.json['password']
    except KeyError:
        return jsonify(status="error", message="Must supply 'email' and 'password'"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}

    if app.config['AUTH_REQUIRED'] and not db.is_user_valid(login=email):
        return jsonify(status="error", message="User or password not valid"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}
    elif not db.is_user_valid(login=email):
        return jsonify(status="error", message="User %s does not exist" % email), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}
    else:
        user = db.get_users(query={"login": email}, password=True)[0]

    if not bcrypt.hashpw(password.encode('utf-8'), user['password'].encode(
            'utf-8')) == user['password'].encode('utf-8'):
        return jsonify(status="error", message="User or password not valid"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}

    if app.config['EMAIL_VERIFICATION'] and not db.is_email_verified(email):
        return jsonify(status="error",
                       message="email address %s has not been verified" %
                       email), 401

    if app.config['AUTH_REQUIRED'] and not (
            '*' in app.config['ALLOWED_EMAIL_DOMAINS']
            or domain in app.config['ALLOWED_EMAIL_DOMAINS']):
        return jsonify(status="error",
                       message="Login for user domain %s not allowed" %
                       domain), 403

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(email, groups=[domain])
        except NoCustomerMatch:
            return jsonify(
                status="error",
                message="No customer lookup defined for user domain %s" %
                domain), 403
    else:
        customer = None

    token = create_token(user['id'],
                         user['name'],
                         email,
                         provider='basic',
                         customer=customer,
                         scopes=scopes(email, groups=[user['role']]))
    return jsonify(token=token)
Exemplo n.º 4
0
def signup():

    if request.json and "name" in request.json:
        name = request.json["name"]
        email = request.json["email"]
        domain = email.split("@")[1]
        password = request.json["password"]
        provider = request.json.get("provider", "basic")
        text = request.json.get("text", "")
        try:
            user_id = db.save_user(str(uuid4()), name, email, password, provider, text, email_verified=False)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        return jsonify(status="error", message="Must supply user 'name', 'email' and 'password' as parameters"), 400

    if user_id:
        user = db.get_user(user_id)
    else:
        return jsonify(status="error", message="User with email %s already exists" % email), 409

    if app.config["EMAIL_VERIFICATION"]:
        send_confirmation(name, email)
        if not db.is_email_verified(email):
            return jsonify(status="error", message="email address %s has not been verified" % email), 401

    if app.config["AUTH_REQUIRED"] and not (
        "*" in app.config["ALLOWED_EMAIL_DOMAINS"] or domain in app.config["ALLOWED_EMAIL_DOMAINS"]
    ):
        return jsonify(status="error", message="Login for user domain %s not allowed" % domain), 403

    if app.config["CUSTOMER_VIEWS"]:
        try:
            customer = customer_match(email, groups=[domain])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user domain %s" % domain), 403
    else:
        customer = None

    token = create_token(user["id"], user["name"], email, provider="basic", customer=customer, role=role(email))
    return jsonify(token=token)
Exemplo n.º 5
0
def signup():

    if request.json and 'name' in request.json:
        name = request.json["name"]
        email = request.json["email"]
        domain = email.split('@')[1]
        password = request.json["password"]
        provider = request.json.get("provider", "basic")
        text = request.json.get("text", "")
        try:
            user_id = db.save_user(str(uuid4()), name, email, password, provider, text, email_verified=False)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        return jsonify(status="error", message="Must supply user 'name', 'email' and 'password' as parameters"), 400

    if user_id:
        user = db.get_user(user_id)
    else:
        return jsonify(status="error", message="User with email %s already exists" % email), 409

    if app.config['EMAIL_VERIFICATION']:
        send_confirmation(name, email)
        if not db.is_email_verified(email):
            return jsonify(status="error", message="email address %s has not been verified" % email), 401

    if app.config['AUTH_REQUIRED'] and not ('*' in app.config['ALLOWED_EMAIL_DOMAINS']
            or domain in app.config['ALLOWED_EMAIL_DOMAINS']):
        return jsonify(status="error", message="Login for user domain %s not allowed" % domain), 403

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(email, groups=[domain])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user domain %s" % domain), 403
    else:
        customer = None

    token = create_token(user['id'], user['name'], email, provider='basic', customer=customer, role=role(email))
    return jsonify(token=token)
Exemplo n.º 6
0
def login():
    try:
        email = request.json['email']
        domain = email.split('@')[1]
        password = request.json['password']
    except KeyError:
        return jsonify(status="error", message="Must supply 'email' and 'password'"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}

    if app.config['AUTH_REQUIRED'] and not db.is_user_valid(login=email):
        return jsonify(status="error", message="User or password not valid"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}
    elif not db.is_user_valid(login=email):
        return jsonify(status="error", message="User %s does not exist" % email), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}
    else:
        user = db.get_users(query={"login": email}, password=True)[0]

    if not bcrypt.hashpw(password.encode('utf-8'), user['password'].encode('utf-8')) == user['password'].encode('utf-8'):
        return jsonify(status="error", message="User or password not valid"), 401, \
            {'WWW-Authenticate': 'Basic realm="%s"' % BASIC_AUTH_REALM}

    if app.config['EMAIL_VERIFICATION'] and not db.is_email_verified(email):
        return jsonify(status="error", message="email address %s has not been verified" % email), 401

    if app.config['AUTH_REQUIRED'] and not ('*' in app.config['ALLOWED_EMAIL_DOMAINS']
            or domain in app.config['ALLOWED_EMAIL_DOMAINS']):
        return jsonify(status="error", message="Login for user domain %s not allowed" % domain), 403

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(email, groups=[domain])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user domain %s" % domain), 403
    else:
        customer = None

    token = create_token(user['id'], user['name'], email, provider='basic', customer=customer, role=role(email))
    return jsonify(token=token)
Exemplo n.º 7
0
def signup():

    if request.json and 'name' in request.json:
        name = request.json["name"]
        email = request.json["email"]
        password = request.json["password"]
        provider = request.json.get("provider", "basic")
        text = request.json.get("text", "")
        try:
            user_id = db.save_user(str(uuid4()), name, email, password, provider, text, email_verified=False)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        return jsonify(status="error", message="must supply user 'name', 'email' and 'password' as parameters"), 400

    if app.config['EMAIL_VERIFICATION']:
        send_confirmation(name, email)
        if not db.is_email_verified(email):
            return jsonify(status="error", message="email address %s has not been verified" % email), 401

    if app.config['AUTH_REQUIRED'] and not ('*' in app.config['ALLOWED_EMAIL_DOMAINS']
            or email.split('@')[1] in app.config['ALLOWED_EMAIL_DOMAINS']):
        return jsonify(status="error", message="User %s is not authorized" % email), 403

    if user_id:
        user = db.get_user(user_id)
    else:
        return jsonify(status="error", message="User with that login already exists"), 409

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(email, groups=[email.split('@')[1]])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user %s" % email), 403
    else:
        customer = None

    token = create_token(user['id'], user['name'], email, provider='basic', customer=customer, role=role(email))
    return jsonify(token=token)
Exemplo n.º 8
0
def create_token(user, name, login, provider=None, customer=None, role="user"):
    payload = {
        "iss": request.url_root,
        "sub": user,
        "iat": datetime.utcnow(),
        "aud": app.config["OAUTH2_CLIENT_ID"] or request.url_root,
        "exp": datetime.utcnow() + timedelta(days=app.config["TOKEN_EXPIRE_DAYS"]),
        "name": name,
        "login": login,
        "provider": provider,
    }

    if app.config["ADMIN_USERS"]:
        payload["role"] = role

    if app.config["CUSTOMER_VIEWS"]:
        payload["customer"] = customer

    if provider == "basic":
        payload["email_verified"] = db.is_email_verified(login)

    token = jwt.encode(payload, key=app.config["SECRET_KEY"])
    return token.decode("unicode_escape")
Exemplo n.º 9
0
def create_token(user, name, login, provider=None, customer=None, role='user'):
    payload = {
        'iss': request.url_root,
        'sub': user,
        'iat': datetime.utcnow(),
        'aud': app.config['OAUTH2_CLIENT_ID'] or request.url_root,
        'exp': datetime.utcnow() + timedelta(days=app.config['TOKEN_EXPIRE_DAYS']),
        'name': name,
        'login': login,
        'provider': provider
    }

    if app.config['ADMIN_USERS']:
        payload['role'] = role

    if app.config['CUSTOMER_VIEWS']:
        payload['customer'] = customer

    if provider == 'basic':
        payload['email_verified'] = db.is_email_verified(login)

    token = jwt.encode(payload, key=app.config['SECRET_KEY'], json_encoder=DateEncoder)
    return token.decode('unicode_escape')