In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "vue how to achieve SMS CAPTCHA", the content of the explanation is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "vue how to achieve SMS CAPTCHA" bar!
Demand 1, demand
When we are doing website development, in many cases, the login page can use the mobile number to receive the SMS verification code, and then log in, so let's do this function today.
Pseudo code:
Go to the login page and click SMS to log in
Enter the mobile phone number, click to get the verification code, and the backend saves the verification code in redis
The user inputs the verification code received by the phone, clicks to log in, and sends the phone number and verification code to the back end, and then verifies it.
To send SMS messages and allow users to receive SMS messages, we have to sign up for an account with the help of an interface of Universe Cloud.
Some parameters required for use:
Download sdk
1. .
2. .
3. .
After the download is complete, extract it. Put it in the libs in the apps of our drf project
Second, sdk parameter configuration 1, directory structure
2, configure the sms.py file
#-*-coding:utf-8-*-from .CCPRestSDK import REST# description: after logging in to the IM website, you can see the developer's main account ACCOUNT SID_accountSid = "xxxxxxxxxxxxx" # 8a216da863f8e6c20164139687e80c1b# in "console-App". Description: main account Token, after logging in to the IM website. You can see the developer's main account AUTH TOKEN_accountToken = "xxxxxxxxxxxxx" # 6dd01b2b60104b3dbc88b2b74158bac6# in the console-App. Please use APPID on the home page of the management console or APPID_appId = "8aaf0708697b6beb01699f3c645f1766" # 8a216da863f8e6c20164139688400c21# of the application created by yourself. Description: request address, production environment is configured as app.cloopen.com_serverIP = "sandboxapp.cloopen.com" # description: request port Production environment is 8883_serverPort = "8883" # Note: REST API version number remains unchanged _ softVersion = "2013-12-26" # the following content does not need to be modified class CCP (object): "def _ new__ (cls, * args, * * kwargs): # determine whether there is a class attribute _ instance,_instance is the only object of class CCP That is, single case if not hasattr (CCP, "_ instance"): cls._instance = super (CCP, cls). _ _ new__ (cls, * args, * * kwargs) cls._instance.rest = REST (_ serverIP, _ serverPort, _ softVersion) cls._instance.rest.setAccount (_ accountSid) _ accountToken) cls._instance.rest.setAppId (_ appId) return cls._instance def send_template_sms (self, to, datas, temp_id): "" send template SMS "" # @ param to Mobile number # @ param datas content data format is an array for example: {"12", "34"} If you do not need to replace, please fill in "# @ param temp_id template Id result = self.rest.sendTemplateSMS (to, datas, temp_id) # if IM sends SMS successfully The value of the statuCode field in the returned dictionary data result is "000000" if result.get ("statusCode") = = "000000": # return 0 indicates success return 0 else: # return-1 indicates failure return-1if _ _ name__ = "_ _ main__": ccp = CCP () # Note: the SMS template number of the test is 1 ccp.send_template_sms ("15914397060" ["1234", 5], 1) III. Code implementation 1 Back-end code
Views.py, which is the processing of getting the CAPTCHA request, that is, the backend generates a random code, sends it to the mobile phone user, stores the random code in redis, and then returns a CAPTCHA signal to the front end
From. Models import Userfrom rest_framework import statusfrom lufei_drf.libs.yuntongxun.sms import CCPfrom django_redis import get_redis_connectionclass SMSCodeAPIView (APIView): def get (self,request): # 1. Get the mobile phone number phone = request.query_params.get ("phone") ty=request.query_params.get ("type") # 2 by querying the string. Verify the mobile phone number if ty== "register": try: User.objects.get (phone=phone) return Response ({"message": "the current mobile number has been registered") before sending SMS messages. Status=status.HTTP_400_BAD_REQUEST) except: pass redis = get_redis_connection ("sms_code") if redis.get ("times_%s"% phone): return Response ({"message": "the current mobile number has sent SMS messages within one minute"}, status=status.HTTP_400_BAD_REQUEST) # 3. Send SMS verification code using mobile phone number # generate an SMS verification code sms_code = "d"% random.randint (0,9999) ccp = CCP () result = ccp.send_template_sms (phone, [sms_code, "5 minutes"], 1) if result = = 0: # SMS sent successfully Save the SMS verification code to the redis database # Open the pipeline operation pl = redis.pipeline () pl.multi () # then execute multiple commands in the pipeline # setex (variable name, validity period [seconds]) Value) SMS_EXPIRE_TIME = 5 * 60 # validity period of SMS verification code SMS_TIMES = 60 # interval between SMS messages # put the command that was executed immediately into the pipeline pl.setex ("sms_%s"% phone, SMS_EXPIRE_TIME, sms_code) pl.setex ("times_%s"% phone, SMS_TIMES) 1) # uniformly execute the command pl.execute () # 4. Response data is sent to the client return Response ({"message": result}, status=status.HTTP_200_OK)
Urls.py
Login view from rest_framework_jwt.views import obtain_jwt_tokenfrom .views import SMSCodeAPIView,urlpatterns= implemented inside from django.urls import path# jwt [path (r "login/", obtain_jwt_token), path ("sms/", SMSCodeAPIView.as_view ()),]
Utils.py, this is the proofreading of the mobile number and CAPTCHA after the user submits the CAPTCHA. After the judgment is correct, an object is returned, including token,user information, etc.
From django.contrib.auth.backends import ModelBackendfrom django_redis import get_redis_connectiondef jwt_response_payload_handler (token, user=None, request=None): "" Custom jwt authentication successfully returned data: jwt: user current login user information returned by token [object]: data submitted by request client this time "" return {"token": token, "id": user.id "username": user.username,} # implement multi-function login import refrom .models import User# to find whether the user name or mobile number is already our user def get_user_by_account (account): "" get the user object according to the account: param account: account It can be a user name It can also be the mobile phone number: return: User object or None "" try: if re.match ("^ 1 [3-9] d {9} $" Account): # account is user = User.objects.get (phone=account) else: # account is user name user = User.objects.get (username=account) except User.DoesNotExist: return None else: return user# verify whether the SMS submitted by the user is consistent with the information we saved in redis def sms_code_verify (phone Sms_code): redis = get_redis_connection ("sms_code") value=redis.get ("sms_%s"% phone). Decode () if value==sms_code: return True return Falseclass UsernameMobileAuthBackend (ModelBackend): "" Custom user name or mobile number authentication "" def authenticate (self, request, username=None, password=None * * kwargs): user = get_user_by_account (username) # when the password length is 4 I judge it to be the mobile phone number and SMS verification code login if len (password) = = 4 and user is not None and sms_code_verify (username,password): return user elif user is not None and user.check_password (password): return user else: return None2, front-end code
Login component
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.