def callback(request): client = get_evernote_client() access_token = '' if 'oauth_verifier' in request.GET: oauth_verifier = request.GET.get("oauth_verifier") access_token = client.get_access_token( request.COOKIES['oauth_token'], request.COOKIES['oauth_token_secret'], oauth_verifier ) client = EvernoteClient(token=access_token) user_store = client.get_user_store() user = user_store.getUser() username = user.username shard_id = user.shardId privilege = user.privilege # request.session['shard_id'] = shard_id u = User( user_id=user.id, access_token=access_token) u.save() # Redirect the user to the Evernote authorization URL try: callbackUrl = request.COOKIES['_redirect_url'] except Exception as e : callbackUrl = 'http://%s/' % (request.get_host()) response = redirect(callbackUrl) if len(access_token) > 0 : response.set_cookie('access_token', access_token) response.delete_cookie('_redirect_url') return response
def cms_create_user(request): username='******' password='******' email='*****@*****.**' p=Hash_Pwd() pwd=p.hash_pwd(password) user=User(username=username,password=pwd,email=email) user.save() return HttpResponse('success')
def patient_register(): if current_user.is_authenticated: if current_user.position == 'doctor' or current_user.position == 'nurse': return redirect(url_for('patients.index')) else: return redirect(url_for('index')) form = PatientRegistrationForm() if form.validate_on_submit(): patient = Patient(first_name=form.first_name.data, last_name=form.last_name.data, gender=form.gender.data, date_of_birth=form.date_of_birth.data, address=form.address.data, contact_no=f'+63{form.contact_no.data}') db.session.add(patient) db.session.commit() hashed = bcrypt.generate_password_hash(form.password.data)\ .decode('utf-8') user = User(name=f'{form.first_name.data} {form.last_name.data}', position='patient', username=form.username.data, password=hashed, patient_id=patient.id) db.session.add(user) db.session.commit() flash(f'Account created for {form.username.data}! You can now log in.', 'success') return redirect(url_for('users.login')) return render_template('patient_register.html', title='Register', form=form)
def user_edit(request, user_id=None): """顧客の編集""" # return HttpResponse('顧客の編集') if user_id: user = get_object_or_404(User, pk=user_id) else: user=User() if request.method == 'POST': form=UserForm(request.POST, instance=user) if form.is_valid(): user=form.save(commit=False) user.save() return redirect('cms:user_list') else: form=UserForm(instance=user) return render(request, 'cms/user_edit.html', dict(form=form, user_id=user_id))
def test_new_user(): """ GIVEN a User model WHEN a new User is created THEN check the email, hashed_password, and role fields are defined correctly """ user = User('Dipin', '*****@*****.**', 'abc', '1', 1) assert user.email == '*****@*****.**' assert user.password_hash != 'abc'
def test_create(app): with app.app_context(): role = 'administrator' name = 'added-user_01' password = '******' user = User(role=role, name=name, password=generate_password_hash(password)) db.session.add(user) db.session.commit() assert user.id == 4
def user_edit(request, user_id=None): '''add user''' if user_id: # book_id が指定されている (修正時) user = get_object_or_404(User, pk=1) print user_id else: # book_id が指定されていない (追加時) user = User() if request.method == 'POST': form = UserForm(request.POST, instance=user) # POST された request データからフォームを作成 if form.is_valid(): # フォームのバリデーション user = form.save(commit=False) user.save() return redirect('cms/user/') else: # GET の時 form = UserForm(instance=user) # book インスタンスからフォームを作成 return render_to_response('cms/user_edit.html', dict(form=form, user_id=user_id), context_instance=RequestContext(request))
def add_user(request): logger = getLogger('add') handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) logger.propagate = False user = User() if request.method == 'POST': form = AddForm(request.POST, instance=user) if form.is_valid(): user = form.save(commit=False) users = User.objects.all().filter(userId=user.userId, password=user.password) logger.debug(users.count()) if users.count() == 0: user.save() return redirect('cms:login') form = AddForm() return render(request, 'cms/add.html', dict(form=form))
def register(): form = RegistrationForm() if form.validate_on_submit(): # user_data={k:v.data for k,v in form} # print(user_data) print("name is", form.name.data) user = User(form.name.data, form.email.data, form.password.data, form.year.data, form.branch.data) db.session.add(user) db.session.commit() flash('Thanks for registration!') return redirect(url_for('users.login')) return render_template('register.html', form=form)
def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user
def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = records.find_one({'email': form.email.data}) if user and bcrypt.check_password_hash(user['password'], form.password.data): user_obj = User(user['username']) login_user(user_obj) next_page = request.args.get('next') flash('You have been loged in!', 'success') return redirect(next_page) if next_page else redirect( url_for('home')) else: flash('Please check your email or password', 'danger') return render_template('login.html', title='Login', form=form)
def load_data(): file_path_list = [ 'tests/data/user.json', 'tests/data/entry.json', ] rows = load_json_file(file_path_list[0]) for row in rows: p = User(**row) db.session.add(p) db.session.commit() rows = load_json_file(file_path_list[1]) for row in rows: p = Entry(**row) db.session.add(p) db.session.commit()
def register(): if current_user.is_authenticated: return redirect(url_for('patients.index')) form = RegistrationForm() if form.validate_on_submit(): hashed = bcrypt.generate_password_hash(form.password.data)\ .decode('utf-8') user = User(name=form.name.data, position=form.position.data, username=form.username.data, password=hashed, patient_id=0) db.session.add(user) db.session.commit() flash(f'Account created for {form.username.data}! You can now log in.', 'success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form, choices=POSITION_CHOICES)
def create(): """Create user. Args: role (str): user's role username (str): user's name password (str): user's password Returns: str: template """ if request.method == 'POST': username = request.form['username'] password = request.form['password'] role = request.form['role'] error = '' if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif not validate_password(password): error = 'Bad data.' elif User.query.filter_by(name=username).first() is not None: error = 'User {0} is already registered.'.format(username) if error: flash_error(error) else: try: user = User( role=role, name=username, password=generate_password_hash(password) ) db.session.add(user) db.session.commit() except AssertionError: flash_error('Bad data.') else: flash_success('Creation succeeded.') return redirect(url_for('user.index')) return render_template('user/create.html', roles=roles)
def login(request): logger = getLogger('login') handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) logger.propagate = False user = User() if request.method == 'POST': form = LoginForm(request.POST, instance=user) logger.debug(form.is_valid()) user = form.save(commit=False) users = User.objects.all().filter(userId=user.userId, password=user.password) logger.debug(users.count()) if users.count() > 0: auth = Auth() auth.authId = get_next_value('authId') auth.userId = user.userId auth.save() refreshToken = RefreshToken() refreshToken.refreshTokenId = get_next_value('refreshId') refreshToken.authId = auth.authId refreshToken.refreshToken = secrets.token_hex() refreshToken.validTs = datetime.now() refreshToken.save() accessToken = AccessToken() accessToken.accessTokenId = get_next_value('accessToken') accessToken.refreshTokenId = refreshToken.refreshTokenId accessToken.accessToken = secrets.token_hex() accessToken.validTs = datetime.now() accessToken.save() return redirect('cms:add_user') else: form = LoginForm() return render(request, 'cms/login.html', dict(form=form))
def signup(request): if request.method == 'GET': return render(request, 'signup.html') elif request.method == 'POST': if 'tandc' in request.POST: if not str(request.POST['g-recaptcha-response']): context = { 'error_message': "Bot check is required.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) req = urllib.request.Request( "https://www.google.com/recaptcha/api/siteverify?secret=6LeBzQgUAAAAAKt953zokMxQ_vE0twJ42q_mgESx&response=" + str(str(request.POST['g-recaptcha-response']))) allhtml = "" with urllib.request.urlopen(req) as res: html = res.read().decode("utf-8") allhtml = allhtml + html jsonData = json.loads(allhtml) if (jsonData['success'] != True): context = { 'error_message': "Bot check error.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) if str(request.POST['password1']) != str( request.POST['password2']): context = { 'error_message': "Passwords are not same.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) if not str(request.POST['password1']): context = { 'error_message': "Password is required.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) email = request.POST['email'] try: user = User.objects.get(email__iexact=email) context = { 'error_message': "This email is already used.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) except: name = request.POST['name'] password = request.POST['password1'] alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" pw_length = 8 activateid = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) activateid = activateid + alphabet[next_index] user = User(email=str(email), name=str(name), password=password, activateid=activateid, firstdate=str(datetime.datetime.now())) try: sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Thanks for signing up" to_email = Email(email) context = {'activateid': activateid} content = Content( "text/html", render_to_string('email_confirm.html', context)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post( request_body=mail.get()) user.save() except: context = { 'error_message': "Incorrect email.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) context = {'name': str(name)} return render(request, 'after_signup.html', context) else: context = { 'error_message': "You need to agree to TERMS AND CONDITIONS.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context)
def test_create_validate(app, role, name, password): with app.app_context(): with pytest.raises(AssertionError): User(role=role, name=name, password=generate_password_hash(password))
def new_user(): user = User('Dipin', '*****@*****.**', 'abc', '1', 1) return user
def init_database(test_client): # Create the database and the database table # Insert user data db.create_all() db.session.add_all(branch_helper.create_branch_array()) db.session.commit() user1 = User('Dipin', '*****@*****.**', 'abc', '1', 1) user2 = Professor("Professor 1", "*****@*****.**", "prof1", 2) # user_other_branch = User('Ram', '*****@*****.**', 'abc', '1', 2) db.session.add(user1) db.session.add(user2) # Commit the changes for the users db.session.commit() course = Course(details="Course on Data structures", prof_id=user2.id, name="Data structures", course_code='203', can_apply=True) db.session.add(course) db.session.commit() quiz = Quiz(course_id=course.id, name="Quiz1", start_time=datetime(2015, 6, 5, 8, 10, 10, 10), end_time=datetime(2015, 6, 5, 8, 10, 12, 10)) db.session.add(quiz) db.session.commit() # Adding two Question in Quiz1 question1 = Question(quiz_id=quiz.id, question="Odd one out", ans='4', marks=2, is_multicorrect=True, is_partial=True) question2 = Question(quiz_id=quiz.id, question="Cities in Maharastra", ans='2,3,4', marks=4, is_multicorrect=True, is_partial=True) db.session.add(question1) db.session.add(question2) db.session.commit() # Options for 1st question option1 = Option(question_id=question1.id, option='django', is_right=False) option2 = Option(question_id=question1.id, option='flask', is_right=False) option3 = Option(question_id=question1.id, option='ruby on rails', is_right=False) option4 = Option(question_id=question1.id, option='expressjs', is_right=True) db.session.add(option1) db.session.add(option2) db.session.add(option3) db.session.add(option4) db.session.commit() # Options for 2nd question option1 = Option(question_id=question2.id, option='Indore', is_right=False) option2 = Option(question_id=question2.id, option='Nasik', is_right=True) option3 = Option(question_id=question2.id, option='Mumbai', is_right=True) option4 = Option(question_id=question2.id, option='Bombay', is_right=True) db.session.add(option1) db.session.add(option2) db.session.add(option3) db.session.add(option4) db.session.commit() # Request for enrollment in course req = Request(user_id=user1.id, course_id=course.id, title="Request to Access Course", details="Please allow me!!") db.session.add(req) db.session.commit() yield # this is where the testing happens! db.drop_all()