def edit_user(): form = EditInfoForm() if session.get('id'): id = session['id'] if request.method == "GET": user = User.select().where(User.id == id)[0] form.fname.data = user.fname form.lname.data = user.lname form.email.data = user.email return render_template('edit_user.html', form=form, id=id) if request.method == "POST": if form.validate_on_submit(): #edit in db codd\ user = User.select().where(User.id == id)[0] user.fname = form.fname.data.strip() user.lname = form.lname.data.strip() user.email = form.email.data.strip() user.save() flash("Edit successful") return redirect(url_for('list_users', )) print(form.errors) return render_template('edit_user.html', form=form) return redirect(url_for('list_users', ))
def setUpTestData(self): """ Run truoc khi thuc hien cac test function setup du lieu cho cac test function """ self.user = User('N16DCCN131', 'D16CQCN03-N', 'Le Tanh Sang', '1998-23-06', 1, 'sakdhksdk', 60)
def register(request): username = request.POST.get('username') password = request.POST.get('password') captcha = request.POST.get('captcha') # 如果有其中一个参数没有传递则返回错误 if not ([username, password, captcha]): return JsonResponse({ "status": status_code.PARAMS_NOT_COMPLETE, "errmsg": "参数不全" }) if not re.match("^[1][34578][0-9]{9}$", username): # 不是手机号码,返回错误 return JsonResponse({ "status": status_code.PARAMS_IS_INVALID, "errmsg": "手机号码错误" }) # 判断手机号是否已经注册过 user = User.objects.filter(username=username) if user: return JsonResponse({ "status": status_code.USER_HAS_EXIST, "errmsg": "该手机号已注册" }) if not re.match("[a-zA-Z0-9]{8,16}", password): # 不是手机号码,返回错误 return JsonResponse({ "status": status_code.PARAMS_TYPE_ERROR, "errmsg": "密码格式错误" }) # 判断验证码是否正确,1.验证码过期 2.验证码错误 sms_code = settings.REDIS_CLIENT.get(username) if not sms_code: # 获取不到数据表示验证码过期 return JsonResponse({ "status": status_code.SMS_SERVER_NOT_CAPTCHA, "errmsg": "验证码已过期" }) if captcha != sms_code.decode("utf-8"): return JsonResponse({ "status": status_code.SMS_SERVER_NOT_CAPTCHA, "errmsg": "验证码错误" }) # 密码加密 sha = hashlib.sha1() sha.update(password.encode("utf-8")) sha_pwd = sha.hexdigest() # 全部参数都正确之后保存到数据库完成注册,需要使用到模型类 try: user = User(username=username, password=sha_pwd) user.save() except Exception as e: return JsonResponse({ "status": status_code.USER_REGISTER_ERROR, "errmsg": "验证码错误" }) return JsonResponse({"status": status_code.SUCCESS, "errmsg": "注册成功"})
def signup(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) user.add_user() return redirect(url_for('app.login')) return render_template('signup.html', form=form)
def update_user(sender, response, access_token): if current_user.is_authenticated(): session[TOKENS_KEY][sender.name] = access_token current_user.access_keys = session[TOKENS_KEY] User.get_collection().update( {'_id':current_user._id}, {'$set': {'access_keys': current_user.access_keys}}) else: login_user(register_user(response, access_token))
def signup(request): if request.POST: email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') u = User(username=username, email=email, password=password) u.save() return render_to_response('login/login.html') else: return render_to_response()
def add_user(username, password, email, sex): same_name_user = User.objects.filter(name=username) if same_name_user: message = '用户名已存在' return None same_email_user = User.objects.filter(email=email) if same_email_user: message = '该邮箱已经被注册了!' return None new_user = User() new_user.name = username new_user.password = hash_code(password) new_user.email = email new_user.sex = sex new_user.has_confirmed = True #直接跳过邮件确认 new_user.save() new_userprofile = UserProfile() new_userprofile.user = new_user new_userprofile.save() new_userprofile.follow_list.add(new_userprofile) new_userprofile.save() return
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('恭喜你成为我们网站的新用户') return redirect(url_for('login_opt.login')) return render_template('register.html', title='注册', form=form)
def test_make_unique_nickname(self): u = User(nickname='john', email='*****@*****.**') db.session.add(u) db.session.commit() nickname = User.make_unique_nickname('john') assert nickname != 'john' u = User(nickname=nickname, email='*****@*****.**') db.session.add(u) db.session.commit() nickname2 = User.make_unique_nickname('john') assert nickname2 != 'john' assert nickname2 != nickname
def logoutUser(req): un = req.GET['un'] try: q=User.objects.raw('SELECT * from login_user where username = "******"')[0].name p=User.objects.raw('SELECT * from login_user where username = "******"')[0].password except: return JsonResponse({"Error":"UserNotFound"}) w=User(username=un,password=p,name=q,auth12='NA') w.save() return JsonResponse({"Success":"Logout Successfull"})
def create(request): request_json = json.loads(request.body); username = request_json['username'] passw = request_json['passw'] try: user = User.objects.get(username__exact=str(username)) return JsonResponse({'success':False}) except : new_user = User(username=username, passw=passw) new_user.save() return JsonResponse({'success':True}) return 0
def createUser(req): un = req.GET['un'] p = req.GET['p'] n=req.GET['n'] try: z=User.objects.raw('SELECT * from login_user where username = "******"')[0].name except: q=User(username=un,password=p,name=n,auth12="aa") q.save() return JsonResponse({"Status":"Success"}) return JsonResponse({"Status":"Fail"})
def addTeacher(request): if request.method == "POST": if User.objects.filter(username=request.POST['name']).exists(): context = {'info': "Username already Exist"} return render(request, 'teacher/add_teacher.html', context) else: user = User() user.username = request.POST['name'] user.email = request.POST['email'] user.set_password(request.POST['password']) user.save() teacher = Teacher() teacher.user = user teacher.dept_id = request.POST['class'] teacher.set_password(request.POST['password']) teacher.t_USN = request.POST['t_USN'] teacher.name = request.POST['name'] teacher.email = request.POST['email'] teacher.sex = request.POST['sex'] teacher.DOB = request.POST['DOB'] teacher.phone = request.POST['phone'] teacher.save() context = { 'class_s': Dept.objects.all(), 'success': "Teacher Added Successfully" } return render(request, 'teacher/add_teacher.html', context) dept = Dept.objects.all() context = {'department': dept} return render(request, 'teacher/add_teacher.html', context)
def ShowcaseView(request): try: # Först testar jag att skapa 2 användare och lägga in dem i tabellen user1 = User( Gender='Male', FirstName='Kevin', LastName='Engström', DateOfBirth=datetime.date.today(), Email='*****@*****.**', Pubkey='asd', ) user1.save() user2 = User( Gender='Female', FirstName='Lisa', LastName='Svensson', DateOfBirth=datetime.date.today(), Email='*****@*****.**', Pubkey='fgh', ) user2.save() except Exception as e: pass # En enkel sökning där jag vill ta fram alla som heter lisa. Och jag vill bara ha attributen id, förnamn och födelsedag result = User.objects.filter(FirstName='Lisa').values( 'UserId', 'FirstName', 'DateOfBirth' ) # För att skicka in variabler till templaten så ska en dict skickas med variablerna. context = {'result': result[0]} return render(request, 'home/showcase.html', {})
def createacc(request): if request.method == 'POST': email = request.POST['email'] contact = request.POST['contact'] uname = request.POST['uname'] password = request.POST['password'] #print(email,contact,uname,password) ins = User(email=email, contact=contact, uname=uname, password=password) ins.save() return render(request, 'createacc1.html')
def update_user(sender, request, access_token): if current_user.is_authenticated(): session[TOKENS_KEY] = access_token current_user.access_key = access_token current_user.uids[request.args['service']] = request.args['uid'] User.get_collection().update( {'_id':current_user._id}, {'$set': {'access_key': current_user.access_key, 'uids': current_user.uids } }) else: login_user(register_user(request, access_token))
def load_user(user_id): user = User.get_collection().find_one(ObjectId(user_id)) if user: return User(**user) else: return None
def users_request_detail(request, request_id): context, sqlQuery = getContextAndSqlQuery(request, REQUESTS_USERS, request_id) with connection.cursor() as c: manager = BaseDBManager() c.execute(sqlQuery) context["users_list"] = [User.from_db(d) for d in manager.fetch_dicts(c)] return render(request, 'dbrequests/list_users_or_tags.html', context)
def login(): if session.get('username'): return redirect(url_for('home')) form = LoginForm() if request.method == 'GET': return render_template('login.html', form=form) if request.method == 'POST': email = form.email.data.strip() password = form.password.data.strip() if form.validate_on_submit(): qs = User.select().where(User.email == email) if len(qs) > 0: qs = qs[0] if qs.password == password: session['username'] = qs.fname session['id'] = qs.id session.permanent = True return redirect(url_for('home')) return render_template('login.html', form=form, error="Wrong password or email") print(form.errors) return render_template('login.html', form=form, error="Wrong password or email")
def login(request): if request.method == 'GET': return render(request, 'login.html') elif request.method == "POST": # req_data = json.loads(request.body) # name = req_data.get('name') # password = req_data.get('password') name = request.POST.get('name') password = request.POST.get('password') user = User.login(name=name, password=password) if user: root_folder_ = FolderInfo.objects.get(user=user, belong_folder=None) data = { 'msg': 'Login Success!', 'code': 1, 'root_folder': root_folder_.folder_id, 'token': user.get_token(), } print( root_folder_.folder_id) # a2edf0fe-f10d-4369-81bf-5cf2c6e53476 return JsonResponse(data, status=200) else: data = { 'msg': 'Login Failed!', 'code': 0, 'root_folder': '', 'token': '', } return JsonResponse(data, status=200)
def signup(request): _username = request.POST['username'] _firstname= request.POST['firstname'] _lastname = request.POST['lastname'] _password = request.POST['pwd'] _gender = request.POST['gender'] _email = request.POST['email'] _dob = request.POST['dob'] if(_username =='' or _firstname =='' or _password =='' or _gender =='' or _email =='' or _dob ==''): errormessage="Please provide all Mandatory Fields" return render(request,"signup.html",{'errormessage':errormessage}) else: a=User(username=_username,firstname=_firstname,lastname=_lastname,password=_password,gender=_gender,email=_email,dob=_dob) a.save() errormessage="Registered Succesfully Please Login!!!!" return render(request,"login.html",{'errormessage':errormessage})
def register(request): if request.method == 'GET': return render(request, 'register.html') elif request.method == "POST": # req_data = json.loads(request.body) # name = req_data.get('name') # password = req_data.get('password') # email = req_data.get('email') name = request.POST.get('name') password = request.POST.get('password') email = request.POST.get('email') user = User.add(name, password, email) if user: data = { 'msg': '注册成功!', 'code': 1, 'token': user.get_token(), } return JsonResponse(data, status=200) else: data = { 'msg': '注册失败!', 'code': 0, 'token': '', } return JsonResponse(data, status=200)
def root_folder(request, user: User): root_folder_ = FolderInfo.objects.get(user=user, belong_folder=None) return JsonResponse({ 'msg': '', 'code': 1, 'root_folder': root_folder_.folder_id, 'token': user.get_token() })
def login(): if request.method == 'POST': user_id = request.form.get('userid') user = query_user(user_id) if user is not None and request.form['password'] == user['password']: curr_user = User() curr_user.id = user_id # 通过Flask-Login的login_user方法登录用户 login_user(curr_user) return redirect(url_for('index')) flash('Wrong username or password!') # GET 请求 return render_template('login.html')
def login(request): uname = request.POST['username'] pwd = request.POST['password'] userobj= User() valid = userobj.authenticate(uname,pwd) if valid: userData = User.objects.get(username=uname) request.session['id']=userData.id request.session['username']=userData.username request.session['firstname']=userData.firstname request.session['lastname']=userData.lastname request.session['gender']=userData.gender request.session['email']=userData.email return redirect('posts') else: errormessage="Authentication failed try again" return render(request,"login.html",{'errormessage':errormessage})
def delete_user(): #delete from db code if session.get('id'): id = session['id'] dq = User.delete().where(User.id == id) dq.execute() return redirect(url_for('logout'))
def create_userprofile_with_github_user_info(request): headers = {'Authorization': '{} {}'.format(request.session.get('token_type'), request.session.get('access_token'))} json_response = requests.get('https://api.github.com/user', headers=headers).json() github_id = extract_from(json_response, "id") name = extract_from(json_response, "name") avatar_url = extract_from(json_response, "avatar_url") email = extract_from(json_response, "email") print("github id {} - name {} - avatar_url {} - email {}".format(github_id, name, avatar_url, email)) try: new_user = User() new_user.authentication_id = github_id new_user.name = name new_user.email = email new_user.save() new_profile = Profile() new_profile.user_id = new_user.id new_profile.avatar_url = avatar_url new_profile.User = new_user new_profile.save() request.session['username'] = name content = {'githubapi.profile_creation': 'User created and Profille authomatic filled with user Github public information'} return Response(content, status=status.HTTP_201_CREATED) except: content = {'githubapi.profile_creation': 'something went bad'} return Response(content, status=status.HTTP_409_CONFLICT)
def register(request): if request.method == "POST": # form = UserForm(request.POST) # if form.is_valid(): # try: # form.save() # return redirect() # except: # pass try: uname = request.POST.get("uname") email = request.POST.get("email") passwd = request.POST.get("passwd") com_passwd = request.POST.get("com_passwd") user = User() if passwd!=com_passwd: raise Exception else: user.uname = uname user.passwd = passwd user.email = email user.save() except: return redirect("/register") else: return HttpResponse("data entered!") return render(request,'register.html',{})
def register(request): name = request.POST['name'] print name IsExist = User.objects.filter(name__icontains=name) print IsExist password = md5(request.POST['password']) print password email = request.POST['email'] if not IsExist: u = User(name = name, password = password, email = email) u.save() dumpResult = makeJSON(u, 'register', 1) else: dumpResult = makeJSON(None, 'register', 0) if 'callback' in request.GET: callback = request.GET['callback'] dumpResult = '%s(%s)' % (callback,dumpResult) return HttpResponse(dumpResult)
def joinFacebook(request): if request.method == "POST": userName = request.POST.get('userName') userMail = request.POST.get('userMail') userAge = request.POST.get('userAge') userGender = request.POST.get('userGender') userRegion = request.POST.get('userRegion') userPhoneNumber = request.POST.get('userPhoneNumber') userAccessToken = request.POST.get('userAccessToken') user = User(name=userName, mail=userMail, age=userAge, gender=userGender, region=userRegion, phonenumber=userPhoneNumber, accesstoken_facebook=userAccessToken) user.save() return HttpResponse(json.dumps({'result': 'signup'}))
def form_valid(self, form): new_user = User(account_name=form.cleaned_data['account_name'], full_name=form.cleaned_data['full_name'], email=form.cleaned_data['email'], password=encrypt_input(form.cleaned_data['password']), last_login_date=timezone.now()) new_user.save() salt, activation_key = encrypt_input(form.cleaned_data['account_name']).split('$') ac = UserActivation(user=new_user, activation_key=activation_key) ac.save() activation_url = self.request.get_host() + reverse('login:activate', args=(activation_key,)) email = EmailMessage('Account activation', 'The activation url for your account %s is %s' % (form.cleaned_data['account_name'], activation_url), to=[form.cleaned_data['email']]) email.send() self.request.session['account_name'] = form.cleaned_data['account_name'] return render_to_response('confirm.html', {'new_user': new_user}, context_instance=RequestContext(self.request))
def joinKakao(request): if request.method == "POST": userName = request.POST.get('userName') userMail = request.POST.get('userMail') userAge = request.POST.get('userAge') userGender = request.POST.get('userGender') userRegion = request.POST.get('userRegion') userPhoneNumber = request.POST.get('userPhoneNumber') userAccessToken = request.POST.get('userAccessToken') if User.objects.filter(mail=userMail).exists(): return HttpResponse(json.dumps({'result': 'mail duplicated'})) user = User(name=userName, mail=userMail, age=userAge, gender=userGender, region=userRegion, phonenumber=userPhoneNumber, accesstoken_kakao=userAccessToken) user.save() return HttpResponse(json.dumps({'result': 'signup'}))
def test_str(self): user = User(username='******', email='*****@*****.**', password1='hanshe', password2='hanshe') self.assertEquals( str(user), 'hans [email protected]', )
def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): user = User.select_by_email(form.email.data) if user and user.validate_password(form.password.data): login_user(user) next = request.args.get('next') if not next: next = url_for('app.welcome') return redirect(next) return render_template('login.html', form=form)
def add(request): if request.method != "POST": return controll(ERR_BAD_CREDENTIALS) parameters = json.loads(request.body) for p in ["user", "password"]: if p not in parameters: return controll(ERR_BAD_CREDENTIALS) user = User.add(parameters["user"], parameters["password"]) if user > 0: return controll(SUCCESS, count = user) else: return controll(user)
def joinItself(request): if request.method == "POST": userName = request.POST.get('userName') userMail = request.POST.get('userMail') userPwd = request.POST.get('userPwd') userAge = request.POST.get('userAge') userGender = request.POST.get('userGender') userRegion = request.POST.get('userRegion') userPhoneNumber = request.POST.get('userPhoneNumber') if User.objects.filter(mail=userMail).exists(): return HttpResponse(json.dumps({'result': 'mail duplicated'})) else: user = User(name=userName, mail=userMail, password=userPwd, age=userAge, gender=userGender, region=userRegion, phonenumber=userPhoneNumber) user.save() return HttpResponse(json.dumps({'result': 'signup'}))
def add(request): if request.method == 'POST': user_field = request.POST.get('username') pass_field = request.POST.get('password') existing_user = User.objects.filter(username=user_field) existing_user = existing_user[0] if existing_user else None error = mvc.SUCCESS if user_field and len(user_field) < mvc.MAX_USERNAME_LENGTH: # username field non empty -> existing user or new user if request.POST.get('login') is not None: # user clicked login print "login" if existing_user and existing_user.password == pass_field: # correct user/pass pair existing_user.counter += 1 existing_user.save() print "update" else: error = mvc.ERR_BAD_CREDENTIALS print "wrong pass" elif request.POST.get('add') is not None: # user clicked add print "add" if existing_user: error = mvc.ERR_USER_EXISTS print "exists" elif len(pass_field) > mvc.MAX_PASSWORD_LENGTH: error = mvc.ERR_BAD_PASSWORD print "badpass" else: existing_user = User(username=user_field, password=pass_field, counter=1) print "new user!" existing_user.save() else: print "huh" else: error = mvc.ERR_BAD_USERNAME print existing_user return render_to_response('login/add.html', {'user' : existing_user, 'error': error,}, RequestContext(request)) else: return HttpResponse("Not a POST response")
def register_customer(request): title = "signup|medstart" user = request.user if request.method == "GET": return render(request, "login/signup.html") else: email = request.POST["email"] mobile = request.POST["mobile"] password = request.POST["password"] u = User() try: if User.objects.filter(email=email): response_data = {"Error": "User with this email Already Exists"} return HttpResponse(json.dumps(response_data), content_type="application/json") elif User.objects.filter(mobile=mobile): response_data = {"Error": "User with this mobile Already Exists"} return HttpResponse(json.dumps(response_data), content_type="application/json") else: u = User.objects.create(email=email, mobile=mobile, user_type="CST", terms=True) group = Group.objects.get(name="customer") u.set_password(password) u.save() c = Customer.objects.create(user=u, source=u, first_name="", last_name="") c.save() group.user_set.add(u) u = authenticate(username=email, password=password) u.backend = "django.contrib.auth.backends.ModelBackend" login(request, u) return HttpResponseRedirect(reverse("index")) except Exception, e: print e return render(request, "login/signup.html")
def register_merchant(request): title = "signup for business | medstart" if request.method == "GET": return render(request, "login/signup1.html") else: merchant = request.POST["merchant"] email = request.POST["email"] mobile = request.POST["mobile"] password = request.POST["password"] u = User() try: if User.objects.filter(email=email): response_data = {"Error": "User with this email Already Exists"} return HttpResponse(json.dumps(response_data), content_type="application/json") elif User.objects.filter(mobile=mobile): response_data = {"Error": "User with this mobile Already Exists"} return HttpResponse(json.dumps(response_data), content_type="application/json") else: u = User.objects.create(email=email, mobile=mobile, user_type="MER", terms=True) group = Group.objects.get(name="merchant") u.set_password(password) u.save() m = Merchant.objects.create(mer_name=merchant, merchant_type="LIC") m.save() man = Managers.objects.create(user=u, merchant=m) man.save() group.user_set.add(u) u = authenticate(username=email, password=password) u.backend = "django.contrib.auth.backends.ModelBackend" login(request, u) return HttpResponseRedirect(reverse("index")) except Exception, e: print e return render(request, "login/signup.html")
def index(request): code = request.GET.get('code', '') if code == '': return HttpResponseRedirect('/login/') user = User.objects.filter(code=code) client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) if user.count() != 0: user = user[0] else: r = client.request_access_token(code) dbuser = User.objects.filter(uid=r.uid) if dbuser.count() == 0: user = User(uid=r.uid, access_token=r.access_token, expires_in=r.expires_in, code=code) user.save() else: user = dbuser[0] user.code, user.access_token, user.expires_in, = code, r.access_token, r.expires_in user.save() access_token = user.access_token # 新浪返回的token,类似abc123xyz456 # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4 expires_in = user.expires_in client.set_access_token(access_token, expires_in) print "login:", user.uid, access_token, expires_in # print client.statuses.user_timeline.get() # print client.statuses.update.post(status=u'测试OAuth 2.0发微博') # print client.statuses.upload.post(status=u'测试OAuth 2.0带图片发微博', # pic=open('/Users/michael/test.png')) template = loader.get_template('main/index.html') # screen_name = client.users.show.get(uid=user.uid)['screen_name'] screen_name = user.uid return HttpResponse(template.render({'screen_name':screen_name}))
def registration(request): if request.method != 'POST': return HttpResponse(ResponseCode.badRequest.value) try: data = json.loads(request.body) username = data['username'] password = data['password'] email = data['email'] print(username + " " + password + " " + email) User(username=username, password=password, email=email).save() return HttpResponse(ResponseCode.success.value) except: return HttpResponse(ResponseCode.badRequest.value)
def register(request): form = SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): username = request.POST.get('username', '') email = request.POST.get('email', '') password = request.POST.get('password', '') cfmPassword = request.POST.get('cfmPassword', '') if password != cfmPassword: return render(request, 'register.html', {'form': form, 'failed': 1}) # print(username, email, password) try: User.objects.get(username = username) return render(request, 'register.html', {'form': form, 'failed':2}) except User.DoesNotExist: addUser = User(username=username, email=email, password = password) addUser.save() return HttpResponse(render(request, 'accountCreated.html')) return render(request, 'register.html', {'form': form, 'failed': 0})
def login(request): # Check that the request method is correct. if request.method != "POST": return controll(ERR_BAD_CREDENTIALS) parameters = json.loads(request.body) for p in ["user", "password"]: if p not in parameters: return controll(ERR_BAD_CREDENTIALS) user = User.login(parameters["user"], parameters["password"]) if user > 0: return controll(SUCCESS, count = user) else: return controll(user)
def register(request): if request.method == 'POST': # Get the bound register form form = forms.RegisterForm(request.POST) # Validate the register form if form.is_valid(): validate_new_password_response = validate_new_password( form.cleaned_data['user_password'], form.cleaned_data['user_password_again']) if not validate_new_password_response['successful']: return render( request, 'login/register.html', { 'page_error': 'The passwords you entered do not match. Please enter the same password twice.', 'form': form }) new_user = User( user_email=form.cleaned_data['user_email'], user_password=form.cleaned_data['user_password'], user_team_name=form.cleaned_data['user_team_name'], user_referring_email=form.cleaned_data['user_referring_email']) new_user.user_password = new_user.hash_password() try: new_user.full_clean() except ValidationError as e: return render( request, 'login/register.html', { 'page_error': 'There was a problem during registration. Try again.', 'form': form }) else: new_user.save() request.session['user_id'] = new_user.user_id return HttpResponseRedirect('/home/') else: form = forms.RegisterForm() registration_locked = False week_one = Week.objects.get(week_number=1) if week_one.picks_lock < timezone.now(): registration_locked = True # Renders the register form if it's a new request return render(request, 'login/register.html', { 'form': form, 'registration_locked': registration_locked })
def loginUser(req): un = req.GET['un'] p = req.GET['p'] a=''.join(random.choice(string.ascii_uppercase + string.digits+ string.ascii_lowercase) for _ in range(16)) q="error" try: q=User.objects.raw('SELECT * from login_user where username = "******" and password = "******"')[0].name a=User.objects.raw('SELECT * from login_user where username = "******" and password = "******"')[0].auth12 except: return JsonResponse({"Error":"UserNotFound"}) trying=False if len(a)<=5 : trying=True while(trying): a=''.join(random.choice(string.ascii_uppercase + string.digits+ string.ascii_lowercase) for _ in range(16)) try: x=User.objects.raw('SELECT * from login_user where auth12 = "'+a+'"')[0].name except: trying = False w=User(username=un,password=p,name=q,auth12=a) w.save() return JsonResponse({"Authentication":a,"Name":q})
def register_after(request): flag = 0 errors=[] if ('username' not in request.GET) or (not request.GET['username']): errors.append("Please enter a username.") flag=1 if ('password' not in request.GET) or (not request.GET['password']): errors.append("Please enter a password.") flag=1 if ('email' not in request.GET) or (not request.GET['email']): errors.append("Please enter a valid e-mail address.") flag=1 if ('first_name' not in request.GET) or (not request.GET['first_name']): errors.append("Please enter a valid first name.") flag=1 if ('last_name' not in request.GET) or (not request.GET['last_name']): errors.append("Please enter a valid last name.") flag=1 if not(request.GET['password'] == request.GET['password2']): errors.append("Passwords do not match") flag=1 try: user = User.objects.get(username=request.GET['username']) flag=1 except User.DoesNotExist: if flag == 0: p = User(username=request.GET['username'], password=request.GET['password'], first_name=request.GET['first_name'], last_name=request.GET['last_name'], email=request.GET['email']) p.save() return render(request, 'register_complete.html', {'newuser': p.first_name}) else: return render(request, 'register_page.html', {'errors': errors}) errors.append("This user name is already taken!") return render(request, 'register_page.html', {'errors': errors})
def register(request): if request.method == 'POST': # Get the bound register form form = forms.RegisterForm(request.POST) # Validate the register form if form.is_valid(): validate_new_password_response = validate_new_password(form.cleaned_data['user_password'], form.cleaned_data['user_password_again']) if not validate_new_password_response['successful']: return render(request, 'login/register.html', { 'page_error': 'The passwords you entered do not match. Please enter the same password twice.', 'form': form }) new_user = User( user_email = form.cleaned_data['user_email'], user_password = form.cleaned_data['user_password'], user_team_name = form.cleaned_data['user_team_name'], user_referring_email = form.cleaned_data['user_referring_email'] ) new_user.user_password = new_user.hash_password() try: new_user.full_clean() except ValidationError as e: return render(request, 'login/register.html', { 'page_error': 'There was a problem during registration. Try again.', 'form': form }) else: new_user.save() request.session['user_id'] = new_user.user_id return HttpResponseRedirect('/home/') else: form = forms.RegisterForm() registration_locked = False week_one = Week.objects.get(week_number=1) if week_one.picks_lock < timezone.now(): registration_locked = True # Renders the register form if it's a new request return render(request, 'login/register.html', { 'form': form, 'registration_locked': registration_locked })
def register_user(request, access_token): btid = request.args.get('btid') if btid: users = User.get_collection() user = User.find_one({'btid': btid}) if user: user['access_key'] = access_token user['uids'][request.args['service']] = request.args['uid'] User.save(user) user = User(**user) else: user = User(btid, access_token, uids = {request.args['service']: request.args['uid']}, confirmed = True) user_id = User.get_collection().insert(dict(user)) user._id = user_id session[TOKENS_KEY] = user['access_key'] return user return None
def main(request): user = User() if user.authUser(request): return render_to_response('info/main.html', context_instance=RequestContext(request)) else: return render_to_response('login/login.html', context_instance=RequestContext(request))
def load_user(user_id): return User(**(User.get_collection().find_one(ObjectId(user_id))))
def register(request): error = [] email = '' passwd = '' passwd1 = '' if request.method == 'POST': data = request.POST if 'email' in data and 'passwd' in data and 'passwd1' in data and ( 'icode' in data and 'icode_ref' in data): email = data['email'] passwd = data['passwd'] passwd1 = data['passwd1'] error = [] import re if not data['email']: error.append('Email should not be NULL') elif not re.match(u'\w+@\w+\.\w+', data['email']): error.append(['Email is not correct']) user = User.objects.filter(email=email) if user: error.append('Email exists') if data['passwd'] != data['passwd1']: error.append('Twice Password are different') elif len(data['passwd']) < 8: error.append('Length of password should be 8 at least') error.append('Lower and upper character, digit and operator should have one at least') elif len(data['passwd']) > 100: error.append('Length of password should be less than 128') elif not is_valid(data['passwd']): error.append('Lower and upper alpha and digit and operator should have one at least') if not data['icode']: error.append('Identifying code should not be NULL') elif data['icode'].lower() != data['icode_ref'].split('.')[0].lower(): error.append('Identifying code is not correct') if not error: email = data['email'] password = data['passwd'] user = User(email=email, password=password) user.save() userinfo = UserInfo(email=email, name=email, lovebridge=True) userinfo.save() # It's very important request.session['email'] = email request.session['name'] = email return render(request, 'login/register_succ.html', {'email' : user.email, 'passwd' : user.password, 'csrf_token' : request.COOKIES['csrftoken']}) import os import random ident_pics = os.listdir('static/pic/verify') random.shuffle(ident_pics) return render(request, 'login/register.html', {'title' : 'LOGIN', 'ident_pic' : ident_pics[0], 'error' : error, 'email' : email, 'passwd' : passwd, 'passwd1' : passwd1})
def testdb(request): test1 = User(1, 'fuyang', 'fuyang') test1.save() return HttpResponse('<p>添加成功</p>')