示例#1
0
def save_user(): 
    form = UserForm()
    service = UserService()
    if form.is_submitted():
        _id = service.save_user(form.raw_inputs, form.mode)
        if _id is not None:
            return jsonify({'id':str(_id)})
        else:
            return jsonify({'id':''})
    else:
        return jsonify({'id':''})
示例#2
0
def login():
    '''When a user logs in, their session is marked as 'fresh'.
    '''
    form = LoginForm()
    if form.errors == []:
        service = UserService()
        ret = service.login(form.account, form.password, form.remember_me)
        # flash('Logged in successfully!')
        return jsonify({'error':str(ret)})
    else:  # If input has error
        return jsonify({'error':str(form.errors[0])})
示例#3
0
def token_verify(token):
    secret_key = current_app.config.get('SECRET_KEY')
    try:
        data = jwt.decode(token, secret_key, algorithm='HS256')
        return UserService.instance().get_one_or_fail(data['id'])
    except jwt.DecodeError:
        return False
示例#4
0
class UserFriendsView(HTTPMethodView):
    user_repository = UserRepository(MySQLConnection)
    user_service = UserService(user_repository)

    friend_repository = FriendRepository(MySQLConnection)
    friend_service = FriendService(friend_repository)

    @doc.summary('Get friends of user')
    @doc.produces({'friends': [Friend]}, description='Friends of user')
    async def get(self, request, username: str):
        user = await self.user_service.get(username)
        return json(
            {'friends': await self.friend_service.get_all(user['seq'])})

    @doc.summary('Create friend relationship of ')
    @doc.consumes(FriendCreation,
                  content_type='application/json',
                  location='body',
                  required=True)
    async def post(self, request, username: str):
        user = await self.user_service.get(username)
        if user['seq'] != request.json['user_id']:
            abort(403)

        await self.friend_service.create(request.json)
class UserFriendRequestDetailView(HTTPMethodView):
    user_repository = UserRepository(MySQLConnection)
    user_service = UserService(user_repository)

    friend_request_repository = FriendRequestRepository(MySQLConnection)
    friend_request_service = FriendRequestService(friend_request_repository)

    @doc.summary('Get friend request')
    @doc.produces({'request': FriendRequest},
                  description='Request for the friend_request_id',
                  content_type='application/json')
    async def get(self, request, username: str, friend_request_id: int):
        user = await self.user_service.get(username)
        friend_request = await self.friend_request_service.get(
            friend_request_id)

        if user['seq'] != friend_request_id['recipient']:
            abort(403)

        return json({'request': friend_request})

    @doc.summary('Delete the friend request')
    async def delete(self, request, username: str, friend_request_id: int):
        user = await self.user_service.get(username)
        friend_request = await self.friend_request_service.get(
            friend_request_id)

        if user['seq'] != friend_request['recipient']:
            abort(403)

        await self.friend_request_service.delete(friend_request_id)
示例#6
0
class User:
    def __init__(self):
        self.user_service = UserService()

    def on_post(self, req, resp):
        """crea un usuario para el sistema con su rol"""
        try:
            result = self.user_service.create(req.context['data'],
                                              self.session)
            resp.status = falcon.HTTP_201  # This is the default status
            resp.context['result'] = response_ok(result, "ok", 'created',
                                                 'post', req.path)
        except ValidationError as err:
            resp.status = falcon.HTTP_400
            resp.context['result'] = response_error(err.messages,
                                                    str("Validation Error"),
                                                    'post', req.path)
        except SerializerException as exc:
            resp.status = falcon.HTTP_500
            resp.context['result'] = response_error(
                {}, "Internal Error. Contact the Admin.", 'post', req.path)
        except Exception as exc:
            resp.status = falcon.HTTP_400
            resp.context['result'] = response_error({}, str(exc), 'post',
                                                    req.path)
class UserFriendRequestView(HTTPMethodView):
    user_repository = UserRepository(MySQLConnection)
    user_service = UserService(user_repository)

    friend_request_repository = FriendRequestRepository(MySQLConnection)
    friend_request_service = FriendRequestService(friend_request_repository)

    @doc.summary('Get friend requests to the user')
    @doc.produces({'requests': [FriendRequest]},
                  description='Requests to the user',
                  content_type='application/json')
    async def get(self, request, username: str):
        user = await self.user_service.get(username)
        return json({
            'requests':
            await self.friend_request_service.get_all(user['seq'])
        })

    @doc.summary('Create friend request')
    @doc.consumes(FriendRequestCreation,
                  location='body',
                  content_type='application/json')
    async def post(self, request, username: str):
        user = await self.user_service.get(username)
        if user['seq'] != request.json['sender']:
            abort(403)

        await self.friend_request_service.create(request.json)
示例#8
0
def auth_login(email: fields.Email(), password: fields.String()):
    user = UserService.instance().login(email, password)

    if not user:
        raise HTTPBadRequest("login", "failed")

    token_data = dict(id=user.id)
    return {"token": token_generate(token_data)}
示例#9
0
class UserInformationView(HTTPMethodView):
    repository = UserRepository(MySQLConnection)
    service = UserService(repository)

    @doc.summary('Get user information')
    @doc.produces(User, description='User of the username', content_type='application/json')
    async def get(self, request, username: str):
        user = await self.service.get(username)
        del user['seq']
        del user['user_id']
        return json(user)
class UserSignupView(HTTPMethodView):
    repository = UserRepository(MySQLConnection)
    service = UserService(repository)

    @doc.summary('Register account')
    @doc.consumes(
        UserRegistration,
        location='body',
        content_type='application/json',
        required=True)
    @doc.produces({'success': bool}, description='the result of account registration', content_type='application/json')
    async def post(self, request: Request):
        await self.service.create(request.json)
        return json({
            'success': True
        })
    class UserFieldGetterView(HTTPMethodView):
        repository = UserRepository(MySQLConnection)
        service = UserService(repository)

        field_name: str = getter_field
        field_type: type = getter_field_type

        @doc.summary(f'Get {field_name} of user')
        @doc.produces({getter_field: getter_field_type},
                      content_type='application/json',
                      description=f'The value of {getter_field} field')
        async def get(self, request, username: str):
            field_name = self.field_name
            if field_name not in self.repository.patchable_fields:
                abort(404)
            user = await self.service.get(username)
            return json({field_name: user[field_name]})
class UserSigninView(HTTPMethodView):
    repository = UserRepository(MySQLConnection)
    service = UserService(repository)

    @doc.summary('Authenticate account')
    @doc.consumes(UserAuthentication,
                  location='body',
                  content_type='application/json',
                  required=True)
    @doc.produces({'success': bool},
                  description='the result of account authentication',
                  content_type='application/json')
    async def post(self, request: Request):
        user = await self.service.get(request.json['username'])
        return json({
            'success':
            check_password_hash(user['password'], (request.json['password']))
        })
示例#13
0
文件: app.py 项目: steventt07/Buzz
def start_service():
    service = Service()
    add_post_service = AddPostService(service)
    remove_post_service = RemovePostService(service)
    feed_service = FeedService(service)
    category_service = CategoryService(service)
    vote_service = VoteService(service)
    comment_service = CommentService(service)
    user_service = UserService(service)
    user_liked_post_service = UserLikedPostService(service)
    email_validation_service = EmailValidationService(service)

    app = falcon.API(middleware=[HandleCORS()])
    app.add_route('/add_post_to_category', add_post_service)
    app.add_route('/remove_post_from_category', remove_post_service)
    app.add_route('/feed', feed_service)
    app.add_route('/category', category_service)
    app.add_route('/vote', vote_service)
    app.add_route('/comment', comment_service)
    app.add_route('/user', user_service)
    app.add_route('/user_liked_post', user_liked_post_service)
    app.add_route('/email_validation', email_validation_service)
    return app
示例#14
0
    class UserPatchView(HTTPMethodView):
        repository = UserRepository(MySQLConnection)
        service = UserService(repository)

        field_name: str = patch_field
        field_type: type = patch_field_type

        @doc.summary(f'Get {field_name} of user')
        @doc.produces({patch_field: patch_field_type},
                      content_type='application/json',
                      description=f'The value of {patch_field} field')
        async def get(self, request, username: str):
            field_name = self.field_name
            if field_name not in self.repository.patchable_fields:
                abort(404)
            user = await self.service.get(username)
            return json({field_name: user[field_name]})

        @doc.summary(f'Patch {field_name} of user')
        @doc.consumes({'patch_data': {
            patch_field: patch_field_type
        }},
                      location="body",
                      content_type='application/json')
        @doc.produces({'success': bool},
                      description='Result of the patch',
                      content_type='application/json')
        async def put(self, request, username: str):
            field_name = self.field_name
            if field_name not in self.service.patchable_fields:
                abort(403)
            user = await self.service.get(username)
            await self.repository.patch(
                username,
                {field_name: user[field_name] + request.json[field_name]})
            return json({'success': True})
示例#15
0
 def __init__(self):
     self.user_service = UserService()
示例#16
0
 def __init__(self, user_id: int) -> None:
     self.user_svc = UserService()
     self.user_id = user_id
     cur_validators = self.user_svc.get_all_validators(user_id)
     self.indices = [validator.indice for validator in cur_validators]
示例#17
0
def user_info():
    s = UserService()
    s.get_info()
    return s.render()
示例#18
0
def edit_user():
    payload = request.json
    user_svc = UserService()
    user_svc.update(current_identity.id, payload)
    return {'code': HTTPStatus.OK}
示例#19
0
def register():
    payload = request.json
    user_svc = UserService()

    user_svc.create(payload)
    return {'code': HTTPStatus.CREATED}
示例#20
0
class ValidatorService:
    def __init__(self, user_id: int) -> None:
        self.user_svc = UserService()
        self.user_id = user_id
        cur_validators = self.user_svc.get_all_validators(user_id)
        self.indices = [validator.indice for validator in cur_validators]

    def create(self, indices: List[str]) -> List[ValidatorDT]:
        resp = requests.get(f'{config.BEACON_RPC_URI}/validators',
                            params={'indices': indices})
        resp = resp.json()
        index_to_pubkey = {}
        for val in resp['validatorList']:
            index_to_pubkey[val['index']] = b64_to_hex(
                val['validator']['publicKey'])
        validators_to_add = [
            Validator(indice=i,
                      pubkey=index_to_pubkey[i],
                      user_id=self.user_id) for i in indices
        ]
        with SessionManager.session() as session:
            session.add_all(validators_to_add)

        return [ValidatorDT.from_model(m) for m in validators_to_add]

    def remove(self, indice: str) -> None:
        with SessionManager.session() as session:
            session.query(Validator).filter_by(
                indice=indice,
                user_id=self.user_id).delete(synchronize_session=False)

    def get(self) -> List[ValidatorDT]:
        with SessionManager.session() as session:
            rows = session.query(Validator).filter_by(
                user_id=self.user_id).all()

        return [ValidatorDT.from_model(m) for m in rows]

    def info(self) -> Dict:
        """Retrieve a validator total balance, balance over time,
        avg rating and rating per index.
        """
        activation_epoch = self._get_activation_epoch()
        balances = self._get_balance(activation_epoch)
        validator_perf = self._get_validator_performance(activation_epoch)
        balance_overtime = self._get_balance_ovetime(activation_epoch,
                                                     balances['total'])

        info_validator = {}
        for i in self.indices:
            info_validator[i] = {
                'balance': balances['validators'][i],
                'rating': validator_perf['validators'][i],
            }

        return {
            'global': {
                'balance': balances['total'],
                'rating': validator_perf['avg'],
                'overtime': balance_overtime,
            },
            'validators': info_validator,
        }

    def _get_balance_ovetime(self, activation_epoch: Dict[str, str],
                             total_balance: str) -> Dict[str, str]:
        num_validators = len(activation_epoch)
        cur_epoch = int(self._get_current_epoch())
        earliest_epoch = cur_epoch
        overtime = {}
        for epoch in activation_epoch.values():
            if int(epoch) < int(earliest_epoch):
                earliest_epoch = int(epoch)

        if cur_epoch == earliest_epoch:
            increment = int(cur_epoch) // 6
            step = 0
            for _ in range(6):
                overtime[step] = 0
                step += increment
            return overtime

        for _ in range(6):
            distance_epoch = cur_epoch - earliest_epoch
            increment = int(distance_epoch) // 6
            balance_increment = (float(total_balance) -
                                 (num_validators * 32.00)) / 6

            step = earliest_epoch
            step_balance = 32 * num_validators
            for _ in range(6):
                overtime[step] = step_balance
                step_balance += balance_increment
                step += increment
            return overtime

    def _get_validator_performance(self, activation_epoch: Dict[str,
                                                                str]) -> Dict:
        """GET eth/v1alpha1/validators/performance
        Retrieve the inclusion distance for each validators assigned to current_user
        """
        cur_epoch = int(self._get_current_epoch())
        filter_active_indices = [
            i for i in self.indices
            if int(activation_epoch[i]) <= int(cur_epoch)
        ]
        if len(filter_active_indices) == 0:
            return {i: '?' for i in self.indices}
        resp = requests.get(f'{config.BEACON_RPC_URI}/validators/performance',
                            params={'indices': self.indices})
        resp = resp.json()
        validator_perf = {i: '?' for i in self.indices}
        sum_distance = 0
        for n, inclusion_dist in enumerate(resp['inclusionDistances']):
            distance_int = int(inclusion_dist)
            validator_perf[filter_active_indices[n]] = distance_int
            sum_distance += distance_int
        avg_perf = int(round(sum_distance // len(filter_active_indices)))
        return {'validators': validator_perf, 'avg': avg_perf}

    def _get_balance(self, activation_epoch: Dict[str, str]) -> Dict:
        """GET eth/v1alpha1/validator/balances
        Retrieve:
        a) the overall balance for all validators assigned to current_user over time
        b) balance for each individual validators
        """
        # last_n_epoch = self._get_last_n_epoch()
        cur_epoch = int(self._get_current_epoch())
        balances = {}
        balance_per_index = {i: '0' for i in self.indices}
        # for epoch in last_n_epoch:
        total_balance_epoch, balance_per_index = self._balance_for_epoch(
            activation_epoch, cur_epoch)
        balances['total'] = total_balance_epoch
        balances['validators'] = balance_per_index
        return balances

    def _balance_for_epoch(self, activation_epoch: Dict[str, str],
                           epoch: str) -> Tuple[str, Dict[str, str]]:
        filter_active_indices = [
            i for i in self.indices if int(activation_epoch[i]) <= int(epoch)
        ]
        if len(filter_active_indices) == 0:
            return '0', {i: '0' for i in self.indices}

        total_balance = 0
        resp = requests.get(
            f'{config.BEACON_RPC_URI}/validators/balances',
            params={
                'indices': filter_active_indices,
                'epoch': epoch
            },
        )
        resp = resp.json()
        balance_per_index = {}
        for json in resp['balances']:
            total_balance += int(json['balance'])
            balance_per_index[json['index']] = gwei_to_ether(json['balance'])
        return gwei_to_ether(total_balance), balance_per_index

    def _get_current_epoch(self) -> str:
        """Calculate the current epoch from genesis"""
        sec_since_genesis = int(time.time()) - config.EPOCH_GENESIS
        current_epoch = int(sec_since_genesis / config.SEC_PER_EPOCH)
        return str(current_epoch)

    def _get_last_n_epoch(self) -> List[str]:
        """Fetch last 7 days epoch"""
        pointer_epoch = int(self._get_current_epoch())
        last_n_epoch = [pointer_epoch]
        for _ in range(6):
            pointer_epoch = max(1, pointer_epoch - config.EPOCH_PER_DAY)
            last_n_epoch = [pointer_epoch] + last_n_epoch
            if pointer_epoch == 0:
                break

        return last_n_epoch

    def _get_activation_epoch(self) -> Dict[str, str]:
        """GET /eth/v1alpha1/validators
        Retrieve activation epoch for each validator, None if not activated yet
        """
        resp = requests.get(f'{config.BEACON_RPC_URI}/validators',
                            params={'indices': self.indices})
        resp = resp.json()
        validator_activation_epoch = {}
        for val in resp['validatorList']:
            validator_activation_epoch[
                val['index']] = val['validator']['activationEpoch']
        return validator_activation_epoch
示例#21
0
def user_login():
    s = UserService()
    s.login()
    return s.render()
示例#22
0
class UserBaseResource(BaseResource):
    user_service = UserService()
    task_service = TaskService()
    user_serializer = UserSerializer()