예제 #1
0
 def post(self, request, *args, **kwargs):
     """
 提交用户数据
 """
     serializer = CreateUserSerializer(instance=request, data=request.data)
     if serializer.is_valid():
         # serializer.validated_data
         del request.data['sign']
         changeStatus, errorMsg, newUserDn, newUser = CmdbLDAP(
         ).create_ldap_user(request.data)
         if changeStatus:
             returnData = {"status": changeStatus}
             dbdata = user_payload_handler(request.data, newUserDn, newUser)
             dbUsers = Users(**dbdata)
             dbUsers.set_password(request.data['userPassword'])
             dbUsers.save()
             if 'mail' in request.data and changeStatus:
                 reqdata = {
                     "sn": request.data['sn'],
                     "userPassword": request.data['userPassword'],
                     "username": newUser
                 }
                 send_register_email.delay(request.data['mail'], reqdata)
                 logger.info("正发送用户的注册相关信息到用户[%s]" % newUser)
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #2
0
    def post(self, request, *args, **kwargs):
        """
    提交用户数据
    """
        serializer = UpdateUserSerializer(instance=request, data=request.data)
        if serializer.is_valid():
            olddn = request.data['userdn']
            request.data.pop('userdn')
            request.data.pop('sign')
            userid = olddn.split(",")[0].split("=")[0]
            username = olddn.split(",")[0].split("=")[1]
            newUserid = request.data[userid]
            changeStatus, errorMsg = CmdbLDAP().update_ldap_user(
                request.data, olddn)
            if changeStatus:
                if newUserid == username:
                    newdn = olddn
                else:
                    try:
                        Users.objects.get(username=username,
                                          userdn=olddn).delete()
                    except Exception as e:
                        logger.warn(e)
                    username = newUserid
                    newdn = olddn.replace("=%s," % username, "%s," % newUserid)
                if "sshPublicKey" in request.data and cache.get(
                        "user_%s_public_key" % username):
                    dbdata = {
                        "username": username,
                        "userdn": newdn,
                        "publickey":
                        cache.get("user_%s_public_key" % username),
                        "privatekey":
                        cache.get("user_%s_private_key" % username),
                    }
                    if "mail" in request.data:
                        dbdata['email'] = request.data['mail']
                        sendmailuser = {
                            "username": username,
                            "email": request.data.get("mail"),
                        }
                        send_reset_sshkey_email.delay(sendmailuser)
                    Users.objects.update_or_create(defaults=dbdata,
                                                   username=username)

                returnData = {"status": changeStatus}
                returnStatus = status.HTTP_200_OK
            else:
                returnData = {"error": errorMsg}
                returnStatus = status.HTTP_400_BAD_REQUEST
        else:
            returnData = serializer.errors
            returnStatus = status.HTTP_400_BAD_REQUEST
        return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #3
0
 def get(self, request, *args, **kwargs):
     queryOU = settings.AUTH_LDAP_GROUP_SEARCH_OU
     ous, errorMsg = CmdbLDAP().get_base_ou(queryOU)
     if errorMsg:
         logger.error(errorMsg)
     if len(ous) > 0:
         return JsonResponse(ous, encoder=LDAPJSONEncoder, safe=False)
     else:
         return JsonResponse({"error": errorMsg},
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #4
0
def generateSSHKeyViewSet(request, *args, **kwargs):
    """
  生成sshkey
  """
    logger.info(request.data)
    serializer = GenerateSSHKeySerializer(data=request.data)
    if serializer.is_valid():
        valideddata = serializer.validated_data
        generatekey = GenerateSSHKey(valideddata)
        publickey, errorMsg = generatekey.generatekey()
        if publickey:
            if valideddata.get('writetable'):
                writeUser = {"username": valideddata.get("username")}
                if valideddata.get("email"):
                    writeUser['email'] = valideddata.get("email")
                    # 发送邮件提示
                    send_reset_sshkey_email.delay(writeUser)
                if valideddata.get("userdn"):
                    writeUser['userdn'] = valideddata.get("userdn")
                    # 保存到LDAP sshPublickey
                    ldap = CmdbLDAP()
                    ldap.update_sshpublickey(
                        {"sshPublicKey": publickey.get('publickey')},
                        writeUser['userdn'])
                    del ldap
                # 保存到数据库
                Users.objects.update_or_create(
                    defaults=dict(writeUser, **publickey),
                    username=valideddata.get("username"))

            returnData = publickey
            returnStatus = status.HTTP_200_OK
        else:
            returnData = {"error": errorMsg}
            returnStatus = status.HTTP_400_BAD_REQUEST
    else:
        returnData = serializer.errors
        returnStatus = status.HTTP_400_BAD_REQUEST

    return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #5
0
 def get(self, request, *args, **kwargs):
     """
 根据用户获取用户信息
 """
     attrsOrClass, errorMsg = CmdbLDAP().get_attrsorclass_list(type='attr')
     if attrsOrClass:
         return JsonResponse(attrsOrClass,
                             encoder=LDAPJSONEncoder,
                             safe=False)
     else:
         return JsonResponse(errorMsg,
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #6
0
 def get(self, request, *args, **kwargs):
     """
 根据用户获取用户信息
 """
     userdn = kwargs.get('userdn')
     userattrs, errMsg = CmdbLDAP().get_user_permissions(userdn)
     # return JsonResponse(userattrs[0],encoder=LDAPJSONEncoder,safe=False)
     if userattrs:
         return JsonResponse(userattrs, encoder=LDAPJSONEncoder, safe=False)
     else:
         return JsonResponse(errMsg,
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #7
0
 def get(self, request, *args, **kwargs):
     """ 
 获取所有用户的列表信息
 """
     user_list, errorMsg = CmdbLDAP().get_user_list()
     if user_list:
         page = PageNumberPagination()
         page_roles = page.paginate_queryset(queryset=user_list,
                                             request=request,
                                             view=self)
         return JsonResponse(user_list, encoder=LDAPJSONEncoder, safe=False)
     else:
         return JsonResponse({'error': errorMsg},
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #8
0
 def post(self, request, *args, **kwargs):
     serializer = ChangePasswordSerializer(instance=request,
                                           data=request.data)
     if serializer.is_valid():
         changeStatus, errorMsg = CmdbLDAP().change_self_password(
             request.data)
         if changeStatus == True:
             returnData = {"status": "密码修改成功!"}
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #9
0
 def get(self, request, *args, **kwargs):
     """
 根据用户获取用户信息
 """
     username = kwargs.get('username')
     userattrs = CmdbLDAP().get_user_list(username, ['*', '+'])
     # get_sshkey_fingerprint
     if userattrs[0][0] and 'sshPublicKey' in userattrs[0][0][1] and len(
             userattrs[0][0][1]['sshPublicKey']) == 1:
         userattrs[0][0][1]['sshPublicKey'].append(
             get_sshkey_fingerprint(
                 userattrs[0][0][1]['sshPublicKey'][0].decode('utf-8')))
         logger.info(userattrs[0][0][1]['sshPublicKey'])
     return JsonResponse(userattrs[0][0],
                         encoder=LDAPJSONEncoder,
                         safe=False)
예제 #10
0
 def post(self, request, *args, **kwargs):
     """
 删除用户
 """
     serializer = DeleteDNSerializer(instance=request, data=request.data)
     if serializer.is_valid():
         changeStatus, errorMsg = CmdbLDAP().delete_ldap_dn(request.data)
         if changeStatus:
             returnData = {"status": changeStatus}
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #11
0
 def get(self, request, *args, **kwargs):
     """
 获取所有LDAP的CLASSES名称及字段信息
 """
     attrsOrClass = cache.get('attrsOrClass')
     if not attrsOrClass:
         attrsOrClass, errorMsg = CmdbLDAP().get_attrsorclass_list()
         cache.set('attrsOrClass', attrsOrClass)
     if attrsOrClass:
         return JsonResponse(attrsOrClass,
                             encoder=LDAPJSONEncoder,
                             safe=False)
     else:
         return JsonResponse(errorMsg,
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #12
0
 def post(self, request, *args, **kwargs):
     """
 根据用户获取用户信息
 """
     permissionData = request.data
     if 'sign' in request.data:
         request.data.pop('sign')
     success, errmsg = CmdbLDAP().save_permissions_group(permissionData)
     if success:
         return JsonResponse({'status': success},
                             encoder=LDAPJSONEncoder,
                             safe=False)
     else:
         return JsonResponse(errmsg,
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #13
0
 def post(self, request, *args, **kwargs):
     """
 锁定/解锁用户
 """
     serializer = LDIFScriptsSerializer(instance=request, data=request.data)
     if serializer.is_valid():
         ldif = request.data.get('ldif')
         changeStatus, errorMsg = CmdbLDAP().ldif_script(ldif)
         if changeStatus:
             returnData = {"status": changeStatus}
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #14
0
 def get(self, request, *args, **kwargs):
     logger.info(kwargs)
     if "baseou" in kwargs and kwargs.get('baseou') != "":
         queryOU = {"queryOU": kwargs.get('baseou')}
     else:
         queryOU = {
             "queryOU": settings.AUTH_LDAP_BASE_DN,
             "ldapType": ldap.SCOPE_BASE
         }
     ous, errorMsg = CmdbLDAP().get_base_ou(**queryOU)
     if errorMsg:
         logger.error(errorMsg)
     if len(ous) > 0:
         return JsonResponse(ous, encoder=LDAPJSONEncoder, safe=False)
     else:
         return JsonResponse({"error": errorMsg},
                             encoder=LDAPJSONEncoder,
                             status=status.HTTP_400_BAD_REQUEST,
                             safe=False)
예제 #15
0
 def post(self, request, *args, **kwargs):
     """
 提交用户数据
 """
     serializer = CreateDNSerializer(instance=request, data=request.data)
     if serializer.is_valid():
         parentDn = request.data['currentDn']
         request.data.pop('currentDn')
         changeStatus, errorMsg = CmdbLDAP().create_ldap_entry_dn(
             request.data, parentDn)
         if changeStatus:
             returnData = {"status": changeStatus}
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #16
0
 def post(self, request, *args, **kwargs):
     """
 删除用户
 """
     serializer = DeleteUserSerializer(instance=request, data=request.data)
     if serializer.is_valid():
         changeStatus, errorMsg = CmdbLDAP().delete_ldap_userdn(
             request.data)
         if changeStatus:
             usernames = []
             for udn in request.data.get('userdn'):
                 usernames.append(udn.split(',')[0].split("=")[1])
             Users.objects.filter(username__in=usernames).delete()
             returnData = {"status": changeStatus}
             returnStatus = status.HTTP_200_OK
         else:
             returnData = {"error": errorMsg}
             returnStatus = status.HTTP_400_BAD_REQUEST
     else:
         returnData = serializer.errors
         returnStatus = status.HTTP_400_BAD_REQUEST
     return JsonResponse(returnData, status=returnStatus, safe=False)
예제 #17
0
    def post(self, request, *args, **kwargs):

        serializer = ResetPasswordSerializer(instance=request,
                                             data=request.data)
        if serializer.is_valid():
            userdn = serializer.validated_data.get('userdn')
            newpassword = generat_random_password(encode=True)
            resetStatus, errorMsg = CmdbLDAP().reset_user_password(
                userdn, newpassword)
            if resetStatus == True:
                returnData = {"status": "用户密码重置成功,请在参见邮件进行密码修改。"}
                returnStatus = status.HTTP_200_OK
                username = userdn.split(',')[0].split('=')[1]
                if username:
                    send_reset_password_email.delay(username, newpassword)
                    logger.info("发送重置密码的邮件到用户[%s]" % username)
            else:
                returnData = {"error": errorMsg}
                returnStatus = status.HTTP_400_BAD_REQUEST
        else:
            returnData = serializer.errors
            returnStatus = status.HTTP_400_BAD_REQUEST

        return JsonResponse(returnData, status=returnStatus, safe=False)