def save_user_from_row(user_row): user = User() user.id = user_row[1] user.username = user_row[2] user.age = user_row[5] user.gender = user_row[6] user.occupation = user_row[0] print(user.id, user.username, user.age, user.gender, user.occupation) user.save()
def signup(request): success = 1 if request.method == 'POST': key = request.POST.get('username', None) if key: # 계좌 생성 today = (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S') headers = {'Content-Type': 'application/json; charset=utf-8'} url = host + 'init_wallet' data = {'user_id': key, 'from_id': 'admin', 'date': today} param_data = {'param_data': json.dumps(data)} response = requests.post(url, params=param_data, headers=headers) msg = response.json() if msg['result'] == 'fail': success = 3 else: try: get_object_or_404(User, email=request.POST.get('email', None)) except: sleep(3) # 3000 rc 발행 today = ( datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S') headers = { 'Content-Type': 'application/json; charset=utf-8' } url = host + 'publish' data = { 'user_id': key, 'from_id': 'admin', 'amount': '3000', 'date': today } param_data = {'param_data': json.dumps(data)} response = requests.post(url, params=param_data, headers=headers) msg = response.json() if msg['result'] == 'success': success = 2 user = User() user.username = request.POST.get('username', None) user.set_password(request.POST.get('password1', None)) user.email = request.POST.get('email', None) user.gender = request.POST.get('gender', None) user.birth_year = request.POST.get('birth_year', None) user.birth_month = request.POST.get('birth_month', None) user.birth_date = request.POST.get('birth_date', None) user.type = 2 user.status = 1 user.save() return redirect('/signup' + str(success) + '/done/') else: return render(request, 'account/signup.html', {})
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))
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')
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))
def import_users(csv_file): error_messages = [] count_success = 0 try: # check for valid encoding (will raise UnicodeDecodeError if not) csv_file.read().decode('utf-8') csv_file.seek(0) with transaction.commit_on_success(): dialect = csv.Sniffer().sniff(csv_file.readline()) dialect = csv_ext.patchup(dialect) csv_file.seek(0) for (line_no, line) in enumerate(csv.reader(csv_file, dialect=dialect)): if line_no: try: (first_name, last_name, gender, structure_level, type, committee, comment) = line[:7] except ValueError: error_messages.append( _('Ignoring malformed line %d in import file.') % line_no + 1) continue user = User() user.last_name = last_name user.first_name = first_name user.username = gen_username(first_name, last_name) user.gender = gender user.structure_level = structure_level user.type = type user.committee = committee user.comment = comment user.default_password = gen_password() user.save() user.reset_password() count_success += 1 except csv.Error: error_messages.appen( _('Import aborted because of severe errors in the input file.')) except UnicodeDecodeError: error_messages.appen( _('Import file has wrong character encoding, only UTF-8 is supported!' )) return (count_success, error_messages)
def import_users(csv_file): error_messages = [] count_success = 0 try: # check for valid encoding (will raise UnicodeDecodeError if not) csv_file.read().decode('utf-8') csv_file.seek(0) with transaction.commit_on_success(): dialect = csv.Sniffer().sniff(csv_file.readline()) dialect = csv_ext.patchup(dialect) csv_file.seek(0) for (line_no, line) in enumerate(csv.reader(csv_file, dialect=dialect)): if line_no: try: (first_name, last_name, gender, structure_level, type, committee, comment) = line[:7] except ValueError: error_messages.append(_('Ignoring malformed line %d in import file.') % line_no + 1) continue user = User() user.last_name = last_name user.first_name = first_name user.username = gen_username(first_name, last_name) user.gender = gender user.structure_level = structure_level user.type = type user.committee = committee user.comment = comment user.default_password = gen_password() user.save() user.reset_password() count_success += 1 except csv.Error: error_messages.appen(_('Import aborted because of severe errors in the input file.')) except UnicodeDecodeError: error_messages.appen(_('Import file has wrong character encoding, only UTF-8 is supported!')) return (count_success, error_messages)
def addUser(request): page_title = "Add User" form_class = UserForm if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): obj = User() obj.username = form.cleaned_data['username'] obj.first_name = form.cleaned_data['first_name'] obj.last_name = form.cleaned_data['last_name'] obj.email = form.cleaned_data['email'] obj.phone = form.cleaned_data['phone'] obj.gender = form.cleaned_data['gender'] obj.password1 = form.cleaned_data['password1'] obj.password2 = form.cleaned_data['password2'] obj.save() messages.success(request, 'User details saved successfully..!') return HttpResponse('Added') else: form = form_class() return render(request, 'users/usersform.html', { 'form': form, 'page_title': page_title })
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'
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')
'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()
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/')
def motion_import(request): if request.method == 'POST': form = MotionImportForm(request.POST, request.FILES) if form.is_valid(): import_permitted = form.cleaned_data['import_permitted'] try: # check for valid encoding (will raise UnicodeDecodeError if not) request.FILES['csvfile'].read().decode('utf-8') request.FILES['csvfile'].seek(0) users_generated = 0 motions_generated = 0 motions_modified = 0 groups_assigned = 0 groups_generated = 0 with transaction.commit_on_success(): dialect = csv.Sniffer().sniff(request.FILES['csvfile'].readline()) dialect = csv_ext.patchup(dialect) request.FILES['csvfile'].seek(0) for (lno, line) in enumerate(csv.reader(request.FILES['csvfile'], dialect=dialect)): # basic input verification if lno < 1: continue try: (number, title, text, reason, first_name, last_name, is_group) = line[:7] if is_group.strip().lower() in ['y', 'j', 't', 'yes', 'ja', 'true', '1', 1]: is_group = True else: is_group = False except ValueError: messages.error(request, _('Ignoring malformed line %d in import file.') % (lno + 1)) continue form = MotionForm({'title': title, 'text': text, 'reason': reason}) if not form.is_valid(): messages.error(request, _('Ignoring malformed line %d in import file.') % (lno + 1)) continue if number: try: number = abs(long(number)) if number < 1: messages.error(request, _('Ignoring malformed line %d in import file.') % (lno + 1)) continue except ValueError: messages.error(request, _('Ignoring malformed line %d in import file.') % (lno + 1)) continue if is_group: # fetch existing groups or issue an error message try: user = Group.objects.get(name=last_name) if user.group_as_person == False: messages.error(request, _('Ignoring line %d because the assigned group may not act as a person.') % (lno + 1)) continue else: user = get_person(user.person_id) groups_assigned += 1 except Group.DoesNotExist: group = Group() group.group_as_person = True group.description = _('Created by motion import.') group.name = last_name group.save() groups_generated += 1 user = get_person(group.person_id) else: # fetch existing users or create new users as needed try: user = User.objects.get(first_name=first_name, last_name=last_name) except User.DoesNotExist: user = None if user is None: if not first_name or not last_name: messages.error(request, _('Ignoring line %d because it contains an incomplete first / last name pair.') % (lno + 1)) continue user = User() user.last_name = last_name user.first_name = first_name user.username = gen_username(first_name, last_name) user.structure_level = '' user.committee = '' user.gender = '' user.type = '' user.default_password = gen_password() user.save() user.reset_password() users_generated += 1 # create / modify the motion motion = None if number: try: motion = Motion.objects.get(number=number) motions_modified += 1 except Motion.DoesNotExist: motion = None if motion is None: motion = Motion(submitter=user) if number: motion.number = number motions_generated += 1 motion.title = form.cleaned_data['title'] motion.text = form.cleaned_data['text'] motion.reason = form.cleaned_data['reason'] if import_permitted: motion.status = 'per' motion.save(user, trivial_change=True) if motions_generated: messages.success(request, ungettext('%d motion was successfully imported.', '%d motions were successfully imported.', motions_generated) % motions_generated) if motions_modified: messages.success(request, ungettext('%d motion was successfully modified.', '%d motions were successfully modified.', motions_modified) % motions_modified) if users_generated: messages.success(request, ungettext('%d new user was added.', '%d new users were added.', users_generated) % users_generated) if groups_generated: messages.success(request, ungettext('%d new group was added.', '%d new groups were added.', groups_generated) % groups_generated) if groups_assigned: messages.success(request, ungettext('%d group assigned to motions.', '%d groups assigned to motions.', groups_assigned) % groups_assigned) return redirect(reverse('motion_overview')) except csv.Error: message.error(request, _('Import aborted because of severe errors in the input file.')) except UnicodeDecodeError: messages.error(request, _('Import file has wrong character encoding, only UTF-8 is supported!')) else: messages.error(request, _('Please check the form for errors.')) else: messages.warning(request, _("Attention: Existing motions will be modified if you import new motions with the same number.")) messages.warning(request, _("Attention: Importing an motions without a number multiple times will create duplicates.")) form = MotionImportForm() return { 'form': form, }