示例#1
0
    def signup_user(self, validated_data):
        oid = validated_data['oid']
        oid = oid.lower()
        username = validated_data['username']
        access_token = validated_data['access_token']
        try:
            phone = get_phone(access_token)
        except Exception as e:
            raise ValidationError(detail='Invalid phone token!')

        if check_oid_exists(oid):
            raise PermissionDenied(detail='Organization exists!')
        if check_username_exists(oid=oid, username=username):
            raise PermissionDenied(detail='Username exists!')

        org = Organization.objects.create(oid=oid)
        usage = Usage(org=org, exp_date=trial_cycle())
        usage.save()
        subscription = Subscription(org=org,
                                    current_usage=usage,
                                    _is_trial=True)
        subscription.save()

        user = User(
            username=create_username(oid=oid, username=username),
            phone=phone,
            is_active=True,
            role=ROLE_DICT['Organizer'],
            org=org,
        )
        user.set_unusable_password()
        user.save()
        userstate = UserState.objects.create(user=user)
        jwt_token = jwt_encode_handler(jwt_payload_handler(user))
        return user, jwt_token
示例#2
0
 def save_data(self, f, datos):
     data = {}
     if f.is_valid():
         use = User()
         use.username = datos['cedula']
         use.cedula = datos['cedula']
         use.first_name = datos['first_name']
         use.last_name = datos['last_name']
         use.sexo = datos['sexo']
         use.email = datos['email']
         use.telefono = datos['telefono']
         use.celular = datos['celular']
         use.direccion = datos['direccion']
         use.tipo = 0
         use.password = make_password(datos['cedula'])
         use.save()
         data['resp'] = True
         data['cliente'] = use.toJSON()
         grupo = Group.objects.get(name__icontains='cliente')
         usersave = User.objects.get(id=use.id)
         usersave.groups.add(grupo)
         usersave.save()
     else:
         data['error'] = f.errors
     return data
示例#3
0
    def post(self, request, *args, **kwargs):
        email_address = request.data["email"]
        username = email_address.split("@")
        code = code_generator()

        try:
            new_user = User(email=email_address,
                            username=username[0],
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=code)
            registration_profile.save()
        except IntegrityError:
            return Response(
                f"The email address '{email_address}' is already taken.")

        send_mail(
            'Fresh Garden Registration Code',
            f"Here is your registration code {registration_profile.code}",
            '*****@*****.**',
            [new_user.email],
            fail_silently=False,
        )
        serializer = self.get_serializer(new_user)
        return Response(serializer.data)
示例#4
0
    def post(self, request, *args, **kwargs):
        email_address = request.data["email"]
        username = email_address.split("@")
        code = code_generator()

        try:
            new_user = User(email=email_address,
                            username=username[0],
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=code)
            registration_profile.save()
        except IntegrityError:
            return Response(
                f"The email address '{email_address}' is already taken.")

        # TODO uncomment for production
        # send_mail(
        #     'Motion Registration Code',
        #     f"Here is your registration code {registration_profile.code}",
        #     '*****@*****.**',
        #     [new_user.email],
        #     fail_silently=False,
        # )
        serializer = self.get_serializer(new_user)
        return Response(serializer.data)
示例#5
0
    def add_user(self, validated_data):
        result = dict()
        print(validated_data)
        # 新增用户
        try:
            new_user = User(
                user_guid=validated_data['user_guid'],
                user_name=validated_data['user_name'],
                real_name=validated_data['real_name'],
                mobile=validated_data['mobile'],
                balance=validated_data['balance'],
                available_balance=validated_data['available_balance'])
            new_user.save()

        except Exception as ex:
            print('--------------------')
            print(ex)
            print('--------------------')
            result["error_code"] = ErrorCode.用户不存在.value
            result["error"] = ''
            return result

        result["error_code"] = ErrorCode.正确.value
        result["error"] = ""
        return result
示例#6
0
文件: views.py 项目: majki97/Luna
    def post(self, request, *args, **kwargs):
        email_data = self.request.data
        email_address = email_data.__getitem__("email")
        length = 5
        numbers = '0123456789'
        validation_code = ''.join(
            random.choice(numbers) for _ in range(length))
        subject = 'Welcome to Luna'
        message = 'Here is your validation code ' + validation_code
        recipient = email_address
        send_mail(subject,
                  message,
                  EMAIL_HOST_USER, [recipient],
                  fail_silently=False)

        try:
            new_user = User(email=email_address,
                            username=email_address,
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=validation_code)
            registration_profile.save()
            return Response(status=status.HTTP_200_OK)
        except IntegrityError:
            return Response(data="This email is already taken.", status=400)
示例#7
0
def read_xls(self, request, obj, change):
    print(obj.file)
    df = pandas.read_excel(obj.file)
    print(df)
    # df.drop([0],inplace=True)
    # df.columns = ['username','sex','age']
    for i in range(0, len(df['学工号'])):
        username = df.iloc[i, 0]
        email = df.iloc[i, 1]
        professor = df.iloc[i, 2]
        jidian = df.iloc[i, 3]
        password = 123456
        role_id = df.iloc[i, 4]
        #导入用户信息
        role = Role.objects.get(id=role_id)
        user = User()
        user.username = username
        user.role = role
        user.professor = professor
        user.email = email
        user.set_password(password)
        user.is_active = 1
        user.save()
        #导入绩点信息
        rate_jidians = Work_rate_jidian.objects.get(pro_name=professor)
        id = User.objects.get(username=username).id
        Work_count.objects.create(usernum=id,
                                  count_jidians=jidian,
                                  rate_jidians=rate_jidians)
    return 'success'
示例#8
0
def cliente_add(request):
    data = {}
    f = UserForm_cliente(request.POST)
    datos = request.POST
    if f.is_valid():
        with transaction.atomic():
            if verificar(f.data['cedula']):
                use = User()
                use.username = datos['cedula']
                use.cedula = datos['cedula']
                use.first_name = datos['first_name']
                use.last_name = datos['last_name']
                use.sexo = datos['sexo']
                use.email = datos['email']
                use.telefono = datos['telefono']
                use.celular = datos['celular']
                use.direccion = datos['direccion']
                use.tipo = 0
                use.password = make_password(datos['cedula'])
                use.save()
                permission = Permission.objects.get(codename='add_venta')
                permission2 = Permission.objects.get(codename='view_venta')
                use.user_permissions.add(permission)
                use.user_permissions.add(permission2)
                # venta.add_venta

                # u.user_permissions.add(permission)
                data['resp'] = 'error'
            else:
                f.add_error("cedula",
                            "Numero de Cedula no valido para Ecuador")
                data['error'] = f.errors
    else:
        data['error'] = f.errors
    return HttpResponse(json.dumps(data), content_type="application/json")
示例#9
0
 def post(self, request):
     form = RegisterForm(request.POST)
     if form.is_valid():
         username = form.cleaned_data.get('username', '')
         email = form.cleaned_data.get('email', '')
         password = form.cleaned_data.get('password', '')
         users = User()
         users.username = username
         users.password = make_password(password)
         users.email = email
         users.is_active = False
         users.save()
         token = token_confirm.generate_validate_token(username)
         # message = "\n".join([u'{0},欢迎加入我的博客'.format(username), u'请访问该链接,完成用户验证,该链接1个小时内有效',
         #                      '/'.join([settings.DOMAIN, 'activate', token])])
         #send_mail(u'注册用户验证信息', message, settings.EMAIL_HOST_USER, [email], fail_silently=False)
         send_register_email.delay(email=email,
                                   username=username,
                                   token=token,
                                   send_type="register")
         return JsonResponse({
             'valid': True,
             'status': 200,
             'message': u"请登录到注册邮箱中验证用户,有效期为1个小时"
         })
     return JsonResponse({
         'status': 400,
         'data': form.errors,
         'valid': False
     })
示例#10
0
def register(request):
    r = json.loads(request.body)
    account = r['account']
    password = r['password']
    code = r['code']
    if judge_type(account) is None:
        return JsonResponse({'success': False, 'msg': "账号格式有误!"})
    # 从redis缓存中读取缓存信息 account唯一
    check_code = cache.get(account)
    print(check_code)
    # 验证验证码是否正确
    if check_code == code:
        # 新加用户
        user = User()
        user.username = '******' + shuffle_str(True)[0:6]
        # 判断账号类型
        if judge_type(account) == 'phone':
            user.phone = account
        else:
            user.email = account
        # 密码加密
        user.password = encrypt(password)
        print(user.password)
        # 保存
        user.save()
        return JsonResponse({'success': True, 'msg': "注册成功!"})
    else:
        return JsonResponse({'success': False, 'msg': "验证码错误!"})
示例#11
0
def register(req):
    """
    注册
    """
    print("############")
    is_verified = req.session.get("verified")
    if req.method == 'POST' and is_verified:
        urf = UserRegisterForm(req.POST)
        if urf.is_valid():
            try:
                user = User(
                    username=urf.cleaned_data['username'],
                    first_name=urf.cleaned_data['first_name'],
                    last_name=urf.cleaned_data['last_name'],
                    email=urf.cleaned_data['email'],
                    phone=urf.cleaned_data['phone'],
                    mac=urf.cleaned_data['mac'],
                    is_teacher=urf.cleaned_data['is_teacher'],
                )
                user.set_password(urf.cleaned_data['password'])
                user.save()
                return HttpResponse("User {0} Register success".format(
                    user.username))
            except IntegrityError as e:
                return HttpResponse("IntegrityError error: {0}".format(e))
        else:
            # TODO
            return HttpResponse(str(urf.cleaned_data))
    return HttpResponse(status=403)
示例#12
0
def register(req):

    if req.method == "GET":
        return render(req, 'register.html')
    elif req.method == 'POST':
        username = req.POST.get('username')
        password = req.POST.get('password')
        confirm_password = req.POST.get('confirm_password')
        email = req.POST.get('email')
        phone = req.POST.get('phone')
        if password and username and email and password == confirm_password:
            users = User.objects.filter(username=username)
            if users:
                return render(req, 'register.html', {'msg': "账号存在"})
            else:
                user = User(username=username,
                            password=password,
                            email=email,
                            phone=phone)
                user.save()
                return render(req, 'register.html')
        else:
            return render(req, 'register.html', {'msg': "参数不正确"})
    else:
        return render(req, 'register.html', {'msg': "不支持该方式传送"})
示例#13
0
def bindingQQ(request):
    """
    QQ 注册账号
    :param request:
    :return:
    """
    if request.method == 'POST':
        openid = request.POST.get('openid')
        figureurl_qq_1 = request.POST.get('figureurl_qq_1')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        email = request.POST.get('email')
        if password != password1:
            return render(
                request, 'pc/qqregister.html', {
                    'openid': openid,
                    'figureurl_qq_1': figureurl_qq_1,
                    'nickname': nickname,
                    'error': '两次密码不一致'
                })
        else:
            User.objects.filter(email=email).exists()
            if User.objects.filter(email=email).exists():
                return render(
                    request, 'pc/qqregister.html', {
                        'openid': openid,
                        'figureurl_qq_1': figureurl_qq_1,
                        'nickname': nickname,
                        'error': '邮箱已存在'
                    })
            else:
                user = User()
                user.username = nickname
                user.email = email
                user.user_image = figureurl_qq_1
                user.is_staff = False
                user.is_superuser = False
                user.is_active = True
                user.password = make_password(password1)
                user.save()
                qq = OAuthQQ()
                user_id = get_object_or_404(User, email=email).id
                qq.user_id = user_id
                msg = UserMessage()
                msg.user_id = user_id
                msg.to_user = User.objects.get(is_superuser=True)
                msg.message = '欢迎加入本站,在使用过程中有什么疑问,请联系管理员,Email: <a target="_blank" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=iuzv5O3g4_T748rs7_Tt4OPk__Ok6eXn" style="text-decoration:none;">[email protected]</a>'
                msg.has_read = False
                msg.is_supper = True
                msg.save()
                qq.qq_openid = openid
                qq.nickname = nickname
                qq.figureurl_qq = figureurl_qq_1
                qq.save()
                user = authenticate(request, username=email, password=password)
                login(request, user)
                return HttpResponseRedirect(reverse('home'))
示例#14
0
def register(request):
    """
    注册
    :param request:
    :return:
    """
    if request.session.get('is_login', False):
        redirect('/lianjia/')
    if request.method == 'POST':
        message = '请检查填写的内容!'

        # 通过表单验证提交的数据是否合规
        # registerForm = RegisterForm(request.POST)
        # if registerForm.is_valid():
        #     pass
        username = request.POST.get('username', '')
        nickname = request.POST.get('nickname', '')
        password = request.POST.get('password', '')
        mobile = password
        guid = 'u' + datetime.now().strftime('%Y%m%d%H%M%S') + str(
            random.randrange(1000, 9999))

        try:
            print('-' * 10)
            new_user = User()
            new_user.user_guid = guid
            new_user.user_name = username
            new_user.real_name = nickname
            new_user.mobile = mobile
            new_user.balance = 100
            new_user.all_balance = 80
            new_user.available_balance = 50
            new_user.create_date = datetime.now(pytz.utc)
            new_user.last_login_date = datetime.now(pytz.utc)
            new_user.gender = 1
            new_user.province = '河南'
            new_user.save()

            request.session['is_login'] = True
            request.session['user_guid'] = new_user.user_guid
            request.session['user_name'] = new_user.user_name
            return redirect('/lianjia/')

        except Exception as ex:
            message = '注册失败!'

        return render(request, 'lianjia/login.html', {
            'title': '注册',
            'year': datetime.now().year,
            'message': message,
        })

    return render(request, 'lianjia/register.html', {
        'title': '注册',
        'year': datetime.now().year,
    })
示例#15
0
def bindingQQ(request):
    """
    QQ 注册账号
    :param request:
    :return:
    """
    if request.method == 'POST':
        openid = request.POST.get('openid')
        figureurl_qq_1 = request.POST.get('figureurl_qq_1')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        email = request.POST.get('email')
        if password != password1:
            return render(
                request, 'pc/qqregister.html', {
                    'openid': openid,
                    'figureurl_qq_1': figureurl_qq_1,
                    'nickname': nickname,
                    'error': '两次密码不一致'
                })
        else:
            User.objects.filter(email=email).exists()
            if User.objects.filter(email=email).exists():
                return render(
                    request, 'pc/qqregister.html', {
                        'openid': openid,
                        'figureurl_qq_1': figureurl_qq_1,
                        'nickname': nickname,
                        'error': '邮箱已存在'
                    })
            else:
                user = User()
                user.username = nickname
                user.email = email
                user.user_image = figureurl_qq_1
                user.password = make_password(password1)
                user.save()
                qq = OAuthQQ()
                user_id = get_object_or_404(User, email=email).id
                qq.user_id = user_id
                msg = UserMessage()
                msg.user_id = user_id
                msg.to_user = User.objects.get(username='******')
                msg.message = '欢迎加入本站,在使用过程中有什么疑问,请联系管理员'
                msg.has_read = False
                msg.is_supper = True
                msg.save()
                qq.qq_openid = openid
                qq.nickname = nickname
                qq.figureurl_qq = figureurl_qq_1
                qq.save()
                user = authenticate(request, username=email, password=password)
                login(request, user)
                return HttpResponseRedirect(reverse('home'))
示例#16
0
    def post(self, request):
        data = request.data
        user_type = ''
        return_data = dict()

        return_data['status'] = 'Success'

        dup_data = User.objects.all().filter(
            username=data['username']).values()
        if len(dup_data) > 0:
            return_data['status'] = 'Failure'
            return_data['message'] = 'username already exists'

        # dup_data = User.objects.all().filter(email = data['email']).values()
        # if len(dup_data) > 0:
        #     return_data['status'] = 'Failure'
        #     return_data['message'] = 'email already exists'

        user_type = data['user_type']

        try:
            if return_data['status'] == 'Success':
                if user_type == 'Farmer':
                    register = User(username=data['username'],
                                    password=hashlib.sha256(
                                        data['username'].encode()).hexdigest(),
                                    firstname=data['first_name'],
                                    lastname=data['last_name'],
                                    email=data['email'],
                                    user_type=User.Farmer,
                                    facebook_account=True,
                                    verify=True)
                elif user_type == 'Factory':
                    register = User(username=data['username'],
                                    password=hashlib.sha256(
                                        data['username'].encode()).hexdigest(),
                                    firstname=data['first_name'],
                                    lastname=data['last_name'],
                                    factory_name=data['first_name'] + " " +
                                    data['last_name'],
                                    email=data['email'],
                                    user_type=User.Factory,
                                    verify=True,
                                    facebook_account=True)
                register.save()
                return_data['data'] = User.objects.filter(
                    username=data['username'],
                    facebook_account=True).values()[0]
        except Exception as e:
            return_data['status'] = 'Failure'
            return_data['message'] = str(e)

        return Response(return_data)
示例#17
0
 def add_to_roster(self):
     new_user = User(
         first_name=self.first_name.capitalize(),
         last_name=self.last_name.capitalize(),
         cid=self.cid,
         email=self.email,
         oper_init=assign_oper_init(self.first_name[0], self.last_name[0]),
         home_facility=self.home_facility,
         rating=self.rating,
         main_role='VC',
     )
     new_user.save()
     new_user.assign_initial_cert()
示例#18
0
def create_organizer(username, oid='org1'):
    org = create_org(oid)

    organizer = User(
        username=create_username(oid, username), is_active=True,
        role=ROLE_DICT['Organizer'],
        org=org,
        full_name='Organizer',
    )
    organizer.set_unusable_password()
    organizer.save()
    state = UserState.objects.create(user=organizer)
    return organizer
示例#19
0
    def post(self, request):
        # 1.获取参数
        user_num = request.POST.get('user_num')
        password = request.POST.get('pwd')
        professor = request.POST.get('cpwd')
        email = request.POST.get('email')
        role_id = request.POST.get('loc')
        print(role_id)
        # 2.校验参数完整性
        if not all([user_num, password, professor, email, role_id]):
            return render(request, 'register.html', {'errmsg': '数据不完整,请重新输入'})
        # 2.1校验邮箱是否合法
        # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',
                        email):
            return render(request, 'register.html', {'errmsg': '邮箱格式不正确'})
        # 2.2校验用户是否存在
        try:
            user = User.objects.get(user_num=user_num)
        except User.DoesNotExist:
            # 用户不存在
            user = None
        if user:
            # 用户名已存在
            return render(request, 'register.html', {'errmsg': '用户名已存在'})

        # 3.业务处理,进行注册操作
        role = Role.objects.get(id=role_id)
        user = User()
        user.username = user_num
        user.role = role
        user.professor = professor
        user.email = email
        user.set_password(password)
        user.is_active = 0
        user.save()

        # 注册成功需要通过邮箱返回激活链接
        # 使用itsdangerous生成激活的token信息
        seeializer = Serializer(settings.SECRET_KEY, 3600)
        info = {'confirm': user.id}
        # 进行加密
        token = seeializer.dumps(info)
        # 转换类型
        token = token.decode()
        # 组织邮件内容
        send_mail_register(email, user_num, token)
        # 返回应答

        # 4.返回响应
        return render(request, 'login.html')
示例#20
0
def add(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        try:
            user = User.objects.get(id=int(request.session.get('my_user_id', 0)))
        except User.DoesNotExist:
            user = User()
        user.name = name
        user.save()
        request.session['my_user_id'] = user.id
        if request.is_ajax():
            return JsonResponse({'user': user.id})
        else:
            return redirect('/ginny/%s/' % user.id)
    raise Http404
示例#21
0
def create_agent(username, parent, is_present=True):
    oid = parent.org.oid
    org = parent.org
    agent = User(
        username=create_username(oid, username), is_active=True,
        org=org, role=ROLE_DICT['Employee'], parent=parent,
        is_present=is_present,
        full_name='Agent',
    )
    agent.set_unusable_password()
    agent.save()
    org.subscription.added_agents += 1
    org.subscription.save()
    state = UserState.objects.create(user=agent)
    return agent
示例#22
0
def create_manager(username, parent, org):
    manager = User(
        username=create_username(org.oid, username), is_active=True,
        role=ROLE_DICT['Manager'],
        org=org,
        parent=parent,
        full_name='Manager',
    )

    manager.set_unusable_password()
    manager.save()
    manager.org.subscription.added_agents += 1
    manager.org.subscription.save()
    state = UserState.objects.create(user=manager)
    return manager
示例#23
0
def register(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        truename = request.POST['truename']
        department = request.POST['department']
        phone = request.POST['phone']
        user = User(username=username,
                    password=password,
                    truename=truename,
                    department=department,
                    phone=phone)
        user.save()
        return HttpResponse(json.dumps(dict(succeed=True)))
示例#24
0
    def test_email_case_insensivity(self):
        u1 = User(
            email='*****@*****.**',
            password='******',
        )
        u1.save()

        with self.assertRaises(ValidationError) as context:
            u2 = User(
                email='*****@*****.**',
                password='******',
            )
            u2.full_clean()

        self.assertEqual(str(context.exception.message_dict['__all__'][0]),
                         'Email not unique')
示例#25
0
 def register(cls, user_name, real_name, password, email, telephone,
              role_id, job):
     if UserManager.verify_existence(user_name):
         return jsonify({"code": 400, "message": "用户已存在,请更换用户名"})
     user = User()
     user.user_name = user_name
     user.real_name = real_name
     user.email = email
     user.telephone = telephone
     user.role_id = role_id
     user.job = job
     user.create_time = TimeManager.now()
     user.pwd = password
     db.session.add(user)
     user.save()
     return jsonify({"code": 200, "message": "注册成功"})
示例#26
0
 def add_to_roster(self):
     new_user = User(
         first_name=self.first_name.capitalize(),
         last_name=self.last_name.capitalize(),
         cid=self.cid,
         email=self.email,
         oper_init=assign_oper_init(self.first_name[0], self.last_name[0]),
         home_facility=self.home_facility,
         rating=self.rating,
         main_role='VC',
     )
     new_user.save()
     new_user.assign_initial_cert()
     req = requests.post(
         f'https://api.vatusa.net/v2/facility/{os.getenv("ARTCC_ICAO")}/roster/manageVisitor/{new_user.cid}',
         data={'apikey': os.getenv('API_KEY')})
     if req.status_code != 200:
         raise ConnectionError("Failed to POST visitor to VATUSA API.")
示例#27
0
    def post(self, request):
        data = request.data
        user_type = ''
        return_data = dict()

        return_data['status'] = 'Success'

        dup_data = User.objects.all().filter(email=data['phone']).values()
        if len(dup_data) > 0:
            return_data['status'] = 'Failure'
            return_data['message'] = 'phone already exists'

        if 'factory_name' in data:
            user_type = 'Factory'
        else:
            user_type = 'Farmer'

        if return_data['status'] == 'Success':
            if user_type == 'Farmer':
                register = User(
                    username=data['phone'],
                    password=hashlib.sha256(
                        data['password'].encode()).hexdigest(),
                    firstname=data.get('first_name', ''),
                    lastname=data.get('last_name', ''),
                    email=data.get('email', ''),
                    phone=data['phone'],
                    user_type=User.Farmer,
                    verify=False,
                )
            elif user_type == 'Factory':
                register = User(username=data.get('phone', ''),
                                password=hashlib.sha256(
                                    data['password'].encode()).hexdigest(),
                                factory_name=data.get('factory_name', ''),
                                email=data.get('email', ''),
                                phone=data.get('phone', ''),
                                user_type=User.Factory,
                                verify=False)
            register.save()

        return Response(return_data)
示例#28
0
def create_teams_sync(user_list, organizer):
    oid = organizer.org.oid
    new_agents = 0

    for user_dict in user_list:
        cur_dict = user_dict.copy()
        cur_dict.pop('parent')
        if not check_username_exists(oid, cur_dict['username']):
            cur_dict['username'] = create_username(oid, cur_dict['username'])
            user = User(**cur_dict)
            user.org = organizer.org
            user.is_active = True
            user.save()
            userstate = UserState.objects.create(user=user)
            new_agents += 1
        else:
            username = create_username(oid, cur_dict['username'])
            cur_dict.pop('username')
            User.objects.filter(Q(username=username)).update(**cur_dict)

    for user_dict in user_list:
        # print(user_dict)
        if len(user_dict['parent']) > 0:
            manager_qs = User.objects.filter(
                username=create_username(oid, user_dict['parent']))
            if manager_qs.exists():
                parent = manager_qs[0]
                user = User.objects.get(
                    username=create_username(oid, user_dict['username']))
                try:
                    user.parent = parent
                    user.save()
                except Exception as e:
                    raise NotAcceptable(detail=str(e))
            else:
                err_msg = 'Manager : ' + user_dict['parent'] + ' not found!'
                raise NotAcceptable(detail=err_msg)
    organizer.org.subscription.added_agents += new_agents
    organizer.org.subscription.save()

    return True
示例#29
0
 def save_data(self, f):
     data = {}
     if f.is_valid():
         f.save(commit=False)
         if verificar(f.data['cedula']):
             cli = f.save()
             data['resp'] = True
             data['empleado'] = cli.toJSON()
             if cli.cargo == 0 or 1 or 2:
                 us = User()
                 us.cedula = cli.cedula
                 us.username = cli.cedula
                 us.set_password(cli.cedula)
                 us.save()
         else:
             f.add_error("cedula",
                         "Numero de Cedula no valido para Ecuador")
             data['error'] = f.errors
     else:
         data['error'] = f.errors
     return data
示例#30
0
 def post(self, request):
     username = request.POST.get("user_name")
     password = request.POST.get("pwd")
     email = request.POST.get('email')
     allow = request.POST.get('allow')
     if not all([username, password, email]):
         return render(request, 'register.html', {'errmsg': '信息填写不完整'})
     if allow != 'on':
         return render(request, 'register.html', {'errmsg': '请同意协议'})
     try:
         user = User.objects.get(username=username)
     except Exception as e:
         print(e)
         user = None
     if user is not None:
         return render(request, 'register.html', {'errmsg': '用户已存在'})
     user = User()
     user.username = username
     user.password = password
     user.email = email
     user.save()
     return redirect(reverse('user:login'))
示例#31
0
    def activate_user(self, activation_key):
        # check if valid sha1 hash
        if SHA1_RE.search(activation_key.lower()):
            try:
                profile = self.get(activation_key=activation_key)
            except self.model.DoesNotExist:
                return False
            if not profile.activation_key_expired():
                user = profile.user
                user.is_active = True
                user.save()
                profile.activation_key = self.model.ACTIVATED
                profile.save()

                # create showcase user
                new_user = User(alias=user.first_name.capitalize())
                new_user.auth_user = user
                # because first and last name are set from email
                # the combination must be unique
                new_user.unique_name = user.first_name + user.last_name
                new_user.save()

                return new_user
        return False
    def test_password_hashing(self):
        user = User(
            email='*****@*****.**',
            password='******',
        )
        user.save()

        # Check that password is converted to a hash upon saving
        self.assertTrue(check('password', user.password))

        # Check that password is not hashed again when its value did not change
        user.save()
        self.assertTrue(check('password', user.password))

        # Check that password is hashed again when its value changed
        user.password = '******'
        user.save()
        self.assertFalse(check('password', user.password))
        self.assertTrue(check('$this_is_my_new_password', user.password))