def process_request(request): form = CreateAccountForm() if request.method == "POST": form = CreateAccountForm(request.POST) if form.is_valid(): # create the user here u = User() u.username = form.cleaned_data.get("username") u.first_name = form.cleaned_data.get("first_name") u.last_name = form.cleaned_data.get("last_name") u.BirthDate = form.cleaned_data.get("BirthDate") u.Phone = form.cleaned_data.get("Phone") u.set_password(form.cleaned_data.get("password")) u.save() return HttpResponse( """ <script> window.location.href = '/homepage/index/'; </script> """ ) template_vars = {"form": form} return dmp_render_to_response(request, "createaccount.html", template_vars)
def create_account(request): c = {} c.update(csrf(request)) is_signed_in = request.user.is_authenticated() is_admin = request.user.is_superuser matched = False if request.method == 'POST': match = models.User.objects.filter(username=request.POST['usr']) if len(match) > 0: matched = True return render(request,'sign-up.html',{'signed_in': is_signed_in,'admin':is_admin, 'guest': not is_signed_in,'matched':matched}) else: djuser = models.User.objects.create_user(username = request.POST['usr'], email = request.POST['mail'], password= request.POST['pass'], ) djuser.first_name = request.POST['name'], djuser.last_name = request.POST['lastname'], user = User( address = request.POST['addr'], phone_num = request.POST['tel'], gender = request.POST['gender'], avatar = None, userType = 'Normal', ) user.user = djuser djuser.save() user.save() is_signed_in = request.user.is_authenticated() is_admin = request.user.is_superuser return redirect('/main/')
def process_request(request): #process the form form = SignupForm() if request.method == 'POST': # just submitted the form form = SignupForm(request.POST) if form.is_valid(): u = User() u.username = form.cleaned_data.get('username') u.first_name = form.cleaned_data.get('first_name') u.last_name = form.cleaned_data.get('last_name') u.address1 = form.cleaned_data.get('address1') u.address2 = form.cleaned_data.get('address2') u.set_password(form.cleaned_data.get('password')) u.save() # authenticate(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password')) # login(request, form.user) # create a user object # fill the user object with the data from the form return HttpResponseRedirect('/homepage/index/') template_vars = { 'form': form, } return dmp_render_to_response(request, 'signup.html', template_vars)
def _perform(self, username, password): session = self._app.db.session() user = session.query(User).filter_by(username=username).first() if user is None: new_user = User(username=username) new_user.set_password(password) session.add(new_user) return BusinessResponse.response_ok({}) else: return BusinessResponse.response_invalid_data({'message': 'User with this name already exists'})
def save (self): user = User(username=self.cleaned_data['username'], email=self.cleaned_data['email'], is_staff=self.cleaned_data['is_staff'], is_active=self.cleaned_data['is_active'], is_superuser=self.cleaned_data['is_superuser'], ) user.save() for g in self.cleaned_data['groups']: user.groups.add(g) for p in self.cleaned_data['user_permissions']: user.user_permissions.add(p) return user
def create_user(name, password, email, phone_number, phone_activation_code, email_activation_key): obj = User( name=name, password=password, email=email, phone_number=phone_number, phone_activation_code=phone_activation_code, email_activation_key=email_activation_key ) # Encrypts the password. obj.set_password(password) return obj
def register(request): if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] user = User() user.username = username user.password = password user.save() return render_to_response('success.html',{'username':username}, context_instance = RequestContext(request)) else: uf = UserForm() return render_to_response('register.html', {'uf' : uf}, context_instance = RequestContext(request))
def test_user_creation(self): """ Create user """ u = User(username=self.user_username, email=self.user_email) u.set_password(self.user_password) u.save() self.assertIsNotNone(u.id) self.assertTrue(User.objects.filter( username=self.user_username).exists()) self.assertEqual(User.objects.get( username=self.user_username).email, self.user_email) self.assertTrue(User.objects.get(username=self.user_username).is_active) self.assertIsNotNone(User.objects.get( username=self.user_username).created_at)
def create_from_sha(project, new_rev, create=True): from account.models import User new_rev_commit = project.git.commit(new_rev) # Extract the project tree and diffs parents = [p for p in new_rev_commit.parents] # Extract formatted author details new_author = new_rev_commit.author author_info = User.from_commit(new_author, project) author, author_name, author_email = author_info # Extract formatted committer details new_committer = new_rev_commit.committer committer_info = User.from_commit(new_committer, project) committer, committer_name, committer_email = committer_info fts = datetime.datetime.utcfromtimestamp utc = pytz.timezone("UTC") author_time = new_rev_commit.author_time author_time = utc.localize(fts(author_time)) commit_time = new_rev_commit.commit_time commit_time = utc.localize(fts(commit_time)) # The actual Commit object is fairly heavy c = Commit( commit_time=commit_time, sha1sum=new_rev_commit.sha().hexdigest(), author=author, author_name=author_name, author_email=author_email, author_time=author_time, committer=committer, committer_name=committer_name, committer_email=committer_email, message=new_rev_commit.message, diff=[], tree=[], parents=parents, project=project, ) if create: c.save() return c
def setUpTestData(self): self.student_id = 'B03705024' self.username = '******' self.password = '******' self.user = User(username=self.username) self.user.set_password(self.password) self.user.kind = User.STATION self.user.save() self.name = 'NTU' self.station = Station() self.station.name = self.name self.station.user = self.user self.station.external_id = 1 self.station.max_sessions = 3 self.station.save() # login data = {'username': self.username, 'password': self.password, 'api_key': settings.API_KEY, 'version': settings.API_VERSION} client = APIClient() client.post(reverse('register'), data, format='json') try: session = Session.objects.get(user=self.user) except: session = None self.session = session self.token = session.token self.authcode = AuthCode(kind='70', code='70-ZU2U0RAKX-KOXLUYHJI-7C05B') self.authcode.save()
def gets_info(cls, engagements, userinfo='tar_user'): from account.models import User if userinfo == 'tar_user': uids = [e.tar_uid for e in engagements] else: uids = [e.req_uid for e in engagements] users = User.gets(uids) id_users = dict([(user.id, user) for user in users]) infos = [] for e in engagements: info = dict( id=e.id, tar_uid=e.tar_uid, req_uid=e.req_uid, status=e.status, price=e.price, date=e.date.strftime('%B %d,%Y'), note=e.note, contact=e.contact, create_time=e.create_time.strftime('%B %d,%Y %H:%M:%S'), ) if userinfo == 'tar_user': info.update({'user': id_users.get(e.tar_uid).get_simple_info()}) else: info.update({'user': id_users.get(e.req_uid).get_simple_info()}) infos.append(info) return infos
def setUpTestData(self): self.username = '******' self.password = '******' self.user = User(username=self.username) self.user.set_password(self.password) self.user.kind = User.STATION self.user.save() self.name = 'NTU' self.station = Station() self.station.name = self.name self.station.user = self.user self.station.external_id = 1 self.station.max_sessions = 3 self.station.save() self.url = reverse('general:ping') # login data = {'username': self.username, 'password': self.password, 'api_key': settings.API_KEY} client = APIClient() client.post(reverse('general:register'), data, format='json') try: session = Session.objects.get(user=self.user) except: session = None self.session = session self.token = session.token
def __call__ (self, *args, **kwargs): request = args[0] request.json = json.loads(request.body) if 'token' in request.json: session = User.get_session(request.json['token']) user = None try: user_id = session[SESSION_KEY] backend_path = session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) if user: request.user = user return self.target(*args, **kwargs) return http.JsonResponse({'status': 'login-required'})
def post(self): oldpwd = self.request.get("oldpwd") pwd = self.request.get("pwd") result, info = User.update_pwd(self.user.email, oldpwd, pwd) self.template_value["pwd_error"] = info self.render("setting.html")
def register2(request): print("hhhhhhhhh====") if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): #获取表单信息 username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] phone = uf.cleaned_data['phone'] email = uf.cleaned_data['email'] #将表单写入数据库 print('1111======') user = User() user.username = username user.password = password user.phone = phone user.email = email user.save() print('save======') #返回注册成功页面 return render(request, 'success.html', {'username':username}) else: uf = UserForm() return render(request, 'register.html', {'uf':uf})
def post(self): source_url = self.request.get("source_url") source_user = self.request.get("source_user") user_name = self.request.get("user") logging.info("bbb"+user_name) user = User.get_user_by_name(user_name) logging.info("aaa"+user.name) if not user is None: Mention.new(user,source_url,source_user)
def post(self): openid_user = users.get_current_user() result, error = User.add_openid(self.user.name, openid_user.federated_identity(), openid_user.user_id()) if not result: self.template_value["error"] = error self.template_value["logout_url"] = users.create_logout_url("/a/setting/") return self.render("openid_add.html") memcache.delete(self.session_key) self.redirect("/a/setting/")
def post(self): openid_user = users.get_current_user() self.template_value["openid_user"] = openid_user name = self.request.get("name") self.template_value["name"] = name if not User.check_email(openid_user.email()): self.template_value["email_error"] = u"%s已经存在,请登录后绑定" % openid_user.email() return self.render("openid_signup.html") if not check_name(name): self.template_value["name_error"] = u"%s不符合规定[a-z0-9]{3,16}" % name return self.render("openid_signup.html") if not User.check_name(name): self.template_value["name_error"] = u"%s已经存在,请更换用户名" % name return self.render("openid_signup.html") if not User.check_openid_id(openid_user.user_id()): self.template_value["id_error"] = u"此OpenID已经绑定过了,请直接登录" return self.render("openid_signup.html") User.new_by_openid(openid_user.email(), name, openid_user.federated_identity(), openid_user.user_id()) self.redirect("/a/openid/signin/")
def handleMatch(self, m): user = m.group(2) if user.endswith("."): return if User.check_name(user): return el = markdown.etree.Element("a") el.set("href", "/u/%s/" % user.lower()) el.text = user return el
def get(self, name): u = User.get_user_by_name(name) if u is None: return self.error(404) self.template_value["u"] = u self.template_value["is_following"] = UserFollow.is_following(self.user, name) self.template_value["recent_dis"] = Discussion.get_recent_dis(u) self.template_value["recent_comment"] = RecentCommentLog.get_recent_comment(u) self.template_value["recent_bookmark"] = Bookmark.get_recent_bookmark(u) self.template_value["f_tag"] = {"key": "u/%s" % u.name_lower, "title": u.name, "show": True} self.render("user.html")
def process_request(request): form = SignupForm() if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): u = User() u.username = form.cleaned_data.get('username') u.first_name = form.cleaned_data.get('first_name') u.last_name = form.cleaned_data.get('last_name') u.address1 = form.cleaned_data.get('address1') u.address2 = form.cleaned_data.get('address2') u.set_password(form.cleaned_data.get('password')) u.save() return HttpResponseRedirect('/homepage/index/') #Show HTML template_vars = { 'form':form, } return dmp_render_to_response(request, 'signup.html', template_vars)
def create_account(request): c = {} c.update(csrf(request)) if request.method == 'POST': djuser = models.User.objects.create_user(username = request.POST['usr'], email = request.POST['mail'], password= request.POST['pass'], ) djuser.first_name = request.POST['name'], djuser.last_name = request.POST['lastname'], user = User( address = request.POST['addr'], phone_num = request.POST['tel'], gender = request.POST['gender'], avatar = request.POST['file-4[]'], userType = 'Normal', ) user.user = djuser djuser.save() user.save() return render(request,"main.html",{'signed_in':True})
def logout_view (request, token): try: session = User.get_session(token) except: raise http.Http404 else: session.flush() return http.JsonResponse({'result': 'OK'})
def test_null_station_id(self): username = '******' password = '******' user = User(username=username) user.set_password(password) user.kind = User.STATION user.save() station = Station() station.name = 'no name' station.user = user station.max_sessions = 3 station.save() # login data = {'username': username, 'password': password, 'api_key': settings.API_KEY} client = APIClient() client.post(reverse('general:register'), data, format='json') try: session = Session.objects.get(user=user) except: session = None data = {'token': session.token, 'api_key': settings.API_KEY} response = self.client.post(self.url, data) self.assertEqual(response.data, {'status': 'error', 'reason': 'station_error'}) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_status(self): username = '******' password = '******' user = User(username=username) user.set_password(password) user.kind = User.ADMIN user.save() # login data = {'username': username, 'password': password, 'api_key': settings.API_KEY, 'version': settings.API_VERSION} client = APIClient() client.post(reverse('register'), data, format='json') try: session = Session.objects.get(user=user) except: session = None else: url = '/api/status' data = { 'token': session.token, 'api_key': settings.API_KEY, 'version': settings.API_VERSION, } response = self.client.post(url, data)
def post(self): email = self.request.get("email").strip() name = self.request.get("name").strip() pwd = self.request.get("pwd").strip() funclist = [ (check_email, email, "email_error", u"邮箱格式不对"), (check_name, name, "name_error", u"用户名格式不对,[a-z,0-9]{3,16}"), (User.check_email, email, "email_error", u"邮箱已经存在"), (User.check_name, name, "name_error", u"用户名已经存在"), (check_pwd, pwd, "pwd_error", u"密码长度6-16"), ] for func, var, error_name, error in funclist: if not func(var): self.template_value[error_name] = error self.template_value["name"] = name self.template_value["pwd"] = pwd self.template_value["email"] = email return self.render("signup.html") User.new(email, name, pwd) # login user self.redirect("/a/signin/")
def post(self): email = self.request.get("email").strip() pwd = self.request.get("pwd").strip() go = self.request.get("go").strip() user, session = User.login(email, pwd) if user and session: d = datetime.datetime.now() + datetime.timedelta(days=30) self.response.headers["Set-Cookie"] = "xfox-session-key=%s;path=/;expires=%s" % ( session.key().name(), get_gmt(d), ) self.redirect(go) if go else self.redirect("/") self.template_value["error"] = u"邮箱或密码不正确" self.render("signin.html")
def get(self): go = self.request.get("go", "/") if not self.user is None: self.redirect("/") openid_user = users.get_current_user() user, session = User.openid_login(openid_user.user_id()) if user and session: d = datetime.datetime.now() + datetime.timedelta(days=30) self.response.headers["Set-Cookie"] = "xfox-session-key=%s;path=/;expires=%s" % ( session.key().name(), get_gmt(d), ) return self.redirect(go) # need reg self.redirect("/a/openid/signup/")
def setUpTestData(self): self.username = '******' self.password = '******' self.user = User(username=self.username) self.user.set_password(self.password) self.user.save() self.name = 'NTU' self.station = Station() self.station.name = self.name self.station.user = self.user self.station.external_id = 1 self.station.max_sessions = 3 self.station.save() self.url = reverse('general:register')
def test_user(self): username = '******' first_name = 'Karley' last_name = 'Corkery' email = '*****@*****.**' password = '******' u = User(username=username, first_name=first_name, last_name=last_name, email=email) u.set_password(password) u.save() self.assertEqual(u.username, username) self.assertEqual(u.first_name, first_name) self.assertEqual(u.last_name, last_name) self.assertEqual(u.email, email) self.assertTrue(u.check_password(password))
def login(self, request, params): """ :param request :param params: name password :return: """ if not params.has('name', 'password'): raise Exception message = create_dict() message.set('title', "login success") result = User.is_pwd_right(params.get('name'), params.get('password')) if not result: message.set('body', "Name or Password is Error!") else: message.set('body', "Welcome to My WebSite!") return render(request, "message_box.html", message.data())
def register(self, request, *args, **kwargs): phone_number = request.POST.get('phone_number') if User.existPhoneNumber(phone_number, raise_exception=False): return DefaultJsonResponse(code=appcodes.CODE_PHONE_IS_EXIST, message=R.String.PHONE_EXISTED) if (isTestAccount(phone_number) or vertifySmsCode(request, SmsRecord.BUSINESS_TYPE_REGISTE)): try: # todo 测试 if request.POST.get('test', None): user = User.objects.create(phone_number=phone_number) user.role = user.HOTEL_PARTNER user.save() PartnerMember.objects.create(user=user) from chaolife.serializers.user import UserSerializer serializer = UserSerializer(user) else: member = CustomerMember.objects.create(phone_number) user = member.user serializer = CustomerUserSerializer(user, ) # end token = Token.create_for_mobile_client(user, request.client_type) # warn 测试 inviter = request.POST.get('inviter') print('邀请者是{}'.format(inviter)) if inviter: from account.invitation.service import invited_service invited_service(inviter, user) user.save() user_data = {'user': serializer.data} except BaseException as e: # raise e raise e else: # 都没出错 response = DefaultJsonResponse(data=user_data, code=appcodes.CODE_100_OK, message=R.String.REGISTER_SUCCESS) response['token'] = token return response else: return DefaultJsonResponse(code=appcodes.CODE_SMS_ERROR, message=R.String.REGISTER_SMS_VERTIFY_FAILED)
def save(self): account = User( email=self.validated_data['email'].lower(), username=self.validated_data['username'], Is_User=self.validated_data['Is_User'], ) password = self.validated_data['password'] confirm_password = self.validated_data['confirm_password'] if password != confirm_password: raise serializers.ValidationError( {'password': '******'}) account.set_password(password) account.save() return account
def m_add_teacher(request): if request.method == "POST": ret = {"status": True, "msg": None} obj = AddTeacher(request.POST) if obj.is_valid(): username = obj.cleaned_data.get("username") name = obj.cleaned_data.get("name") gender = obj.cleaned_data.get("gender") college = obj.cleaned_data.get("college") place = obj.cleaned_data.get("place") province = obj.cleaned_data.get("province") card_id = obj.cleaned_data.get("card_id") nation = obj.cleaned_data.get("nation") email = obj.cleaned_data.get("email") telephone = obj.cleaned_data.get("telephone") qq = obj.cleaned_data.get("qq") print(obj.cleaned_data) try: user = User( username=username, name=name, gender=gender, college=college, place=place, province=province, card_id=card_id, nation=nation, email=email, telephone=telephone, QQ=qq, birthday=card_id[6:10] + '-' + card_id[10:12] + '-' + card_id[12:14], role_id=2 ) user.set_password(card_id[-6:]) user.save() ret["msg"] = "创建成功" return HttpResponse(json.dumps(ret, ensure_ascii=False)) except ValidationError as e: print(str(e)) ret["msg"] = str(e) ret["status"] = False return HttpResponse(json.dumps(ret, ensure_ascii=False)) else: ret["status"] = False ret["msg"] = obj.errors print(obj.errors) return HttpResponse(json.dumps(ret, ensure_ascii=False))
def register(request): if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): #获取表单信息 username = uf.cleaned_data['username'] passworld = uf.cleaned_data['passworld'] email = uf.cleaned_data['email'] #将表单写入数据库 user = User() user.username = username user.passworld = passworld user.email = email user.save() #返回注册成功页面 return render_to_response('success.html',{'username':username}) else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(User.USERNAME_FIELD) if username is None or password is None: return phone = to_python(username) if phone and phone.is_valid(): try: user = User.objects.get(phone=phone) except User.DoesNotExist: User().set_password(password) else: if user.check_password( password) and self.user_can_authenticate(user): return user else: return super(EmailPhoneBackend, self).authenticate(request, username=username, password=password, **kwargs)
def register(request): """ 注册账号界面 """ message = "" if request.session.get('is_login', None): return redirect('/account/') if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') message = "请检查填写的内容!" if _makesure_password(password1, password2): message = _makesure_password(password1, password2) else: same_username = User.objects.filter(username=username) same_email = User.objects.filter(email=email) if same_username: message = '用户名已经存在!' elif same_email: message = '该邮箱已经被注册了!' else: new_user = User() new_user.username = username new_user.email = email new_user.password = _hash_code(password1) new_user.save() code = _make_confirm_string(new_user) _send_email(email, code) message = '请前往邮箱进行确认!' return render(request, 'account/login.html', {'message': message}) captcha_form = forms.captchaForm(request.POST) content = { 'captcha_form': captcha_form, 'message': message, 'page_register': True } return render(request, 'account/register.html', content)
def insert_solr(solrtype, **kwargs): """对象序列化问题尚未解决 json or pickle 目前使用传递字典代替""" sleep(2) solr = None obj = None try: if solrtype == "answer": solr = AnswerSolr() obj = Answer(**kwargs) #obj=Answer(id=id,content=content,question_id=question_id,user_id=user_id) elif solrtype == "question": solr = QuestionSolr() obj = Question(**kwargs) elif solrtype == "user": solr = UserSolr() obj = User(**kwargs) solr.add(obj) return True except Exception, e: print e return e
def create(self): request_data = self.validated_data email = request_data.get('email', None) full_name = request_data.get('full_name', None) password = request_data.get('password', None) if email is None or full_name is None or password is None: serializers.ValidationError("email, password, full_name 모두 입력해주세요") new_user = User( email=self.validated_data['email'], full_name=self.validated_data['full_name'], ) password = self.validated_data['password'] new_user.set_password(password) new_user.save() return new_user
def register_user(**kwargs): try: name = kwargs.pop("name") print(name[0]) username = kwargs.pop("username") password = kwargs.pop("password") mobile = kwargs.pop("mobile") print(mobile) email = kwargs.pop("email") user = User(name=name[0], email=email[0], username=username[0], mobile=mobile[0], password=password[0]) print(user) user.save() user.set_password(password[0]) user.save() return user except Exception as e: print(e) return None
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # self.perform_create(serializer) user = User(username=serializer.data['username']) user.set_password(serializer.data['password']) user.save() payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) headers = self.get_success_headers(serializer.data) return Response( { 'username': serializer.data['username'], 'token': token }, status=status.HTTP_201_CREATED, headers=headers)
def register(request): if request.method == 'POST': uf = RegisterFrom(request.POST) if uf.is_valid(): #get post information username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] email = uf.cleaned_data['email'] #write data into sql user = User() user.username = username user.password = password user.email = email user.save() #return successed page return render_to_response('successRegister.html', {'username': username}) else: uf = RegisterFrom() return render_to_response('register.html', {'uf': uf}, context_instance=RequestContext(request))
def handle(self, *args, **kwargs): if kwargs['n']: for _ in tqdm.tqdm(range(kwargs['n']), desc='Users Created', unit='loop'): users = [] passwd = [] try: f = faker.Faker(['en_US', 'hi_IN']) username = f.user_name() password = f.password() u = User( username=username, email=f.email(), first_name=f.first_name(), last_name=f.last_name(), date_of_birth=f.date_of_birth(), state=f.random_element( [i[0] for i in User.state.field.choices[1:]]), city=f.city(), pincode=f.postcode(), full_address=f.address(), ) u.set_password(password) u.save() u.profile.save( f'{uuid.uuid4()}.jpg', ContentFile( requests.get('https://picsum.photos/300').content)) users.append(username) passwd.append(password) except Exception as e: kwargs['n'] -= 1 Users = { str(i): { 'username': users[i], 'password': passwd[i] } for i in range(len(users)) } self.stdout.write( self.style.SUCCESS(f'{kwargs["n"]} Fake Users is Created...')) for key in Users: self.stdout.write(self.style.SUCCESS(f'{Users[key]}'))
def register(request): if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] user = User() user.username = username user.password = password user.save() return render( request, 'success.html', ) else: uf = UserForm() return render(request, 'sign_up.html', {'uf': uf})
def create(self, validated_data): ''' # below is the hint for AbstractBaseUser DRF generation #http://www.cloudypoint.com/Tutorials/discussion/django-solved-how-to-create-a-new-user-with-django-rest-framework-and-custom-user-model/ # user = super(UserRegistrationSerializer, self).create(validated_data) ''' user = User( username = self.validated_data['username'], email = self.validated_data['email'], first_name = self.validated_data['first_name'], last_name = self.validated_data['last_name'], phone = self.validated_data['phone'], role = self.validated_data['role'] ) # assign_role(user,role) user.set_password(validated_data['password']) user.save() assign_role(user,self.validated_data['role']) return user
def get_activity_list(self,userid,**kwargs): """获取好友最新动态 使用了存储过程 目前动态有0、1、2、3四类 分别代表 提问、回答问题、关注问题、赞或反对问题 """ activity_list=[] question_submit_count=0 answer_count=0 page=kwargs.pop('page',1) pagecount=kwargs.pop('pagecount',15) cursor=connection.cursor() cursor.callproc("sp_friendactiviy",(userid,(page-1)*15,pagecount)) for row in cursor.fetchall(): #import pdb;pdb.set_trace() if row[0]==0: question=Question(id=row[13],title=row[14]) user=User(id=row[15],name=row[16],surname=row[17],avatar=row[18]) question.user=user activity_list.append({'activitytype':row[0],'addtime':row[1],"data":question,"fuser":User(id=row[20],name=row[21],\ surname=row[22],avatar=row[23])}) question_submit_count+=1 elif row[0]==1: answer=Answer(id=row[3],content=row[4],addtime=row[5],commentcount=row[6],favorcount=row[7],opposecount=row[8]) answer.user=User(id=row[9],name=row[10],surname=row[11],avatar=row[12]) answer.question=Question(id=row[13],title=row[14],user=User(id=row[15],name=row[16],surname=row[17],avatar=row[18])) activity_list.append({'activitytype':row[0],'addtime':row[1],"data":answer,"fuser":User(id=row[20],name=row[21],\ surname=row[22],avatar=row[23])}) answer_count +=1 elif row[0]==2: follow=QustionFollow(id=row[19]) question=Question(id=row[13],title=row[14]) user=User(id=row[15],name=row[16],surname=row[17],avatar=row[18]) question.user=user follow.question=question activity_list.append({'activitytype':row[0],'addtime':row[1],"data":follow,"fuser":User(id=row[20],name=row[21],\ surname=row[22],avatar=row[23])}) elif row[0]==3: evalue=AnswerEvaluation(status=row[2]) answer=Answer(id=row[3],content=row[4],addtime=row[5],commentcount=row[6],favorcount=row[7],opposecount=row[8]) answer.user=User(id=row[9],name=row[10],surname=row[11],avatar=row[12]) answer.question=Question(id=row[13],title=row[14],user=User(id=row[15],name=row[16],surname=row[17],avatar=row[18])) evalue.answer=answer activity_list.append({'activitytype':row[0],'addtime':row[1],"data":evalue,"fuser":User(id=row[20],name=row[21],\ surname=row[22],avatar=row[23])}) return {"activity_list":activity_list,"statistics":{"submit_question":question_submit_count,"answer":answer_count}}
def mutate(self, info, username, password, email, role): user = get_user(info) role = json.loads(user.role) if role['role'] != 'manager': raise Exception('只有管理员可以添加新用户') if not (username and password and email and role): raise Exception('字段值不可为空') if User.objects.filter(username=username).count() > 0: raise Exception('username: %s already exists' % username) if User.objects.filter(email=email).count() > 0: raise Exception('email: %s already exists' % email) user = User( username=username, email=email, role=role, ) user.set_password(password) user.save() return CreateUser(created_user=user)
def form_valid(self, form): if self.request.user.is_authenticated: form.instance.user = self.request.user self.object = form.save() else: # If user is anonymous get or create non_active account email = form.cleaned_data["email"] user = User.objects.filter(email=email).first() if not user: user = User(email=email, is_active=False) user.set_password("pass") user.save() form.instance.user = user form.cleaned_data.pop("email", None) # get address if exists, otherwise create address = Address.objects.filter(user=user, **form.cleaned_data).first() if not address: self.object = form.save() else: self.object = address return HttpResponseRedirect(self.get_success_url())
def get(self, request): access_token = request.headers['Authorization'] print(access_token) kakao_request = requests.get( 'https://kapi.kakao.com/v2/user/me', headers={ "Host": "kapi.kakao.com", 'Authorization': f'Bearer {access_token}', "Content-type": "application/x-www-from-urlencoded;charset=utf-8" }, timeout=2) kakao_id = kakao_request.json().get('id') kakao_info = kakao_request.json() try: if User.objects.filter(kakao_id=kakao_id).exists(): user_info = User.objects.get( email=kakao_info['kakao_account']['email']) new_refresh_token = RefreshToken.objects.get(user=user_info) new_refresh_token.token = jwt.encode( { "email": user_info.email, "site": user_info.login_site, "exp": datetime.utcnow() + timedelta(weeks=2) }, SECRET['secret'], algorithm='HS256').decode('utf-8') new_refresh_token.save() access_token = jwt.encode( { "email": user_info.email, "site": user_info.login_site, "exp": datetime.utcnow() + timedelta(seconds=600) }, SECRET['secret'], algorithm='HS256') return JsonResponse( { "access_token": access_token.decode('utf-8'), "refresh_token": new_refresh_token.token, "name": user_info.name }, status=200) else: User(kakao_id=kakao_id, email=kakao_info['kakao_account']['email'], name=kakao_info['kakao_account']['profile']['nickname'], login_site='k', is_corrector='0').save() user_info = User.objects.get( email=kakao_info['kakao_account']['email']) RefreshToken( user=user_info, token=jwt.encode( { "email": user_info.email, "site": user_info.login_site, "exp": datetime.utcnow() + timedelta(weeks=2) }, SECRET['secret'], algorithm='HS256').decode('utf-8')).save() new_refresh_token = RefreshToken.objects.get(user=user_info) access_token = jwt.encode( { "email": user_info.email, "site": user_info.login_site, "exp": datetime.utcnow() + timedelta(seconds=600) }, SECRET['secret'], algorithm='HS256') return JsonResponse( { "access_token": access_token.decode('utf-8'), "refresh_token": new_refresh_token.token, "name": user_info.name }, status=200) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=400)
def user_registration(request): try: firstName = request.data.get('firstname', None) lastName = request.data.get('lastname', None) phoneNumber = request.data.get('phonenumber', None) email = request.data.get('email', None) gender = request.data.get('gender', None) password = request.data.get('password', None) reg_field = [firstName, lastName, phoneNumber, email, password, gender] #print([reg_field]) # print(request.data) if not None in reg_field and not "" in reg_field: if User.objects.filter( user_phone=phoneNumber).exists() or User.objects.filter( email=email).exists(): return_data = { "error": "1", "message": "User Exists", # "user":User.objects.filter(email =email)[0].email, # "pass":User.objects.filter(email =email)[0].user_password } # or validator.checkphone(phoneNumber)== False elif validator.checkmail(email) == False: return_data = { "error": "1", "message": "Email or Phone number is Invalid" } else: #generate user_id userRandomId = string_generator.alphanumeric(20) #encrypt password encryped_password = password_hasher.generate_password_hash( password) #Save user_data new_userData = User( user_id=userRandomId, firstname=firstName, lastname=lastName, email=email, user_phone=phoneNumber, user_gender=gender, user_password=encryped_password, ) new_userData.save() #get user role role = User.objects.get(user_id=userRandomId).role #Generate token timeLimit = datetime.datetime.now() + datetime.timedelta( minutes=1440) #set duration for token payload = { "user_id": f"{userRandomId}", "role": role, "exp": timeLimit } token = jwt.encode(payload, settings.SECRET_KEY) message = f"Welcome to CIT CLUB, your verification code is {payload}" # sms.sendsms(phoneNumber[1:],message) print(f""" {message} """) return_data = { "error": "0", "message": "The registration was successful,you can now login", "token": f"{token.decode('UTF-8')}", "elapsed_time": f"{timeLimit}", } else: return_data = {"error": "2", "message": "Invalid Parrameter"} except Exception as e: return_data = {"error": "3", "message": f"An error occured {e}"} return Response(return_data)
def register(request): user = User(username='******') user.password = '******' user.save() return HttpResponse('注册成功')
def load_user(username): print 'load_user - userid', username return User.get_with_username(username)
def perform_create(self, serializer): user = User(username=serializer.data['username']) user.set_password(serializer.data.get('password')) user.save() return user # 把保存的 User 对象返回
db_path = os.path.join(app.root_path, 'webapp.sqlite') app.config.update(dict( SQLALCHEMY_DATABASE_URI='sqlite:////' + db_path )) db = SQLAlchemy() ## Initialize database settings # with app.test_request_context(): from account.models import User db.init_app(app) # Create a test user for testing auser = User.create(username='******', password='******', firstname='Mr.', middlename='', lastname='Tester', email='*****@*****.**') if auser: # If this user is being registered for the first time. auser.save() ## Blueprint setup # app.register_blueprint(account_views, url_prefix='/account') app.register_blueprint(facade_views, url_prefix='') app.register_blueprint(main_views,url_prefix='/main') ## Flask-Login Configuration # login_manager = LoginManager() login_manager.session_protection = "strong" login_manager.init_app(app)
from datetime import datetime from config import config from account.models import User from library.models import Library config() root = User.objects(userName='******').first() if not root: now = datetime.now() root = User(userName='******', password='', roles=['root'], status=1, createTime=now, updateTime=now) root.save()
def get_current_user(request): user_id = request.session.get('user_id', None) user = None if user_id is not None: user = User.by_id(user_id) return user if user else None
def get(self, request): access_token = request.headers["Authorization"] kakao_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={ "Host": "kapi.kakao.com", "Authorization": f"Bearer {access_token}", "Content-type": "application/x-www-from-urlencoded;charset=utf-8" }, timeout=2) kakao_id = kakao_request.json().get("id") kakao_info = kakao_request.json() random_picture = { 1: 'https://i.pinimg.com/564x/fb/fa/b5/fbfab5595b2edb76f4aa574999ca52d7.jpg', 2: 'https://i.pinimg.com/564x/8f/6a/e5/8f6ae57185d5347ac66ae23bbe83802a.jpg', 3: 'https://i.pinimg.com/564x/7b/d2/73/7bd273aaa294b948fbe71a4dfb932aac.jpg' } picture_number = randint(1, 3) try: if User.objects.filter(kakao_id=kakao_id).exists(): user_info = User.objects.get( email=kakao_info["kakao_account"]["email"]) user_info.access_token = jwt.encode( { "email": user_info.email, "site": user_info.login_site }, SECRET["secret"], algorithm=ALGORITHM).decode("utf-8") try: user_info.profile_thumbnail = kakao_info["kakao_account"][ "profile"]["profile_image_url"] except KeyError: user_info.profile_thumbnail = random_picture[ picture_number] user_info.save() access_token = user_info.access_token return JsonResponse( { "access_token": access_token, "name": user_info.name, "image": user_info.profile_thumbnail, "is_corrector": user_info.is_corrector }, status=200) else: User(kakao_id=kakao_id, email=kakao_info["kakao_account"]["email"], name=kakao_info["kakao_account"]["profile"]["nickname"], login_site="k", access_token=jwt.encode( { "email": kakao_info["kakao_account"]["email"], "site": "k" }, SECRET["secret"], algorithm=ALGORITHM).decode("utf-8")).save() user_info = User.objects.get( email=kakao_info["kakao_account"]["email"]) if kakao_info["kakao_account"]["profile"][ "profile_image_url"] != None: user_info.profile_thumbnail = kakao_info["kakao_account"][ "profile"]["profile_image_url"] else: user_info.profile_thumbnail = random_picture[ picture_number] user_info.save() access_token = user_info.access_token return JsonResponse( { "access_token": access_token, "name": user_info.name, "image": user_info.profile_thumbnail, "is_corrector": user_info.is_corrector }, status=200) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=400)
class PingTestCase(APITestCase): @classmethod def setUpTestData(self): self.username = '******' self.password = '******' self.user = User(username=self.username) self.user.set_password(self.password) self.user.kind = User.STATION self.user.save() self.name = 'NTU' self.station = Station() self.station.name = self.name self.station.user = self.user self.station.external_id = 1 self.station.max_sessions = 3 self.station.save() self.url = reverse('general:ping') # login data = { 'username': self.username, 'password': self.password, 'api_key': settings.API_KEY } client = APIClient() client.post(reverse('general:register'), data, format='json') try: session = Session.objects.get(user=self.user) except: session = None self.session = session self.token = session.token def test_ping_success(self): data = {'token': self.token, 'api_key': settings.API_KEY} response = self.client.post(self.url, data) self.assertEqual(response.data['status'], 'success') def test_null_station_id(self): username = '******' password = '******' user = User(username=username) user.set_password(password) user.kind = User.STATION user.save() station = Station() station.name = 'no name' station.user = user station.max_sessions = 3 station.save() # login data = { 'username': username, 'password': password, 'api_key': settings.API_KEY } client = APIClient() client.post(reverse('general:register'), data, format='json') try: session = Session.objects.get(user=user) except: session = None data = {'token': session.token, 'api_key': settings.API_KEY} response = self.client.post(self.url, data) self.assertEqual(response.data, { 'status': 'error', 'reason': 'station_error' }) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def createSuperuser(): from django.utils import timezone from account.models import User, Profile print(bcolors.OKBLUE + "\n 建立超級管理員帳號" + bcolors.ENDC) try: while(True): username = raw_input("帳號: ") check = len(list(User.objects.filter(username=username))) if check==0: break print(bcolors.FAIL + "帳號已經被註冊 \n" + bcolors.ENDC) password = "" password2 = "" while(True): password = getpass.getpass("密碼: ") password2 = getpass.getpass("密碼(再一次): ") if password==password2: break else: print(bcolors.FAIL + "密碼不一樣,重新輸入 \n" + bcolors.ENDC) while(True): email = raw_input("電子郵件: ") if email_valid(email): break print(bcolors.FAIL + "請輸入正確的電子郵件" + bcolors.ENDC) admin = User() admin.username = username admin.set_password(password) admin.email = email admin.is_superuser = True admin.is_staff = True admin.is_active = True admin.date_joined = timezone.now() admin.save() userProflie = Profile() userProflie.user = admin userProflie.fullName=username userProflie.type = 2 #0=normal user, 1=manager, 2=administrator userProflie.isActive = True userProflie.isAuth = False userProflie.save() print(bcolors.OKBLUE + "\n "+ username +"超級管理員帳號建立成功 \n \n" + bcolors.ENDC) except Exception as e: s = str(e) print(bcolors.FAIL + "\n\n取消建立帳號 \n" + bcolors.ENDC) if """does not exist""" in s: print(bcolors.FAIL + "資料庫有問題,請檢查 \n" + bcolors.ENDC)
def post(self, request): parameter_missing = False parameter_missing_name = "" if request.data.get("first_name") is None or request.data.get( "first_name") == "": parameter_missing_name = parameter_missing_name + "first_name, " parameter_missing = True elif request.data.get("last_name") is None or request.data.get( "last_name") == "": parameter_missing_name = parameter_missing_name + "last_name, " parameter_missing = True elif request.data.get("email") is None or request.data.get( "email") == "": parameter_missing_name = parameter_missing_name + "email, " parameter_missing = True elif request.data.get("phone") is None or request.data.get( "phone") == "": parameter_missing_name = parameter_missing_name + "phone, " parameter_missing = True elif request.data.get("aadhar") is None or request.data.get( "aadhar") == "": parameter_missing_name = parameter_missing_name + "aadhar, " parameter_missing = True if parameter_missing: return Response({ "status": False, "status_code": HTTP_204_NO_CONTENT, "message": parameter_missing_name + " missing" }) existed_user_email = User.objects.filter( email=request.data.get("email")).first() if existed_user_email is None: existed_user_phone = User.objects.filter( phone=request.data.get("phone")).first() if existed_user_phone is None: existed_user_aadhar = User.objects.filter( aadhar=request.data.get("aadhar")).first() if existed_user_aadhar is None: user = User() user.first_name = request.data.get("first_name") user.middle_name = request.data.get("middle_name") user.last_name = request.data.get("last_name") user.email = request.data.get("email") user.phone = request.data.get("phone") user.aadhar = request.data.get("aadhar") user.country = request.data.get("country") user.state = request.data.get("state") user.city = request.data.get("city") user.constitucy = request.data.get("constitucy") user.ward = request.data.get("ward") user.landmark = request.data.get("landmark") user.pincode = request.data.get("pincode") user.gender = request.data.get("gender") user.date_of_birth = request.data.get("date_of_birth") user.role = "member" user.occupation_type = request.data.get("occupation_type") user.occupation_title = request.data.get( "occupation_title") user.save() return Response({ "status": True, "status_code": HTTP_200_OK, "message": "User Created.", "user": UserSerializer(user).data }) else: return Response({ "status": False, "status_code": HTTP_302_FOUND, "message": "Aadhar Exist." }) else: return Response({ "status": False, "status_code": HTTP_302_FOUND, "message": "Phone Exist." }) else: return Response({ "status": False, "status_code": HTTP_302_FOUND, "message": "Email Exist." })