def test_issues_login(self, requests_post, get_landowner): """Can we successfully login?""" tester = User(username='******', password=make_password('test')) tester.save() self.client.login(username='******', password='******') response = self.client.get(reverse('office:issues')) self.assertEqual(response.status_code, 200)
def oauth_callback(provider): # validate the provider if provider not in current_app.config['OAUTH_PROVIDERS']: return redirect(url_for('auth.login')) oauth = OAuthSignIn(provider) try: resp = oauth.callback(request) except OAuthCallbackError as e: flash(e.__str__(), category='error') else: # process user information email = resp['email'] user = User.get_by_email(email) if not user: # register the user user = User( username=email.split('@')[0], email=email, avatar=resp['picture'], signature='', name=resp['name'], password=token_urlsafe(20), question=0, answer=token_urlsafe(10), ) db.session.add(user) db.session.commit() create_welcome_message(user) if user and user.status == 1: # authenticate the user init_session(user.id) return redirect(request.args.get('next') or url_for('core.home')) flash('User not found.', category='error') return redirect(url_for('auth.login'))
def setUp(self): self.app = app self.app.config['TESTING'] = True self.ctx = self.app.app_context() self.ctx.push() u = User(username=self.default_username) u.set_password(self.default_password) u.save() self.client = TestClient(self.app, self.default_username, self.default_password)
def api_get_users(*, page='1'): page_index = get_page_index(page) num = yield from User.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, users=()) users = yield from User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) for u in users: u.passwd = '******' return dict(page=p, users=users)
def addUser(request): aa = User.objects.filter(username=request.POST.get('username')) if aa.exists(): return JsonResponse({'success': 'false', 'msg': '用户已存在!'}) else: user = User(username=request.POST.get('username'), phone=request.POST.get('phone'), password=request.POST.get('password')) user.save() return JsonResponse({'success': 'true', 'msg': '用户添加成功!'})
def test_start_qa(self, requests_post, get_landowner): """Do we find all QA critical issues?""" tester = User(username='******', password=make_password('test')) tester.save() group = Group(name='testers') group.save() group.user_set.add(tester) group.save() cat = Category(name='test cat') cat.save() requests_post.json.return_value = {'features': []} get_landowner.return_value = 'TEST landowner' Issue(description='A old issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now() - timedelta(days=30), status=StatusTypes.WIP, published=False, assigned=group).save() Issue(description='Old assigned but unreviewed issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now() - timedelta(days=30), status=StatusTypes.REVIEW, published=False, assigned=group).save() Issue(description='Another Old assigned but unreviewed issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now() - timedelta(days=20), status=StatusTypes.REVIEW, published=False, assigned=group).save() Issue(description='Assigned very new issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now(), status=StatusTypes.REVIEW, published=False, assigned=group).save() Issue(description='Unupdated issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now() - timedelta(days=35), status=StatusTypes.WIP, status_created_at=timezone.now() - timedelta(days=35), published=True, assigned=group).save() # Check if we get only old unreviewed issues back self.client.login(username='******', password='******') response = self.client.get(reverse('office:start')) qs = response.context['issues3dunchecked'] self.assertEqual(len(qs), 2) qs = response.context['issues30dunupdated'] self.assertEqual(len(qs), 1)
def post(self, request, *args, **kwargs): field = request.POST.get('field') data = request.POST.get('data') if field and data and field[0] and data[0]: params = {'id': request.user.id, field: data} user = User(**params) user.save(update_fields=[field]) res = {'status': True, 'data': data, 'msg': "修改成功"} else: res = {'status': False, 'data': None, 'msg': "数据不能为空哦"} return JsonResponse(res)
def adduser(username): """Register a new user.""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit('Error: passwords do not match.') user = User(username=username) user.set_password(password) user.save() print('User {0} was registered successfully.'.format(username))
def authenticate(self, request): token = request.META.get('HTTP_TOKEN') if token: try: payload = jwt.decode(token, SECRET_KEY) user = User() user.userid = payload['data']['userid'] user.is_authenticated = True return user, token except InvalidTokenError: raise AuthenticationFailed('无效的令牌或令牌已过期') raise AuthenticationFailed('请提供用户身份令牌')
def register(self, request): if self.is_valid(): user = User() cleaned_data = self.clean() (user.email, user.nickname, user.password_hash) = (cleaned_data.get('email'), cleaned_data.get('nickname'), make_password( cleaned_data.get('password'))) user.save() request.session['user_id'] = user.id return user
def init_db(tApp): from datetime import datetime, timedelta db.create_all() for i in range(1, 201): user = User() user.age = i user.name = 'NAME-{0}'.format(i) user.gender = True if i%2 == 1 else False user.birthday = datetime.now() - timedelta(seconds=i) db.session.add(user) db.session.commit() print 'Database Init completed!'
def post(self): req_val = UserRegisterParse().load(request.values) result = User.register(**req_val) if result['status'] == "failure": abort(400, description=result['msg']) return {"code": 200, "msg": "注册成功"}
def land(): # TODO: This needs to be a decorator if not session.get('user_id', False): return redirect(COMMON_URL_LOGIN) user = User.get_by_id(session['user_id']) w = WrapBokeh(PAGE_URL, app.logger) w.init() # Create a dominate document, see https://github.com/Knio/dominate # this line should go after any "return redirect" statements w.dominate_document() url_page_css(w.dom_doc, PAGE_URL) args, _redirect_page_metrics = w.process_req(request) if not args: return _redirect_page_metrics app.logger.info("{} : args {}".format(PAGE_URL, args)) redir, url = toolbar_menu_redirect(args) if redir: return redirect(url) doc_layout = layout(sizing_mode="fixed") page_toolbar_menu(w, doc_layout, args, user) doc_layout.children.append( Div(text="""<h1>Your Stuff Goes Here...</h1>""")) return w.render(doc_layout)
def register_user(): body = request.get_json() body['email'] = body['email'].lower() if not is_email_correct(body['email']): return INCORRECT_EMAIL_FORMAT, 200 if is_email_registered(body['email']): return EMAIL_REGISTERED, 200 new_user = User(email=body['email'], password=hash_password(body['password']), first_name=body['first_name'], last_name=body['last_name']) for category_id in body['stack']: category = EventCategory.query.filter_by(id=category_id).first() if category is None: return INCORRECT_CATEGORY_ID, 200 new_user.stack.append(category) db.session.add(new_user) db.session.commit() dispatch('user_registered', { 'id': new_user.id, 'stack': [category.id for category in new_user.stack] }) return create_access_token(new_user), 200
def cookie2user(cookie_str): ''' Parse cookie and load user if cookie is valid. ''' if not cookie_str: return None try: L = cookie_str.split('-') if len(L) != 3: return None uid, expires, sha1 = L if int(expires) < time.time(): return None user = yield from User.find(uid) local_auths = yield from LocalAuth.findAll('user_id=?',[uid]) local_auth = local_auths[0] if user is None: return None s = '%s-%s-%s-%s' % (uid, local_auth.user_pwd, expires, _COOKIE_KEY) if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest(): logging.info('invalid sha1') return None return user except Exception as e: logging.exception(e) return None
def validate_password(username, password): try: user = User.get(User.username == username) except User.DoesNotExist: return False return user.validate(password)
def generate_schedules(request): if request.method == "POST": # 開始 log = Log() log.name = u"generate schedules" log.started_at = datetime.now() # ユーザ全員を取得 users = User.all().fetch(1000) # 日付を取得 today = datetime.today() target_day = date(today.year, today.month + 1, 1) nn_month = date(today.year, today.month + 2, 1) # 1日ずつスケジュールを入れる schedules = [] while target_day < nn_month: # 時間をずらす for hour in range(9, 24): # 分をずらす for minutes in [0, 30]: # ユーザずつ for user in users: # シフト # 0/1: 月曜休みAM/月曜休みPM # 2/3: 火曜休みAM/火曜休みPM weekday = target_day.weekday() if user.shift == weekday * 2 or user.shift == weekday * 2 + 1: continue # AM: 9 - 17 # PM: 15 - 23 if user.shift % 2 == 0 and hour > 18: continue if user.shift % 2 == 1 and hour < 15: continue # スケジュール入れる target_datetime = datetime(target_day.year, target_day.month, target_day.day, hour, minutes) schedule = Schedule( name=generate_string(20), user=user, title=generate_string(100), schedule_at=target_datetime ) # リストに追加 schedules.append(schedule) # 追加 db.put(schedules) schedules = [] # 1日追加 target_day = target_day + timedelta(days=1) # 終了 log.ended_at = datetime.now() log.put() return Response(status=200)
def wrap(request, *args, **kwargs): access = False user_roles = User.user_roles(request.user.id) if 'client' in user_roles: access = True if not access: return redirect(reverse('client:client_auth')) return view_func(request, *args, **kwargs)
def wrapper(self, request, *args, **kwargs): token = request.META.get('HTTP_TOKEN') if token: try: payload = jwt.decode(token, SECRET_KEY) user = User() user.userid = payload['data']['userid'] return func(self, request, user, *args, **kwargs) except InvalidTokenError: return Response({ 'code': 4001, 'message': '无效的令牌或令牌已过期', }) return Response({ 'code': 4002, 'message': '请提供有效的身份标识', })
def login(): print("进来登录了") form = LoginForm() if form.validate_on_submit(): print("进来这个函数了") user_name = request.form.get('username', None) password = request.form.get('password', None) remember_me = request.form.get('remember_me', False) print(user_name,password) user = User(user_name) if user.verify_password(password): print("进来储存用户啦") print(user.username,user.id) login_user(user, remember=remember_me) print("zheyibu") return redirect(url_for('main')) flash(u"用户名或密码错误!") return render_template('login.html', title="Sign In", form=form)
def getInfos(): ''' 发起预支付 ''' now = str(datetime.datetime.now()) idx = now.index(".") create_time = now[0:idx] params = request.json pay_way = "alipay" if params.get("type") == "1" else "wechat" app_secret = "a2e81f680103f8787fbce8d9ed1dc4df" pay_infos = { "app_id": "21364048", "out_order_sn": get_code(), "name": "内容付费产品", "pay_way": pay_way, "price": params.get("price") * 100, # 单位为分 "attach": "商家的自定义字段,支付回调会原路返回", "notify_url": "http://www.hbwjshan.com:8001/index/getPayState", } generate_key = pay_infos.get("app_id") + pay_infos.get("out_order_sn") + pay_infos.get("name") + \ pay_infos.get("pay_way") + str(pay_infos.get("price")) + pay_infos.get("attach") + pay_infos.get( "notify_url") + app_secret sign = get_md5(generate_key) pay_infos["sign"] = sign headers = {'content-type': 'application/x-www-form-urlencoded'} # 1. 生成系统订单,存入数据库 user = User(params.get("domain"), params.get("phone"), pay_infos.get("out_order_sn"), create_time) db.session.add(user) db.session.commit() # 2. 发起预支付,获取支付二维码 result = requests.post("https://open.yunmianqian.com/api/pay", data=pay_infos, headers=headers) result_data = json.loads(result.text) if result_data.get("code") == 200: # 成功调用 data = result_data.get("data") return jsonify(return_data("调用成功", data)) elif result_data.get("code") == 1001: # 签名错误 return jsonify(return_data("签名错误")) elif result_data.get("code") == 1002: # 无可用二维码 return jsonify(return_data("无可用二维码")) elif result_data.get("code") == 1003: # 缺少参数 return jsonify(return_data("缺少参数")) elif result_data.get("code") == 1004: # 请求值错误 return jsonify(return_data("请求值错误")) return "hello world"
def setUp(self): self.app = create_app('Test') self.app_context = self.app.app_context() self.app_context.push() self.client = self.app.test_client(use_cookies=True) db.create_all() user = User(username='******', name='Tim', password='******', question='0', answer='tacos', role='1') db.session.add(user) admin = User(username='******', name='Administrator', password='******', question='1', answer='Ralf', role='0') db.session.add(admin) db.session.commit()
def index(request): user_count = User.all().count(999999) schedule_count = Schedule.all().count(999999) log_count = Log.all().count(999999) processes = Process.all().order('-created_at').fetch(1) process = processes[0] if len(processes) > 0 else None return render_to_response('index/index.html', { 'user_count': user_count, 'schedule_count': schedule_count, 'log_count': log_count, 'process': process, })
def SessionBaseAuthenication(): session = request.cookies.get('session', '') if session: try: session_info = Session.get(session_token=session) except Session.DoesNotExist: return userid = session_info.user_id if userid: user = User.get(pk=userid) request.user = user
def check_login(request): try: if not request.session.has_key('user_id'): raise User.DoesNotExist() user = User.objects.get(pk=request.session['user_id']) result = model_to_dict(user) result['signed_in'] = True if result.has_key('password_hash'): del result['password_hash'] except User.DoesNotExist: return JsonResponse({'signed_in': False}) return JsonResponse(result)
def post(self): '''Creates and sends a password reset link.''' credential = request.json.get('credential') user = None if credential: user = User.get_by_email(credential) or User.get_by_username( credential) if not user or not user.is_enabled: abort(400, 'Invalid email address or username.') # create a JWT token = encode_jwt(user.id) # "send an email" with a reset link using the token base_url = request.headers['origin'] link = f"{base_url}/#/reset/{user.id}/{token}" send_email( sender=User.query.first().email, recipient=user.email, subject='PwnedHub Password Reset', body= f"Hi {user.name}!<br><br>You recently requested to reset your PwnedHub password. Visit the following link to set a new password for your account.<br><br><a href=\"{link}\">{link}</a><br><br>If you did not request this password reset, please respond to this email to reach an administrator. Thank you.", ) return {'success': True}, 201
def post(self): '''Returns a JWT for the user that owns the provided credentials.''' id_token = request.json.get('id_token') username = request.json.get('username') password = request.json.get('password') user = None # process OIDC credentials if id_token: payload = get_unverified_jwt_payload(id_token) email = payload['email'] user = User.get_by_email(email) if not user: # register the user user = User( username=email.split('@')[0], email=email, avatar=payload['picture'], signature='', name=payload['name'], password=token_urlsafe(20), question=0, answer=token_urlsafe(10), ) db.session.add(user) db.session.commit() # process username and password credentials elif username and password: user = User.get_by_username(username) if user and not user.check_password(password): user = None # handle authentication if user and user.is_enabled: data = {'user': user.serialize_self()} # build other claims claims = {} path = os.path.join(current_app.config['UPLOAD_FOLDER'], md5(str(user.id).encode()).hexdigest()) if not os.path.exists(path): os.makedirs(path) claims['upload_folder'] = path # create a JWT token = encode_jwt(user.id, claims=claims) # send the JWT as a Bearer token when the feature is enabled if Config.get_value('BEARER_AUTH_ENABLE'): data['access_token'] = token # remove any existing access token cookie return data, 200, { 'Set-Cookie': 'access_token=; Expires=Thu, 01-Jan-1970 00:00:00 GMT' } # default to cookie authentication # return a CSRF token when using cookie authentication csrf_obj = CsrfToken(user.id) csrf_obj.sign(current_app.config['SECRET_KEY']) data['csrf_token'] = csrf_obj.serialize() # set the JWT as a HttpOnly cookie return data, 200, {'Set-Cookie': f"access_token={token}; HttpOnly"} abort(400, 'Invalid username or password.')
def view(self, request): """docstring for view""" limit = int(request.get("limit", "20")) offset = int(request.get("offset", "0")) query = self.group.get_all_topics(has_order=True) page = Page(query=query, offset=offset, limit=limit, request=request) topics = page.data() members = [User.get(mk) for mk in self.group.recent_members] # var_dict = locals() # can't assign variable below this line return template("page_group_view.html", locals())
def view(self, request): """docstring for view""" limit = int(request.get('limit', '20')) offset = int(request.get('offset', '0')) query = self.group.get_all_topics(has_order=True) page = Page(query=query, offset=offset, limit=limit, request=request) topics = page.data() members = [User.get(mk) for mk in self.group.recent_members] #var_dict = locals() # can't assign variable below this line return template('page_group_view.html', locals())
def register(): print("进来注册") form = registerForm() if form.validate_on_submit(): phone = request.form.get('phone', None) name = request.form.get('name', None) pwd = request.form.get('pwd', None) valid = request.form.get('valid', None) valid2 = request.form.get('valid2', None) if valid == valid2: remember_me = request.form.get('remember_me', False) create = User.create_user(phone,name,pwd) if create["status"] == 200: user = User(phone) login_user(user, remember=remember_me) return redirect(url_for('main')) elif create["status"] == 401: flash(create["msg"]) else: return redirect(url_for('login')) else: flash("验证码错误!") return render_template('register.html', title="register", form=form)
def api_register_user(*, email, name, passwd): if not name or not name.strip(): raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not passwd or not _RE_SHA1.match(passwd): raise APIValueError('passwd') users = yield from User.findAll('email=?', [email]) if len(users) > 0: raise APIError('register:failed', 'email', 'Email is already in use.') uid = next_id() sha1_passwd = '%s:%s' % (uid, passwd) pwd = hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest() user = User(id=uid, name=name.strip(), email=email, image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()) yield from user.save() local_auth = LocalAuth(user_id=uid,user_name=name,user_pwd=pwd); yield from local_auth.save() # make session cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user,local_auth, 86400), max_age=86400, httponly=True) r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def test_detail_assigned(self, requests_post, get_landowner): tester = User(username='******', password=make_password('test')) tester.save() self.client.login(username='******', password='******') group = Group(name='testers') group.save() group.user_set.add(tester) group.save() cat = Category(name='test cat') cat.save() requests_post.json.return_value = {'features': []} get_landowner.return_value = 'TEST landowner' myIssue = Issue(description='My issue', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now(), status=StatusTypes.WIP, published=False, assigned=group) myIssue.save() response = self.client.get( reverse('office:issue', kwargs={'pk': myIssue.id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['issue'], myIssue) # Everybody should at least read otherIssue = Issue(description='Not mine', position=Point(54.1, 12.1, srid=4326), category=cat, created_at=timezone.now(), status=StatusTypes.WIP, published=False, assigned=group) otherIssue.save() response = self.client.get( reverse('office:issue', kwargs={'pk': otherIssue.id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['issue'], otherIssue)
def post(self): '''Returns a JWT for the user that owns the provided credentials.''' id_token = request.json.get('id_token') username = request.json.get('username') password = request.json.get('password') user = None if id_token: payload = get_unverified_jwt_payload(id_token) user = User.get_by_email(payload['email']) elif username and password: user = User.get_by_username(username) if user and not user.check_password(password): user = None if user and user.is_enabled: data = {'user': user.serialize()} # build other claims claims = {} path = os.path.join(current_app.config['UPLOAD_FOLDER'], md5(str(user.id).encode()).hexdigest()) if not os.path.exists(path): os.makedirs(path) claims['upload_folder'] = path # create a JWT token = encode_jwt(user.id, claims=claims) # send the JWT as a Bearer token when the feature is enabled if Config.get_value('BEARER_AUTH_ENABLE'): data['token'] = token # remove any existing access token cookie return data, 200, { 'Set-Cookie': 'access_token=; Expires=Thu, 01-Jan-1970 00:00:00 GMT' } # set the JWT as a HttpOnly cookie by default return data, 200, { 'Set-Cookie': 'access_token=' + token + '; HttpOnly' } return {'message': 'Invalid username or password.'}
def register(request): """用户注册""" if request.method == 'GET': return render(request, 'register.html') else: try: if request.POST['code'] == request.session['code']: form = RegisterForm(request.POST) if form.is_valid(): del form.cleaned_data['repassword'] del form.cleaned_data['code'] form.cleaned_data['token'] = uuid.uuid1().hex form.cleaned_data['lastvisit'] = timezone.now() user = User(**form.cleaned_data) user.save(is_insert=True) request.session['code'] = gen_mobile_code() return render(request, 'login.html', {'hint': '注册成功请登录'}) else: hint = handle_register_errors(form.errors) else: hint = '请输入正确的手机验证码' except KeyError: hint = '请先获取手机验证码再完成注册' return render(request, 'register.html', {'hint': hint})
def post(self): '''Creates an account.''' username = request.json.get('username') if User.query.filter_by(username=username).first(): abort(400, 'Username already exists.') email = request.json.get('email') if User.query.filter_by(email=email).first(): abort(400, 'Email already exists.') password = request.json.get('password') if not is_valid_password(password): abort(400, 'Password does not meet complexity requirements.') user = User(**request.json) db.session.add(user) db.session.commit() return {'success': True}, 201
def pick_item(request): try: form_data = json.loads(request.body) except: return JsonResponse({'errorMessage': 'Bad JSON format.'}, 400) try: result = {} if request.session.has_key('user_id'): user = User.objects.get(pk=request.session['user_id']) else: raise User.DoesNotExist() form = forms.PickItemForm(form_data) if form.is_valid(): result = model_to_dict(form.pick(user)) result['errors'] = form.errors except User.DoesNotExist: return JsonResponse({'errorMessage': 'Please login first.'}, 403) return JsonResponse(result)
def post(self, request, *args, **kwargs): generated_pwd = '00000{0}'.format(random.randint(0, 999999))[-6:] email = request.data['email'].lower() username = email password_date = datetime.datetime.now() user_instance = None try: user_instance = User.objects.get(is_active=True, email__lower=email) except: user_instance = User( is_superuser=False, is_staff=False, is_active=True, username=username, email=email, ) user_instance.set_password(generated_pwd) user_instance.password_change_date = password_date user_instance.save() subject = 'Код для входа на 4Paws' html_message = render_to_string( 'registration_msg_russian.html', { 'registration_code': generated_pwd, 'deep_link': '{0}/#/authorization/?email={1}&code={2}'.format( settings.BASE_URL, email, generated_pwd) }) plain_message = strip_tags(html_message) send_mail( subject=subject, message=plain_message, from_email=settings.EMAIL_HOST_USER, recipient_list=[email], fail_silently=False, html_message=html_message, ) return Response({ 'status': status.HTTP_200_OK, 'sent': True, })
def member_register(): """ 註冊 會員 """ request_data = request.get_json() email = request_data.get('email') username = request_data.get('username') non_hash_password = request_data.get('password') hash_password = Encrypt.encrypt_password(non_hash_password) source = OAuthType.OUR user = User(email=email, username=username, password=hash_password, source=source) db.session.add(user) db.session.commit() response_data = {'email': email, 'username': username, 'source': source} return jsonify(response_data)
def user_register(request): """用户注册""" data = request.data print(data) serializer = RegisterSerializer(data=data) serializer.is_valid(raise_exception=True) # 获取验证码 tel = serializer.validated_data['tel'] tel_code = request.data.get('tel_code') if tel_code == caches['default'].get(f'{tel}_time'): # 验证码失效 caches['default'].delete_pattern(f'{tel}_time') with atomic(): user = User() user.password = to_md5_hex(serializer.validated_data['password']) user.tel = serializer.validated_data['tel'] user.username = serializer.validated_data['username'] user.user_image = DefaultImagePath user.save() return DefaultResponse(*REGISTER_SUCCESS) return DefaultResponse(*CACHE_ERROR)
def authenticate(*, email, passwd): if not email: raise APIValueError('email', 'Invalid email.') if not passwd: raise APIValueError('passwd', 'Invalid password.') users = yield from User.findAll('email=?', [email]) if len(users) == 0: raise APIValueError('email', 'Email not exist.') user = users[0] # check passwd: sha1 = hashlib.sha1() sha1.update(user.id.encode('utf-8')) sha1.update(b':') sha1.update(passwd.encode('utf-8')) local_auth = yield from LocalAuth.findAll('user_id=?', [user.id]) passwd = local_auth[0].user_pwd if passwd != sha1.hexdigest(): raise APIValueError('passwd', 'Invalid password.') # authenticate ok, set cookie: r = web.Response() r.set_cookie(COOKIE_NAME, user2cookie(user, local_auth[0], 86400), max_age=86400, httponly=True) r.content_type = 'application/json' r.body = json.dumps(user, ensure_ascii=False).encode('utf-8') return r
def delete_all_users(request): if request.method == "POST": db.delete(User.all()) return Response(status=200)
def tearDown(self): User.drop_collection() self.ctx.pop()
def _migrate(self): # Drop all tables print('Dropping tables...') auth.models.User.objects.all().delete() Administrator.objects.all().delete() User.objects.all().delete() Folder.objects.all().delete() Message.objects.all().delete() Announcement.objects.all().delete() ApplyAnnouncement.objects.all().delete() ApplyRoute.objects.all().delete() Comment.objects.all().delete() CommentAnnouncement.objects.all().delete() CommentRoute.objects.all().delete() Day.objects.all().delete() Route.objects.all().delete() StopAnnouncement.objects.all().delete() StopRoute.objects.all().delete() print("Dropping tables OK!") print('Create administrators accounts...') admin1 = auth.models.User.objects.create_superuser(username='******', email='*****@*****.**', password='******') print('Create administrators accounts OK!') print('Create users accounts...') user_account1 = auth.models.User.objects.create_user(username='******', email='*****@*****.**', password='******') user_account2 = auth.models.User.objects.create_user(username='******', email='*****@*****.**', password='******') print('Create users accounts OK!') print('Create administrators...') administrator = Administrator(user_account = admin1) administrator.save() print('Create administrators OK!') print('Create users...') user1 = User(user_account = user_account1,name = "Nombre", surnames = "Apellido1 Apellido2", city = "Sevilla", birthdate = date(1993, 4, 6), phone = "666999888",searchingCar = True) user1.save() user2 = User(user_account = user_account2,name = "Nombre2", surnames = "Apellido1 Apellido2", city = "Sevilla", birthdate = date(1993, 4, 6), phone = "666999888",searchingCar = True) user2.save() print('Create user OK!') print('Create folders...') folder1 = Folder(name = "1", actor = user1) folder1.save() folder2 = Folder(name = "2", actor = user1) folder2.save() folder3 = Folder(name = "3", actor = user1) folder3.save() folder4 = Folder(name = "1", actor = user2) folder4.save() folder5 = Folder(name = "2", actor = user2) folder5.save() folder6 = Folder(name = "3", actor = user2) folder6.save() folder7 = Folder(name = "1", actor = administrator) folder7.save() folder8 = Folder(name = "2", actor = administrator) folder8.save() folder9 = Folder(name = "3", actor = administrator) folder9.save() print('Create folders OK!') print('Create messages...') message1 = Message(subject = "Asunto 1", body = "Este es un mensaje de prueba enviado", folder = folder1, sender = user1, recipient = user2) message1.save() message2 = Message(subject = "Asunto 1", body = "Este es un mensaje de prueba enviado", folder = folder5, sender = user1, recipient = user2) message2.save() print('Create messages OK!') print('Create comments...') comment1 = Comment(subject = "Muy bueno", comment = "Muy buen conductor, totalmente recomendable", rating = 9, referrer = user1, evaluated = user2) comment1.save() comment2 = Comment(subject = "Regular", comment = "Como pasajero deja mucho que desear", rating = 4, referrer = user2, evaluated = user1) comment2.save() print('Create comments OK!') print('Create routes...') route1 = Route(origin = "Alcalá de Guadaíra", destination = "Facultad de Informática", description = "Viaje regular durante 3 meses", kind = "1", seating = 4, unitPrice = 2.00, user = user2) route1.save() route2 = Route(origin = "Arahal", destination = "Isla de la cartuja", description = "Viaje regular durante 6 meses", kind = "1", seating = 4, unitPrice = 2.00, user = user1) route2.save() print('Create routes OK!') print('Create stop routes...') stopRoute1 = StopRoute(stop = "Alcalá de Guadaíra", sequence = 1, route = route2) stopRoute1.save() print('Create stop routes OK!') print('Create days...') day1 = Day(day = 1, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day1.save() day2 = Day(day = 2, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day2.save() day3 = Day(day = 3, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day3.save() day4 = Day(day = 4, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day4.save() day5 = Day(day = 5, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day5.save() day6 = Day(day = 6, route = route2, active = False) day6.save() day7 = Day(day = 7, route = route2, active = False) day7.save() day8 = Day(day = 1, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day8.save() day9 = Day(day = 2, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day9.save() day10 = Day(day = 3, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day10.save() day11 = Day(day = 4, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day11.save() day12 = Day(day = 5, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day12.save() day13 = Day(day = 6, route = route1, active = False) day13.save() day14 = Day(day = 7, route = route1, active = False) day14.save() print('Create days OK!') print('Create applys routes...') applyRoute1 = ApplyRoute(comment = "Buenas, yo entro a las 9 de la mañana y salgo a las dos, te viene bien en Alcalá de Guadaíra?", route= route2, user = user1) applyRoute1.save() print('Create applys routes OK!') print('Create comments routes...') commentRoute1 = CommentRoute(subject = "Buena ruta!", comment = "Muy buen trayecto, excelente conductor", rating = 10, user = user1, route = route2) commentRoute1.save() print('Create comments routes OK!') print('Create announcements ...') announcement1 = Announcement(origin = "Alcalá de Guadaíra", destination = "Facultad de informática", description = "Viaje puntual" , seating = 2, unitPrice = 2, date = datetime(2015, 12, 6, 16, 29, 43, 79043), user = user1) announcement1.save() print('Create announcements OK!') print('Create applys announcements...') applyAnnouncement1 = ApplyAnnouncement(comment = "Buenas, yo entro a las 17:00 de la tarde te viene bien los arcos?", announcement=announcement1, user=user1) applyAnnouncement1.save() print('Create applys announcements OK!') print('Create stops announcements...') stopAnnouncement1 = StopAnnouncement(stop = "Sevilla", sequence = 1, announcement = announcement1) stopAnnouncement1.save() print('Create stops announcements OK!') print('Create comments announcements...') commentAnnouncement1 = CommentAnnouncement(subject = "Buena ruta!", comment = "Muy buen trayecto, excelente conductor", rating = 10, user = user1, announcement = announcement1) commentAnnouncement1.save() print('Create comments announcements OK!')
def post(self, user_id): """docstring for post""" user = User.get_by_id(int(user_id)) user_stream_info = UserStreamInfo.get_instance(user=user) return self.post_impl(UserStreamUI(user_stream_info))