def post(self): """POST method for user login Returns: tuple: Success response with 200 status code """ request_data = request.get_json() user, is_authenticated = User.authenticate( email=request_data.get('email'), password=request_data.get('password')) user_schema = UserSchema(exclude=['password', 'confirm_password']) if user and is_authenticated: return { 'status': 'success', 'message': SUCCESS_MESSAGES['USER_LOGIN'], 'data': { 'token': user.token, 'user': user_schema.dump(user).data } }, 200 else: return { 'status': 'fail', 'message': ERROR_MESSAGES['USER_LOGIN'], 'error': ERROR_MESSAGES['INVALID_LOGIN_CREDENTIALS'] }, 401
def create_user(): try: data = request.get_json() 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) data["password"] = User.generate_hash(data["password"]) user_schema = UserSchema() user = user_schema.load(data) token = generate_verification_token(data["email"]) verification_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='{{ verification_email }}'>{{ verification_email }}</a></p> <br> <p>Thanks!</p>", verification_email=verification_email, ) subject = "Please verify your email." send_email(to=user.email, subject=subject, template=html) result = user_schema.dump(user.create()) return response_with(resp.SUCCESS_201, value={"user": result}) except IntegrityError: return response_with(resp.INVALID_INPUT_422, message="User already registered.") except Exception as e: print(e) return response_with(resp.INVALID_INPUT_422)
def post(self): """ Endpoint to create the user """ request_data = request.get_json() UserValidators.validate(request_data) request_data = request_data_strip(request_data) bytes_password = bytes(request_data['password'], encoding='utf-8') hashed = bcrypt.hashpw(bytes_password, bcrypt.gensalt(10)) request_data['password'] = hashed.decode('utf-8') new_user = User(**request_data) new_user.save() user_schema = UserSchema() user_data = user_schema.dump(new_user) send_email(user_data, 'Confirmation Email', 'confirmation_email.html') return { 'status': 'success', 'message': 'User successfully created. Please check your email to continue.' }, 201
async def get(self, request: Request) -> HTTPResponse: """ Resource for get all users """ schema = UserSchema(many=True) users = await UserModel.find(sort="name") return json(schema.dump(users.objects))
def admin_auth_header(init_db, new_admin): """ Admin auth header fixture """ new_admin.save() user_schema = UserSchema() user_data = user_schema.dump(new_admin) token = generate_auth_token(user_data) return {'Authorization': token, 'Content-Type': 'application/json'}
def test_user_schema_has_user_role_by_default(app): with app.app_context(): schema = UserSchema() user = schema.load( {"first": "Emmy", "last": "Noether", "email": "*****@*****.**"} ) assert user["roles"] == [{"name": "user"}]
def admin_auth_header(init_db, admin_user): """ admin auth header fixture """ admin_user.save() user_schema = UserSchema() token = generate_auth_token(user_schema.dump(admin_user)['id']) return { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }
def user_auth_header(init_db, new_user): """ user auth header fixture """ new_user.save() new_user.update({'is_verified': True}) user_schema = UserSchema() token = generate_auth_token(user_schema.dump(new_user)['id']) return { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }
def decorated(*args, **kwargs): decoded_token = request.decoded_token current_user = User.find_by_id(decoded_token['user']['id']) user_schema = UserSchema() user_data = user_schema.dump(current_user) if not user_data['is_admin']: message = 'Permission denied. You are not authorized to perform this action' error_response['message'] = message return error_response, 403 return f(*args, **kwargs)
def updateLastLogin(uid): user = User.getUser(user_id=uid) if user: user.last_login_ip = request.environ['REMOTE_ADDR'] user.last_login_date = datetime.utcnow() user.save_to_db() return jsonify(UserSchema().dump(user).data)
def post(self): """ Endpoint to request password reset link """ request_data = request.get_json() email = request_data['email'] user = User.find_by_email(email) if not user: error_response['message'] = 'User not found' return error_response, 404 user_schema = UserSchema() send_email(user_schema.dump(user), 'Password Reset Request', 'password_reset_email.html') return { 'status': 'success', 'message': 'Request successfully submitted. Please check your email to continue.' }, 200
def post(self): """ Endpoint to login the user """ request_data = request.get_json() email = request_data['email'] password = bytes(request_data['password'], encoding='utf-8') user = User.query.filter(User.email == email, User.is_activated).first() error_response['message'] = 'Incorrect username or password' user_schema = UserSchema() if user: user_data = user_schema.dump(user) hashed = bytes(user_data['password'], encoding='utf-8') if bcrypt.checkpw(password, hashed): user_schema = UserSchema(exclude=['password']) logged_in_user = user_schema.dump(user) token = generate_auth_token(logged_in_user) success_response['message'] = 'User successfully logged in' success_response['data'] = { 'token': token, 'user': logged_in_user } return success_response, 200 return error_response, 404 return error_response, 404
def post(self): """POST method for user signup Returns: tuple: Success response with 201 status code """ request_data = request.get_json() user_schema = UserSchema() user_data = user_schema.load_object_into_schema(request_data) user = User(**user_data) user.save() return { 'status': 'success', 'message': SUCCESS_MESSAGES['USER_SIGNUP'], 'data': { 'token': user.token, 'user': user_schema.dump(user).data } }, 201
class NoteSchema(ma.SQLAlchemySchema): class Meta: model = NoteModel id = ma.auto_field() text = ma.auto_field() private = ma.auto_field() author = ma.Nested(UserSchema()) tags = ma.Nested(TagSchema(many=True)) _links = ma.Hyperlinks({ 'self': ma.URLFor('noteresource', values=dict(note_id="<id>")), 'collection': ma.URLFor('noteslistresource') })
from flask import request, jsonify, make_response, g from flask_restful import Resource from api.models.user import UserModel from api.models.blog_news import BlogNewsStory, BlogNewsStoryComment from api.schemas.user import (UserSchema, UserSigninSchema, UserPasswordUpdateSchema, UsernameSchema) from api.schemas.blog_news import (BlogNewsStorySchema, StoryIdSchema, NewsPaginationSchema) from marshmallow import ValidationError from sqlalchemy_pagination import paginate from sqlalchemy import desc from passlib.hash import argon2 from sqlalchemy.exc import IntegrityError from uuid import uuid4 user_register_schema = UserSchema() users_schema = UserSchema(many=True) user_signin_schema = UserSigninSchema() user_password_schema = UserPasswordUpdateSchema() username_schema = UsernameSchema() blognews_stories_schema = BlogNewsStorySchema(many=True) blognews_story_schema = BlogNewsStorySchema() story_id_schema = StoryIdSchema() news_pagination_schema = NewsPaginationSchema() class UsersResource(Resource): @classmethod def get(cls): """ Getting GET requests on the '/api/users' endpoint, and returning a list
def register_user(): schema = UserSchema() input_data = request.get_json() if 'uid' not in input_data['data']['attributes'].keys(): data, err = schema.load(input_data) if err: return jsonify(err) try: user = auth.create_user( email=data['email'], email_verified=False, password=data['password'], display_name=data['username'], ) except auth.AuthError as e: if e.code == 'USER_CREATE_ERROR': errmsg = 'User with email already exists' return ErrorResponse( FirebaseError(errmsg).message, 422, { 'Content-Type': 'application/json' }).respond() newUser = User(id_=user.uid, username=data['username'], email=user.email, password=data['password']) if user.email in admins: newUser.siteAdmin = True newUser.save_to_db() if newUser.email in admins: perm = Permissions(isUser=True, isAdmin=True, user_permissions=newUser) perm.save_to_db() else: perm = Permissions(isUser=True, user_permissions=newUser) perm.save_to_db() return jsonify(schema.dump(newUser).data) else: schema = OAuthUserSchema() data, err = schema.load(input_data) if err: return jsonify(err) uid = input_data['data']['attributes']['uid'] user_ = User.getUser(user_id=uid) if not user_: newUser = User(id_=uid, username=data['username'], email=data['email'], password=data['password'], photoURL=data['photoURL']) if data['email'] in admins: newUser.siteAdmin = True newUser.save_to_db() if newUser.email in admins: perm = Permissions(isUser=True, isAdmin=True, user_permissions=newUser) perm.save_to_db() else: perm = Permissions(isUser=True, user_permissions=newUser) perm.save_to_db() else: newUser = user_ return jsonify(schema.dump(newUser).data)
from flask_restplus import Resource from flask import request from api.middlewares.base_validator import ValidationError, validate_request from api.models.user import bcrypt from api.utilities.helpers.generate_token import generate_token from api.models import User from api.schemas.user import UserSchema from api.utilities.helpers.response import response from api.utilities.messages.serialization import serialization_messages from api.utilities.messages.success import success_messages from main import flask_api schema = UserSchema() @flask_api.route('/auth/register') class UserSignUpResource(Resource): """ Resource class for carrying out user registration """ @validate_request def post(self): """ An endpoint to register a user """ request_data = request.get_json() user_data = schema.load_object_into_schema(request_data) email = request_data.get('email')
from flask_api import status from api.models import User from api.schemas.user import UserSchema user_schema = UserSchema() def get_users(request_args=None): result = User.query.filter_by(**request_args.to_dict()) return user_schema.jsonify(result) def get_user_by_id(id, request_args=None): # result = User.get(id, **request_args.to_dict()) result = User.query.get(1) return user_schema.jsonify(result) def post_user(request_args=None): pass # try: # user = User(**request_args.to_dict()) # result = user.save() # return result.to_json(), status.HTTP_200_OK # except ValidationError as e: # return str(e), status.HTTP_400_BAD_REQUEST
""" Created on at 7/4/2020 10:46 AM @author: Abhishek Kushwaha """ import os from flask import request, url_for, render_template from flask_restful import Resource from flask_jwt_extended import jwt_optional, get_jwt_identity, jwt_required from http import HTTPStatus from api.utils.mailgun import MailgunApi from api.models.user import User from api.schemas.user import UserSchema from api.utils.utility import generate_token, verify_token user_schema = UserSchema() user_public_schema = UserSchema(exclude=('email', )) mailgun = MailgunApi(domain=os.environ.get('MAILGUN_DOMAIN'), api_key=os.environ.get('MAILGUN_API_KEY')) class Registration(Resource): """ This class will Register the users """ def post(self): json_data = request.get_json() data, errors = user_schema.load(data=json_data)