Beispiel #1
0
 def create_user(self,
                 username,
                 password=None,
                 active=True,
                 is_student=False,
                 is_teacher=False,
                 is_admin=False,
                 name=None,
                 surname=None,
                 sname=None):
     if not username:
         raise ValueError("User must have a username")
     if not password:
         raise ValueError("User must have password")
     user_instance = User()
     user_instance.username = username
     user_instance.set_password(password)
     user_instance.is_active = active
     user_instance.student = is_student
     user_instance.teacher = is_teacher
     user_instance.admin = is_admin
     if is_admin:
         user_instance.staff = True
     user_instance.name = name
     user_instance.second_name = sname
     user_instance.surname = surname
     user_instance.save()
     return user_instance
Beispiel #2
0
def perform_user_register(request):
    err = ''
    uf = UserRegForm(request.POST)
    if uf.is_valid():
        email = uf.cleaned_data['email']
        name = uf.cleaned_data['name']
        password = uf.cleaned_data['password']
        phone_number = uf.cleaned_data['phone_number']
        building_id = int(uf.cleaned_data['building'])
        building = Building.objects.get(id=building_id)
        check_exist = User.objects.filter(email=email)
        if check_exist:
            err = 'exist'
        user = User()
        user_profile = UserProfile()  # Other data for user
        user.email = email
        user.name = name
        user.set_password(password)
        user.save()
        user_profile.user = user
        user_profile.phone_number = phone_number
        user_profile.building = building
        user_profile.save()
        return HttpResponseRedirect('login')
    else:
        context = RequestContext(request)
        return render_to_response('register.html', context)
Beispiel #3
0
def SubirCSV(request):
    csv_filepathname="/home/c30/desarrollos/grupos.csv"
    dataReader = csv.reader(open(csv_filepathname), delimiter=';', quotechar='"')
    cont = 0
    grupo1 = Group.objects.get(name="Trabajador")
    for row in dataReader:
        #if row[0] != 'ZIPCODE': # ignoramos la primera línea del archivo CSV
        
        try:
            user = User()
            user.username = row[2]
            user.name = row[1]
            user.set_password(123)
            
            user.save()
            if (row[3] == 'Gestión Interna'):
                grupo2 = Group.objects.get(name="Dirección de Gestión")
                user.groups.add(grupo2)
            if (row[3] == 'Presidente'):
                grupo2 = Group.objects.get(name="Presidencia")
                user.groups.add(grupo2)
            if (row[3] == 'Directora Ejecutiva'):
                grupo2 = Group.objects.get(name="Dirección Ejecutiva")
                user.groups.add(grupo2)
            user.groups.add(grupo1)    
        except:
            pass
        
        print cont
        print user.name
        cont += 1
    return HttpResponse("Ya están cargados")
Beispiel #4
0
    def handle(self, *args, **options):

        print('Loading user data')
        for row in DictReader(open('./user_data.csv')):
            if(User.objects.filter(id = row['ID'])):
                continue
            form = User()
            form.username = row['username']
            form.password = row['password']
            form.email = row['email']
            form.first_name = row['fname']
            form.last_name = row['lname']
            
        for row in DictReader(open('./company_data.csv')):
            if(user.objects.filter(id = row['ID'])):
                continue
            form = CompanyProfile()
            form.name = row['Name']
            form.phoneNumber = row['phone number']
            form.image = row['image']
            form.address row['address']
            form.company_description['description']
            
            raw_user = row['username']
            submit_user = User.objects.get(username=raw_user)
Beispiel #5
0
    def test_creating_loans(self):
        #We need a user object first in order to be able to add the business
        user_object = User()
        user_object.name = "test"
        user_object.phone_number = "12345678"
        user_object.email = "*****@*****.**"
        user_object.save()

        #We need a business object in order to to be able to add the loan
        business_object = Business()
        business_object.business_name = "Test business"
        business_object.registered_company_number = "12345678"
        business_object.business_sector = "Food & Drink"
        business_object.user = user_object
        business_object.address1 = "Test Address 1"
        business_object.address2 = "Test Address 2"
        business_object.post_code = "ES1 34GH"
        business_object.city_name = "London"
        business_object.save()

        #We need a user object first in order to be able to add the business
        loan_object = Loan()
        loan_object.number_of_days = 25
        loan_object.amount = 50000
        loan_object.reason = "Test Loan"
        loan_object.user = user_object
        loan_object.business_name = business_object
        loan_object.save()
Beispiel #6
0
def register(request):
    u = User()
    u.email = request.POST.get('email')
    u.name = request.POST.get('name')
    u.password = request.POST.get('password')
    u.mobile = request.POST.get('mobile')
    u.username = request.POST.get('username')
    error = ""
    if (u.password == request.POST.get('reppassword')):
        u.save()
        return render(request, 'login.html')
    else:
        error = "Password didn't match"

    return render(request, 'signup.html', {"error": error})
Beispiel #7
0
def userSignup(request):
    if request.method == 'POST':
        try:
            user = User()
            user.name = request.POST['name']
            user.email = request.POST['email']
            user.gender = request.POST['gender']
            if User.objects.filter(email=user.email).exists():
                user = User.objects.get(email=user.email)
                if user.is_active is True:
                    messages.warning(request, 'Account is already created')
                    return redirect('login')
                elif user.is_active is False:
                    messages.warning(
                        request,
                        'Check the mail sent on {} to activate your account'.
                        format(user.creationTime))
                    return redirect('/')
            else:
                user.set_password(request.POST['password'])
                user.is_active = False
                user.save()
                site = get_current_site(request)
                print(site)
                mail_subject = 'Site Activation Link'
                message = render_to_string(
                    'email.html', {
                        'user': user,
                        'domain': site,
                        'uid': user.id,
                        'token': activation_token.make_token(user)
                    })
                to_email = user.email
                to_list = [to_email]
                from_email = settings.EMAIL_HOST_USER
                send_mail(mail_subject,
                          message,
                          from_email,
                          to_list,
                          fail_silently=True)
                messages.success(request,
                                 'Check your mail to activate your account')
                return redirect('/')
        except Exception as problem:
            messages.error(request, '{}'.format(problem))
            return redirect('signup')
    else:
        return render(request, 'signup.html')
Beispiel #8
0
def UserLogin(request):
    if request.method == "POST":
        from main.models import User

        # Find if User already exists
        newUser = User()
        oldUser = User.objects.filter(facebook_id=request.POST["id"])
        if len(oldUser) > 0:
            newUser.id = oldUser[0].id
            newUser.token = oldUser[0].token
        else:
            import string, random

            chars = string.ascii_uppercase + string.digits + string.ascii_lowercase
            newUser.token = "".join(random.choice(chars) for x in range(40))

            # Update user data
        if "name" in request.POST:
            newUser.name = request.POST["name"]

        if "first_name" in request.POST:
            newUser.first_name = request.POST["first_name"]

        if "last_name" in request.POST:
            newUser.last_name = request.POST["last_name"]

        if "username" in request.POST:
            newUser.username = request.POST["username"]

        if "email" in request.POST:
            newUser.email = request.POST["email"]

        if "gender" in request.POST:
            newUser.gender = request.POST["gender"]

            # if 'birthday' in request.POST:
            # 	user.birthday = request.POST['birthday']

        newUser.avatar = "http://graph.facebook.com/" + request.POST["id"] + "/picture"
        newUser.facebook_id = request.POST["id"]

        newUser.save()

        context = {"token": newUser.token}
    else:
        context = {"token": "Forbidden"}

    return render_to_response("login.html", context, context_instance=RequestContext(request))
Beispiel #9
0
 def create_users(self):
     """
     Cadastra os usuários para inscrição em especialidades
     """
     user_new = User()
     user_new.name = 'Usuário 123'
     user_new.password = make_password('123')
     user_new.username = '******'
     user_new.first_name = 'Nome 1'
     user_new.last_name = 'Nome 2'
     user_new.email = '*****@*****.**'
     user_new.is_active = 1
     user_new.is_staff = 1
     user_new.save()
     group = Group.objects.get(name=u'Escoteiro')
     group.user_set.add(user_new)
Beispiel #10
0
def UserLogin(request):
	if request.method == 'POST':
		from main.models import User

		# Find if User already exists
		newUser = User()
		oldUser = User.objects.filter(facebook_id=request.POST['id'])
		if len(oldUser) > 0:
			newUser.id = oldUser[0].id
			newUser.token = oldUser[0].token
		else:
			import string, random
			chars = string.ascii_uppercase + string.digits + string.ascii_lowercase
			newUser.token = ''.join(random.choice(chars) for x in range(40))

		# Update user data
		if 'name' in request.POST:
			newUser.name = request.POST['name']

		if 'first_name' in request.POST:
			newUser.first_name = request.POST['first_name']

		if 'last_name' in request.POST:
			newUser.last_name = request.POST['last_name']

		if 'username' in request.POST:
			newUser.username = request.POST['username']

		if 'email' in request.POST:
			newUser.email = request.POST['email']

		if 'gender' in request.POST:
			newUser.gender = request.POST['gender']

		#if 'birthday' in request.POST:
		#	user.birthday = request.POST['birthday']

		newUser.avatar = 'http://graph.facebook.com/' + request.POST['id'] + '/picture'
		newUser.facebook_id = request.POST['id']		

		newUser.save()

		context = { 'token': newUser.token }		
	else:
		context = { 'token': 'Forbidden' }

	return render_to_response('login.html', context, context_instance=RequestContext(request))
Beispiel #11
0
    def test_creating_business(self):
        #We need a user object first in order to be able to add the business
        user_object = User()
        user_object.name = "test"
        user_object.phone_number = "12345678"
        user_object.email = "*****@*****.**"
        user_object.save()

        business_object = Business()
        business_object.business_name = "Test business"
        business_object.registered_company_number = "12345678"
        business_object.business_sector = "Food & Drink"
        business_object.user = user_object
        business_object.address1 = "Test Address 1"
        business_object.address2 = "Test Address 2"
        business_object.post_code = "ES1 34GH"
        business_object.city_name = "London"
        business_object.save()
Beispiel #12
0
def handle_card(connection):
    resp = input("Create user (Y/N) >>> ")
    if resp.upper() == "Y":
        u = User()
        uname = input("Enter username >>> ")
        name = input("Enter name >>> ")
        pwd = input("Enter password >>> ")
        u.username = uname
        u.name = name
        u.password = pwd
        u.save()
    else:
        uname = input("Enter existing username to link to >>> ")
        u = User.objects.get(username=uname)
    # user model
    t_user = TapUser()
    t_user.pin = input("Enter pin >>> ")
    t_user.userid = u
    t_user.save()
    # write UID to card
    # its ascii
    uid_str = str(t_user.id)
    sector_data = list((uid_str + ('\0' * 12)).encode("UTF-8"))
    keysec = [0xFF] * 6 + CARD_ACL + [0xFF] * 6
    write_sector(connection, 1, [0xFF] * 6, sector_data + keysec)
    # decode the blockdata and keydata into their respectinv things
    keydata = t_user.keys
    blockdata = t_user.token
    keydata += '=' * (-len(keydata) % 4)
    blockdata += '=' * (-len(blockdata) % 4)
    keydata = list(base64.urlsafe_b64decode(keydata.encode("UTF-8")))
    blockdata = list(base64.urlsafe_b64decode(blockdata.encode("UTF-8")))
    keys = [keydata[i:i + 6] for i in range(0, len(keydata), 6)]
    blocks = [blockdata[i:i + 48] for i in range(0, len(blockdata), 48)]
    for i in range(14):
        sector_key_acl_thing = keys[i] + CARD_ACL + keys[i]
        write_sector(connection, i + 2, [0xFF] * 6,
                     blocks[i] + sector_key_acl_thing)
        print(f"Writing sector {i+2}")
Beispiel #13
0
def register_view(request):
    if request.method == 'POST':
        if User.objects.filter(username=request.POST['emailid']).exists():
            messages.error(request, 'User is alredy registered?')
            return render(request, 'register.html')
        else:
            if request.POST['password'] == request.POST['confirmpassword']:
                user = User()
                user.name = request.POST['name']
                user.email = request.POST['emailid']
                user.username = request.POST['emailid']
                user.mobile_no = request.POST['mobile']
                user.password = make_password(request.POST['password'])
                user.save()

                messages.success(request, 'User is Registered successfully?')
                return redirect('login')
            else:
                messages.error(request,
                               "password and confirm password did'nt match")
                return render(request, 'register.html')
    else:
        return render(request, 'register.html')
Beispiel #14
0
def load_db():
    print bcolors.WARNING+'Start loading data in DB'

    t = Tpa()
    t.name = 'tpa1com'
    t.domain ='tpa1.com'
    t.get_balance_url = 'http://%s/api/[user_id]/tpa1com/get_balance' % TPA_SERVER
    t.billing_page = 'http://%s/account/get-coins' % TPA_SERVER
    t.charge_url = 'http://%s/api/charge' % TPA_SERVER
    t.timeout_chating = 33
    t.save()

    men = ['vova','fedor', 'oleg', 'serg', 'dima', 'alex']
    women = ['olga','sveta', 'luba', 'marina', 'natasha', 'vera']
    cmen = []

    
    u = User()
    u.username = '******'
    u.set_password('admin')
    u.is_active=True
    u.is_staff=True
    u.is_superuser = True

    try:
        u.save()
    except:
        pass

    for m in men:
        print 'process..........%s' % m
        u = ChatUser()
        u.gender = 'm'
        u.name = m
        year = random.choice(range(1950, 2001))
        month = random.choice(range(1, 13))
        day = random.choice(range(1, 29))
        u.birthday = str(year)+'-'+str(month)+'-'+str(day)
        u.email = m+'@gmail.com'
        cr = random.randint(0,5)
        country = (['Ukraine','Russia','Great Britain','Poland','Germany','USA'])
        city = (['Kiev','Odessa'],
        ['Moskow','Sant Peterburg'],
        ['London','Glasgo'],
        ['Washava','Krakiv'],
        ['Berlin','Munhen'],
        ['Texas','Chicago'])
        u.country = country[cr]
        u.city = city[cr][random.randint(0,1)]
        u.image = '/static/images/avatar.jpg'
        u.profile_url = m+'_plofile_url'
        u.culture = random.choice(['de','ru','en'])
        u.is_online = random.choice([True,False])
        u.user_id = str(ChatUser.objects.all().count())
        u.tpa = t
        u.save()
        cmen.append(u)

    for w in women:
        print 'process..........%s' % w
        u = ChatUser()
        u.gender = 'w'
        u.name = w
        year = random.choice(range(1950, 2001))
        month = random.choice(range(1, 13))
        day = random.choice(range(1, 29))
        u.birthday = str(year)+'-'+str(month)+'-'+str(day)
        u.email = m+'@gmail.com'
        cr = random.randint(0,5)
        country = (['Ukraine','Russia','Great Britain','Poland','Germany','USA'])
        city = (['Kiev','Odessa'],
        ['Moskow','Sant Peterburg'],
        ['London','Glasgo'],
        ['Washava','Krakiv'],
        ['Berlin','Munhen'],
        ['Texas','Chicago'])
        u.country = country[cr]
        u.city = city[cr][random.randint(0,1)]
        u.image = '/static/images/avatar.jpg'
        u.profile_url = m+'_plofile_url'
        u.culture = random.choice(['de','ru','en'])
        u.is_online = random.choice([True,False])
        u.user_id = str(ChatUser.objects.all().count())
        u.tpa = t
        u.save()
        chat_c = ChatContacts()
        chat_c.owner = u
        rc = random.randint(0,5)
        chat_c.contact = cmen[rc]
        chat_c.tpa = t
        chat_c.save()
        chat_c = ChatContacts()
        chat_c.owner = cmen[rc]
        chat_c.contact = u
        chat_c.tpa = t
        chat_c.save() 

     
    for u in range(5):
        men.append('man'+str(u))
        women.append('woman'+str(u))

    for m in men:
        u = User()
        u.username = m
        u.set_password('111')

    for m in women:
        u = User()
        u.username = m
        u.set_password('111')

    print 'Done loading data in DB'
Beispiel #15
0
    a.description = ''
    alphabet = 'qwertyui  opasdfg   hjklzxcvbnm      '
    for i in xrange(int(random.random() * 799)):
        a.description += random.choice(alphabet)
    x = college.models.userprofile.objects.all()
    a.author = random.choice(x)
    a.approved = True
    a.save()
print '......................................',
print 'done'

#make students
print 'Students',
for i in students:
    a = college.models.student()
    a.name = i
    a.course = college.models.course.objects.first()
    a.save()
print '......................................',
print 'done'

#add a contact
print 'Contacts',
a = college.models.contact()
a.name = 'Phone'
a.value = '+91-11-2766 7271 '
a.save()
a = college.models.contact()
a.name = 'Admission Help Line'
a.value = '011-27662168'
a.save()
Beispiel #16
0
def register(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect('/register/')
	if request.method=='POST': 
		data=json.loads( request.body.decode('utf-8') )
		print(data['college'])
		recaptcha_response = data['captcha']
		url = 'https://www.google.com/recaptcha/api/siteverify'
		values = {
			'secret': '6LcNq10UAAAAAJVLztulO5FzlWynQ6p93k1rLnuk',
			'response': recaptcha_response
		}

		#### uncomment for python 2 #####
		#data2 = urllib.urlencode(values)
		#req = urllib2.Request(url, data2)
		#response = urllib2.urlopen(req)
		#result = json.load(response)
		#################################
		#### comment for python 2 #######
		data2 = urllib.parse.urlencode(values).encode()
		req =  urllib.request.Request(url, data=data2)
		response = urllib.request.urlopen(req)
		result = json.loads(response.read().decode())
		#################################	

		if result['success']:
			pass
		else:
			return JsonResponse({'error': "Invalid CAPTCHA. Please try again."})
		for idno in data['sport_id']:
			sp=Sport.objects.get(pk=int(idno))
			if data['register_as']!='C' and data['gender']!=sp.gender and sp.gender!='both':
				return JsonResponse({'error': 'Selected gender does not fit the gender requirement of the selected sports'})

		team = Team.objects.get(pk=data['college'])
		up=User()
		up.username=data['username']
		up.name=data['name']
		up.set_password(data['password'])
		try:
			up.save()
		except IntegrityError:
			state="Duplicacy in Username"
			return JsonResponse({'error':state})
		if data['register_as']=='C' :
			if len(data['sport_id'])>1:
				return JsonResponse({'error':"coach cannot register in more than 1 sport"})
			else:
				for idno in data['sport_id']:
					sp=Sport.objects.get(pk=idno)
					up.sport.add(sp)
					up.coach=idno
					up.sportid=replaceindex(up.sportid,idno,'1')
		elif data['register_as']=='L' :
			if len(data['sport_id'])>1:
				return JsonResponse({'error':"captain cannot initially register in more than 1 sport"})
			else:
				for idno in data['sport_id']:
					sp=Sport.objects.get(pk=idno)
					up.sport.add(sp)
					up.captain=idno
					up.sportid=replaceindex(up.sportid,idno,'1')
		else:
			for idno in data['sport_id']:
				sp=Sport.objects.get(pk=int(idno))
				up.sport.add(sp)
				up.sportid=replaceindex(up.sportid,int(idno),'1')

		up.phone=data['phone']
		if re.match(r"[^@]+@[^@]+\.[^@]+", data['email'])==None:
			state="Invalid Email Address"
			#return render(request,'register.html',{'state':state})
			return JsonResponse({'error':state})
		up.gender=data['gender']
		up.email=data['email']
		up.grp_leader = 1
		up.team = team
		if team.activate==1:
			up.deleted=1
		up.is_active=False
		up.save()
		to_email = up.email
		current_site = get_current_site(request)
		message = render_to_string('register/msg.html', {
											'user':up, 
											'domain':current_site.domain,
											'uid': urlsafe_base64_encode(force_bytes(up.pk)),
											'token': account_activation_token.make_token(up),
											})
		mail_subject = 'Registration for BOSM \'19'
		#mail.send_mail(mail_subject, message,'*****@*****.**',[to_email])
		email = EmailMessage(mail_subject, message, to=[to_email])
		email.content_subtype = "html"
		try:
			email.send()
		except:
			return JsonResponse({'error':'activation mail could not be sent please try again'})
		#return HttpResponseRedirect('login/')
		switch_data = [8,4]
		pusher_client.trigger('my-channel8', 'my-event8', switch_data)
		return JsonResponse({'error':'activation mail has been sent. please activate your account and wait for further correspondence'})
	return HttpResponseRedirect('/register/')
Beispiel #17
0
def add_participant(request):
    if request.user.is_authenticated():
        if is_firewallz_admin(request.user):
            pass
        else:
            logout(request)
            return HttpResponseRedirect('/regsoft/')
    else:
        return HttpResponseRedirect('/regsoft/')
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        up = User()
        up.save()
        up.username = (''.join(choice(ascii_uppercase)
                               for i in range(5))) + str(up.pk)
        passworduser = (''.join(choice(ascii_uppercase)
                                for i in range(12))) + str(up.pk)
        up.save()
        up.set_password(passworduser)
        up.name = data['data'][0]['name']
        up.email = data['data'][0]['email']
        up.confirm1 = 2
        up.gender = data['data'][0]['gender']
        up.save()
        pl = Regplayer()
        pl.name = up
        pl.gender = data['data'][0]['gender']
        tm = Team.objects.get(pk=int(data['data'][0]['college']))
        if (int(data['data'][0]['college']) == 16):
            pl.bitsian = True
        pl.college = tm.college
        pl.city = tm.city
        pl.mobile_no = str(data['data'][0]['phone'])
        pl.email_id = data['data'][0]['email']
        pl.entered = False
        pl.sport = ''
        for i in data['data'][0]['sport']:
            up.sportid = replaceindex(up.sportid, int(i), '2')
            sp = Sport.objects.get(idno=int(i))
            up.sport.add(sp)
            up.save()
            pl.sport = pl.sport + Sport.objects.get(idno=int(i)).sport + ','
        pl.save()
        pl.uid = "18CB" + str(100000 + pl.pk)[-4:]
        pl.save()

        if (pl.bitsian == True):
            up.pcramt = 1100
            up.save()
            pl.unbilled_amt = 0
            pl.uid = "18BP" + str(100000 + pl.pk)[-4:]
            pl.save()

        to_email = up.email
        message = render_to_string('register/msg2.html', {
            'user': up.name,
            'username': up.username,
            'password': passworduser,
        })
        mail_subject = 'Your account details.'
        email = EmailMessage(mail_subject, message, to=[to_email])
        #email.send()
        dat = {"pk": pl.pk, "college": pl.college}
        return HttpResponse(json.dumps(dat), content_type='application/json')
Beispiel #18
0
		a.description+=random.choice(alphabet)
	x=college.models.userprofile.objects.all()
	a.author=random.choice(x)
	a.approved=True
	a.save()
print '......................................',
print 'done'




#make students
print 'Students',
for i in students:
	a=college.models.student()
	a.name=i
	a.course=college.models.course.objects.first()
	a.save()
print '......................................',
print 'done'



#add a contact
print 'Contacts',
a=college.models.contact()
a.name='Phone'
a.value='+91-11-2766 7271 '
a.save()
a=college.models.contact()
a.name='Admission Help Line'
Beispiel #19
0
    def post(self, request):

        try:
            account = getAccount(request)
            isAdmin = Account.objects.get(id=account.id, isAdmin=True)
            phone = request.POST.get("phone","")

            try:
                accountExist = Account.objects.get(phone=phone)

                error_message = 'Account with this phone id already exist'
                err = {
                    'error_message' : error_message
                }
                serializer = ErrorCheckSerializer( err, many=False)
                return Response(serializer.data)
            except:
                pass

            name = request.POST.get("name","")
            password = request.POST.get("password","")
            lga = request.POST.get("lga","")
            gender = request.POST.get("gender","")
            pollingUnit = request.POST.get("pollingUnit", "")
            hasVotersCard = request.POST.get("hasVotersCard", "")
            email = request.POST.get("email","")

            lgaObject = Lga.objects.get(id = lga)
            pollingUnitObject = PollingUnit.objects.get(id = pollingUnit)

            raw_password = password
            password = make_password(password)
            
            user = User()
            user.username = phone
            user.password = password
            user.name = name
            user.save()

            userAccount = Account()
            userAccount.name = name
            userAccount.phone = phone
            userAccount.password = password
            userAccount.email = email
            userAccount.gender = gender
            userAccount.hasVotersCard = hasVotersCard
            userAccount.lga = lgaObject
            userAccount.pollingUnit = pollingUnitObject
            userAccount.save()

            adminUser = AdminUser()
            adminUser.user = user.id
            adminUser.admin = account
            adminUser.save()

            userList = Account.objects.all()
            bucket = []
            for admin in userList:

                name = admin.name
                phone = admin.phone

                lga = Lga.objects.get(id = admin.lga_id)
                lga_name = lga.name

                buffer = {
                    'name': name,
                    'phone': phone,
                    'lga': lga_name,
                }

                bucket.append(buffer)

            serializer = UserSerializer(bucket, many=True)
            return Response(serializer.data)

        except:
            pass

        error_message = 'You are not authorised to carry out this task'
        err = {
            'error_message' : error_message
        }
        serializer = ErrorCheckSerializer( err, many=False)
        return Response(serializer.data)
Beispiel #20
0
    def post(self, request):
        
        try:
            phone = request.POST.get("phone","")

            try:
                accountExist = Account.objects.get(phone=phone)

                error_message = 'Account with this phone id already exist'
                err = {
                    'error_message' : error_message
                }
                serializer = ErrorCheckSerializer( err, many=False)
                return Response(serializer.data)
            except:
                pass

            notificationToken = request.POST.get("notificationToken", "")
            name = request.POST.get("name","")
            password = request.POST.get("password","")
            lga = request.POST.get("lga","")
            pollingUnit = request.POST.get("pollingUnit", "")

            lgaObject = Lga.objects.get(id = lga)
            pollingUnitObject = PollingUnit.objects.get(id = pollingUnit)

            raw_password = password
            password = make_password(password)
            
            user = User()
            user.username = phone
            user.password = password
            user.name = name
            user.save()

            un = name.strip()
            username = un[0:8]


            userAccount = Account()
            userAccount.name = name
            userAccount.phone = phone
            userAccount.password = password
            userAccount.notificationToken = notificationToken
            userAccount.username = username
            userAccount.lga = lgaObject
            userAccount.pollingUnit = pollingUnitObject
            userAccount.save()

            serializer = AccountSerializer(userAccount, many=False)
            return Response(serializer.data)

        except:
            pass

        error_message = 'Sorry something went wrong, retry'
        err = {
            'error_message' : error_message
        }
        serializer = ErrorCheckSerializer( err, many=False)
        return Response(serializer.data)
Beispiel #21
0
    def post(self,request):

        serializer = NewAccountSerializer(data=request.data)
        if serializer.is_valid():

            name = serializer.data['name']
            phone = serializer.data['phone']
            password = serializer.data['password']

            try:

                User.objects.get(username = phone)
                account = Account.objects.get(phone = phone)
                
                status = authenticateLogin(request, phone, password)
                
                if status : 
                    serializer = AccountSerializer(account, many=False)
                    return Response(serializer.data)

                else:

                    error_message = 'Oops login details do not match'
                    err = {
                        'error_message' : error_message
                    }

                    serializer = ErrorCheckSerializer( err, many=False)
                    return Response(serializer.data)

            except:
                
                if str(name) == 'admin':
                    error_message = 'Login details does not match a registered admin'
                    err = {
                        'error_message' : error_message
                    }
                    serializer = ErrorCheckSerializer( err, many=False)

                    return Response(serializer.data)


            
            raw_password = password
            password = make_password(password)
            

            user = User()
            user.username = phone
            user.password = password
            user.name = name
            user.save()

            account = Account()
            account.name = name
            account.phone = phone
            account.password = password
            account.save()

            serializer = AccountSerializer(account, many=False)
            return Response(serializer.data)
        
        else:
            pass
    
        error_message = 'Sorry could not complete process, reload page and try again'
        err = {
            'error_message' : error_message
        }
        serializer = ErrorCheckSerializer( err, many=False)
        return Response(serializer.data)
Beispiel #22
0
    def post(self, request):

        try:
            phone = request.POST.get("phone", "")

            try:
                accountExist = DemoAccount.objects.get(phone=phone)

                error_message = 'Account with this phone number already exist'
                err = {'error_message': error_message}
                serializer = ErrorCheckSerializer(err, many=False)
                return Response(serializer.data)
            except:
                pass

            registrationNumber = request.POST.get("registrationNumber", "")

            try:
                accountExist = DemoAccount.objects.get(
                    registrationNumber=registrationNumber)

                error_message = 'Account with this registration number already exist'
                err = {'error_message': error_message}
                serializer = ErrorCheckSerializer(err, many=False)
                return Response(serializer.data)
            except:
                pass

            # notificationToken = request.POST.get("notificationToken", "")
            firstname = request.POST.get("firstname", "")
            middlename = request.POST.get("middlename", "")
            lastname = request.POST.get("lastname", "")
            age = request.POST.get("age", "")
            votercard = request.POST.get("votercard", "")
            password = request.POST.get("password", "")
            gender = request.POST.get("gender", "")
            isOldMember = request.POST.get("isOldMember", "")
            registrationNumber = request.POST.get("registrationNumber", "")
            lga = request.POST.get("lga", "")
            ward = request.POST.get("ward", "")
            pollingUnit = request.POST.get("pollingUnit", "")

            lgaObject = Lga.objects.get(id=lga)
            wardObject = Ward.objects.get(id=ward)
            pollingUnitObject = PollingUnit.objects.get(id=pollingUnit)

            raw_password = password
            password = make_password(password)

            userAccount = DemoAccount()
            userAccount.firstname = firstname
            userAccount.middlename = middlename
            userAccount.lastname = lastname
            userAccount.age = age
            userAccount.votercard = votercard
            userAccount.phone = phone
            userAccount.gender = gender
            userAccount.password = password
            userAccount.isOldMember = isOldMember
            if isOldMember == 1:
                userAccount.registrationNumber = registrationNumber
            else:
                lName = lgaObject.name
                n = random.randint(200000, 500000)
                reg = "PL/" + lgaObject.code + "/" + pollingUnit + "/" + str(n)
                userAccount.registrationNumber = reg.upper()

            userAccount.lga = lgaObject
            userAccount.ward = wardObject
            userAccount.pollingUnit = pollingUnitObject
            internalId = createInternalIdDemo(pollingUnitObject.delimitation,
                                              pollingUnit)
            userAccount.internalId = internalId
            userAccount.save()

            user = User()
            user.username = userAccount.internalId
            user.password = password
            user.name = firstname + ' ' + middlename + ' ' + lastname
            user.save()

            code = userAccount.internalId

            success = {'code': code}

            serializer = SuccessCodeSerializer(success, many=False)
            return Response(serializer.data)

        except:
            pass

        error_message = 'Sorry something went wrong, retry'
        err = {'error_message': error_message}
        serializer = ErrorCheckSerializer(err, many=False)
        return Response(serializer.data)
Beispiel #23
0
 def test_creating_user(self):
     user_object = User()
     user_object.name = "test"
     user_object.phone_number = "12345678"
     user_object.email = "*****@*****.**"
     user_object.save()
Beispiel #24
0
  'Curtis',
  'Dale',
  'Dalton',
  'Daniel',
  'Daniels',
  'Daugherty',
  'Davenport',
  'David',
  'Davidson']


for i in range(0,60):
  us = User()
  us.username = array[i+90]
  us.set_password(array[i+90]+"007")
  us.name = array[i+90]
  us.confirm1 = 2
  us.sportid = replaceindex(us.sportid,i%4,'2')
  us.gender = "Male"
  us.team = Team.objects.get(pk=(18+i%5))
  us.save()
  rp = Regplayer()
  rp.name = us
  rp.gender = us.gender
  rp.college = us.team.college
  rp.city = us.team.city
  rp.sport=''
  for s in Sport.objects.all():
  	if us.sportid[s.idno]=='2':
  		rp.sport=rp.sport+s.sport+','
  rp.save()