def register(): error_message = '' if request.method == 'POST': first_name = request.form.get('first_name') last_name = request.form.get('last_name') email_address = request.form.get('email_address') password1 = request.form.get('password') password2 = request.form.get('password2') user = User.query.filter_by(email_address=email_address).first() if user: error_message = 'Email already exists. Please log in!' passwords_match = password1 == password2 if not error_message and not passwords_match: error_message = 'Passwords do not match' if not error_message: user = User(name=first_name + ' ' + last_name, email_address=email_address, password=password1) db.session.add(user) db.session.commit() return redirect(url_for('auth.login')) return render_template('register.html', error_message=error_message)
def register(req): context = {} if req.method == "POST": username = req.POST.get('username') password = req.POST.get('password') password_two = req.POST.get('password_two') print username, password, password_two user = User.objects.filter(username=username) if user: req.session['username'] = username return HttpResponse('用户名已经被占用') elif password == password_two: print "----" user = User() user.username = username user.password = password print "--------" user.save() print username, password, password_two #return HttpResponse(u'恭喜你!注册成功,您的用户名为'+username) return HttpResponseRedirect('/login/', context_instance=RequestContext(req)) else: return HttpResponse(u'您两次输入的密码不匹配,请重新输入') else: uf = UserForm() return render_to_response('register.html', context_instance=RequestContext(req))
def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.is_staff = True user.save() return user
def register(): if current_user.is_authenticated: return redirect (url_for('main.home')) form= RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf_8') user = User(username = form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! you can be able to login','success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
def user_login(request): if request.POST: email = request.POST['email'] password = request.POST['password'] user = User() count = User.objects.filter(email=email, password=password).count() if count > 0: return redirect('/home') else: messages.error(request, 'Invalid Email And Password') return redirect('/') return render(request, 'login.html')
def user_register(request): if request.POST: name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] obj = User(name=name, email=email, password=password, phone=phone) obj.save() messages.success(request, 'you are register sucessfully') # return redirect('/') return render(request, 'signup.html')
def register(): if current_user.is_authenticated: return redirect(url_for('dashboard')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf8') dam = Dam.query.filter_by(name=form.dam.data).first() user = User(username=form.username.data, password=hashed_password, dam_id=dam.id) db.session.add(user) db.session.commit() flash("Your account has been created. You can now login", 'flash_success') return render_template("register.html", form=form)
def myapps_shibboleth_callback(request): # should auth user login or signup # then redirect to my apps homepage eppn = request.META['HTTP_EPPN'] groups = request.META['HTTP_UCLINTRANETGROUPS'] cn = request.META['HTTP_CN'] department = request.META['HTTP_DEPARTMENT'] given_name = request.META['HTTP_GIVENNAME'] display_name = request.META['HTTP_DISPLAYNAME'] employee_id = request.META['HTTP_EMPLOYEEID'] try: user = User.objects.get(email=eppn) except ObjectDoesNotExist: # create a new user new_user = User(email=eppn, full_name=display_name, given_name=given_name, department=department, cn=cn, raw_intranet_groups=groups, employee_id=employee_id) new_user.save() add_user_to_mailing_list_task.delay(new_user.email, new_user.full_name) request.session["user_id"] = new_user.id keen_add_event.delay("signup", { "id": new_user.id, "email": eppn, "name": display_name }) else: # user exists already, update values request.session["user_id"] = user.id user.full_name = display_name user.given_name = given_name user.department = department user.raw_intranet_groups = groups user.employee_id = employee_id user.save() keen_add_event.delay("User data updated", { "id": user.id, "email": eppn, "name": display_name }) return redirect("/oauth/myapps")
def handle(self, *args, **options): if not settings.DEBUG: print("This must not be run in production!") return print("Setting up the well-known development user...") try: # The email is set from the EPPN header user = User.objects.get(email='*****@*****.**') except User.DoesNotExist: user = User( email='*****@*****.**', full_name='UCL API Developer', given_name='UCL API', department='Dept of API Development', cn='develop', raw_intranet_groups='ucl-all;ucl-ug;schsci-all', employee_id='uclapi1' ) user.save() print("Setting up the well-known Local OAuth Test app...") try: app = App.objects.get(user=user, name="Local OAuth Test") except App.DoesNotExist: app = App( user=user, name="Local OAuth Test", api_token='uclapi-4286bc18b235d86-ab0998cc3a47a9b-07b6dfe234a04bf-97407a655b33ae8', # noqa client_id='1105308584328350.9460393713696551', client_secret='251e9f9553bb3b86829c18bf795844d977dedf569b24a70e4d4e753958fcc2f3', # noqa callback_url='http://localhost:8002/uclapi/callback' ) app.save() print( "Well-known user: {}. Well-known app: {}".format( user.full_name, app.name ) ) if len(TimetableLock.objects.all()) == 0: call_command("create_timetable_lock") print("Building Medium Cache...") call_command("update_medium") print("*** Development environment ready for use! ***")
def login(): if current_user.is_authenticated: return redirect(url_for('hcs')) form = LoginForm() if form.validate_on_submit(): os.environ['SESSION_ID'] = form.sessionID.data try: user = User(user_id=form.sessionID.data) # checks if user is already in database if User.query.filter_by( user_id=form.sessionID.data).first() != None: login_user(user) flash(f'Hi, you have been logged in.', 'success') return redirect(url_for('hcs')) # if not, add user to db and call forum fetcher else: db.session.add(user) # fetch Hcs HcFetch = HcFetcher(form.sessionID.data) HcFetch.get_grades() # fetch Los LoFetch = LoFetcher(form.sessionID.data) LoFetch.get_grades() db.session.commit() login_user(user) flash(f'Hi, you have been logged in.', 'success') return redirect(url_for('hcs')) except: flash('Login unsuccessful. Please check Session ID.', 'danger') db.session.rollback() return render_template('login.html', title='Welcome', form=form)
def post(self, request): basic_auth = request.META.get( 'HTTP_AUTHORIZATION', '' ) if re.match('Basic [A-Za-z0-9]', basic_auth): auth = basic_auth.partition(' ')[2] username, _, password = b64decode(auth).decode().partition(':') print(username, password) user = User(username=username, password=password) if valid_user(user): print('User validated!') parser = LandingPageParser(user) print('Parsing student...') student = parser.parse().__dict__ print('Finished parsing student!') student.pop('_state') return JsonResponse(student) else: return JsonResponse({}, status=400) else: return JsonResponse({}, status=400)
def __create_brother_if_possible(semester, brother_status, first_name, last_name, caseid): if User.objects.filter(username=caseid).exists(): user = User.objects.get(username=caseid) elif caseid != "": user = User() user.username = caseid user.save() else: pass # nothing to do here since the if below will return false # ie `user` is never accessed # if able to add, create the brother with the given data if __can_brother_be_added(first_name, last_name, caseid): new_brother = Brother() new_brother.user = user new_brother.first_name = first_name new_brother.last_name = last_name new_brother.case_ID = user.username new_brother.birthday = datetime.date.today() new_brother.semester = semester new_brother.brother_status = brother_status new_brother.save()
def shibcallback(request): # Callback from Shib login. Get ALL the meta! appdata_signed = request.GET.get("appdata", None) if not appdata_signed: response = PrettyJsonResponse({ "ok": False, "error": ("No signed app data returned from Shibboleth." " Please use the authorise endpoint.") }) response.status_code = 400 return response signer = TimestampSigner() try: # Expire our signed tokens after five minutes for added security appdata = signer.unsign(appdata_signed, max_age=300) except signing.SignatureExpired: response = PrettyJsonResponse({ "ok": False, "error": ("Login data has expired. Please attempt to log in " "again. If the issues persist please contact the " "UCL API Team to rectify this.") }) response.status_code = 400 return response except signing.BadSignature: response = PrettyJsonResponse({ "ok": False, "error": ("Bad signature. Please attempt to log in again. " "If the issues persist please contact the UCL API " "Team to rectify this.") }) response.status_code = 400 return response client_id = appdata[:33] state = appdata[33:] # We can trust this value because it was extracted from the signed data # string sent via Shibboleth app = App.objects.get(client_id=client_id) # Sometimes UCL doesn't give us the expected headers. # If a critical header is missing we error out. # If non-critical headers are missing we simply put a placeholder string. try: # This is used to find the correct user eppn = request.META['HTTP_EPPN'] # We don't really use cn but because it's unique in the DB we can't # really put a place holder value. cn = request.META['HTTP_CN'] # (aka UPI), also unique in the DB employee_id = request.META['HTTP_EMPLOYEEID'] except KeyError: response = PrettyJsonResponse({ "ok": False, "error": ("UCL has sent incomplete headers. If the issues persist" "please contact the UCL API Team to rectify this.") }) response.status_code = 400 return response # TODO: Ask UCL what on earth are they doing by missing out headers, and # remind them we need to to be informed of these types of changes. # TODO: log to sentry that fields were missing... department = request.META.get('HTTP_DEPARTMENT', '') given_name = request.META.get('HTTP_GIVENNAME', '') display_name = request.META.get('HTTP_DISPLAYNAME', '') groups = request.META.get('HTTP_UCLINTRANETGROUPS', '') # We check whether the user is a member of any UCL Intranet Groups. # This is a quick litmus test to determine whether they should be able to # use an OAuth application. # We deny access to alumni, which does not have this Shibboleth attribute. # Test accounts also do not have this attribute, but we can check the # department attribute for the Shibtests department. # This lets App Store reviewers log in to apps that use the UCL API. if not groups: if department == "Shibtests" or eppn == SHIB_TEST_USER: groups = "shibtests" else: response = HttpResponse( ("Error 403 - denied. <br>" "Unfortunately, alumni are not permitted to use UCL Apps.")) response.status_code = 403 return response # If a user has never used the API before then we need to sign them up try: # TODO: Handle MultipleObjectsReturned exception. # email field isn't unique at database level (on our side). # Alternatively, switch to employee_id (which is unique). user = User.objects.get(email=eppn) except User.DoesNotExist: # create a new user user = User(email=eppn, full_name=display_name, given_name=given_name, department=department, cn=cn, raw_intranet_groups=groups, employee_id=employee_id) user.save() else: # User exists already, so update the values if new ones are non-empty. user = User.objects.get(email=eppn) user.employee_id = employee_id if display_name: user.full_name = display_name if given_name: user.given_name = given_name if department: user.department = department if groups: user.raw_intranet_groups = groups user.save() # Log the user into the system using their User ID request.session["user_id"] = user.id signer = TimestampSigner() response_data = { "client_id": app.client_id, "state": state, "user_upi": user.employee_id } response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder) response_data_signed = signer.sign(response_data_str) s = Scopes() page_data = { "app_name": app.name, "creator": app.user.full_name, "client_id": app.client_id, "state": state, "scopes": s.scope_dict(app.scope.scope_number), "user": { "full_name": user.full_name, "cn": user.cn, "email": user.email, "department": user.department, "upi": user.employee_id }, "signed_data": response_data_signed } initial_data = json.dumps(page_data, cls=DjangoJSONEncoder) return render(request, 'permissions.html', {'initial_data': initial_data})
def myapps_shibboleth_callback(request): # should auth user login or signup # then redirect to my apps homepage # Sometimes UCL doesn't give us the expected headers. # If a critical header is missing we error out. # If non-critical headers are missing we simply put a placeholder string. try: # This is used to find the correct user eppn = request.META['HTTP_EPPN'] # We don't really use cn but because it's unique in the DB we can't # really put a place holder value. cn = request.META['HTTP_CN'] # (aka UPI), also unique in the DB employee_id = request.META['HTTP_EMPLOYEEID'] except KeyError: response = PrettyJsonResponse({ "ok": False, "error": ("UCL has sent incomplete headers. If the issues persist" "please contact the UCL API Team to rectify this.") }) response.status_code = 400 return response # TODO: Ask UCL what on earth are they doing by missing out headers, and # remind them we need to to be informed of these types of changes. # TODO: log to sentry that fields were missing... department = request.META.get('HTTP_DEPARTMENT', '') given_name = request.META.get('HTTP_GIVENNAME', '') display_name = request.META.get('HTTP_DISPLAYNAME', '') groups = request.META.get('HTTP_UCLINTRANETGROUPS', '') try: user = User.objects.get(email=eppn) # TODO: Handle MultipleObjectsReturned exception. # email field isn't unique at database level (on our side). # Alternatively, switch to employee_id (which is unique). except User.DoesNotExist: # create a new user new_user = User(email=eppn, full_name=display_name, given_name=given_name, department=department, cn=cn, raw_intranet_groups=groups, employee_id=employee_id) new_user.save() request.session["user_id"] = new_user.id else: # User exists already, so update the values if new ones are non-empty. user = User.objects.get(email=eppn) user.employee_id = employee_id if display_name: user.full_name = display_name if given_name: user.given_name = given_name if department: user.department = department if groups: user.raw_intranet_groups = groups user.save() return redirect("/oauth/myapps")
def signup_page(name=None): form = RegistrationForm(request.form, captcha={'ip_address': request.environ.get('HTTP_X_REAL_IP', request.remote_addr)}) if name is None: abort(404) if current_user.is_authenticated: return redirect(url_for('home')) if request.method == 'POST': if name is None: abort(404) if form.validate_on_submit(): query = User.query.filter_by(is_reseller=True, username=name).first_or_404() email = form.email.data restrict_email = email.split('@') if restrict_email[1] == 'gmail.com' or restrict_email[1] == 'yahoo.com': registered_email = User.query.filter_by(email=form.email.data).first() registered_user = User.query.filter_by(username=form.username.data).first() if registered_user is None and registered_email is None: verification_code = email_key_generator() msg = Message('SafeCore Identity Confirmation', recipients=[form.email.data] ) msg.html = render_template('email.html', email=form.email.data, confirmation=verification_code) mail.send(msg) query = User( form.first_name.data, form.last_name.data, form.email.data, form.username.data, form.password.data, query.username ) email_expiration = datetime.now() + timedelta(days=1) email_verify = Email(user=query, confirmation_key=verification_code, registration_date=datetime.now(), valid=True, expiration_date=email_expiration ) notify = Notifications(user_id=query.id, notification_type='signup', confirmed_date=datetime.now(), notification_ip=request.environ.get('HTTP_X_REAL_IP', request.remote_addr)) db.session.add(query, email_verify, notify) db.session.commit() flash('Please check your email for verification!', 'info') return redirect(url_for('login')) else: flash('Username or email already exists!', 'warning') return redirect(url_for('reseller.signup_page')) else: flash('We only accept email in Google and Yahoo', 'warning') return redirect(url_for('reseller.signup_page')) else: flash('Something went wrong! Please check your form and try again', 'warning') return redirect(url_for('reseller.signup_page')) form = RegistrationForm(request.form, captcha={'ip_address': request.environ.get('HTTP_X_REAL_IP', request.remote_addr)}) query = User.query.filter_by(is_reseller=True, username=name).first_or_404() if query.account_status == 'banned' or query.account_status == 'deactivated': abort(404) else: return render_template('my_page_signup.html', query=User.query.filter_by(is_reseller=True, username=name).first_or_404(), form=form, page_title='Register under ' + query.username)
def shibcallback(request): # Callback from Shib login. Get ALL the meta! appdata_signed = request.GET.get("appdata", None) if not appdata_signed: response = PrettyJsonResponse({ "ok": False, "error": ("No signed app data returned from Shibboleth." " Please use the authorise endpoint.") }) response.status_code = 400 return response signer = TimestampSigner() try: # Expire our signed tokens after five minutes for added security appdata = signer.unsign(appdata_signed, max_age=300) except signing.SignatureExpired: response = PrettyJsonResponse({ "ok": False, "error": ("Login data has expired. Please attempt to log in " "again. If the issues persist please contact the " "UCL API Team to rectify this.") }) response.status_code = 400 return response except signing.BadSignature: response = PrettyJsonResponse({ "ok": False, "error": ("Bad signature. Please attempt to log in again. " "If the issues persist please contact the UCL API " "Team to rectify this.") }) response.status_code = 400 return response client_id = appdata[:33] state = appdata[33:] # We can trust this value because it was extracted from the signed data # string sent via Shibboleth app = App.objects.get(client_id=client_id) eppn = request.META['HTTP_EPPN'] groups = request.META['HTTP_UCLINTRANETGROUPS'] cn = request.META['HTTP_CN'] department = request.META['HTTP_DEPARTMENT'] given_name = request.META['HTTP_GIVENNAME'] display_name = request.META['HTTP_DISPLAYNAME'] employee_id = request.META['HTTP_EMPLOYEEID'] # If a user has never used the API before then we need to sign them up try: user = User.objects.get(email=eppn) except User.DoesNotExist: # create a new user user = User(email=eppn, full_name=display_name, given_name=given_name, department=department, cn=cn, raw_intranet_groups=groups, employee_id=employee_id) user.save() keen_add_event.delay("signup", { "id": user.id, "email": eppn, "name": display_name }) else: # User exists already, so update the values user = User.objects.get(email=eppn) user.full_name = display_name user.given_name = given_name user.department = department user.raw_intranet_groups = groups user.employee_id = employee_id user.save() keen_add_event.delay("User data updated", { "id": user.id, "email": eppn, "name": display_name }) # Log the user into the system using their User ID request.session["user_id"] = user.id signer = TimestampSigner() response_data = { "client_id": app.client_id, "state": state, "user_upi": user.employee_id } response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder) response_data_signed = signer.sign(response_data_str) s = Scopes() page_data = { "app_name": app.name, "creator": app.user.full_name, "client_id": app.client_id, "state": state, "scopes": s.scope_dict(app.scope.scope_number), "user": { "full_name": user.full_name, "cn": user.cn, "email": user.email, "department": user.department, "upi": user.employee_id }, "signed_data": response_data_signed } initial_data = json.dumps(page_data, cls=DjangoJSONEncoder) return render(request, 'permissions.html', {'initial_data': initial_data})