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 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 run(): populate_question_list() for i in question_list: question_list[i].save() entry_list = parse() for i in entry_list: user_args = {} user_args["uid"] = i["序号"] sys.stdout.write("\r%s" % i["序号"]) sys.stdout.flush() user_args["is_male"] = (i["性别"] == "M") user_args["ip_address"] = i["IP 地址"] user_args["birth_year"] = i["出生年份"] if i["出生年份"] != "" else None user_args["income"] = i["年收入"] if i["年收入"] != "" else None user_args["education_background"] = i["学历"] try: t = i["参与时间"] if t and t != 'NULL': time.strptime(t, "%Y-%m-%d %H:%M:%S") user_args['time_created'] = t except ValueError: pass # print(user_args) user = User(**user_args) user.save() for j in i: if j not in ['序号', '参与时间', 'IP 地址', '性别', '出生年份', '年收入', '学历']: answer = Answer( question = question_list[j], user = user, answer = option_map[i[j]] ) answer.save()
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 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 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 __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 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})