class Tag(db.Model):
    __tablename__ = 'tags'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String, nullable=False)

    tag_response_resource_model = v1_api.model('Tags', {'name': fields.String})
Пример #2
0
class Product(db.Model):
    __tablename__ = 'product'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(250))
    price = db.Column(db.Integer, default=0)
    active = db.Column(db.Boolean(), default=False)

    category_id = db.Column(db.Integer, ForeignKey('category.id'))
    category = relationship("Category", back_populates="products")

    product_resource_model = v1_api.model(
        'Product', {
            'id':
            fields.Integer(
                readOnly=True,
                description='The product unique identifier. ReadOnly.'),
            'title':
            fields.String(required=True, description='The product name'),
            'description':
            fields.String(description='Bla bla bla'),
            'price':
            fields.Integer(required=True, description='The price of product'),
            'category_id':
            fields.Integer(attribute='category.id'),
            'category':
            fields.String(attribute='category.title'),
        })
Пример #3
0
class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, ForeignKey('user.id'))
    question = db.Column(db.String(500))
    grade = db.Column(db.Integer(), default=10)

    question_resource_model = v1_api.model('Question', {
        'id': fields.Integer(readOnly=True, description='The question unique identifier. ReadOnly.'),
        'question': fields.String(required=True, description='The question details'),
        'grade': fields.Integer(description='Grade to which question belongs')
    })
Пример #4
0
class Refresh(Resource):
    @auth_ns.expect(v1_api.model(
        'RefreshToken', {'refresh_token': fields.String(required=True)}),
                    validate=True)
    @auth_ns.response(200, 'Success', return_token_model)
    def post(self):
        _refresh_token = v1_api.payload['refresh_token']

        try:
            payload = jwt.decode(_refresh_token,
                                 current_app.config['SECRET_KEY'])

            refresh_token = RefreshToken.query.filter_by(
                user_id=payload['uid'], refresh_token=_refresh_token).first()

            if not refresh_token:
                raise jwt.InvalidIssuerError

            # Generate new pair

            _access_token = jwt.encode(
                {
                    'uid':
                    refresh_token.user_id,
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=15),
                    'iat':
                    datetime.datetime.utcnow()
                }, current_app.config['SECRET_KEY']).decode('utf-8')
            _refresh_token = jwt.encode(
                {
                    'uid': refresh_token.user_id,
                    'exp':
                    datetime.datetime.utcnow() + datetime.timedelta(days=30),
                    'iat': datetime.datetime.utcnow()
                }, current_app.config['SECRET_KEY']).decode('utf-8')

            refresh_token.refresh_token = _refresh_token
            db.session.add(refresh_token)
            db.session.commit()

            return {
                'access_token': _access_token,
                'refresh_token': _refresh_token
            }, 200

        except jwt.ExpiredSignatureError as e:
            raise e
        except (jwt.DecodeError, jwt.InvalidTokenError) as e:
            raise e
        except:
            auth_ns.abort(401, 'Unknown token error')
Пример #5
0
class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, ForeignKey('user.id'))
    task = db.Column(db.String(50))
    done = db.Column(db.Boolean(), default=False)

    todo_resource_model = v1_api.model(
        'Todo', {
            'id':
            fields.Integer(
                readOnly=True,
                description='The task unique identifier. ReadOnly.'),
            'task':
            fields.String(required=True, description='The task details'),
            'done':
            fields.Boolean(description='Bla bla bla')
        })
Пример #6
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50))
    password_hash = db.Column(db.String(80))
    from .auth import RefreshToken
    refresh_tokens = relationship('RefreshToken', backref='user')
    from .question import Question
    questions = relationship('Question', backref='user')

    @property
    def password(self):
        raise AttributeError('Password not readable')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    user_resource_model = v1_api.model(
        'User', {'username': fields.String(required=True)})
Пример #7
0
class Category(db.Model):
    __tablename__ = 'category'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), nullable=False)
    active = db.Column(db.Boolean(), default=True)
    products = relationship("Product", back_populates="category")

    category_resource_model = v1_api.model(
        'Category', {
            'id':
            fields.Integer(
                readOnly=True,
                description='The category unique identifier. ReadOnly.'),
            'title':
            fields.String(required=True, description='The category name'),
        })

    products_resource_model = v1_api.inherit(
        'products resource model', category_resource_model, {
            'products': fields.List(
                fields.Nested(Product.product_resource_model))
        })
Пример #8
0
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(64), nullable=False)
    first_name = db.Column(db.String(64), nullable=False)
    last_name = db.Column(db.String(64), nullable=False)
    uuid = db.Column(db.String(64), nullable=False)
    admin = db.Column(db.Boolean, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow())
    last_updated = db.Column(db.DateTime, default=datetime.utcnow())
    password_hash = db.Column(db.String(128))

    def check_password(self, password):
        return flask_bcrypt.check_password_hash(self.password_hash, password)

    @staticmethod
    def encode_auth_token(user_id):
        """
        Generates the Auth Token
        :return: string
        """
        try:
            payload = {
                "exp": datetime.utcnow() + timedelta(days=1, seconds=5),
                "iat": datetime.utcnow(),
                "sub": user_id,
            }
            return jwt.encode(payload, key, algorithm="HS256")
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        """
        Decodes the auth token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, key)
            is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
            if is_blacklisted_token:
                return "Token blacklisted. Please log in again."
            else:
                return payload["sub"]
        except jwt.ExpiredSignatureError:
            return "Signature expired. Please log in again."
        except jwt.InvalidTokenError:
            return "Invalid token. Please log in again."

    get_user_response_model = v1_api.model(
        "User",
        {
            "uuid": fields.String,
            "email": fields.String,
            "first_name": fields.String,
            "last_name": fields.String,
            "admin": fields.Boolean,
            "created_at": fields.DateTime,
        },
    )

    create_user_response_model = v1_api.model("User", {
        "uuid": fields.String,
    })

    create_user_request_model = v1_api.model(
        "Create User Request Model",
        {
            "email": fields.String,
            "password": fields.String,
            "first_name": fields.String,
            "last_name": fields.String,
        },
    )

    login_user_request_model = v1_api.model("User", {
        "email": fields.String,
        "password": fields.String
    })

    def __repr__(self):
        return "<User '{}'>".format(self.username)
Пример #9
0
# -*- coding: utf-8 -*-
# @Author: guomaoqiu
# @File Name: serial.py
# @Date:   2018-08-18 21:41:37
# @Last Modified by:   [email protected]
# @Last Modified time: 2018-08-24 00:06:51
from app.v1 import v1_api

from flask_restplus import fields, Namespace

register_model = v1_api.model(
    'Register', {
        'email': fields.String(required=True,
                               description='user email address'),
        'username': fields.String(required=True, description='user username'),
        'password': fields.String(required=True, description='user password'),
    })

login_model = v1_api.model(
    'Login', {
        'email': fields.String(required=True,
                               description='user email address'),
        'password': fields.String(required=True, description='user password'),
    })

logout_model = v1_api.model('Logout', {
    'refresh_token':
    fields.String(required=True, description='refresh token'),
})

refresh_token_model = v1_api.model('RefeshToken', {
class Source(db.Model):
    __tablename__ = 'sources'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(128), nullable=False)
    description = db.Column(db.Text, nullable=False)
    link = db.Column(db.String(512), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow())
    last_updated = db.Column(db.DateTime, default=datetime.utcnow())
    user_id = db.Column(db.Integer)
    tags = db.relationship('Tag',
                           secondary=source_tag,
                           backref=db.backref('source_tags', lazy='dynamic'))

    get_sources_response_resource_model = v1_api.model(
        'Sources', {
            'id': fields.Integer,
            'name': fields.String,
            'description': fields.String,
            'link': fields.String,
            'tags': fields.List(fields.Nested(
                Tag.tag_response_resource_model)),
            'created_at': fields.DateTime,
            'last_updated': fields.DateTime
        })

    get_source_by_id_response_model = v1_api.model(
        'Source', {
            'id': fields.Integer,
            'name': fields.String,
            'description': fields.String,
            'link': fields.String,
            'tags': fields.List(fields.Nested(
                Tag.tag_response_resource_model)),
            'created_at': fields.DateTime,
            'last_updated': fields.DateTime
        })

    create_source_request_resource_model = v1_api.model(
        'Create new source request model', {
            'name': fields.String,
            'description': fields.String,
            'link': fields.String,
            'tags': fields.List(fields.Nested(
                Tag.tag_response_resource_model)),
        })

    create_source_response_resource_model = v1_api.model(
        'Create new source response model', {
            'id': fields.Integer,
            'name': fields.String
        })

    delete_source_response_model = v1_api.model('Delete source response model',
                                                {'id': fields.Integer})

    update_source_response_model = v1_api.model(
        'Update source response model', {
            'id': fields.Integer,
            'last_updated': fields.DateTime
        })

    def __repr__(self):
        return f'<{__name__}.{__class__} id: {self.id}>'
Пример #11
0
from flask import current_app, request
from flask_restplus import Resource, Namespace, fields
from ..models.user import User
from ..models.auth import RefreshToken
from app import db
from app.v1 import v1_api
from ..exceptions import ValidationException
import re
import jwt
import datetime
import hashlib

auth_ns = Namespace('auth')

register_model = v1_api.model('Register', {
    'username': fields.String(required=True),
    'password': fields.String(required=True)
})

return_token_model = v1_api.model('ReturnToken', {
    'access_token': fields.String(required=True),
    'refresh_token': fields.String(required=True)
})


@auth_ns.route('/register')
class Register(Resource):
    # 4-16 symbols, can contain A-Z, a-z, 0-9, _ (_ can not be at the begin/end and can not go in a row (__))
    USERNAME_REGEXP = r'^(?![_])(?!.*[_]{2})[a-zA-Z0-9._]+(?<![_])$'

    # 6-64 symbols, required upper and lower case letters. Can contain !@#$%_  .
    PASSWORD_REGEXP = r'^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])[\w\d!@#$%_]{6,64}$'
Пример #12
0
# -*- coding: utf-8 -*-
# @Author: guomaoqiu
# @File Name: serial.py
# @Date:   2018-08-18 21:41:37
# @Last Modified by:   [email protected]
# @Last Modified time: 2018-08-24 00:11:29
from app.v1 import v1_api

from flask_restplus import fields, reqparse

user_put_model = v1_api.model(
    'DeleterUserRequired', {
        'email': fields.String(required=True,
                               description='user email address'),
        'username': fields.String(required=True, description='user username'),
        'password': fields.String(required=True, description='user password'),
    })

get_user_fields = v1_api.model(
    'user', {
        'email':
        fields.String(required=True, description='user email address'),
        'user_role':
        fields.String(required=True, description='user user_role'),
        'is_active':
        fields.String(required=True, description='user is_active'),
        'mobile':
        fields.String(required=True, description='user mobile'),
        'about_me':
        fields.String(required=True, description='user info'),
        'public_id':