Python django.contrib.auth.authenticate() Examples

The following are 30 code examples for showing how to use django.contrib.auth.authenticate(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.contrib.auth , or try the search function .

Example 1
Project: yang-explorer   Author: CiscoDevNet   File: testview.py    License: Apache License 2.0 7 votes vote down vote up
def test_01_login(self):
        """Verify user creation"""
       	user = authenticate(username='demo', password='demo123')
       	self.assertTrue(user is not None)
       	self.assertTrue(user.is_active == True)

        user = authenticate(username='demo', password='demo122')
        self.assertTrue(user is None)

        user = authenticate(username='demo', password='')
        self.assertTrue(user is None)

        user = authenticate(username='demo1', password='demo123')
        self.assertTrue(user is None)

        user = authenticate(username='', password='demo123')
        self.assertTrue(user is None) 
Example 2
Project: oxidizr   Author: pixlie   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def form_valid(self, form):
        user_email = form.cleaned_data['email'].lower().strip()
        password = form.cleaned_data['password']
        user = authenticate(email=user_email, password=password)
        if user and user.is_active:
            login(self.request, user)
            return redirect(self.get_success_url())
        else:
            try:
                user = User.objects.get(email__iexact=user_email)
                if not check_password(password, user.password):
                    form._errors['password'] = ErrorList([u'That is not the correct Password.'])
            except User.DoesNotExist:
                form._errors['email'] = ErrorList([u'This email is not registered with us.'])
            context = self.get_context_data(form=form)
            return self.render_to_response(context) 
Example 3
Project: seqr   Author: macarthur-lab   File: auth_api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def login_view(request):
    request_json = json.loads(request.body)
    if not request_json.get('email'):
        return create_json_response({}, status=400, reason='Email is required')
    if not request_json.get('password'):
        return create_json_response({}, status=400, reason='Password is required')

    users = User.objects.filter(email__iexact=request_json['email'])
    if users.count() != 1:
        return create_json_response({}, status=401, reason='Invalid credentials')

    u = authenticate(username=users.first().username, password=request_json['password'])
    if not u:
        return create_json_response({}, status=401, reason='Invalid credentials')

    login(request, u)

    return create_json_response({'success': True}) 
Example 4
Project: seqr   Author: macarthur-lab   File: users_api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def set_password(request, username):
    user = User.objects.get(username=username)

    request_json = json.loads(request.body)
    if not request_json.get('password'):
        return create_json_response({}, status=400, reason='Password is required')

    user.set_password(request_json['password'])
    user.first_name = request_json.get('firstName') or ''
    user.last_name = request_json.get('lastName') or ''
    user.save()

    u = authenticate(username=username, password=request_json['password'])
    login(request, u)

    return create_json_response({'success': True}) 
Example 5
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 6 votes vote down vote up
def test_log_out_the_user_if_the_id_token_is_not_valid(self, rf):
        request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        user = backend.authenticate(request, 'nonce')
        request.session['oidc_auth_id_token_exp_timestamp'] = \
            (tz.now() - dt.timedelta(minutes=1)).timestamp()
        request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
        auth.login(request, user)
        request.user = user

        httpretty.register_uri(
            httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
            body=json.dumps({
                'id_token': 'badidtoken', 'access_token': 'accesstoken',
                'refresh_token': 'refreshtoken', }),
            content_type='text/json')

        middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
        middleware(request)
        assert not request.user.is_authenticated 
Example 6
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 6 votes vote down vote up
def test_log_out_the_user_if_the_refresh_token_is_expired(self, rf):
        request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        user = backend.authenticate(request, 'nonce')
        request.session['oidc_auth_id_token_exp_timestamp'] = \
            (tz.now() - dt.timedelta(minutes=1)).timestamp()
        request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
        auth.login(request, user)
        request.user = user

        httpretty.register_uri(
            httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
            body=json.dumps({'error': 'yes'}),
            content_type='text/json', status=400)

        middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
        middleware(request)
        assert not request.user.is_authenticated 
Example 7
Project: arches   Author: archesproject   File: auth.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request):
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        user = authenticate(username=username, password=password)
        if user:
            if hasattr(user, "userprofile") is not True:
                models.UserProfile.objects.create(user=user)
            userDict = JSONSerializer().serializeToPython(user)
            userDict["password"] = None
            userDict["is_reviewer"] = user_is_resource_reviewer(user)
            userDict["viewable_nodegroups"] = user.userprofile.viewable_nodegroups
            userDict["editable_nodegroups"] = user.userprofile.editable_nodegroups
            userDict["deletable_nodegroups"] = user.userprofile.deletable_nodegroups
            response = JSONResponse(userDict)
        else:
            response = Http401Response()

        return response 
Example 8
Project: StormOnline   Author: stormsha   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data 
Example 9
Project: ideascube   Author: ideascube   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def welcome_staff(request):
    """Allow to create a staff user if None exists yet."""
    if user_model.objects.filter(is_staff=True).exists():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = CreateStaffForm(request.POST)
        if form.is_valid():
            user = form.save()
            user = authenticate(serial=user.serial,
                                password=request.POST['password'])
            login(request, user)
            msg = _(u'Welcome to {}, {}!').format(
                get_config('server', 'site-name'), user)
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect('/')
    else:
        form = CreateStaffForm()
    return render(request, 'ideascube/welcome_staff.html', {'form': form}) 
Example 10
Project: AnsibleUI   Author: lotus-dgas   File: account.py    License: GNU General Public License v3.0 6 votes vote down vote up
def myLogin(request):
    errors = []
    data = ''
    next = request.GET.get('next') or request.GET.get('redirect_to') or '/'
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        if not request.POST.get('username',''):
            errors.append('Enter a user')
        if not request.POST.get('password',''):
            errors.append('Enter a passwd')
        if not errors:
            user = auth.authenticate(username=username,password=password)
            if user is not None and user.is_active:
                auth.login(request,user)
                return redirect('%s' % next)
            else:
                data = '登陆失败,请核对信息'
        print(errors)
    return render(request, 'login2.html', {'errors': errors, 'data': data},) 
Example 11
Project: GTDWeb   Author: lanbing510   File: forms.py    License: GNU General Public License v2.0 6 votes vote down vote up
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data 
Example 12
Project: kobo-predict   Author: awemulya   File: test_base.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _make_submission_w_attachment(self, path, attachment_path):
        with open(path) as f:
            a = open(attachment_path)
            post_data = {'xml_submission_file': f, 'media_file': a}
            url = '/%s/submission' % self.user.username
            auth = DigestAuth('bob', 'bob')
            self.factory = APIRequestFactory()
            request = self.factory.post(url, post_data)
            request.user = authenticate(username='bob',
                                        password='bob')
            self.response = submission(request,
                                       username=self.user.username)

            if auth and self.response.status_code == 401:
                request.META.update(auth(request.META, self.response))
                self.response = submission(request,
                                           username=self.user.username) 
Example 13
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter_queryset(self, queryset):
        project = self.kwargs.get('pk', None)
        if project:
            queryset = queryset.filter(
                user__user_roles__project__id = project,
                user__is_active=True).order_by('user__first_name')
            return queryset
        try:
            org = self.request.user.user_profile.organization
            queryset = queryset.filter(organization = org,user__is_active=True).order_by('user__first_name')
        except:
            queryset = []
        return queryset


# def web_authenticate(username=None, password=None):
#         # returns User , Email_correct, Password_correct
#         try:
#             user = User.objects.get(email__iexact=username)
#             if user.check_password(password):
#                 return authenticate(username=user.username, password=password)
#             else:
#                 return None, True, False
#         except User.DoesNotExist:
#             return None, False, True 
Example 14
Project: kobo-predict   Author: awemulya   File: test_briefcase_client.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def form_list_xml(url, request, **kwargs):
    response = requests.Response()
    factory = RequestFactory()
    req = factory.get(url.path)
    req.user = authenticate(username='bob', password='bob')
    req.user.profile.require_auth = False
    req.user.profile.save()
    id_string = 'transportation_2011_07_25'
    if url.path.endswith('formList'):
        res = formList(req, username='bob')
    elif url.path.endswith('form.xml'):
        res = download_xform(req, username='bob', id_string=id_string)
    elif url.path.find('xformsManifest') > -1:
        res = xformsManifest(req, username='bob', id_string=id_string)
    elif url.path.find('formid-media') > -1:
        data_id = url.path[url.path.rfind('/') + 1:]
        res = download_media_data(
            req, username='bob', id_string=id_string, data_id=data_id)
        response._content = get_streaming_content(res)
    else:
        res = formList(req, username='bob')
    response.status_code = 200
    if not response._content:
        response._content = res.content
    return response 
Example 15
Project: kobo-predict   Author: awemulya   File: test_briefcase_api.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_submission_with_instance_id_on_root_node(self):
        self._publish_xml_form()
        message = u"Successful submission."
        instanceId = u'5b2cc313-fc09-437e-8149-fcd32f695d41'
        self.assertRaises(
            Instance.DoesNotExist, Instance.objects.get, uuid=instanceId)
        submission_path = os.path.join(
            self.this_directory, 'fixtures', 'transportation',
            'view', 'submission.xml')
        count = Instance.objects.count()
        with codecs.open(submission_path, encoding='utf-8') as f:
            post_data = {'xml_submission_file': f}
            self.factory = APIRequestFactory()
            request = self.factory.post(self._submission_url, post_data)
            request.user = authenticate(username='bob',
                                        password='bob')
            response = submission(request, username=self.user.username)
            self.assertContains(response, message, status_code=201)
            self.assertContains(response, instanceId, status_code=201)
            self.assertEqual(Instance.objects.count(), count + 1) 
Example 16
Project: django-useraudit   Author: muccg   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def simulate_login(username, password, headers=None):
    rf = RequestFactory()
    request = rf.request(**headers)
    engine = import_module(settings.SESSION_ENGINE)
    request.session = engine.SessionStore()

    # TODO remove when we don't support Django 1.10 anymore
    # request passed in to authenticate only after Django 1.10
    # Also the middleware saving the request to thread local can be dropped
    try:
        user = authenticate(request, username=username, password=password)
    except TypeError:
        middleware.thread_data.request = request
        user = authenticate(username=username, password=password)
    if user:
        login(request, user) 
Example 17
Project: OpenMDM   Author: OpenMDM   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def site_login(request):
    """
    Logs in current user
    :param request:
    :return render:
    """
    if request.method == "POST":
        user = None
        user_login = request.POST['login']
        user_password = request.POST['password']
        print("Login tryout by "+user_login)
        if user_login != "" and user_password != "":
            user = authenticate(username=user_login, password=user_password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse('public_gate:home'))
        else:
            # User.objects.create_user(user_login, '', user_password).save()
            return render(request, 'public_gate/home.html', {"error_message": "Wrong login/password combination"})
    return render(request, 'public_gate/home.html', {"error_message": "One or more fields are empty"}) 
Example 18
Project: gazetteer   Author: LibraryOfCongress   File: views.py    License: MIT License 5 votes vote down vote up
def login_json(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        user_json = {
            'id': user.id,
            'username': user.username
        }
        return render_to_json_response({'success': 'User logged in', 'user': user_json})
    return render_to_json_response({'error': 'Username / password do not match'}) 
Example 19
Project: gazetteer   Author: LibraryOfCongress   File: permissions.py    License: MIT License 5 votes vote down vote up
def user_has_perms(self, request):
        '''
            Check if user has permissions for the URL path and method in the request.
        '''
        path, user, method = (request.path, request.user, request.method,)
        #If it is not an API call, always return True
        if not path.startswith(API_BASE):
            return True
        #Return True for all GET requests
        if method == 'GET':
            return True
        #If request is POST, PUT or DELETE, check if user is authenticated. More fine-grained permissions checks can be handled here
        if method in ['POST', 'PUT', 'DELETE']:

            if not user.is_authenticated():
                #If user is not authenticated by session var, check for http basic
                if 'HTTP_AUTHORIZATION' in request.META:
                    auth = request.META['HTTP_AUTHORIZATION'].split()
                    if len(auth) == 2:
                        if auth[0].lower() == "basic":
                            uname, passwd = base64.b64decode(auth[1]).split(':')
                            user = authenticate(username=uname, password=passwd)
                            if user is not None:
                                if user.is_active:
                                    login(request, user)
                                    request.user = user
                                    return True
                return False
            else:
                return True
        #Ideally, should never reach here. #QUESTION: perhaps we want to return False by default?
        return True 
Example 20
Project: yang-explorer   Author: CiscoDevNet   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def login_handler(request):
    """ HTTP Request handler function for user login / logout requests """
    if request.POST:
        action = request.POST['action']
        if action == 'login':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # Correct password, and the user is marked "active"
                login(request, user)
            else:
                return HttpResponse(Response.error('login', 'Authentication Failed'))
        else:
            username = ''
            try:
                if request.session.session_key is not None and request.session.session_key != '':
                    session_dir = ServerSettings.session_path(request.session.session_key)
                    if os.path.exists(session_dir):
                        logger.debug('Cleaning ' + session_dir)
                        shutil.rmtree(session_dir)
                logout(request)
            except:
                logger.exception("Failed")
            else:
                logger.debug('Logout success!!')
        session = get_session_config(username)
        return HttpResponse(Response.success(action, 'ok', session))
    return HttpResponse(Response.error('unknown', 'Invalid request!!')) 
Example 21
Project: crowdata   Author: crowdata   File: views.py    License: MIT License 5 votes vote down vote up
def login(request):
    next_page = request.REQUEST.get(auth.REDIRECT_FIELD_NAME, reverse('document_set_index'))

    if request.user.is_authenticated():
        return HttpResponseRedirect(next_page)

    request.session['redirect_after_login'] = next_page

    user = auth.authenticate(request=request)
    if user is not None:
        auth.login(request, user)
        return HttpResponseRedirect(reverse('after_login'))
    else:
        return { } 
Example 22
Project: django-rest-registration   Author: apragacz   File: users.py    License: MIT License 5 votes vote down vote up
def authenticate_by_login_data(
        data: Dict[str, Any], **kwargs) -> 'AbstractBaseUser':
    serializer = kwargs.get('serializer')
    if serializer:
        # TODO: Issue #114 - remove code supporting deprecated behavior
        get_authenticated_user = getattr(
            serializer, 'get_authenticated_user', None)
        if callable(get_authenticated_user):
            user = get_authenticated_user()
            if not user:
                raise UserNotFound()
            return user

    login_field_names = get_user_login_field_names()
    password = data.get('password')
    login = data.get('login')
    if password is None:
        raise UserNotFound()
    auth_tests = []  # type: List[Dict[str, Any]]
    if login is not None:
        auth_tests.extend({
            field_name: login,
            'password': password,
        } for field_name in login_field_names)

    for field_name in login_field_names:
        field_value = data.get(field_name)
        if field_value is None:
            continue
        auth_tests.append({
            field_name: field_value,
            'password': password,
        })

    for auth_kwargs in auth_tests:
        user = auth.authenticate(**auth_kwargs)
        if user:
            return user

    raise UserNotFound() 
Example 23
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_can_refresh_the_access_token_of_a_previously_authenticated_user(self, rf):
        request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        user = backend.authenticate(request, 'nonce')
        request.session['oidc_auth_id_token_exp_timestamp'] = \
            (tz.now() - dt.timedelta(minutes=1)).timestamp()
        request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
        auth.login(request, user)
        request.user = user
        middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
        middleware(request)
        assert request.session['oidc_auth_refresh_token'] == 'refreshtoken' 
Example 24
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_can_properly_handle_the_case_where_a_user_was_authenticated_using_the_model_backend(
            self, rf):
        request = rf.get('/')
        SessionMiddleware().process_request(request)
        request.session.save()
        user = get_user_model().objects.create_user('test', 'test@example.com', 'insecure')
        request.user = user
        auth.authenticate(username='test', password='insecure')
        auth.login(request, user)
        middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
        middleware(request)
        assert request.user == user
        assert request.user.is_authenticated 
Example 25
Project: django-oidc-rp   Author: impak-finance   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_do_nothing_if_the_access_token_is_still_valid(self, rf):
        request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        user = backend.authenticate(request, 'nonce')
        request.session['oidc_auth_id_token_exp_timestamp'] = \
            (tz.now() + dt.timedelta(minutes=1)).timestamp()
        request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
        auth.login(request, user)
        request.user = user
        middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
        middleware(request)
        assert request.session['oidc_auth_refresh_token'] == 'this_is_a_refresh_token' 
Example 26
Project: arches   Author: archesproject   File: auth.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request):
        # POST request is taken to mean user is logging in
        auth_attempt_success = None
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        user = authenticate(username=username, password=password)
        next = request.POST.get("next", reverse("home"))

        if user is not None and user.is_active:
            login(request, user)
            user.password = ""
            auth_attempt_success = True
            return redirect(next)

        return render(request, "login.htm", {"auth_failed": True, "next": next}, status=401) 
Example 27
Project: arches   Author: archesproject   File: auth.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request):
        messages = {"invalid_password": None, "password_validations": None, "success": None, "other": None, "mismatched": None}
        try:
            user = request.user
            old_password = request.POST.get("old_password")
            new_password = request.POST.get("new_password")
            new_password2 = request.POST.get("new_password2")
            if user.check_password(old_password) == False:
                messages["invalid_password"] = _("Invalid password")
            if new_password != new_password2:
                messages["mismatched"] = _("New password and confirmation must match")
            try:
                validation.validate_password(new_password, user)
            except ValidationError as val_err:
                messages["password_validations"] = val_err.messages

            if messages["invalid_password"] is None and messages["password_validations"] is None and messages["mismatched"] is None:
                user.set_password(new_password)
                user.save()
                authenticated_user = authenticate(username=user.username, password=new_password)
                login(request, authenticated_user)
                messages["success"] = _("Password successfully updated")

        except Exception as err:
            messages["other"] = err

        return JSONResponse(messages) 
Example 28
Project: arches   Author: archesproject   File: auth.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request):
        if settings.MOBILE_OAUTH_CLIENT_ID == "":
            message = _("Make sure to set your MOBILE_OAUTH_CLIENT_ID in settings.py")
            response = HttpResponse(message, status=500)
            logger.warning(message)
        else:
            username = request.POST.get("username", None)
            password = request.POST.get("password", None)
            user = authenticate(username=username, password=password)
            if user:
                response = JSONResponse({"clientid": settings.MOBILE_OAUTH_CLIENT_ID})
            else:
                response = Http401Response()
        return response 
Example 29
Project: arches   Author: archesproject   File: auth.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request):
        if settings.MOBILE_OAUTH_CLIENT_ID == "":
            message = _("Make sure to set your MOBILE_OAUTH_CLIENT_ID in settings.py")
            logger.warning(message)

        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        user = authenticate(username=username, password=password)
        if user:
            server_settings = {"version": __version__, "clientid": settings.MOBILE_OAUTH_CLIENT_ID}
            response = JSONResponse(server_settings)
        else:
            response = Http401Response()

        return response 
Example 30
Project: StormOnline   Author: stormsha   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None
# -----------------------------end---------------------------------------------------


# --------------------使用类继承django/static.view实现登陆业务逻辑--------------------------
# 最长用的继承view对象是get和post


# ------------------------邮箱验证业务逻辑----------------------------------