def seed_db(): """Seeds the database.""" db.session.add( User(username='******', email='*****@*****.**', password='******')) db.session.add( User(username='******', email='*****@*****.**', password='******')) db.session.commit()
def set_users(): pwd1 = 'f0oBarPasswd' user1 = User(email='*****@*****.**', username='******', password=User.generate_hash(pwd1), isVerified=True) pwd2 = 'bar @sswOyyy' user2 = User(email='*****@*****.**', username='******', password=User.generate_hash(pwd2)) return (user1, pwd1), (user2, pwd2)
def register_user(): # get post data post_data = request.get_json() if not post_data: response_object = {'status': 'error', 'message': 'Invalid payload.'} return jsonify(response_object), 400 username = post_data.get('username') email = post_data.get('email') password = post_data.get('password') try: # check for existing user user = User.query.filter( or_(User.username == username, User.email == email)).first() if not user: # add new user to db new_user = User(username=username, email=email, password=password) db.session.add(new_user) db.session.commit() # generate auth token auth_token = new_user.encode_auth_token(new_user.id) response_object = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return jsonify(response_object), 201 else: response_object = { 'status': 'error', 'message': 'Sorry. That user already exists.' } return jsonify(response_object), 400 # handler errors except (exc.IntegrityError, ValueError) as e: db.session().rollback() response_object = {'status': 'error', 'message': 'Invalid payload.'} return jsonify(response_object), 400
def authenticate_user(): try: data = request.get_json() if data.get('email'): current_user = User.find_by_email(data['email']) elif data.get('username'): current_user = User.find_by_username(data['username']) else: # TODO: raise exception pass if not current_user: return response_with(resp.SERVER_ERROR_404) if current_user and not current_user.isVerified: return response_with(resp.BAD_REQUEST_400) if User.verify_hash(data['password'], current_user.password): access_token = create_access_token(identity=current_user.username, expires_delta=False) refresh_token = create_refresh_token( identity=current_user.username, expires_delta=False) return response_with(resp.SUCCESS_200, value={ 'message': f'Logged in as {current_user.username}', 'access_token': access_token, 'refresh_token': refresh_token }) else: return response_with(resp.UNAUTHORIZED_401) except Exception as ex: logging.error(f"Intercepted Exception: {ex}") return response_with(resp.INVALID_INPUT_422)
def add_user(resp): if not is_admin(resp): response_object = { 'status': 'error', 'message': 'You do not have permission to do that.' } return jsonify(response_object), 401 post_data = request.get_json() if not post_data: response_object = { 'status': 'fail', 'message': 'Invalid payload.' } return jsonify(response_object), 400 username = post_data.get('username') email = post_data.get('email') password = post_data.get('password') try: user = User.query.filter_by(email=email).first() if not user: db.session.add(User( username=username, email=email, password=password)) db.session.commit() response_object = { 'status': 'success', 'message': 'was added!' } return jsonify(response_object), 201 else: response_object = { 'status': 'fail', 'message': 'Sorry. That email already exists.' } return jsonify(response_object), 400 except (exc.IntegrityError, ValueError) as e: db.session().rollback() response_object = { 'status': 'fail', 'message': 'Invalid payload.' } return jsonify(response_object), 400
def decorated_function(*args, **kwargs): response_object = { 'status': 'error', 'message': 'Something went wrong. Please contact us.' } code = 401 auth_header = request.headers.get('Authorization') if not auth_header: response_object['message'] = 'Provide a valid auth token.' code = 403 return jsonify(response_object), code auth_token = auth_header.split(" ")[1] resp = User.decode_auth_token(auth_token) if isinstance(resp, str): response_object['message'] = resp return jsonify(response_object), code user = User.query.filter_by(id=resp).first() if not user or not user.active: return jsonify(response_object), code return f(resp, *args, **kwargs)
def add_user(): post_data = request.get_json() if not post_data: response_object = {'status': 'fail', 'message': 'Invalid payload.'} app.logger.error('POST /api/users' + ' invalid post payload') return jsonify(response_object), 400 name = post_data.get('name') email = post_data.get('email') password = post_data.get('password') try: user = User.query.filter_by(email=email).first() if not user: password = password.encode('utf-8') hashed = bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8') user = User(name=name, email=email, password=hashed) db.session.add(user) db.session.commit() token = jwt.encode( { 'name': user.name, 'email': user.email, 'id': user.id }, super_secret, algorithm='HS256').decode('utf-8') print(token) response_object = {'status': 'success', 'token': token} app.logger.info('POST /api/users' + ' user created successfully') return jsonify(response_object), 201 else: app.logger.warning('POST /api/users' + ' user exists with that account') return jsonify( {"email": "An account already exists for that email"}), 404 except exc.IntegrityError as e: db.session.rollback() app.logger.error('POST /api/users' + ' ' + str(e)) return jsonify({"success": False, "errors": str(e)}), 400
def add_user(name, email, hashed): user = User(name=name, email=email, password=hashed) db.session.add(user) db.session.commit() return user
def create_user(): """ Create user endpoint --- parameters: - in: body name: body schema: id: UserSignup required: - username - password - email properties: username: type: string description: Unique username of the user default: "John Doe" password: type: string description: Password of the user default: "something strong" email: type: string description: email of the user default: "*****@*****.**" responses: 201: description: User successfully created schema: id: UserSignUpSchema properties: code: type: string 422: description: Invalid input arguments schema: id: invalidInput properties: code: type: string message: type: string """ try: data = request.get_json() ## user already defined if User.find_by_email(data['email']) is not None or \ User.find_by_username(data['username']) is not None: return response_with(resp.INVALID_INPUT_422) ## ok user does not yet exist data['password'] = User.generate_hash(data['password']) user_schema = UserSchema() user = user_schema.load(data) token = generate_verification_token(data['email']) verif_email = url_for('user_routes.verify_email', token=token, _external=True) html = render_template_string( "<p>Welcome! Thanks for signing up.Please follow this link to activate your account:</p> <p><a href='{{ verif_email }}'>{{ verif_email }}</a></p> <br /> <p>Thank you</p>", verification_email=verif_email) subject = "Please Verify your email" curr_env = current_app.config['ENV'] if curr_env != 'development' and curr_env != 'testing': send_email(user.email, subject, html) else: logging.error(f"email: {user.email}, subject: {subject}") logging.error(html) logging.error(verif_email) result = user_schema.dump(user.create()) return response_with(resp.CREATED_201) except Exception as ex: logging.error(f"Intercepted Exception: {ex}") return response_with(resp.INVALID_INPUT_422)