2023-09-08 08:38:27 -07:00
|
|
|
import os
|
2023-10-19 12:22:36 -07:00
|
|
|
import time
|
|
|
|
|
import uuid
|
2023-09-08 08:38:27 -07:00
|
|
|
|
2023-10-19 12:22:36 -07:00
|
|
|
import jwt
|
|
|
|
|
import requests
|
2016-01-05 17:08:50 +00:00
|
|
|
from flask import (
|
2018-02-20 11:22:17 +00:00
|
|
|
Markup,
|
2024-04-16 12:06:33 -07:00
|
|
|
Response,
|
2018-02-20 11:22:17 +00:00
|
|
|
abort,
|
2023-10-19 12:22:36 -07:00
|
|
|
current_app,
|
2016-03-14 16:30:48 +00:00
|
|
|
flash,
|
2018-02-20 11:22:17 +00:00
|
|
|
redirect,
|
|
|
|
|
render_template,
|
2016-03-30 16:16:34 +01:00
|
|
|
request,
|
2018-02-20 11:22:17 +00:00
|
|
|
session,
|
|
|
|
|
url_for,
|
2016-03-30 16:16:34 +01:00
|
|
|
)
|
2018-02-20 11:22:17 +00:00
|
|
|
from flask_login import current_user
|
2024-04-02 13:32:32 -07:00
|
|
|
from notifications_utils.url_safe_token import generate_token
|
2016-03-17 13:07:52 +00:00
|
|
|
|
2023-09-08 12:53:35 -07:00
|
|
|
from app import login_manager, user_api_client
|
2016-03-30 16:16:34 +01:00
|
|
|
from app.main import main
|
2015-12-08 15:30:55 +00:00
|
|
|
from app.main.forms import LoginForm
|
2024-03-21 09:34:55 -07:00
|
|
|
from app.main.views.index import error
|
2023-09-08 08:38:27 -07:00
|
|
|
from app.main.views.verify import activate_user
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
from app.models.user import InvitedUser, User
|
2023-12-15 12:07:54 -08:00
|
|
|
from app.utils import hide_from_search_engines
|
2021-07-14 23:10:49 +01:00
|
|
|
from app.utils.login import is_safe_redirect_url
|
2024-04-16 12:06:33 -07:00
|
|
|
from app.utils.time import is_less_than_days_ago
|
2015-11-27 09:47:29 +00:00
|
|
|
|
|
|
|
|
|
2023-12-15 12:16:03 -08:00
|
|
|
def _reformat_keystring(orig):
|
2023-12-15 12:07:54 -08:00
|
|
|
new_keystring = orig.replace("-----BEGIN PRIVATE KEY-----", "")
|
|
|
|
|
new_keystring = new_keystring.replace("-----END PRIVATE KEY-----", "")
|
|
|
|
|
new_keystring = new_keystring.strip()
|
2024-01-17 07:46:27 -08:00
|
|
|
new_keystring = new_keystring.replace(" ", "\n")
|
2023-12-15 12:07:54 -08:00
|
|
|
new_keystring = "\n".join(
|
|
|
|
|
["-----BEGIN PRIVATE KEY-----", new_keystring, "-----END PRIVATE KEY-----"]
|
|
|
|
|
)
|
|
|
|
|
new_keystring = f"{new_keystring}\n"
|
|
|
|
|
return new_keystring
|
|
|
|
|
|
|
|
|
|
|
2023-10-19 12:22:36 -07:00
|
|
|
def _get_access_token(code, state):
|
2023-10-20 08:48:04 -07:00
|
|
|
client_id = os.getenv("LOGIN_DOT_GOV_CLIENT_ID")
|
|
|
|
|
access_token_url = os.getenv("LOGIN_DOT_GOV_ACCESS_TOKEN_URL")
|
2023-11-14 10:14:35 -08:00
|
|
|
keystring = os.getenv("LOGIN_PEM")
|
2023-12-15 12:07:54 -08:00
|
|
|
if " " in keystring:
|
2023-12-15 12:16:03 -08:00
|
|
|
keystring = _reformat_keystring(keystring)
|
2023-12-15 12:07:54 -08:00
|
|
|
|
2023-10-19 12:22:36 -07:00
|
|
|
payload = {
|
2023-10-20 08:48:04 -07:00
|
|
|
"iss": client_id,
|
|
|
|
|
"sub": client_id,
|
|
|
|
|
"aud": access_token_url,
|
2023-10-19 12:22:36 -07:00
|
|
|
"jti": str(uuid.uuid4()),
|
|
|
|
|
# JWT expiration time (10 minute maximum)
|
|
|
|
|
"exp": int(time.time()) + (10 * 60),
|
|
|
|
|
}
|
2023-10-31 12:22:06 -07:00
|
|
|
token = jwt.encode(payload, keystring, algorithm="RS256")
|
2023-10-20 08:48:04 -07:00
|
|
|
base_url = f"{access_token_url}?"
|
2023-10-19 12:22:36 -07:00
|
|
|
cli_assert = f"client_assertion={token}"
|
|
|
|
|
cli_assert_type = "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer"
|
|
|
|
|
code_param = f"code={code}"
|
|
|
|
|
url = f"{base_url}{cli_assert}&{cli_assert_type}&{code_param}&grant_type=authorization_code"
|
|
|
|
|
headers = {"Authorization": "Bearer %s" % token}
|
|
|
|
|
response = requests.post(url, headers=headers)
|
2024-04-10 13:17:00 -07:00
|
|
|
if response.json().get("access_token") is None:
|
|
|
|
|
# Capture the response json here so it hopefully shows up in error reports
|
|
|
|
|
current_app.logger.error(f"Error when getting access token {response.json()}")
|
|
|
|
|
raise KeyError(f"'access_token' {response.json()}")
|
2023-10-19 12:22:36 -07:00
|
|
|
access_token = response.json()["access_token"]
|
|
|
|
|
return access_token
|
|
|
|
|
|
|
|
|
|
|
2024-03-08 09:04:56 -08:00
|
|
|
def _get_user_email_and_uuid(access_token):
|
2023-10-19 12:22:36 -07:00
|
|
|
headers = {"Authorization": "Bearer %s" % access_token}
|
2023-10-20 08:48:04 -07:00
|
|
|
user_info_url = os.getenv("LOGIN_DOT_GOV_USER_INFO_URL")
|
2023-10-19 12:22:36 -07:00
|
|
|
user_attributes = requests.get(
|
2023-10-20 08:48:04 -07:00
|
|
|
user_info_url,
|
2023-10-19 12:22:36 -07:00
|
|
|
headers=headers,
|
|
|
|
|
)
|
|
|
|
|
user_email = user_attributes.json()["email"]
|
2024-03-08 09:04:56 -08:00
|
|
|
user_uuid = user_attributes.json()["sub"]
|
|
|
|
|
return user_email, user_uuid
|
2023-10-19 12:22:36 -07:00
|
|
|
|
|
|
|
|
|
2024-03-21 09:34:55 -07:00
|
|
|
def _do_login_dot_gov():
|
2023-10-19 12:22:36 -07:00
|
|
|
# start login.gov
|
2023-10-18 15:18:37 -07:00
|
|
|
code = request.args.get("code")
|
|
|
|
|
state = request.args.get("state")
|
2023-10-19 12:22:36 -07:00
|
|
|
login_gov_error = request.args.get("error")
|
2024-04-10 13:17:00 -07:00
|
|
|
|
|
|
|
|
if login_gov_error:
|
|
|
|
|
current_app.logger.error(f"login.gov error: {login_gov_error}")
|
|
|
|
|
raise Exception(f"Could not login with login.gov {login_gov_error}")
|
|
|
|
|
elif code and state:
|
2023-10-19 12:22:36 -07:00
|
|
|
|
|
|
|
|
# activate the user
|
2024-03-21 09:34:55 -07:00
|
|
|
try:
|
2024-04-10 13:17:00 -07:00
|
|
|
access_token = _get_access_token(code, state)
|
|
|
|
|
user_email, user_uuid = _get_user_email_and_uuid(access_token)
|
|
|
|
|
redirect_url = request.args.get("next")
|
2024-03-21 09:34:55 -07:00
|
|
|
user = user_api_client.get_user_by_uuid_or_email(user_uuid, user_email)
|
2024-04-16 12:06:33 -07:00
|
|
|
|
|
|
|
|
# Check if the email needs to be revalidated
|
|
|
|
|
is_fresh_email = is_less_than_days_ago(
|
|
|
|
|
user["email_access_validated_at"], 90
|
|
|
|
|
)
|
|
|
|
|
if not is_fresh_email:
|
|
|
|
|
return verify_email(user, redirect_url)
|
|
|
|
|
|
|
|
|
|
usr = User.from_email_address(user["email_address"])
|
|
|
|
|
activate_user(usr.id)
|
2024-03-21 09:34:55 -07:00
|
|
|
except BaseException as be: # noqa B036
|
|
|
|
|
current_app.logger.error(be)
|
|
|
|
|
error(401)
|
2023-10-19 12:22:36 -07:00
|
|
|
return redirect(url_for("main.show_accounts_or_dashboard", next=redirect_url))
|
|
|
|
|
|
|
|
|
|
# end login.gov
|
2023-10-18 15:18:37 -07:00
|
|
|
|
2024-03-21 09:34:55 -07:00
|
|
|
|
2024-04-16 12:06:33 -07:00
|
|
|
def verify_email(user, redirect_url):
|
|
|
|
|
user_api_client.send_verify_code(user["id"], "email", None, redirect_url)
|
|
|
|
|
title = "Email resent" if request.args.get("email_resent") else "Check your email"
|
|
|
|
|
redirect_url = request.args.get("next")
|
|
|
|
|
return render_template(
|
|
|
|
|
"views/re-validate-email-sent.html", title=title, redirect_url=redirect_url
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2024-03-21 09:34:55 -07:00
|
|
|
@main.route("/sign-in", methods=(["GET", "POST"]))
|
|
|
|
|
@hide_from_search_engines
|
|
|
|
|
def sign_in():
|
2024-04-16 12:06:33 -07:00
|
|
|
# If we have to revalidated the email, send the message
|
|
|
|
|
# via email and redirect to the "verify your email page"
|
|
|
|
|
# and don't proceed further with login
|
|
|
|
|
email_verify_template = _do_login_dot_gov()
|
|
|
|
|
if (
|
|
|
|
|
email_verify_template
|
|
|
|
|
and not isinstance(email_verify_template, Response)
|
|
|
|
|
and "Check your email" in email_verify_template
|
|
|
|
|
):
|
|
|
|
|
return email_verify_template
|
|
|
|
|
|
2023-08-25 09:12:23 -07:00
|
|
|
redirect_url = request.args.get("next")
|
2023-09-08 08:38:27 -07:00
|
|
|
|
2023-09-11 14:23:12 -07:00
|
|
|
if os.getenv("NOTIFY_E2E_TEST_EMAIL"):
|
2023-11-10 14:10:49 -08:00
|
|
|
current_app.logger.warning("E2E TESTS ARE ENABLED.")
|
|
|
|
|
current_app.logger.warning(
|
|
|
|
|
"If you are getting a 404 on signin, comment out E2E vars in .env file!"
|
|
|
|
|
)
|
2023-09-11 14:23:12 -07:00
|
|
|
user = user_api_client.get_user_by_email(os.getenv("NOTIFY_E2E_TEST_EMAIL"))
|
2023-09-08 12:53:35 -07:00
|
|
|
activate_user(user["id"])
|
|
|
|
|
return redirect(url_for("main.show_accounts_or_dashboard", next=redirect_url))
|
2023-09-08 08:38:27 -07:00
|
|
|
|
2023-11-10 11:08:52 -08:00
|
|
|
current_app.logger.info(f"current user is {current_user}")
|
2016-05-04 13:01:55 +01:00
|
|
|
if current_user and current_user.is_authenticated:
|
2021-07-14 23:10:49 +01:00
|
|
|
if redirect_url and is_safe_redirect_url(redirect_url):
|
|
|
|
|
return redirect(redirect_url)
|
2023-08-25 09:12:23 -07:00
|
|
|
return redirect(url_for("main.show_accounts_or_dashboard"))
|
2016-02-23 15:45:19 +00:00
|
|
|
|
2016-01-27 12:22:32 +00:00
|
|
|
form = LoginForm()
|
2023-11-10 11:08:52 -08:00
|
|
|
current_app.logger.info("Got the login form")
|
2023-08-25 09:12:23 -07:00
|
|
|
password_reset_url = url_for(".forgot_password", next=request.args.get("next"))
|
2017-12-06 20:24:25 +00:00
|
|
|
|
2016-01-27 12:22:32 +00:00
|
|
|
if form.validate_on_submit():
|
Make user API client return JSON, not a model
The data flow of other bits of our application looks like this:
```
API (returns JSON)
⬇
API client (returns a built in type, usually `dict`)
⬇
Model (returns an instance, eg of type `Service`)
⬇
View (returns HTML)
```
The user API client was architected weirdly, in that it returned a model
directly, like this:
```
API (returns JSON)
⬇
API client (returns a model, of type `User`, `InvitedUser`, etc)
⬇
View (returns HTML)
```
This mixing of different layers of the application is bad because it
makes it hard to write model code that doesn’t have circular
dependencies. As our application gets more complicated we will be
relying more on models to manage this complexity, so we should make it
easy, not hard to write them.
It also means that most of our mocking was of the User model, not just
the underlying JSON. So it would have been easy to introduce subtle bugs
to the user model, because it wasn’t being comprehensively tested. A lot
of the changed lines of code in this commit mean changing the tests to
mock only the JSON, which means that the model layer gets implicitly
tested.
For those reasons this commit changes the user API client to return
JSON, not an instance of `User` or other models.
2019-05-23 15:27:35 +01:00
|
|
|
user = User.from_email_address_and_password_or_none(
|
|
|
|
|
form.email_address.data, form.password.data
|
|
|
|
|
)
|
|
|
|
|
|
2021-06-10 19:07:35 +01:00
|
|
|
if user:
|
|
|
|
|
# add user to session to mark us as in the process of signing the user in
|
2023-08-25 09:12:23 -07:00
|
|
|
session["user_details"] = {"email": user.email_address, "id": user.id}
|
2016-03-30 16:16:34 +01:00
|
|
|
|
2023-08-25 09:12:23 -07:00
|
|
|
if user.state == "pending":
|
|
|
|
|
return redirect(
|
|
|
|
|
url_for("main.resend_email_verification", next=redirect_url)
|
|
|
|
|
)
|
2021-06-10 19:07:35 +01:00
|
|
|
|
|
|
|
|
if user.is_active:
|
2023-08-25 09:12:23 -07:00
|
|
|
if session.get("invited_user_id"):
|
2021-06-10 19:07:35 +01:00
|
|
|
invited_user = InvitedUser.from_session()
|
|
|
|
|
if user.email_address.lower() != invited_user.email_address.lower():
|
|
|
|
|
flash("You cannot accept an invite for another person.")
|
2023-08-25 09:12:23 -07:00
|
|
|
session.pop("invited_user_id", None)
|
2021-06-10 19:07:35 +01:00
|
|
|
abort(403)
|
|
|
|
|
else:
|
|
|
|
|
invited_user.accept_invite()
|
|
|
|
|
|
|
|
|
|
user.send_login_code()
|
|
|
|
|
|
|
|
|
|
if user.sms_auth:
|
2023-08-25 09:12:23 -07:00
|
|
|
return redirect(url_for(".two_factor_sms", next=redirect_url))
|
2023-09-08 08:38:27 -07:00
|
|
|
|
2021-06-10 19:07:35 +01:00
|
|
|
if user.email_auth:
|
2023-08-25 09:12:23 -07:00
|
|
|
return redirect(
|
|
|
|
|
url_for(".two_factor_email_sent", next=redirect_url)
|
|
|
|
|
)
|
2017-11-07 16:11:31 +00:00
|
|
|
|
2016-01-28 16:36:36 +00:00
|
|
|
# Vague error message for login in case of user not known, locked, inactive or password not verified
|
2023-08-25 09:12:23 -07:00
|
|
|
flash(
|
|
|
|
|
Markup(
|
|
|
|
|
(
|
|
|
|
|
f"The email address or password you entered is incorrect."
|
|
|
|
|
f" <a href={password_reset_url} class='usa-link'>Forgot your password?</a>"
|
|
|
|
|
)
|
2020-10-05 15:38:34 +01:00
|
|
|
)
|
2023-08-25 09:12:23 -07:00
|
|
|
)
|
2016-01-05 14:30:06 +00:00
|
|
|
|
2017-02-17 14:06:09 +00:00
|
|
|
other_device = current_user.logged_in_elsewhere()
|
2023-12-11 07:50:45 -08:00
|
|
|
|
2024-04-02 13:32:32 -07:00
|
|
|
token = generate_token(
|
|
|
|
|
str(request.remote_addr),
|
|
|
|
|
current_app.config["SECRET_KEY"],
|
|
|
|
|
current_app.config["DANGEROUS_SALT"],
|
|
|
|
|
)
|
2024-04-02 14:02:04 -07:00
|
|
|
url = os.getenv("LOGIN_DOT_GOV_INITIAL_SIGNIN_URL")
|
2024-04-02 13:46:47 -07:00
|
|
|
# handle unit tests
|
|
|
|
|
if url is not None:
|
|
|
|
|
url = url.replace("NONCE", token)
|
|
|
|
|
url = url.replace("STATE", token)
|
2023-12-11 07:50:45 -08:00
|
|
|
|
2017-02-17 14:06:09 +00:00
|
|
|
return render_template(
|
2023-08-25 09:12:23 -07:00
|
|
|
"views/signin.html",
|
2017-02-17 14:06:09 +00:00
|
|
|
form=form,
|
2020-10-09 11:41:06 +01:00
|
|
|
again=bool(redirect_url),
|
2020-10-05 15:38:34 +01:00
|
|
|
other_device=other_device,
|
2023-08-25 09:12:23 -07:00
|
|
|
password_reset_url=password_reset_url,
|
2024-04-02 13:32:32 -07:00
|
|
|
initial_signin_url=url,
|
2017-02-17 14:06:09 +00:00
|
|
|
)
|
2017-02-16 13:33:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@login_manager.unauthorized_handler
|
|
|
|
|
def sign_in_again():
|
2023-08-25 09:12:23 -07:00
|
|
|
return redirect(url_for("main.sign_in", next=request.path))
|