• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

observatorycontrolsystem / ocs-authentication / 10325886202

09 Aug 2024 09:21PM UTC coverage: 86.348% (+5.6%) from 80.714%
10325886202

Pull #4

github

Jon
Removed auth classes from server called endpoint since its all handled by the permission
Pull Request #4: Ignore throttling from clients

3 of 4 new or added lines in 1 file covered. (75.0%)

1 existing line in 1 file now uncovered.

506 of 586 relevant lines covered (86.35%)

2.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

66.13
/ocs_authentication/backends.py
1
from django.contrib.auth import get_user_model
3✔
2
from django.core.validators import validate_email
3✔
3
from django.contrib.auth.backends import ModelBackend, BaseBackend
3✔
4
from django.core.exceptions import ValidationError, PermissionDenied
3✔
5
from django.utils.translation import gettext as _
3✔
6
from rest_framework.authentication import TokenAuthentication, exceptions
3✔
7
from ocs_authentication.util import generate_tokens, get_profile, create_or_update_user
3✔
8
from ocs_authentication.auth_profile.models import AuthProfile
3✔
9
from ocs_authentication.exceptions import ProfileException, OAuthTokenException
3✔
10

11

12
class OCSTokenAuthentication(TokenAuthentication):
3✔
13
    """
14
    This Allows authentication based on the api_key stored in the AuthProfile model.
15
    This should allow users to use the same api_key between client apps and the Oauth Server.
16
    TODO:: Once we switch to just using the DRF tokens rather than allowing both DRF tokens and
17
           the AuthProfile api_tokens, this backend should no longer be necessary.
18
    """
19
    def authenticate_credentials(self, key):
3✔
20
        try:
×
21
            output = super().authenticate_credentials(key)
×
22
            return output
×
23
        except exceptions.AuthenticationFailed:
×
24
            pass
×
25
        # Fallback on trying the api_token in the AuthToken model
26
        try:
×
27
            token = AuthProfile.objects.select_related('user').get(api_token=key)
×
28
        except AuthProfile.DoesNotExist:
×
29
            raise exceptions.AuthenticationFailed(_('Invalid token.'))
×
30

31
        if not token.user.is_active:
×
32
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
×
33

34
        return (token.user, token)
×
35

36

37
class OAuthUsernamePasswordBackend(ModelBackend):
3✔
38
    """
39
    Authenticate against the OAuth Authorization server using
40
    grant_type: password
41

42
    This backend should be placed after a backend that checks the local database for if the user exists there.
43
    """
44
    def authenticate(self, request, username=None, password=None):
3✔
45
        try:
3✔
46
            access_token, refresh_token = generate_tokens(username, password)
3✔
47
        except OAuthTokenException:
3✔
48
            # The authorization server failed to generate tokens. The username and password still might be
49
            # able to authenticate via another backend, so return `None`.
50
            return None
3✔
51

52
        try:
3✔
53
            profile = get_profile(access_token=access_token)
3✔
54
        except ProfileException:
3✔
55
            # Failed to get profile data using newly created access token. Something is wrong, indicate not authorized.
56
            raise PermissionDenied('Failed to access user profile')
3✔
57

58
        return create_or_update_user(profile, password)
3✔
59

60
    def get_user(self, user_id):
3✔
61
        try:
×
62
            return get_user_model().objects.get(pk=user_id)
×
63
        except get_user_model().DoesNotExist:
×
64
            return None
×
65

66

67
class EmailOrUsernameModelBackend(BaseBackend):
3✔
68
    """
69
    Authenticate either with username and password, or with email and password.
70
    """
71
    def authenticate(self, request, username=None, password=None):
3✔
72
        is_email = True
3✔
73
        try:
3✔
74
            validate_email(username)
3✔
75
        except ValidationError:
3✔
76
            is_email = False
3✔
77
        if is_email:
3✔
78
            kwargs = {'email': username}
3✔
UNCOV
79
        else:
×
80
            kwargs = {'username': username}
3✔
81
        try:
3✔
82
            user = get_user_model().objects.get(**kwargs)
3✔
83
            if user.check_password(password):
3✔
84
                return user
3✔
85
        except get_user_model().DoesNotExist:
3✔
86
            return None
3✔
87

88
    @staticmethod
3✔
89
    def get_user(user_id):
3✔
90
        try:
×
91
            return get_user_model().objects.get(pk=user_id)
×
92
        except get_user_model().DoesNotExist:
×
93
            return None
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc