Пример #1
0
    def get():
        user_info = AuthAccessTokens.objects.filter(
            access_token=request.headers.get('Authorization').split(
                ' ')[1]).aggregate([{
                    "$lookup": {
                        "from":
                        "users",
                        "let": {
                            "userId": "$userid"
                        },
                        "pipeline": [{
                            "$match": {
                                "$expr": {
                                    "$eq": ["$userid", "$$userId"]
                                }
                            }
                        }, {
                            "$project": {
                                "ID": 1,
                                "name": 1,
                                "email": 1
                            }
                        }],
                        "as":
                        "userinfo"
                    }
                }, {
                    "$unwind": "$userinfo"
                }])

        user_data = list(user_info)[0]['userinfo']
        user_data['_id'] = str(user_data['_id'])

        return ResService.created('User Info',
                                  user_data), ResService.created()['status']
Пример #2
0
    def delete(self):
        try:
            AUTH.sign_out()
            return ResService.deleted(
                'Signout Successful!'), ResService.deleted()['status']

        except Exception as err:
            LOG.report(err)
            return ResService.bad_request(), ResService.bad_request()['status']
Пример #3
0
        def __is_client_authenticate(*args, **kwargs):
            if request.authorization:
                iscLient = AuthClients.objects(name=request.authorization.username, secret=request.authorization.password).first()

                if iscLient and 'name' in iscLient and 'secret' in iscLient:
                    result = f(*args, **kwargs)
                    return result
                else:
                    return ResService.not_acceptable('Invalid Request'), ResService.not_acceptable()['status']
            else:
                return ResService.not_acceptable('Invalid Request'), ResService.not_acceptable()['status']
Пример #4
0
        def __is_user_authenticate(*args, **kwargs):
            auth_header = request.headers.get('Authorization')
            if auth_header:
                access_token = auth_header.split(' ')[1]

                user_info = AuthAccessTokens.objects(access_token=access_token).first()
                if user_info:
                    result = f(*args, **kwargs)
                    return result
                else:
                    return ResService.unauthorized('Token Expired'), ResService.unauthorized()['status']
            else:
                return ResService.unauthorized('Invalid Token'), ResService.unauthorized()['status']
Пример #5
0
    def post(self):
        try:
            body = request.form.to_dict(flat=True)

            PostForm = model_form(Users, exclude=['name', 'confirm'])
            form = PostForm(request.form, csrf_enabled=False)

            if request.method == 'POST' and form.validate():
                find_user = Users.objects(email=body['email']).first()

                if find_user:
                    if hashlib.md5(body['password'].encode(
                            'utf-8')).hexdigest() != find_user['password']:
                        return ResService.not_acceptable('Invalid email or password!'), \
                               ResService.not_acceptable()['status']

                    user_info = {
                        'user_info': {
                            'user_id': str(find_user.id),
                            'name': find_user.name,
                            'email': find_user.email
                        }
                    }

                    return ResService.created(
                        'Welcome!',
                        dict(AUTH.generate_tokens(str(find_user['id'])),
                             **user_info)), ResService.created()['status']
                else:
                    return ResService.not_acceptable('You do not have an account on our system with this email!'), \
                           ResService.not_acceptable()['status']
            else:
                errors = form.errors
                return ResService.validation_response(
                    errors), ResService.validation_response()['status']
        except Exception as err:
            LOG.report(err)
            return ResService.bad_request(), ResService.bad_request()['status']
Пример #6
0
    def post(self):
        try:
            body = request.form.to_dict(flat=True)

            PostForm = model_form(Users)
            form = PostForm(request.form, csrf_enabled=False)

            if request.method == 'POST' and form.validate():
                email_exists = Users.objects(email=body['email'])
                if email_exists:
                    return ResService.not_acceptable('This email is already taken for another tutor!'), \
                           ResService.not_acceptable()['status']

                body['password'] = hashlib.md5(
                    body['password'].encode('utf-8')).hexdigest()
                save_data = Users(**body).save()

                if save_data:
                    user_info = {
                        'user_info': {
                            'user_id': str(save_data.id),
                            'name': body['name'],
                            'email': body['email']
                        }
                    }

                    return ResService.created(
                        'Welcome!',
                        dict(AUTH.generate_tokens(str(save_data.id)),
                             **user_info)), ResService.created()['status']
            else:
                errors = form.errors
                return ResService.validation_response(
                    errors), ResService.validation_response()['status']
        except Exception as err:
            LOG.report(err)
            return ResService.bad_request(), ResService.bad_request()['status']
Пример #7
0
    def generate_tokens(user_id):
        try:
            data = {
                'access_token': {
                    'token': (hashpw(
                        str('accessToken').encode('UTF_8') +
                        str(datetime.now()).encode('UTF_8') +
                        user_id.encode('UTF_8'), gensalt())).decode('ascii'),
                    'created_at':
                    datetime.today(),
                    'expired_at':
                    datetime.today() + timedelta(minutes=720)
                },
                'refresh_token': {
                    'token': (hashpw(
                        str('refreshToken').encode('UTF_8') +
                        str(datetime.now()).encode('UTF_8') +
                        user_id.encode('UTF_8'), gensalt())).decode('ascii'),
                    'created_at':
                    datetime.today(),
                    'expired_at':
                    datetime.today() + timedelta(minutes=4320)
                }
            }

            if request.authorization:
                find_client = AuthClients.objects(
                    name=request.authorization.username).first()

                if find_client and ObjectId(find_client['id']):
                    access_token_data = {
                        'access_token': data['access_token']['token'],
                        'client_id': ObjectId(find_client['id']),
                        'user_id': user_id,
                        'expired_at': data['access_token']['expired_at'],
                        'created_at': data['access_token']['created_at']
                    }

                    access_token = AuthAccessTokens(**access_token_data).save()
                    access_token_id = access_token.id
                    if str(access_token_id):
                        refresh_token_data = {
                            'access_token_id': str(access_token_id),
                            'refresh_token': data['refresh_token']['token'],
                            'client_id': find_client['id'],
                            'user_id': user_id,
                            'expired_at': data['refresh_token']['expired_at'],
                            'created_at': data['refresh_token']['created_at']
                        }
                        AuthRefreshTokens(**refresh_token_data).save()

                        return ResService.json_formatter(data)
                    else:
                        return ResService.json_formatter(data)
                else:
                    return ResService.json_formatter(data)
            else:
                return ResService.json_formatter(data)

        except Exception as err:
            LOG.report(err)