authentik.stages.authenticator_sms.stage

SMS Setup stage

  1"""SMS Setup stage"""
  2
  3from django.db.models import Q
  4from django.http import HttpRequest, HttpResponse
  5from django.http.request import QueryDict
  6from django.utils.translation import gettext_lazy as _
  7from rest_framework.exceptions import ValidationError
  8from rest_framework.fields import BooleanField, CharField
  9
 10from authentik.flows.challenge import (
 11    Challenge,
 12    ChallengeResponse,
 13    WithUserInfoChallenge,
 14)
 15from authentik.flows.stage import ChallengeStageView
 16from authentik.stages.authenticator_sms.models import (
 17    AuthenticatorSMSStage,
 18    SMSDevice,
 19    hash_phone_number,
 20)
 21from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
 22
 23PLAN_CONTEXT_SMS_DEVICE = "goauthentik.io/stages/authenticator_sms/sms_device"
 24PLAN_CONTEXT_PHONE = "phone"
 25
 26
 27class AuthenticatorSMSChallenge(WithUserInfoChallenge):
 28    """SMS Setup challenge"""
 29
 30    # Set to true if no previous prompt stage set the phone number
 31    # this stage will also check prompt_data.phone
 32    phone_number_required = BooleanField(default=True)
 33    component = CharField(default="ak-stage-authenticator-sms")
 34
 35
 36class AuthenticatorSMSChallengeResponse(ChallengeResponse):
 37    """SMS Challenge response, device is set by get_response_instance"""
 38
 39    device: SMSDevice
 40
 41    code = CharField(required=False)
 42    phone_number = CharField(required=False)
 43
 44    component = CharField(default="ak-stage-authenticator-sms")
 45
 46    def validate(self, attrs: dict) -> dict:
 47        """Check"""
 48        if "code" not in attrs:
 49            phone_number = self.stage._has_phone_number()
 50            if phone_number is None:
 51                if "phone_number" not in attrs:
 52                    raise ValidationError("phone_number required")
 53                phone_number = attrs["phone_number"]
 54            self.device.phone_number = phone_number
 55            self.stage.validate_and_send(phone_number)
 56            return super().validate(attrs)
 57        if not self.device.verify_token(str(attrs["code"])):
 58            raise ValidationError(_("Code does not match"))
 59        self.device.confirmed = True
 60        return super().validate(attrs)
 61
 62
 63class AuthenticatorSMSStageView(ChallengeStageView):
 64    """OTP sms Setup stage"""
 65
 66    response_class = AuthenticatorSMSChallengeResponse
 67
 68    def validate_and_send(self, phone_number: str):
 69        """Validate phone number and send message"""
 70        stage: AuthenticatorSMSStage = self.executor.current_stage
 71        hashed_number = hash_phone_number(phone_number)
 72        query = Q(phone_number=hashed_number) | Q(phone_number=phone_number)
 73        if SMSDevice.objects.filter(query, stage=stage.pk).exists():
 74            raise ValidationError(_("Invalid phone number"))
 75        # No code yet, but we have a phone number, so send a verification message
 76        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
 77        stage.send(self.request, device.token, device)
 78
 79    def _has_phone_number(self) -> str | None:
 80        context = self.executor.plan.context
 81        if PLAN_CONTEXT_PHONE in context.get(PLAN_CONTEXT_PROMPT, {}):
 82            self.logger.debug("got phone number from plan context")
 83            return context.get(PLAN_CONTEXT_PROMPT, {}).get(PLAN_CONTEXT_PHONE)
 84        if PLAN_CONTEXT_SMS_DEVICE in self.executor.plan.context:
 85            self.logger.debug("got phone number from device in session")
 86            device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
 87            if device.phone_number == "":
 88                return None
 89            return device.phone_number
 90        return None
 91
 92    def get_challenge(self, *args, **kwargs) -> Challenge:
 93        return AuthenticatorSMSChallenge(
 94            data={
 95                "phone_number_required": self._has_phone_number() is None,
 96            }
 97        )
 98
 99    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
100        response = super().get_response_instance(data)
101        response.device = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
102        return response
103
104    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
105        user = self.get_pending_user()
106
107        stage: AuthenticatorSMSStage = self.executor.current_stage
108
109        if PLAN_CONTEXT_SMS_DEVICE not in self.executor.plan.context:
110            device = SMSDevice(user=user, confirmed=False, stage=stage, name="SMS Device")
111            device.generate_token(commit=False)
112            self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE] = device
113            if phone_number := self._has_phone_number():
114                device.phone_number = phone_number
115                try:
116                    self.validate_and_send(phone_number)
117                except ValidationError as exc:
118                    # We had a phone number given already (at this point only possible from flow
119                    # context), but an error occurred while sending a number (most likely)
120                    # due to a duplicate device, so delete the number we got given, reset the state
121                    # (ish) and retry
122                    device.phone_number = ""
123                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
124                        PLAN_CONTEXT_PHONE, None
125                    )
126                    self.executor.plan.context.pop(PLAN_CONTEXT_SMS_DEVICE, None)
127                    self.logger.warning("failed to send SMS message to pre-set number", exc=exc)
128                    return self.get(request, *args, **kwargs)
129        return super().get(request, *args, **kwargs)
130
131    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
132        """SMS Token is validated by challenge"""
133        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
134        if not device.confirmed:
135            return self.challenge_invalid(response)
136        stage: AuthenticatorSMSStage = self.executor.current_stage
137        if stage.verify_only:
138            self.logger.debug("Hashing number on device")
139            device.set_hashed_number()
140        device.save()
141        del self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
142        return self.executor.stage_ok()
PLAN_CONTEXT_SMS_DEVICE = 'goauthentik.io/stages/authenticator_sms/sms_device'
PLAN_CONTEXT_PHONE = 'phone'
class AuthenticatorSMSChallenge(authentik.flows.challenge.WithUserInfoChallenge):
28class AuthenticatorSMSChallenge(WithUserInfoChallenge):
29    """SMS Setup challenge"""
30
31    # Set to true if no previous prompt stage set the phone number
32    # this stage will also check prompt_data.phone
33    phone_number_required = BooleanField(default=True)
34    component = CharField(default="ak-stage-authenticator-sms")

SMS Setup challenge

phone_number_required
component
class AuthenticatorSMSChallengeResponse(authentik.flows.challenge.ChallengeResponse):
37class AuthenticatorSMSChallengeResponse(ChallengeResponse):
38    """SMS Challenge response, device is set by get_response_instance"""
39
40    device: SMSDevice
41
42    code = CharField(required=False)
43    phone_number = CharField(required=False)
44
45    component = CharField(default="ak-stage-authenticator-sms")
46
47    def validate(self, attrs: dict) -> dict:
48        """Check"""
49        if "code" not in attrs:
50            phone_number = self.stage._has_phone_number()
51            if phone_number is None:
52                if "phone_number" not in attrs:
53                    raise ValidationError("phone_number required")
54                phone_number = attrs["phone_number"]
55            self.device.phone_number = phone_number
56            self.stage.validate_and_send(phone_number)
57            return super().validate(attrs)
58        if not self.device.verify_token(str(attrs["code"])):
59            raise ValidationError(_("Code does not match"))
60        self.device.confirmed = True
61        return super().validate(attrs)

SMS Challenge response, device is set by get_response_instance

code
phone_number
component
def validate(self, attrs: dict) -> dict:
47    def validate(self, attrs: dict) -> dict:
48        """Check"""
49        if "code" not in attrs:
50            phone_number = self.stage._has_phone_number()
51            if phone_number is None:
52                if "phone_number" not in attrs:
53                    raise ValidationError("phone_number required")
54                phone_number = attrs["phone_number"]
55            self.device.phone_number = phone_number
56            self.stage.validate_and_send(phone_number)
57            return super().validate(attrs)
58        if not self.device.verify_token(str(attrs["code"])):
59            raise ValidationError(_("Code does not match"))
60        self.device.confirmed = True
61        return super().validate(attrs)

Check

class AuthenticatorSMSStageView(authentik.flows.stage.ChallengeStageView):
 64class AuthenticatorSMSStageView(ChallengeStageView):
 65    """OTP sms Setup stage"""
 66
 67    response_class = AuthenticatorSMSChallengeResponse
 68
 69    def validate_and_send(self, phone_number: str):
 70        """Validate phone number and send message"""
 71        stage: AuthenticatorSMSStage = self.executor.current_stage
 72        hashed_number = hash_phone_number(phone_number)
 73        query = Q(phone_number=hashed_number) | Q(phone_number=phone_number)
 74        if SMSDevice.objects.filter(query, stage=stage.pk).exists():
 75            raise ValidationError(_("Invalid phone number"))
 76        # No code yet, but we have a phone number, so send a verification message
 77        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
 78        stage.send(self.request, device.token, device)
 79
 80    def _has_phone_number(self) -> str | None:
 81        context = self.executor.plan.context
 82        if PLAN_CONTEXT_PHONE in context.get(PLAN_CONTEXT_PROMPT, {}):
 83            self.logger.debug("got phone number from plan context")
 84            return context.get(PLAN_CONTEXT_PROMPT, {}).get(PLAN_CONTEXT_PHONE)
 85        if PLAN_CONTEXT_SMS_DEVICE in self.executor.plan.context:
 86            self.logger.debug("got phone number from device in session")
 87            device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
 88            if device.phone_number == "":
 89                return None
 90            return device.phone_number
 91        return None
 92
 93    def get_challenge(self, *args, **kwargs) -> Challenge:
 94        return AuthenticatorSMSChallenge(
 95            data={
 96                "phone_number_required": self._has_phone_number() is None,
 97            }
 98        )
 99
100    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
101        response = super().get_response_instance(data)
102        response.device = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
103        return response
104
105    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
106        user = self.get_pending_user()
107
108        stage: AuthenticatorSMSStage = self.executor.current_stage
109
110        if PLAN_CONTEXT_SMS_DEVICE not in self.executor.plan.context:
111            device = SMSDevice(user=user, confirmed=False, stage=stage, name="SMS Device")
112            device.generate_token(commit=False)
113            self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE] = device
114            if phone_number := self._has_phone_number():
115                device.phone_number = phone_number
116                try:
117                    self.validate_and_send(phone_number)
118                except ValidationError as exc:
119                    # We had a phone number given already (at this point only possible from flow
120                    # context), but an error occurred while sending a number (most likely)
121                    # due to a duplicate device, so delete the number we got given, reset the state
122                    # (ish) and retry
123                    device.phone_number = ""
124                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
125                        PLAN_CONTEXT_PHONE, None
126                    )
127                    self.executor.plan.context.pop(PLAN_CONTEXT_SMS_DEVICE, None)
128                    self.logger.warning("failed to send SMS message to pre-set number", exc=exc)
129                    return self.get(request, *args, **kwargs)
130        return super().get(request, *args, **kwargs)
131
132    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
133        """SMS Token is validated by challenge"""
134        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
135        if not device.confirmed:
136            return self.challenge_invalid(response)
137        stage: AuthenticatorSMSStage = self.executor.current_stage
138        if stage.verify_only:
139            self.logger.debug("Hashing number on device")
140            device.set_hashed_number()
141        device.save()
142        del self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
143        return self.executor.stage_ok()

OTP sms Setup stage

response_class = <class 'AuthenticatorSMSChallengeResponse'>
def validate_and_send(self, phone_number: str):
69    def validate_and_send(self, phone_number: str):
70        """Validate phone number and send message"""
71        stage: AuthenticatorSMSStage = self.executor.current_stage
72        hashed_number = hash_phone_number(phone_number)
73        query = Q(phone_number=hashed_number) | Q(phone_number=phone_number)
74        if SMSDevice.objects.filter(query, stage=stage.pk).exists():
75            raise ValidationError(_("Invalid phone number"))
76        # No code yet, but we have a phone number, so send a verification message
77        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
78        stage.send(self.request, device.token, device)

Validate phone number and send message

def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
93    def get_challenge(self, *args, **kwargs) -> Challenge:
94        return AuthenticatorSMSChallenge(
95            data={
96                "phone_number_required": self._has_phone_number() is None,
97            }
98        )

Return the challenge that the client should solve

def get_response_instance( self, data: django.http.request.QueryDict) -> authentik.flows.challenge.ChallengeResponse:
100    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
101        response = super().get_response_instance(data)
102        response.device = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
103        return response

Return the response class type

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
105    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
106        user = self.get_pending_user()
107
108        stage: AuthenticatorSMSStage = self.executor.current_stage
109
110        if PLAN_CONTEXT_SMS_DEVICE not in self.executor.plan.context:
111            device = SMSDevice(user=user, confirmed=False, stage=stage, name="SMS Device")
112            device.generate_token(commit=False)
113            self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE] = device
114            if phone_number := self._has_phone_number():
115                device.phone_number = phone_number
116                try:
117                    self.validate_and_send(phone_number)
118                except ValidationError as exc:
119                    # We had a phone number given already (at this point only possible from flow
120                    # context), but an error occurred while sending a number (most likely)
121                    # due to a duplicate device, so delete the number we got given, reset the state
122                    # (ish) and retry
123                    device.phone_number = ""
124                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
125                        PLAN_CONTEXT_PHONE, None
126                    )
127                    self.executor.plan.context.pop(PLAN_CONTEXT_SMS_DEVICE, None)
128                    self.logger.warning("failed to send SMS message to pre-set number", exc=exc)
129                    return self.get(request, *args, **kwargs)
130        return super().get(request, *args, **kwargs)

Return a challenge for the frontend to solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
132    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
133        """SMS Token is validated by challenge"""
134        device: SMSDevice = self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
135        if not device.confirmed:
136            return self.challenge_invalid(response)
137        stage: AuthenticatorSMSStage = self.executor.current_stage
138        if stage.verify_only:
139            self.logger.debug("Hashing number on device")
140            device.set_hashed_number()
141        device.save()
142        del self.executor.plan.context[PLAN_CONTEXT_SMS_DEVICE]
143        return self.executor.stage_ok()

SMS Token is validated by challenge