Example #1
0
from datetime import timedelta

from flask import abort
from flask_restx import Namespace, Resource, fields
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_refresh_token_required
from marshmallow import ValidationError

from models.user_model import User, UserSchema
from models.user_roles_model import UserRole, UserRoleSchema
from user_functions.user_role_manager import UserPrivilege

api = Namespace('login', description='Log in')

user_schema = UserSchema()
users_schema = UserSchema(many=True)
user_role_schema = UserRoleSchema()

my_user_model = api.model('Login', {
    'id_no': fields.Integer(required=True, description='ID Number'),
    'password': fields.String(required=True, description='Password')

})


@api.route('')
class Login(Resource):
    @api.doc('login_user')
    @api.expect(my_user_model)
    def post(self):
        '''Log in user'''
Example #2
0
from datetime import timedelta

from flask_restx import Namespace, Resource, fields
from werkzeug.security import generate_password_hash
from flask_jwt_extended import create_access_token, create_refresh_token
from flask import abort
from marshmallow import ValidationError

from models.user_model import User, UserSchema
from models.user_roles_model import UserRole, UserRoleSchema
from user_functions.user_role_manager import UserPrivilege

api = Namespace('signup', description='Sign up')

user_schema = UserSchema()
user_role_schema = UserRoleSchema()

user_model = api.model(
    'SignUp', {
        'email': fields.String(required=True, description='Email'),
        'id_no': fields.Integer(required=True, description='id_no'),
        'full_name': fields.String(required=True, description='Full Name'),
        'country_code': fields.Integer(required=True,
                                       description='Country Code'),
        'phone': fields.Integer(required=True, description='phone'),
        'password': fields.String(required=True, description='Password')
    })


@api.route('')
class Register(Resource):
Example #3
0
    def create_user():
        name = request.json.get('name')
        email = request.json.get('email')
        password = request.json.get('password')
        confirm_password = request.json.get('confirm_password')
        account_type = request.json.get('account_type')
        mentor_id = request.json.get('mentor_id')
        phone_number = request.json.get('phone_number')
        portfolio = request.json.get('portfolio')
        status = check_client(account_type, "pending")
        user_id = request.json.get('id')
        mentor_check = request.json.get('is_mentor')
        rg = request.json.get('rg')
        cpf = request.json.get('cpf')
        services = request.json.get('services')

        if not name:
            return jsonify({"data": {"msg": "Nome é obrigatório"}}), 400
        elif not email:
            return jsonify({"data": {"msg": "E-mail obrigatório"}}), 400
        elif not password:
            return jsonify({"data": {"msg": "Senha é obrigatório"}}), 400
        elif not confirm_password:
            return jsonify(
                {"data": {
                    "msg": "Confirmação de senha é obrigatório"
                }}), 400
        elif not account_type:
            return jsonify({"data": {
                "msg": "Tipo de conta é obrigatório"
            }}), 400
        elif not phone_number:
            return jsonify({"data": {"msg": "Telefone é obrigatório"}}), 400
        elif not mentor_id and account_type == "pro" and status == "pending":
            return jsonify({"data": {"msg": "Selecione um mentor"}}), 400
        elif account_type == "pro" and services == "[]":
            return jsonify(
                {"data": {
                    "msg": "Lista de serviços é obrigatório"
                }}), 400

        #validation
        #name
        email_pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
        url_pattern = r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$'

        if len(name) < 7:
            return jsonify(
                {"data": {
                    "msg": "Seu nome deve ter mais de 6 letras"
                }}), 400
        elif not re.match(email_pattern, email):
            return jsonify({"data": {"msg": "E-mail inválido"}}), 400
        elif phone_number and len(phone_number) < 11:
            return jsonify({"data": {
                "msg": "Número de telefone inválido"
            }}), 400
        elif len(password) < 8:
            return jsonify(
                {"data": {
                    "msg": "Sua senha deve ter mais de 8 dígitos"
                }}), 400
        elif not re.search('[a-zA-Z]', password):
            return jsonify({
                "data": {
                    "msg": "Sua senha deve conter pelo menos uma letra"
                }
            }), 400
        elif not re.search('[0-9]', password):
            return jsonify({
                "data": {
                    "msg": "Sua senha deve conter pelo menos um número"
                }
            }), 400
        elif password != confirm_password:
            return jsonify({"data": {"msg": "Senhas não coincidem"}}), 400
        elif portfolio and not re.match(url_pattern, portfolio):
            return jsonify({"data": {
                "msg": "Link do portfólio inválido"
            }}), 400
        elif cpf and len(cpf) != 11:
            return jsonify({"data": {"msg": "CPF inválido"}}), 400
        elif rg and len(rg) != 9:
            return jsonify({"data": {"msg": "RG inválido"}}), 400

        hashed_pass = bcrypt.hashpw(password.encode('utf-8'),
                                    bcrypt.gensalt(10))
        mentor_data = mentor_id

        if user_id:
            admin = db.session.query(User).filter_by(id=user_id).first()
            mentor_data = admin.id

            if admin.account_type == "admin" or admin.account_type == "mentor" and mentor_check == True:
                account_type = "mentor"
                status = "approved"
            elif admin.account_type == "admin" or admin.account_type == "mentor" and mentor_check == False:
                account_type = "pro"
                status = "approved"

        new_user = User(name, email, hashed_pass, account_type, mentor_data,
                        phone_number, check_client(account_type, portfolio),
                        check_client(account_type, "Amador"), 5,
                        check_client(account_type, 1),
                        check_client(account_type, 1),
                        check_client(account_type, 1),
                        check_client(account_type, 1),
                        check_client(account_type, 1),
                        check_client(account_type, 1),
                        check_client(account_type, 1), None, None,
                        request.json.get('rg'), request.json.get('cpf'),
                        time.time(), time.time(), None, status,
                        check_client(account_type, services))

        try:
            db.session.add(new_user)
            db.session.commit()
        except:
            db.session.close()
            return jsonify(
                {"data": {
                    "msg": "Este E-mail já esta sendo utilizado"
                }}), 400

        json = UserSchema(strict=True).dump(new_user).data

        images = Avatar(json['id'], None, None)
        db.session.add(images)
        db.session.commit()

        data = {
            "id": json['id'],
            "name": json['name'],
            "email": json['email'],
            "account_type": json['account_type'],
            "phone_number": json['phone_number'],
            "mentor_id": json['mentor_id'],
            "portfolio": json['portfolio'],
            "phone_number": json['phone_number'],
            "avatar_name": json['avatar_id'],
            "banner_name": json['banner_id'],
            "rg": json['rg'],
            "cpf": json['cpf'],
            "created_at": json['created_at'],
            "updated_at": json['updated_at'],
            "about_me": json['about_me'],
            "status": json['status'],
            "services": json['services'],
            "ratings": {
                "general":
                json['rating_general'],
                "pro":
                json['rating_pro'],
                "events": [
                    {
                        'rating': json['evt_rating_birthday'],
                        'label': "Aniversário"
                    },
                    {
                        'rating': json['evt_rating_civil'],
                        'label': "Civil"
                    },
                    {
                        'rating': json['evt_rating_baptism'],
                        'label': "Batizado"
                    },
                    {
                        'rating': json['evt_rating_essay'],
                        'label': "Ensaio"
                    },
                    {
                        'rating': json['evt_rating_wedding'],
                        'label': "Casamento"
                    },
                    {
                        'rating': json['evt_rating_corp'],
                        'label': "Corporativo"
                    },
                    {
                        'rating': json['evt_rating_debut'],
                        'label': "Debutante"
                    },
                ]
            }
        }

        db.session.close()
        return jsonify({"data": data})
Example #4
0
        res = DeviceService().manager(data)

        if res["valid"]:
            return make_response(True, res["info"], res['code'])

        return make_response(False, res["info"], res['code'])

    return make_response(False, "Not valid API KEY", 400)


def make_response(is_valid, info, error_code):
    """
    Make response for the client

    :param is_valid: The success of the operation
    :param info: Some information
    :param error_code: HTMl error code
    :return: JSON
    """

    return jsonify({'valid': is_valid, 'info': info}), error_code


if __name__ == "__main__":
    DeviceSchema()
    OctoPrintSchema()
    UserSchema()

    app.run(host='0.0.0.0', debug=True)  # For development
    # serve(app, port=5000, threads=6)