Completed
Push — master ( b6f8ef...f3cde1 )
by Jochen
16:59
created

award_badge_to_user()   B

Complexity

Conditions 6

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 23
nop 0
dl 0
loc 31
rs 8.3946
c 0
b 0
f 0
1
"""
2
byceps.blueprints.api.user_badge.views
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from flask import abort, request
10
11
from ....services.user import service as user_service
12
from ....services.user_badge import (
13
    command_service as badge_command_service,
14
    service as badge_service,
15
)
16
from ....util.framework.blueprint import create_blueprint
17
from ....util.views import respond_no_content
18
19
from ..decorators import api_token_required
20
21
from ...user_badge import signals
22
23
from .schemas import AwardBadgeToUserRequest
24
25
26
blueprint = create_blueprint('api_user_badge', __name__)
27
28
29
@blueprint.route('/awardings', methods=['POST'])
30
@api_token_required
31
@respond_no_content
32
def award_badge_to_user():
33
    """Award the badge to a user."""
34
    if not request.is_json:
35
        abort(415)
36
37
    schema = AwardBadgeToUserRequest()
38
    try:
39
        req = schema.load(request.get_json())
40
    except ValidationError as e:
0 ignored issues
show
Comprehensibility Best Practice introduced by Jochen Kupperschmidt
The variable ValidationError does not seem to be defined.
Loading history...
41
        abort(400, str(e.normalized_messages()))
42
43
    badge = badge_service.find_badge_by_slug(req['badge_slug'])
44
    if not badge:
45
        abort(400, 'Badge slug unknown')
46
47
    user = user_service.find_user(req['user_id'])
48
    if not user:
49
        abort(400, 'User ID unknown')
50
51
    initiator = user_service.find_user(req['initiator_id'])
52
    if not initiator:
53
        abort(400, 'Initiator ID unknown')
54
55
    _, event = badge_command_service.award_badge_to_user(
56
        badge.id, user.id, initiator_id=initiator.id
57
    )
58
59
    signals.user_badge_awarded.send(None, event=event)
60