3333from django .views .decorators .cache import never_cache
3434from django .views .decorators .csrf import csrf_exempt
3535from django .views .decorators .debug import sensitive_post_parameters , sensitive_variables
36+ from django .utils import timezone
3637from django .utils .html import strip_tags
3738from django .utils .translation import gettext as _
3839from django .utils .http import urlencode
@@ -645,38 +646,55 @@ def post(self, request):
645646
646647@method_decorator (never_cache , name = "dispatch" )
647648class TwoFactorAuthenticationSettingsView (View ):
649+ @staticmethod
650+ def get_user_id_from_link (link ):
651+ """Returns the user id from a valid, unexpired reset link, else None."""
652+ try :
653+ decrypted_data = JSONDeserializer ().deserialize (
654+ AESCipher (settings .SECRET_KEY ).decrypt (link )
655+ )
656+ link_time = datetime .fromtimestamp (int (decrypted_data ["ts" ]))
657+ if link_time + timedelta (minutes = 15 ) < datetime .fromtimestamp (
658+ int (time .time ())
659+ ):
660+ return None
661+ return int (decrypted_data ["user" ]["id" ])
662+ except Exception :
663+ return None
664+
648665 def get (self , request ):
649666 link = request .GET .get ("link" , None )
650- AES = AESCipher ( settings . SECRET_KEY )
651-
652- decrypted_data = JSONDeserializer (). deserialize ( AES . decrypt ( link ))
667+ user_id = self . get_user_id_from_link ( link )
668+ if user_id is None :
669+ return HttpResponseForbidden ( _ ( "Link invalid or expired" ))
653670
654- if datetime .fromtimestamp (decrypted_data ["ts" ]) + timedelta (
655- minutes = 15
656- ) >= datetime .fromtimestamp (
657- int (time .time ())
658- ): # if before email expiry
659- user_id = decrypted_data ["user" ]["id" ]
671+ try :
660672 user_profile = models .UserProfile .objects .get (user_id = user_id )
673+ except models .UserProfile .DoesNotExist :
674+ return HttpResponseForbidden (_ ("Link invalid or expired" ))
661675
662- context = {
663- "ENABLE_TWO_FACTOR_AUTHENTICATION" : settings .ENABLE_TWO_FACTOR_AUTHENTICATION ,
664- "FORCE_TWO_FACTOR_AUTHENTICATION" : settings .FORCE_TWO_FACTOR_AUTHENTICATION ,
665- "user_has_enabled_two_factor_authentication" : bool (
666- user_profile .encrypted_mfa_hash
667- ),
668- "user_id" : user_id ,
669- }
670-
671- else :
672- raise Exception ("Link Expired" )
676+ context = {
677+ "ENABLE_TWO_FACTOR_AUTHENTICATION" : settings .ENABLE_TWO_FACTOR_AUTHENTICATION ,
678+ "FORCE_TWO_FACTOR_AUTHENTICATION" : settings .FORCE_TWO_FACTOR_AUTHENTICATION ,
679+ "user_has_enabled_two_factor_authentication" : bool (
680+ user_profile .encrypted_mfa_hash
681+ ),
682+ "link" : link ,
683+ }
673684
674685 return render (request , "two_factor_authentication_settings.htm" , context )
675686
676687 def post (self , request ):
677- user_id = request .POST .get ("user-id" )
678- user = models .User .objects .get (pk = int (user_id ))
679- user_profile = models .UserProfile .objects .get (user_id = user_id )
688+ link = request .POST .get ("link" , None )
689+ user_id = self .get_user_id_from_link (link )
690+ if user_id is None :
691+ return HttpResponseForbidden (_ ("Link invalid or expired" ))
692+
693+ try :
694+ user = models .User .objects .get (pk = user_id )
695+ user_profile = models .UserProfile .objects .get (user_id = user_id )
696+ except (models .User .DoesNotExist , models .UserProfile .DoesNotExist ):
697+ return HttpResponseForbidden (_ ("Link invalid or expired" ))
680698
681699 generate_qr_code = request .POST .get ("generate-qr-code-button" )
682700 generate_manual_key = request .POST .get ("generate-manual-key-button" )
@@ -718,7 +736,8 @@ def post(self, request):
718736
719737 user_profile .save ()
720738
721- for session in Session .objects .all (): # logs user out of all sessions
739+ # logs user out of all sessions
740+ for session in Session .objects .filter (expire_date__gte = timezone .now ()):
722741 if str (session .get_decoded ().get ("_auth_user_id" )) == str (user .id ):
723742 session .delete ()
724743
@@ -730,7 +749,7 @@ def post(self, request):
730749 ),
731750 "new_mfa_hash_qr_code" : new_mfa_hash_qr_code ,
732751 "new_mfa_hash_manual_entry_data" : new_mfa_hash_manual_entry_data ,
733- "user_id " : user_id ,
752+ "link " : link ,
734753 }
735754
736755 return render (request , "two_factor_authentication_settings.htm" , context )
0 commit comments