mirror of
https://github.com/GSA/notifications-api.git
synced 2026-08-17 04:58:50 -04:00
Merge pull request #1383 from alphagov/user-mobile-optional
User mobile optional
This commit is contained in:
@@ -94,7 +94,7 @@ def register_errors(blueprint):
|
||||
current_app.logger.exception(e)
|
||||
if hasattr(e, 'orig') and hasattr(e.orig, 'pgerror') and e.orig.pgerror and \
|
||||
('duplicate key value violates unique constraint "services_name_key"' in e.orig.pgerror or
|
||||
'duplicate key value violates unique constraint "services_email_from_key"' in e.orig.pgerror):
|
||||
'duplicate key value violates unique constraint "services_email_from_key"' in e.orig.pgerror):
|
||||
return jsonify(
|
||||
result='error',
|
||||
message={'name': ["Duplicate service name '{}'".format(
|
||||
|
||||
@@ -9,7 +9,7 @@ from sqlalchemy.dialects.postgresql import (
|
||||
UUID,
|
||||
JSON
|
||||
)
|
||||
from sqlalchemy import UniqueConstraint, and_
|
||||
from sqlalchemy import UniqueConstraint, CheckConstraint, and_
|
||||
from sqlalchemy.orm import foreign, remote
|
||||
from notifications_utils.recipients import (
|
||||
validate_email_address,
|
||||
@@ -97,7 +97,7 @@ class User(db.Model):
|
||||
nullable=True,
|
||||
onupdate=datetime.datetime.utcnow)
|
||||
_password = db.Column(db.String, index=False, unique=False, nullable=False)
|
||||
mobile_number = db.Column(db.String, index=False, unique=False, nullable=False)
|
||||
mobile_number = db.Column(db.String, index=False, unique=False, nullable=True)
|
||||
password_changed_at = db.Column(db.DateTime, index=False, unique=False, nullable=False,
|
||||
default=datetime.datetime.utcnow)
|
||||
logged_in_at = db.Column(db.DateTime, nullable=True)
|
||||
@@ -107,6 +107,9 @@ class User(db.Model):
|
||||
current_session_id = db.Column(UUID(as_uuid=True), nullable=True)
|
||||
auth_type = db.Column(db.String, db.ForeignKey('auth_type.name'), index=True, nullable=False, default=SMS_AUTH_TYPE)
|
||||
|
||||
# either email auth or a mobile number must be provided
|
||||
CheckConstraint("auth_type = 'email_auth' or mobile_number is not null")
|
||||
|
||||
services = db.relationship(
|
||||
'Service',
|
||||
secondary='user_to_service',
|
||||
|
||||
@@ -105,6 +105,26 @@ class UserSchema(BaseSchema):
|
||||
"_password", "verify_codes")
|
||||
strict = True
|
||||
|
||||
@validates('name')
|
||||
def validate_name(self, value):
|
||||
if not value:
|
||||
raise ValidationError('Invalid name')
|
||||
|
||||
@validates('email_address')
|
||||
def validate_email_address(self, value):
|
||||
try:
|
||||
validate_email_address(value)
|
||||
except InvalidEmailError as e:
|
||||
raise ValidationError(str(e))
|
||||
|
||||
@validates('mobile_number')
|
||||
def validate_mobile_number(self, value):
|
||||
try:
|
||||
if value is not None:
|
||||
validate_phone_number(value, international=True)
|
||||
except InvalidPhoneError as error:
|
||||
raise ValidationError('Invalid phone number: {}'.format(error))
|
||||
|
||||
|
||||
class UserUpdateAttributeSchema(BaseSchema):
|
||||
auth_type = field_for(models.User, 'auth_type')
|
||||
@@ -132,7 +152,8 @@ class UserUpdateAttributeSchema(BaseSchema):
|
||||
@validates('mobile_number')
|
||||
def validate_mobile_number(self, value):
|
||||
try:
|
||||
validate_phone_number(value, international=True)
|
||||
if value is not None:
|
||||
validate_phone_number(value, international=True)
|
||||
except InvalidPhoneError as error:
|
||||
raise ValidationError('Invalid phone number: {}'.format(error))
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from flask import (jsonify, request, Blueprint, current_app, abort)
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.config import QueueNames
|
||||
from app.dao.users_dao import (
|
||||
@@ -52,6 +53,19 @@ user_blueprint = Blueprint('user', __name__)
|
||||
register_errors(user_blueprint)
|
||||
|
||||
|
||||
@user_blueprint.errorhandler(IntegrityError)
|
||||
def handle_integrity_error(exc):
|
||||
"""
|
||||
Handle integrity errors caused by the auth type/mobile number check constraint
|
||||
"""
|
||||
if 'ck_users_mobile_or_email_auth' in str(exc):
|
||||
# we don't expect this to trip, so still log error
|
||||
current_app.logger.exception('Check constraint ck_users_mobile_or_email_auth triggered')
|
||||
return jsonify(result='error', message='Mobile number must be set if auth_type is set to sms_auth'), 400
|
||||
|
||||
raise
|
||||
|
||||
|
||||
@user_blueprint.route('', methods=['POST'])
|
||||
def create_user():
|
||||
user_to_create, errors = user_schema.load(request.get_json())
|
||||
@@ -63,23 +77,6 @@ def create_user():
|
||||
return jsonify(data=user_schema.dump(user_to_create).data), 201
|
||||
|
||||
|
||||
@user_blueprint.route('/<uuid:user_id>', methods=['PUT'])
|
||||
def update_user(user_id):
|
||||
user_to_update = get_user_by_id(user_id=user_id)
|
||||
req_json = request.get_json()
|
||||
update_dct, errors = user_schema_load_json.load(req_json)
|
||||
# TODO don't let password be updated in this PUT method (currently used by the forgot password flow)
|
||||
pwd = req_json.get('password', None)
|
||||
if pwd is not None:
|
||||
if not pwd:
|
||||
errors.update({'password': ['Invalid data for field']})
|
||||
raise InvalidRequest(errors, status_code=400)
|
||||
else:
|
||||
reset_failed_login_count(user_to_update)
|
||||
save_model_user(user_to_update, update_dict=update_dct, pwd=pwd)
|
||||
return jsonify(data=user_schema.dump(user_to_update).data), 200
|
||||
|
||||
|
||||
@user_blueprint.route('/<uuid:user_id>', methods=['POST'])
|
||||
def update_user_attribute(user_id):
|
||||
user_to_update = get_user_by_id(user_id=user_id)
|
||||
|
||||
Reference in New Issue
Block a user