def set_user_email_token_hash(user: User, token: str) -> User: """ Set email token hash for user """ user.email_token_hash = bcrypt.generate_password_hash( token, app.config.get('BCRYPT_LOG_ROUNDS')).decode() db.session.commit() return user
def register_user(): # get post data post_data = request.get_json() if not post_data: raise InvalidPayload() username = post_data.get('username') email = post_data.get('email') password = post_data.get('password') if not password or not username or not email: raise InvalidPayload() # check for existing user user = User.first(or_(User.username == username, User.email == email)) if not user: # add new user to db new_user = User(username=username, email=email, password=password) with session_scope(db.session) as session: session.add(new_user) # need another scope if not new_user does not exists yet with session_scope(db.session) as session: token = new_user.encode_email_token() new_user.email_token_hash = bcrypt.generate_password_hash( token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode() if not current_app.testing: from project.api.common.utils.mails import send_registration_email send_registration_email(new_user, token.decode()) # save the device if all(x in request.headers for x in [ Constants.HttpHeaders.DEVICE_ID, Constants.HttpHeaders.DEVICE_TYPE ]): device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID) device_type = request.headers.get( Constants.HttpHeaders.DEVICE_TYPE) with session_scope(db.session): Device.create_or_update(device_id=device_id, device_type=device_type, user=user) # generate auth token auth_token = new_user.encode_auth_token() return { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() }, 201 else: # user already registered, set False to device.active if Constants.HttpHeaders.DEVICE_ID in request.headers: device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID) device = Device.first_by(device_id=device_id) if device: with session_scope(db.session): device.active = False raise BusinessException(message='Sorry. That user already exists.')