Code Monkey home page Code Monkey logo

django-trench's People

Contributors

allow-cookies avatar barseghyanartur avatar bartosz-biskupski avatar bbisk avatar benzkji avatar bplociennik avatar chaosk avatar cody-lofty avatar dependabot[bot] avatar g3rb3n avatar jbgury avatar jhurej avatar lanthos avatar mkusiciel avatar mrspejn avatar pablocesar87 avatar ricco386 avatar rockstarr-programmerr avatar sterenczak-marek avatar vthaian avatar wmaciejewskimer avatar zmudzinski-me avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-trench's Issues

Email backend generates an uncaught exception which results in a 500 response

Describe the bug
When the mail server refuses a connection, django responds with a 500 error.

To Reproduce
Steps to reproduce the behavior:
Configure the mail server wrong.
Call /email/activate/
Internal Server Error: /email/activate/
[...]
ConnectionRefusedError: [Errno 111] Connection refused

Expected behavior
A 422 error with an json error response.

Screenshots
None

Desktop (please complete the following information):
All

Smartphone (please complete the following information):
All

Additional context
None

CONFIRM_DISABLE_WITH_CODE=True doesn't work

I have CONFIRM_DISABLE_WITH_CODE set to True, but whenever I want to disable one of the authentication methods by providing a TOTP code in the HTTP payload, I am getting 400 Bad Request (Code invalid) message back.

Does anybody know why?

# settings.py
TRENCH_AUTH = {
    "CONFIRM_DISABLE_WITH_CODE": True,
    "MFA_METHODS": {
        "app": {
            "VERBOSE_NAME": "app",
            "VALIDITY_PERIOD": 30,
            "USES_THIRD_PARTY_CLIENT": True,
            "HANDLER": "trench.backends.application.ApplicationMessageDispatcher",
        },
        "email": {
            "VERBOSE_NAME": "email",
            "VALIDITY_PERIOD": 60 * 10,
            "HANDLER": "trench.backends.basic_mail.SendMailMessageDispatcher",
            "SOURCE_FIELD": "email",
            "EMAIL_SUBJECT": "Your MFA code",
            "EMAIL_PLAIN_TEMPLATE": "trench/backends/email/code.txt",
            "EMAIL_HTML_TEMPLATE": "trench/backends/email/code.html",
        },
    },
}

# request
Endpoint: http://127.0.0.1:8000/auth/email/deactivate/
Payload:
{
    "code": "TOTP code"
}

# response
400 Bad Request
{
    "code": [
        "Code invalid or expired."
    ]
}

Extra context for email rendering and dynamic email from address

Is your feature request related to a problem? Please describe.
For sending mfa code emails in a multi Site setup. we need to be able to send mails with more context data, like site.name. The current implementation does not pass the request object to the backend which makes it impossible to use the request in rendering the email templates.

Describe the solution you'd like
Pass the request object to the backend. Allow for implementing get_context in subclass. Pass the extra context to the template rendering.

Describe alternatives you've considered
Write a separate backend for each site.

Additional context
None

Error: “Secrets must be at least 160 bits.”

When trying to post to the /authenticate endpoint I get a 500 server error and the error message reads: “Secrets must be at least 160 bits”. This only occurs in production; it works with no issues in development. I really need to get this working as a deadline is upon me. Can you please help?

P.S. Using a Docker microservices setup. There are near identical settings between dev and prod, and the Python package versions between the environments match. There are valid secret key for Django and signing key for django-rest-framework-simplejwt.

How / when is `/auth/code/request/` intended to be used?

Tried to use /auth/code/request/ for login. It is a protected route and needs to know the logged in user, so no good for resending login code.

Tried it for resending the activation code and it fails with {"detail":"Not found."}, because I think its trying to find the method that is not yet activated.

I'm confused by /auth/code/request/, because it doesn't appear to work for what I assumed was it purpose.

Annoying error with drf_yasg

After I installed django-trench I started getting this error. I tried to look it up online but didn't see any fix to it.

django          | Traceback (most recent call last):
django          |   File "/usr/local/lib/python3.8/site-packages/drf_yasg/inspectors/base.py", line 42, in call_view_method
django          |     return view_method()
django          |   File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 109, in get_serializer
django          |     kwargs.setdefault('context', self.get_serializer_context())
django          |   File "/usr/local/lib/python3.8/site-packages/trench/views/base.py", line 204, in get_serializer_context
django          |     raise NotFound()
django          | rest_framework.exceptions.NotFound: Not found.
django          | WARNING 2021-04-02 02:07:55,088 base 29 139791338682112 view's RequestMFAMethodDeactivationView raised exception during schema generation; use `getattr(self, 'swagger_fake_view', False)` to detect and short-circuit this
django          | Traceback (most recent call last):
django          |   File "/usr/local/lib/python3.8/site-packages/trench/views/base.py", line 199, in get_serializer_context
django          |     'name': self.kwargs['method'],
django          | KeyError: 'method'
django          | 
django          | During handling of the above exception, another exception occurred:
django          | 
django          | Traceback (most recent call last):
django          |   File "/usr/local/lib/python3.8/site-packages/drf_yasg/inspectors/base.py", line 42, in call_view_method
django          |     return view_method()
django          |   File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 109, in get_serializer
django          |     kwargs.setdefault('context', self.get_serializer_context())
django          |   File "/usr/local/lib/python3.8/site-packages/trench/views/base.py", line 204, in get_serializer_context
django          |     raise NotFound()
django          | rest_framework.exceptions.NotFound: Not found.

Request Resend

Hey there, while you have the 'request resend' functionality in your demo project, it doesn't seem as though there is an actual endpoint for this? I just want to make sure before I try to build this myself!

Assuming I need to build this, I suspect you would just POST the ephemeral token and the method, and a new code would be sent, and you would keep the same ephemeral token. Does that sound OK to your team?

KeyError prevents Yubico MFA activate for a user

Describe the bug
A KeyError prevents Yubico MFA activation at endpoint auth/yubi/activate/

To Reproduce
Steps to reproduce the behavior:

  1. Follow installation instructions and set up with djangorestframework-simplejwt authentication (i.e. /auth/login/ endpoint)
  2. Ensure you can authenticate a user at the /auth/login/ endpoint to retrieve the bearer token
  3. Add the access token to your Authorization header (can use an extension like ModHeader).
  4. Try to activate Yubico MFA for the user matching this access token through auth/yubi/activate/
  5. KeyError should present itself.

Expected behavior
Either a successful response and yubico MFA activated for the user, or a 400 response with an error message. The fact that there is no 400 response and instead a KeyError blows up the endpoint I think confirms a bug

Screenshots
image

Stack Trace

backend     | Internal Server Error: /auth/yubi/activate/
backend     | Traceback (most recent call last):
backend     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
backend     |     response = get_response(request)
backend     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
backend     |     response = self.process_exception_by_middleware(e, request)
backend     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
backend     |     response = response.render()
backend     |   File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 106, in render
backend     |     self.content = self.rendered_content
backend     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content
backend     |     ret = renderer.render(self.data, accepted_media_type, context)
backend     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 724, in render
backend     |     context = self.get_context(data, accepted_media_type, renderer_context)
backend     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 656, in get_context
backend     |     raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
backend     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form
backend     |     serializer = view.get_serializer()
backend     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py", line 112, in get_serializer
backend     |     return serializer_class(*args, **kwargs)
backend     |   File "/usr/local/lib/python3.7/site-packages/trench/serializers.py", line 79, in __init__
backend     |     self.get_serializer_field_mapping()[klass](
backend     | KeyError: None

Desktop (please complete the following information):

  • OS: PopOS
  • Browser Brave
  • Version 1.27.109 Chromium: 92.0.4515.115 (Official Build) (64-bit)

Additional context
I also cannot get Yubico working on the demo app

AWS support for SMS

Is your feature request related to a problem? Please describe.
Can not send SMS through AWS SNS.

Describe the solution you'd like
Being able to send SMS through AWS SNS.

Describe alternatives you've considered
Other SMS providers.

Additional context
None

When creating the TOTP URL for Google Authenticator app, the time period is set to 1 and hardcoded

When creating the TOTP URL for Google Authenticator app, the time period is set to 1 and hardcoded.
This becomes annoying when using Google Authenticator as the codes keep changing within 1 second.
The codes do work but the end user should be given enough time to view the code and enter them in our respective application.

I looked into to the lib and found that changing this particular file:
"/trench/command/create_otp.py" line 7
and changing the interval helps to create a time period that is desired

but it would be way better if it were set according to the values set in the settings page

missing EMAIL_PLAIN_TEMPLATE and EMAIL_HTML_TEMPLATE breaks method activation

Hi, thanks for your fantastic work!

As the title says currently when setting email as TRENCH_AUTH MFA method, if no email template is specified the server returns 500 to /email/activate/.

I'm currently using django-trench 0.2.3

I'd suggest mentioning it inside documentation, as the error seems to be quite difficult to understand without investigating the stacktrace and the source code. Also a good idea may be providing a default for this configuration.

I'd like to help, so let me know if I can submit a PR to fix this.
Thanks again!

Backup Codes management issue

Describe the bug
Storage for backup codes was changed (from 0.3.0 to 0.3.1)
Previously in 0.3.0, it did not work because some simple quote or delimiter for list were stored in _backup_codes column and not well managed for retrieving.

Now with version 0.3.1, delimiter has changed and use only '|' delimiter between different backup codes. Migration was not supported, and users have to migrate this data from 0.3.0 to 0.3.1.

Moreover now, when a backup code is used, and this backup code is removed of the stored list, the storage value in db is not kept with delimiter "|", but like a set datatype (with { } encloser and ',') delimiter.

To Reproduce
Steps to reproduce the behavior:

  1. Generates backup code for a mfa method
  2. Check in DB the storage format (it is encrypted value separated by | )
  3. try to login with one backup code generated
  4. Login has to be success
  5. Go in DB and checks the values, the storage format has changed
  6. Try to login with an other backup codes ... It fails...

Expected behavior
Storage format has to be constant when using the feature "backup codes" for MFA method.

Screenshots
No screenshot to provide

Desktop (please complete the following information):

  • OS: Linux Mint
  • Browser : Firefox
  • Version 96.0

Adapt to Python 2.7

Should we create separate version of trench for Python 2.7? For example 0.X for py2.7 and 1.0 for python3

error when using mutliple auth backends

Using django-axes, that adds a second authentication backend, I get the following error, from this line: https://github.com/sunscrapers/djoser/blob/master/djoser/utils.py#L19

ValueError: You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user.

When logging in on the "code" endpoint, ie posting the received code. I'll investigate.

  • django-trench==0.2.2
  • djoser==0.7 (not relevant anyway)

Translations for en de pl have only empty msgstr

Is your feature request related to a problem? Please describe.
Translation files for en, de and pl are available, but the translation strings are empty.

Describe the solution you'd like
Translations files with filled in translations.

Describe alternatives you've considered
Translating with translation tools.

Additional context
None

phone_number field in different model

I didn't extend AbstractUser model. Instead I've created a Profile model and connected it to User model with a foreign key. How can I use the phone_number field I've created on the Profile model?

Sending of messages fails on SendGrid

Describe the bug
The SendGrid client uses json to do the API request to SendGrid. The subject field is a lazy proxy which not json serializable. This results in an 'TypeError: Object of type proxy is not JSON serializable' error.

To Reproduce
Steps to reproduce the behavior:

  • implement SendGrid as django email backend with django-sendgrid-v5
  • call /email/activate/

Expected behavior
Email being send.

Screenshots
None

Desktop (please complete the following information):
All

Smartphone (please complete the following information):
All

Additional context
A simple fix is to enforce conversion of django.utils.functional.lazy..proxy to str type. Using a template for the subject would also work.

Possible to override serializer/response from successful login request?

Hi! At a successful login using /auth/login/code/ i get a correct response like:

{
    "auth_token": "123456abc"
} 

And i can see that TokenSerializer is used for the response - but i would like to override the response by firstly changing the key to some other string than "auth_token" and i also would like to pass the User object. Is this possible somehow? Many thanks for a great package!

OTP is not working when using Microsoft Authenticator and Cisco Duo

Describe the bug
During the process of activating MFA method the code generated by Google and Lastpass apps is working while for Microsoft Authenticator and Cisco Duo is not working.

The OTP QR code was generated in following format:
otpauth://totp/MyWebApp:myUser?secret=OTQGJNAJOUQP3UYIETRA2B4XOLJAYRFEP4W37PGYG37K5V35FEJCA7D66DCBZUSLRD3NR45J63CSNDLIJPJGWAT3OIORPGGJOBAIMFTZGCMA3F2U2JC2NJ7AGTXOPK6F77FJODQ6KK5PN2MV5XGWSJLYUMF2G74J&issuer=MyWebApp&period=60

All authenticator apps (Google, Lastpass, Microsoft Authenticator and Cisco Duo) were successfully able to scan QR code, add account and generate OTP but it only worked for Google and Lastpass.

I am receiving following response on the app/activate/confirm/ API endpoint for the Microsoft Authenticator and Cisco Duo:
{"code":["Code invalid or expired."]}

To Reproduce
Steps to reproduce the behavior:

  1. Create MFA method in Django Trench for app (Authenticator app)
  2. Generate and scan QR code or enter Account name and code manually using Microsoft Authenticator or Cisco Duo apps.
  3. Try to activate MFA method using code generated by app.
  4. Check the response

Expected behavior
To be able to activate MFA method using Microsoft Authenticator or Cisco Duo apps.

Zapier integration testing

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

2FA cannot be deactivated starting with trench 0.3

Describe the bug
with pre-0.3 versions, I could disable all mfa methods. this is no more possible with trench 0.3 and upwards, is this correct?

To Reproduce
try to disable your last enabled mfa method.

Expected behavior
should be possible?

Potentially incorrect use of DRF's APISettings that makes it impossible to add a custom 2FA backend

I came across this when I tried to add a custom 2FA backend.

The library uses APISettings from DRF as a base class for TrenchAPISettings:

class TrenchAPISettings(APISettings):
    _FIELD_USER_SETTINGS = "_user_settings"
    _FIELD_TRENCH_AUTH = "TRENCH_AUTH"

This wouldn't be a big deal if the TrenchAPISettings would not parse defaults during config load. Effectively, making it impossible to add any new custom backends.

There is a silent KeyError thrown by for k, v in self.defaults[self._FIELD_MFA_METHODS][method_name].items(): and the only way to get around it is to monkey-patch the constant and override trench_settings.

It is worth mentioning that aforementioned DRF's APISettings explicitly states within its implementation that:

    This is an internal class that is only compatible with settings namespaced
    under the REST_FRAMEWORK name. It is not intended to be used by 3rd-party
    apps, and test helpers like `override_settings` may not work as expected.

Authentication credentials were not provided

Hello again!

Also running into a separate issue where I'm able to get the ephemeral_token (I changed the code in my virtualenv to return a 16 digit key and I was able to add it to Google auth) but when I send that plus the generated code I get the following:

curl -X POST http://localhost:8000/auth/login/code/ -d 'code=260286&ephemeral_token=6c59369d-2f77-4e90-939d-be9ab5794af8-pmh8ix-791be5511d3a6d96f594a5d3dfd3629075f1b366'

{"status_code":401,"message":"Authentication credentials were not provided."}

Upon looking a bit further it looked like part of the problem is that we are using UUIDs for the PKs on our User objects so it was causing problems with user_pk, ts_b36, hash = token.split('-') but making local changes to that and the _make_token_with_timestamp method to test things, still provides that error even when it's using a different character to separate out those items and split on it instead (I used : to test).

I'm using Python 3.6.5
Django==1.11.11
djangorestframework==3.8.2
djangorestframework-simplejwt==2.1

Any help here would be appreciated as well. Let me know if there is any other information I can provide. Thank you!

Trying to activate, code is always Invalid or Expired.

Describe the bug
Trying to activate MFA on the /app/activate/confirm/ always give the following response:

{
  "code": [
    "Code invalid or expired."
  ]
}

Any leads or tips or tricks would be really appreciated! :)

To Reproduce
Steps to reproduce the behavior:

  1. Using Insomnia or Postman, login and get token
  2. Use token as bearer, make request to 127.0.0.1:8000/auth/app/activate/
  3. Get the otpauth, make QR code and scan with Authenticator app of choice
  4. Try using the code from authenticator on `127.0.0.1:8000/auth/app/activate/confirm'
  5. Get the error message above about code invalid or expired

Expected behavior
Should return the backup codes as described in the API endpoint documentation

Screenshots
If applicable, add screenshots to help explain your problem.

{
  "code": [
    "Code invalid or expired."
  ]
}

Desktop (please complete the following information):

  • OS: MacOS 11.6
  • Insomnia

Additional context
Tried to set the timezone of Django, and timezone of my computer, but its just not happening.
Tried also to wipe the sqlite3 database, make new users, etc.

Twilio requires credentials

Describe the bug
Twilio responds with: twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient

To Reproduce
Enable sms_twilio and call /twilio/activate

Expected behavior
SMS being send by Twilio

Screenshots
None

Desktop (please complete the following information):
None

Smartphone (please complete the following information):
None

Additional context
None

Django 3.0 Compatibility

Django 3.0 has now been released and I've run into a minor compatibility issue. In the SimpleJWT view, there's a reference to the django.utils.six library, which has been removed.

from django.utils.six import text_type

If there's a need to maintain Python 2 compatibility, then the text_type method still exists in the six library, but it'll have to be included separately.

Problem with email 2FA method activation

I am experiencing problems with activating EMAIL 2FA method.

I am either getting back:

  • "This field is required" - If I don't provide email field in the POST body
  • "User with this email already exists" - If I provide email field in the POST body

Anybody knows why? Email field isn't required according to the django-trench documentation.

#settings.py
TRENCH_AUTH = { "MFA_METHODS": { "app": { "VERBOSE_NAME": "app", "VALIDITY_PERIOD": 30, "USES_THIRD_PARTY_CLIENT": True, "HANDLER": "trench.backends.application.ApplicationMessageDispatcher", }, "email": { "VERBOSE_NAME": "email", "VALIDITY_PERIOD": 60 * 10, "HANDLER": "trench.backends.basic_mail.SendMailMessageDispatcher", "SOURCE_FIELD": "email", "EMAIL_SUBJECT": "Your MFA code", "EMAIL_PLAIN_TEMPLATE": "trench/backends/email/code.txt", "EMAIL_HTML_TEMPLATE": "trench/backends/email/code.html", }, }, }

User model:
class User(AbstractBaseUser, PermissionsMixin):

email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
username = models.CharField(max_length=100, null=True)

is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)

organization = models.ForeignKey(
    "Organization", on_delete=models.CASCADE, null=True, blank=True, related_name="users"
)
settings = models.OneToOneField("UserSettings", on_delete=models.RESTRICT, null=True, blank=True)

objects = UserManager()

USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["name"]

If email field blank:
Screenshot 2022-06-20 at 17 42 20
If email field present:
Screenshot at Jun 20 17-43-05

issue with drf-spectacular

Describe the bug
Using drf-spectacular and Django-Trench causes the swagger docs to no longer be generated.

I get the following error
django.core.exceptions.ImproperlyConfigured: "^(?P[^/]+))/activate/$" is not a valid regular expression: unbalanced parenthesis at position 18

To Reproduce
setup drf-spectacular for your project
pip install django-trench
include path('auth/', include('trench.urls')), in your urls.py

Expected behavior
api endpoints should be displayed in drf-spectacular's autogenerated docs.

I suspect it has to do with the urls being dynamically generated based on the settings but Im not 100%

no attribute '_action' error when trying to verify code

I've setup django-trench together with djoser. Normal login works, across the trench endpoint (/auth/login). When activating 2FA, I can login, get the ephemeral_token, get the email/sms. But when trying to validate the code, I get the following error (submitting the correct code. with wrong code, there is an error saying "invalid code") :

.../site-packages/trench/views/authtoken.py", line 9, in handle_user_login
    return self._action(serializer)
AttributeError: 'AuthTokenLoginWithMFACode' object has no attribute '_action'

I have no clue where _action should be defined? I've not found it in one of the mixins, neither on the DRF APIView?

urls.py
url(r'^auth/', include('trench.urls')),
url(r'^auth/', include('djoser.urls')),
url(r'^auth/', include('djoser.urls.authtoken')),
url(r'^auth/', include('trench.urls.djoser')),

python: 3.6.7
django: 2.1.8 / 2.2 (tried both)
djangorestframework: 3.9.2
djoser: 1.5.1
django-trench: 0.2.1

Is integration with Djoser gone in 0.3.x ?

Hi and thanks for the awesome and very helpful library.
I'm trying to upgrade from trench 0.2.3 to 0.3.0 . I noticed that the djoser urls are gone.
Is that forever or is there a workaround to get that working again ?
Thanks

Invalid code when trying to activate MFA by `app` method

Describe the bug
Invalid code when trying to activate MFA by app method

    "code": [
        "Code invalid or expired."
    ]
}

To Reproduce
Steps to reproduce the behavior:

  1. Send POST request to /auth/app/activate/
  2. Scan your qr code with a mobile app
  3. Send POST request to /auth/app/activate/congirm with body {"code": }
  4. See error "code": ["Code invalid or expired."]

Expected behavior
A clear and concise description of what you expected to happen.

Desktop (please complete the following information):

  • OS: Windows 11
  • Browser: Chrome
  • Version 100.0.4896.75

Additional context
Issue exists only with app MFA method

Secret length of 20 won't worth with Google Authenticator

Hello,

Trying to set this up to use Google Authenticator for MFA and the secret that is returned is 20 characters long. The Google auth app requires 16 characters. I'm not sure if there are requirements on any others but it might make sense to make this a variable in the settings file for the app MFA method. I'm happy to do a PR for this if you would like.

Cheers!

Add active methods to /login/ response

Is your feature request related to a problem? Please describe.
Currently /login/ has a method field which gives the primary method. It would be nice if all active methods are in the response, so that a end user can choose which method to use for the second step.

Describe the solution you'd like
Add a methods field to the login response with all active method names.

Describe alternatives you've considered
Use /mfa/user-active-methods/ , which requires a second call to the server.

Additional context
None

Reactivating the primary disabled MFAMethod introduces an inconsistent state

Hi! First of all, thank you for this awesome package!

Describe the bug
Reactivating the disabled primary MFAMethod should maintain is_primary=True. This is not working as expected because this statement doesn't take into account if the primary method is the affected one in the process.

To Reproduce
This is the full process for reproducing it.

Login

curl -X POST http://localhost:8000/auth/jwt/login/ -H  "Content-Type: application/json" -d '{"username": "admin", "password": "admin"}'
{"refresh":"...","access":"..."}

Activate app method

curl -X POST http://localhost:8000/auth/app/activate/ -H "Authorization: Bearer ..."
{"details":"otpauth://totp/MyApplication:admin?secret=HAA2VOHKZMJV6I6Y2JYX26OV7SMOULWO&issuer=MyApplication&period=600"}

Confirm app method


curl -X POST http://localhost:8000/auth/app/activate/confirm/ -H "Authorization: Bearer ..." -H  "Content-Type: application/json" -d '{"code": "231528"}'
{"backup_codes":["931780504135","028493362694","608422503394","034115886743","890942714207","867642128148","293494835872","567079811791"]}

Captura de Pantalla 2022-06-13 a las 8 57 29

Deactivate app method

curl -X POST http://localhost:8000/auth/app/deactivate/ -H "Authorization: Bearer ..." -H  "Content-Type: application/json" -d '{"code": "818437"}'
(no content)

Captura de Pantalla 2022-06-13 a las 8 58 38

Reactivate app method

curl -X POST http://localhost:8000/auth/app/activate/ -H "Authorization: Bearer ..." -H  "Content-Type: application/json"
{"details":"otpauth://totp/MyApplication:admin?secret=HAA2VOHKZMJV6I6Y2JYX26OV7SMOULWO&issuer=MyApplication"}

Reactivate app method confirm

curl -X POST http://localhost:8000/auth/app/activate/confirm/ -H "Authorization: Bearer ..." -H  "Content-Type: application/json" -d '{"code": "036716"}'
{"backup_codes":["684375266907","082071192573","288256663115","727551988514","106943114872","437314901576","714604541769","675806917849"]}

Captura de Pantalla 2022-06-13 a las 9 01 03

Expected behavior
MFAMethod instance should keep is_primary=True and is_active=True but it doesn't.

I fixed this behavior annotating the primary method instead of using MFAUserMethodManager.primary_exists method.

I'll publish the fix in a PR.

Only one backup code is usable

Describe the bug
After using one backup code, all the others are unusable.

To Reproduce
Steps to reproduce the behavior:

  • /app/activate
  • /app/activate/confirm/
  • /login/
  • /login/code/ Use a backup code
  • /login/code/ Use another backup code
    Server responds with 401 Invalid or expired code.

Expected behavior
All codes should be usable. Also when one code has been used.

Screenshots

Desktop (please complete the following information):
All

Smartphone (please complete the following information):
All

Additional context
Backup codes changes from:

pbkdf2_sha256$320000$fnpXA7nON1q0GBEWMjbaj9$caKajfko7sjHapgDh1lPvSdBO9AhZ7k3ktT44Jw4Lm4=|pbkdf2_sha256$320000$rgZcC0RZuatydubke38haj$8uFTKcUyh2JdMrFMTtwfi/rVJ+r6paOXX5xIRP01VBg=|pbkdf2_sha256$320000$ulPI761WPEEkWOKohUbd5T$J+tsbjr2adyxuMyuDwG13U0p9UMDIOilqH/poygsBH4=|pbkdf2_sha256$320000$alQKLAZzGLDKXGwIwdE8ev$pqXqMgCwLk0QPmt0YW4zhmzaqRYkK6f5LN5AkwhdSXY=|pbkdf2_sha256$320000$6kW8iYIXIVIbwxh0TZ5cE2$4TeMEA8cr8w55rw03YmGW6KSgNuj94gF8t5BJqZzsvE=

to:

{'pbkdf2_sha256$320000$alQKLAZzGLDKXGwIwdE8ev$pqXqMgCwLk0QPmt0YW4zhmzaqRYkK6f5LN5AkwhdSXY=', 'pbkdf2_sha256$320000$ulPI761WPEEkWOKohUbd5T$J+tsbjr2adyxuMyuDwG13U0p9UMDIOilqH/poygsBH4=', 'pbkdf2_sha256$320000$fnpXA7nON1q0GBEWMjbaj9$caKajfko7sjHapgDh1lPvSdBO9AhZ7k3ktT44Jw4Lm4=', 'pbkdf2_sha256$320000$rgZcC0RZuatydubke38haj$8uFTKcUyh2JdMrFMTtwfi/rVJ+r6paOXX5xIRP01VBg='}

Lougout url missing

Is your feature request related to a problem? Please describe.
There is a MFALogoutView, but no corresponding url.

Describe the solution you'd like
It would be nice if it is included in the trench urls.

Describe alternatives you've considered
Defining my own in my project urls is no problem.

from trench.views.authtoken import MFALogoutView
...
    path('auth/logout/', MFALogoutView.as_view()),

Additional context
None

Request for a release

Your develop version got really good updates where your stable release is far behind. I think you can release a new version from here. And please add a setting for SANDBOX OTP. Thank you.

Table testapp_user has no column named yubikey_id

Describe the bug
When you try to create a superuser in the example demo app you get django.db.utils.OperationalError: table testapp_user has no column named yubikey_id

To Reproduce
Steps to reproduce the behavior:

  1. Go to the Sample App documentation
  2. Make sure after cloning that you are on the demo branch and follow all the instructions up to before make build
  3. make build will fail (separate issue) due to a missing djoser version. Change it in common.txt from djoser==1.2.1 to djoser==1.2.2
  4. Continue the rest of the instructions. make create_admin will display the error message.

Expected behavior
An admin is created and you can log into the admin

Screenshots
image

Desktop:

  • OS: PopOS 20.04
  • Browser: Brave
  • Version 1.27.109 Chromium: 92.0.4515.115 (Official Build) (64-bit)

Additional context
I just want to see how the "out-the-box" Yubico support works. I can use the develop branch to create an admin and then log in. But then I cannot seem to figure out where you add the yubikey U2F and how to map that to the public API. So I am trying the demo, but then I ran into this issue. So instructions on how to add Yubico U2F support to my django rest framework authentication is what I ultimately am looking for. Thank you.

Unable to use custom user model with USERNAME_FIELD

Unable to activate 'app' method when using a custom user model that does not have a username field.

In backends/application.py, the default django user model is being imported directly via from django.contrib.auth.models import User instead of using from django.contrib.auth import get_user_model. This results in an error "details": "'User' object has no attribute 'username'" when generating the QR link.

There are several places where this is done correctly but serializers.py, backends/application.py, and views/base.py are using the default user model.

PIP doesn't install the latest version of django-trench

When installing django-trench

pip install django-trench

pip only installs version 0.3.0 even when specifying the version

pip install django-trench==0.3.1

it shows as non-existent distribution (even tried --pre as it may have been incorrectly tagged)

Screenshot 2022-05-04 at 16 01 08

The latest version is obviously 0.3.1 seen here

Screenshot 2022-05-04 at 16 01 44

and a temporary work around is to pip install from the repo itself like so..

pip install -e git+https://github.com/merixstudio/django-trench.git#egg=django_trench

which installs the latest distro
....
This issue also relates to #155 where the VALIDITY_PERIOD has no effect due to the interval being hardcoded but is resolved in v0.3.1

version 0.3.1

class CreateOTPCommand:
    @staticmethod
    def execute(secret: str, interval: int) -> TOTP:
        return TOTP(secret, interval=interval)
       
create_otp_command = CreateOTPCommand.execute

version 0.3.0


class CreateOTPCommand:
    @staticmethod
    def execute(secret: str) -> TOTP:
        return TOTP(secret, interval=1)


create_otp_command = CreateOTPCommand.execute

exception when using Argon2PasswordHasher first in PASSWORD_HASHERS

Hi,
I use cookiecutter-django in a project, which by default use in this settings

PASSWORD_HASHERS = [
    # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
   "django.contrib.auth.hashers.Argon2PasswordHasher",
   "django.contrib.auth.hashers.PBKDF2PasswordHasher",
   "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
   "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
]

This seems to create a problem with login code verification, in particular when using Argon2PasswordHasher as first hasher

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.