浏览代码

init commit

chenjunkai 5 年之前
当前提交
9d1e3f5f9b

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+/.idea
+/db.sqlite3

+ 0 - 0
azoauth/__init__.py


二进制
azoauth/__pycache__/__init__.cpython-36.pyc


二进制
azoauth/__pycache__/settings.cpython-36.pyc


二进制
azoauth/__pycache__/urls.cpython-36.pyc


二进制
azoauth/__pycache__/wsgi.cpython-36.pyc


+ 151 - 0
azoauth/settings.py

@@ -0,0 +1,151 @@
+"""
+Django settings for azoauth project.
+
+Generated by 'django-admin startproject' using Django 2.1.4.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/2.1/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/2.1/ref/settings/
+"""
+
+import os
+
+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
+BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'p7!s!=fn!a^e_&r46)*8*4y-bdyam$m@kr31e!+r56dtv##bz1'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = ['*']
+
+
+# Application definition
+
+INSTALLED_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'corsheaders',
+    'model'
+]
+
+MIDDLEWARE = [
+    'django.middleware.security.SecurityMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.common.CommonMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
+    'corsheaders.middleware.CorsMiddleware',
+    'django.middleware.common.CommonMiddleware',
+]
+
+ROOT_URLCONF = 'azoauth.urls'
+
+TEMPLATES = [
+    {
+        'BACKEND': 'django.template.backends.django.DjangoTemplates',
+        'DIRS': [os.path.join(BASE_DIR, 'templates')]
+        ,
+        'APP_DIRS': True,
+        'OPTIONS': {
+            'context_processors': [
+                'django.template.context_processors.debug',
+                'django.template.context_processors.request',
+                'django.contrib.auth.context_processors.auth',
+                'django.contrib.messages.context_processors.messages',
+            ],
+        },
+    },
+]
+
+WSGI_APPLICATION = 'azoauth.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
+
+AUTH_PASSWORD_VALIDATORS = [
+    {
+        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
+    },
+    {
+        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
+    },
+]
+
+
+# Internationalization
+# https://docs.djangoproject.com/en/2.1/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_L10N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/2.1/howto/static-files/
+
+STATIC_URL = '/static/'
+# 跨域增加忽略
+CORS_ALLOW_CREDENTIALS = True
+CORS_ORIGIN_ALLOW_ALL = True
+CORS_ORIGIN_WHITELIST = ()
+
+CORS_ALLOW_METHODS = (
+    'DELETE',
+    'GET',
+    'OPTIONS',
+    'PATCH',
+    'POST',
+    'PUT',
+    'VIEW',
+)
+
+CORS_ALLOW_HEADERS = (
+    'accept',
+    'accept-encoding',
+    'authorization',
+    'content-type',
+    'dnt',
+    'origin',
+    'user-agent',
+    'x-csrftoken',
+    'x-requested-with',
+)

+ 24 - 0
azoauth/urls.py

@@ -0,0 +1,24 @@
+"""azoauth URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/2.1/topics/http/urls/
+Examples:
+Function views
+    1. Add an import:  from my_app import views
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
+Class-based views
+    1. Add an import:  from other_app.views import Home
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
+Including another URLconf
+    1. Import the include() function: from django.urls import include, path
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
+"""
+
+from django.contrib import admin
+from django.urls import path
+from controller import index
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('oa2/auth', index.authView.as_view()),
+]

+ 16 - 0
azoauth/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for azoauth project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azoauth.settings')
+
+application = get_wsgi_application()

二进制
controller/__pycache__/index.cpython-36.pyc


+ 148 - 0
controller/index.py

@@ -0,0 +1,148 @@
+#!/usr/bin/env python3  
+# -*- coding: utf-8 -*-  
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@AUTHOR: ASJRD018
+@NAME: azoauth
+@software: PyCharm
+@DATE: 2020/1/13 17:01
+@Version: python3.6
+@MODIFY DECORD:ansjer dev
+@file: index.py
+@Contact: chanjunkai@163.com
+"""
+import json
+import time
+import requests
+from django.views.generic import TemplateView
+from django.shortcuts import render_to_response
+from object.ResObject import ResObject
+import subprocess
+from gevent.pool import Pool
+
+
+class authView(TemplateView):
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = json.loads(request.body.decode('utf-8'))
+        return self.validate(request_dict)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        rq_data = request_dict
+        state = request_dict.get("state", '')
+        client_id = request_dict.get("client_id", '')
+        response_type = request_dict.get("response_type", '')
+        scope = request_dict.get("scope", '')
+        redirect_uri = request_dict.get("redirect_uri", '')
+        context = {
+            'state': state,
+            'client_id': client_id,
+            'response_type': response_type,
+            'scope': scope,
+            'redirect_uri': redirect_uri,
+        }
+        return render_to_response("login.html", context)
+        # return render_template('./login.html', **context)
+
+
+class loginHandleView(TemplateView):
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = json.loads(request.body.decode('utf-8'))
+        return self.validate(request_dict)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        response = ResObject()
+        user = request_dict.get("user", '')
+        pwd = request_dict.get("pwd", '')
+        state = request_dict.get("state", '')
+        client_id = request_dict.get("client_id", '')
+        response_type = request_dict.get("response_type", '')
+        scope = request_dict.get("scope", '')
+        redirect_uri = request_dict.get("redirect_uri", '')
+        # 返回code
+        code = user
+        auth_request_url = 'http://test.dvema.com/account/login?userName=13800138001&userPwd=ansjer999999'
+        requests_data = {
+            'userName': user,
+            'userPwd': pwd
+        }
+        res = requests.post(url=auth_request_url, data=requests_data)
+        print(res.json()['result_code'])
+
+        if res.json()['result_code'] == 0:
+            redirect_uri = redirect_uri + '?code=' + code + '&state=' + state
+            return redirect_uri
+        else:
+            return response.json(0, res={'msg': 'error'})
+
+
+class oa2TokenView(TemplateView):
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = json.loads(request.body.decode('utf-8'))
+        return self.validate(request_dict)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        # 增加对code和client_id的校验代码,返回access_token和refresh_token
+        code = request_dict.get("code", None)
+        client_id = request_dict.get("client_id", None)
+        access_token = "aaaaaaaaaaaaaaa"
+        refresh_token = "tGzv3JOkF0XG5Qx2TlKWIA"
+        res_json = {
+            "access_token": access_token,
+            "token_type": "bearer",
+            "expires_in": 3600,
+            "refresh_token": refresh_token
+        }
+        response = ResObject()
+        return response.json(0, res=res_json)
+
+
+class oa2TokenView(TemplateView):
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = json.loads(request.body.decode('utf-8'))
+        return self.validate(request_dict)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        '''
+        VVDHCVBYDKFMJRWA111A
+        '''
+        UID = request_dict.get("UID", '')
+        PWD = request_dict.get("PWD", '')
+        MSG = request_dict.get("MSG", '')
+        # po = Pool(10)
+        # po.apply_async(runSendRtspMsg, (UID, PWD, MSG))
+        self.runSendRtspMsg(UID, PWD, MSG)
+        response = ResObject()
+        return response.json(0, {'res': 'yes'})
+
+    def runSendRtspMsg(self, UID, PWD, MSG):
+        command = "./test {UID} {PWD} {MSG}".format(UID=UID, PWD=PWD, MSG=MSG)
+        print('command=>{command}'.format(command=command))
+        back = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(
+            timeout=4)
+        print("back0----", back[0].decode())  # 注意需要进行解码操作,默认输出的是字节
+        print("back1----", back[1].decode())  # back是一个元祖,可以通过元祖取值的方式获取结果
+        return

+ 15 - 0
manage.py

@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+import os
+import sys
+
+if __name__ == '__main__':
+    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azoauth.settings')
+    try:
+        from django.core.management import execute_from_command_line
+    except ImportError as exc:
+        raise ImportError(
+            "Couldn't import Django. Are you sure it's installed and "
+            "available on your PYTHONPATH environment variable? Did you "
+            "forget to activate a virtual environment?"
+        ) from exc
+    execute_from_command_line(sys.argv)

+ 0 - 0
model/__init__.py


二进制
model/__pycache__/__init__.cpython-36.pyc


二进制
model/__pycache__/admin.cpython-36.pyc


二进制
model/__pycache__/models.cpython-36.pyc


+ 3 - 0
model/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 5 - 0
model/apps.py

@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class ModelConfig(AppConfig):
+    name = 'model'

+ 49 - 0
model/migrations/0001_initial.py

@@ -0,0 +1,49 @@
+# Generated by Django 2.1.4 on 2020-01-13 08:59
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='UidRtspModel',
+            fields=[
+                ('id', models.AutoField(primary_key=True, serialize=False)),
+                ('uid', models.CharField(default='', max_length=32, verbose_name='设备UID')),
+                ('rtsp_url', models.CharField(default='', max_length=128, verbose_name='rtsp流地址')),
+                ('addTime', models.IntegerField(default=0, verbose_name='添加时间')),
+                ('updTime', models.IntegerField(default=0, verbose_name='更新时间')),
+            ],
+            options={
+                'verbose_name': '用户表',
+                'db_table': 'uid_rtsp',
+                'ordering': ('-addTime',),
+            },
+        ),
+        migrations.CreateModel(
+            name='UserModel',
+            fields=[
+                ('userID', models.AutoField(primary_key=True, serialize=False)),
+                ('token', models.CharField(default='', max_length=64, unique=True, verbose_name='用户名')),
+                ('addTime', models.IntegerField(default=0, verbose_name='添加时间')),
+                ('updTime', models.IntegerField(default=0, verbose_name='更新时间')),
+            ],
+            options={
+                'verbose_name': '用户表',
+                'db_table': 'user',
+                'ordering': ('-addTime',),
+            },
+        ),
+        migrations.AddField(
+            model_name='uidrtspmodel',
+            name='user',
+            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='model.UserModel', verbose_name='用户表id'),
+        ),
+    ]

+ 0 - 0
model/migrations/__init__.py


二进制
model/migrations/__pycache__/0001_initial.cpython-36.pyc


二进制
model/migrations/__pycache__/__init__.cpython-36.pyc


+ 36 - 0
model/models.py

@@ -0,0 +1,36 @@
+from django.db import models
+
+
+# Create your models here.
+
+
+class UserModel(models.Model):
+    userID = models.AutoField(primary_key=True)
+    token = models.CharField(max_length=64, unique=True, default='', verbose_name='用户名')
+    addTime = models.IntegerField(verbose_name='添加时间', default=0)
+    updTime = models.IntegerField(verbose_name='更新时间', default=0)
+
+    class Meta:
+        ordering = ('-addTime',)
+        verbose_name = '用户表'
+        db_table = 'user'
+
+    def __str__(self):
+        return self.userID
+
+
+class UidRtspModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    user = models.ForeignKey(UserModel, verbose_name='用户表id', to_field='userID', on_delete=models.CASCADE)
+    uid = models.CharField(max_length=32, verbose_name=u'设备UID', default='')
+    rtsp_url = models.CharField(max_length=128, verbose_name='rtsp流地址', default='')
+    addTime = models.IntegerField(verbose_name='添加时间', default=0)
+    updTime = models.IntegerField(verbose_name='更新时间', default=0)
+
+    class Meta:
+        ordering = ('-addTime',)
+        verbose_name = '用户表'
+        db_table = 'uid_rtsp'
+
+    def __str__(self):
+        return self.id

+ 3 - 0
model/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 3 - 0
model/views.py

@@ -0,0 +1,3 @@
+from django.shortcuts import render
+
+# Create your views here.

+ 18 - 0
object/ResObject.py

@@ -0,0 +1,18 @@
+from django.shortcuts import HttpResponse
+import simplejson as json
+
+
+class ResObject(object):
+
+    def __init__(self, lang='cn'):
+        self.lang = lang
+
+    def json(self, code, res={}, extra={}):
+        msg_data = {
+            0: 'Success',
+        }
+        result = {'code': code, 'msg': msg_data[code], 'res': res}
+        if extra:
+            for k in extra:
+                result[k] = extra[k]
+        return HttpResponse(json.dumps(result, ensure_ascii=False))

二进制
object/__pycache__/ResObject.cpython-36.pyc


+ 69 - 0
object/tkObject.py

@@ -0,0 +1,69 @@
+#!/usr/bin/env python3  
+# -*- coding: utf-8 -*-  
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@AUTHOR: ASJRD018
+@NAME: AnsjerFormal
+@software: PyCharm
+@DATE: 2019/6/1 17:25
+@Version: python3.6
+@MODIFY DECORD:ansjer dev
+@file: tkObject.py
+@Contact: chanjunkai@163.com
+"""
+
+import base64
+import urllib.parse
+from random import Random
+
+
+class tkObject(object):
+    def __init__(self, tk='', rank=0):
+        self.data = ''
+        self.rank = rank
+        self.parseUid(tk)
+
+    def parseUid(self, tk):
+        try:
+            c = base64.b64decode(tk)
+            rank = self.rank
+            c = c[rank:-1*rank]
+            c = urllib.parse.unquote(c.decode('utf-8'))
+            c = base64.b64decode(c)
+            data = c.decode('utf-8')
+            self.data = data
+        except Exception as e:
+            print(repr(e))
+
+    def encrypt(self, data):
+        s = data.encode()
+        s = base64.b64encode(s)
+        rank = self.rank
+        startStr = self.randomParam(rank=rank)
+        endStr = self.randomParam(rank=rank)
+        s = '{startStr}{s}{endStr}'.format(startStr=startStr, s=s.decode('utf-8'), endStr=endStr)
+        s = base64.b64encode(s.encode())
+        s = s.decode('utf-8')
+        return s
+
+    def randomParam(self, rank):
+        characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
+                       'tUuVvWwXxYyZz0123456789'
+        length = len(characterSet) - 1
+
+        random = Random()
+        ss = ''
+        for index in range(rank):
+            ss += characterSet[random.randint(0, length)]
+        return ss
+
+# tkobj = tkObject(tk='',rank=30)
+# PP = tkobj.encrypt(data='data')
+# print('encode_data:')
+# print(PP)
+# print('decode_data:')
+#######################################################
+# ttk = 'cnlJNUUyMmRXNUxmNFBIMk54enRtSjBmZWRqUTdiWkdGMFlRPT1leHJ1ZTQ0WG5pd3lXUDBLU1VoanNiUnZLM0kxbjU='
+# tkobj = tkObject(tk=ttk,rank=30)
+# data = tkobj.data
+# print(data)

+ 49 - 0
templates/login.html

@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+
+<html>
+<head>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+    <meta name="viewport" content="width=device-width">
+    <!--
+        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
+    -->
+
+    <title>XXXX Login</title>
+    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
+</head>
+
+<body>
+
+<div id="login">
+    <h1>WELCOME</h1>
+    <input id="user_text" type="text" placeholder="Account"/>
+    <input id="password_text" type="text" placeholder="Password"/>
+    <input type="button" id="login_button" value="Connect" onclick="Login();return false;"/>
+    <p><a href="javascript:void(0);">Forgot your password?</a></p>
+</div>
+
+<script type="text/javascript">
+    function Login() {
+        var user = document.getElementById("user_text");
+        var pwd = document.getElementById("password_text");
+        if (user.value.length > 0) {
+            //console.log("user: " + user.value);
+            //console.log("pwd: " + pwd.value);
+
+            var params = "user=" + user.value + "&pwd=" + pwd.value + "&state={{ state }}" + "&client_id={{ client_id }}" +
+                "&response_type={{ response_type }}" + "&scope={{ scope }}" + "&redirect_uri={{ redirect_uri }}";
+
+            alert('1234')
+            $.get("/oa2/login", params, function (reUrl) {
+                //alert(reUrl);
+                console.log('request start')
+                window.location = reUrl;
+            });
+        } else {
+            alert("please input user and password");
+        }
+    }
+</script>
+
+</body>
+</html>