def login(request): """ Log a user in. Creates an access_token using a persona assertion and the client secret. Sets this access token as a cookie. 'target_url' based as a GET parameter determines where the user is redirected. """ target_url = request.POST.get('target_url') assertion = request.POST.get('Assertion') postdata = { 'Assertion': assertion, 'ClientSecret':settings.CLIENT_SECRET } url = build_url(request.get_host(), ['auth']) try: response = requests.post(url, data=postdata, headers={}) except RequestException: return ErrorView.server_error(request) access_token = response.json()['data'] if access_token is None: return ErrorView.server_error(request) response = HttpResponseRedirect(target_url if target_url != '' else '/') expires = datetime.datetime.fromtimestamp(2 ** 31 - 1) response.set_cookie('access_token', access_token, expires=expires, httponly=True) return response
def set_language(request, runinfo=None, next=None): """ Change the language, save it to runinfo if provided, and redirect to the provided URL (or the last URL). Can also be used by a url handler, w/o runinfo & next. """ if not next: next = request.REQUEST.get('next', None) if not next: next = request.META.get('HTTP_REFERER', None) if not next: next = '/' response = HttpResponseRedirect(next) response['Expires'] = "Thu, 24 Jan 1980 00:00:00 GMT" if request.method == 'GET': lang_code = request.GET.get('lang', None) if lang_code and translation.check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language'] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) if runinfo: runinfo.subject.language = lang_code runinfo.subject.save() return response
def translation_set_language(request, select_language): """ Set and activate a language, if that language is available. """ if translation.check_for_language(select_language): fallback = False else: # The page is in a language that Django has no messages for. # We display anyhow, but fall back to primary language for # other messages and other applications. It is *highly* recommended to # create a new django.po for the language instead of # using this behaviour. select_language = django_settings.LANGUAGES[0][0] fallback = True translation.activate(select_language) request.LANGUAGE_CODE = translation.get_language() if hasattr(request, 'session'): # User has a session, then set this language there if select_language != request.session.get('django_language'): request.session['django_language'] = select_language elif request.method == 'GET' and not fallback: # No session is active. We need to set a cookie for the language # so that it persists when the user changes his location to somewhere # not under the control of the CMS. # Only do this when request method is GET (mainly, do not abort # POST requests) response = HttpResponseRedirect(request.get_full_path()) response.set_cookie(django_settings.LANGUAGE_COOKIE_NAME, select_language) return response
def force_desktop_version(request): url = request.GET.get("back_url") if not url: url = reverse("index") response = HttpResponseRedirect(url) response.set_cookie("force_desktop", True) return response
def i18n(request): """ Set client language preference, lasts for one month """ from django.conf import settings next = request.META.get('HTTP_REFERER', settings.SITE_ROOT) lang = request.GET.get('lang', settings.LANGUAGE_CODE) if lang not in [e[0] for e in settings.LANGUAGES]: # language code is not supported, use default. lang = settings.LANGUAGE_CODE # set language code to user profile if user is logged in if not request.user.is_anonymous(): p = Profile.objects.get_profile_by_user(request.user.username) if p is not None: # update exist record p.set_lang_code(lang) else: # add new record Profile.objects.add_or_update(request.user.username, '', '', lang) # set language code to client res = HttpResponseRedirect(next) res.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang, max_age=30*24*60*60) return res
def process_request(self, request): if not getattr(settings, 'MOBILE_DOMAIN', False): return # test for mobile browser if ( # check for override cookie, do not check if present request.COOKIES.get('ismobile', '0') == '1' or ( # browser info present 'HTTP_USER_AGENT' in request.META and # desktop browser override not set request.COOKIES.get('isbrowser', '0') != '1' and # check browser type is_mobile(request.META['HTTP_USER_AGENT']) ) ): # redirect to mobile domain response = HttpResponseRedirect(settings.MOBILE_DOMAIN) # set cookie to identify the browser as mobile max_age = getattr(settings, 'MOBILE_COOKIE_MAX_AGE', DEFAULT_COOKIE_MAX_AGE) expires_time = time.time() + max_age expires = cookie_date(expires_time) response.set_cookie('ismobile', '1', domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires) return response
def change_town(request): tw = Town.objects.filter(is_active=True).order_by('title') if tw.count() < 3: ftowns = {'col1':tw, 'col2':None, 'col3':None} elif tw.count() >= 3: step = tw.count() / 3 ftowns = { 'col1':tw[0:step], 'col2':tw[step:2*step], 'col3':tw[2*step:], } response = render_to_response('dealers/change_town.html', {'towns_list':ftowns}, RequestContext(request)) idd = None if 'i' in request.GET: try: id = int(request.GET.get('i')) except: raise Http404() else: try: tw = Town.objects.get(id=id, is_active=True) except: pass else: idd = tw.id messages.add_message(request, messages.INFO, _("Town %s changed") % tw.title) response = HttpResponseRedirect('/change-town/') if idd: response.set_cookie("town", str(idd), path="/") else: response = render_to_response('dealers/change_town.html', {'towns_list':ftowns}, RequestContext(request)) return response ####################################################################################################################### #######################################################################################################################
def login(request, template): """Try to log the user in.""" if request.method == 'GET' and not request.MOBILE: url = reverse('users.auth') + '?' + request.GET.urlencode() return HttpResponsePermanentRedirect(url) next_url = get_next_url(request) or reverse('home') form = handle_login(request) if request.user.is_authenticated(): # Add a parameter so we know the user just logged in. # fpa = "first page authed" or something. next_url = urlparams(next_url, fpa=1) res = HttpResponseRedirect(next_url) max_age = (None if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE else settings.SESSION_COOKIE_AGE) res.set_cookie(settings.SESSION_EXISTS_COOKIE, '1', secure=False, max_age=max_age) return res if request.MOBILE: return render(request, template, { 'form': form, 'next_url': next_url}) return user_auth(request, login_form=form)
def apollo_connect(request): ''' Used in My Organism, Launch, login into Apollo ''' user_mapping = UserMapping.objects.get(django_user=request.user) #get account name and password data = {'username':user_mapping.apollo_user_name, 'password':decodeAES(user_mapping.apollo_user_pwd)} req = urllib2.Request(_APOLLO_URL+'/Login?operation=login') req.add_header('Content-Type', 'application/json') cookies = cookielib.LWPCookieJar() handlers = [ urllib2.HTTPHandler(), urllib2.HTTPSHandler(), urllib2.HTTPCookieProcessor(cookies) ] opener = urllib2.build_opener(*handlers) response = opener.open(req, json.dumps(data)) result = json.loads(response.read()) if len(result) != 0: return HttpResponse(json.dumps(result), content_type="application/json") response = HttpResponseRedirect(request.session['apollo_url']+'/annotator/loadLink?organism='+request.GET['oid']) #set sookie for cookie in cookies: if(cookie.name == 'JSESSIONID'): response.set_cookie(key=cookie.name, value=cookie.value, domain=i5k.settings.APOLLO_COOKIE_DOMAIN, path=cookie.path, expires=cookie.expires) return response
def parent_login(request, key=""): if key == "": HttpResponseBadRequest('{"error_msg": "No identifier supplied"}') try: pare = ParentEmail.objects.get(key__exact=key) if pare.answered == True: return HttpResponseBadRequest('{"error_msg": "You have already answered to the questionnaire"}') user = authenticate(username=pare.parent.username, password="******") login(request, user) # pare.answered = True pare.save() except: return HttpResponse('{"error_msg": "User not found"}', status=404, content_type="application/json") # user = authenticate(username=pare.parent.username, password='******') # login(request, user) site_name = Site.objects.get(id=settings.SITE_ID).name response = HttpResponseRedirect(reverse("parent_start")) if hasattr(request, "session"): request.session["is_parent"] = "True" else: response.set_cookie("is_parent", "True") # return HttpResponse('{"message": "login successfully"}') return response
def profile(request): if request.method == 'POST': form = ProfileForm(request.POST, instance = request.user.get_profile()) subscriptionform = SubscriptionForm(request.POST, instance = request.user.get_profile()) userform = UserForm(request.POST, instance = request.user) if form.is_valid() and userform.is_valid() and subscriptionform.is_valid(): form.save() subscriptionform.save() userform.save() set_lang(request.user, request = request, user = request.user) # Need to redirect to allow language change response = HttpResponseRedirect('/accounts/profile/') response.set_cookie(settings.LANGUAGE_COOKIE_NAME, request.user.get_profile().language) return response else: form = ProfileForm(instance = request.user.get_profile()) subscriptionform = SubscriptionForm(instance = request.user.get_profile()) userform = UserForm(instance = request.user) response = render_to_response('profile.html', RequestContext(request, { 'form': form, 'userform': userform, 'subscriptionform': subscriptionform, 'title': _('User profile'), })) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, request.user.get_profile().language) return response
def get(self, request): next = "/" if "next" in request.GET: next = request.GET.get("next") response = HttpResponseRedirect(next) if not request.GET: return response form = forms.LanguageCodeForm(data=request.GET) if not form.is_valid(): return response language = form.cleaned_data['language'] if not translation.check_for_language(language): return response if hasattr(request, "session"): request.session[translation.LANGUAGE_SESSION_KEY] = language else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) translation.activate(language) return response
def auth_finish(request): try: access_token, user_id, url_state = get_auth(request.session).finish(request.GET) client = DropboxClient(access_token) user = request.user client_email = client.account_info()["email"] uid = client.account_info()["uid"] name = client.account_info()["display_name"] try: formerAccount = DropboxAccount.objects.get(uid=uid) formerAccount.token = access_token formerAccount.display_name = name formerAccount.email = client_email formerAccount.save() new_account = False except ObjectDoesNotExist: new_account = True account = user.dropboxaccount_set.create(uid=uid, token=access_token, email=client_email, display_name=name) response = HttpResponseRedirect("/services") response.set_cookie("service_added", "dropbox", path="/") response.set_cookie("new_account", new_account, path="/") response.set_cookie("account_uid", uid, path="/") return response except DropboxOAuth2Flow.BadRequestException, e: http_status(400) info = "error404" return render(request, "dropbox.html", {"info": info})
def register(request): if request.method == "POST": #获取表单信息 m = hashlib.md5() username = request.POST.get('account','') if LocalAuth.objects.filter(user_account = str(username)): return render_to_response('reg.html', locals(), context_instance=RequestContext(request)) else: password = request.POST.get('password','') m.update(password) #将表单写入数据库 user = User() user.user_name = username user.save() userAuth = LocalAuth() userAuth.user_account = username userAuth.user_password= m.hexdigest() userAuth.create_time = datetime.now() userAuth.is_login = True userAuth.user = user userAuth.save() #返回注册成功页面 response = HttpResponseRedirect('/thesisApp/course/') request.session['user_obj'] = user response.set_cookie('username',username,3600) return response else: return render_to_response('reg.html', locals(), context_instance=RequestContext(request))
def auth_return(request): oauth2_flow = oauth2.OAuth2Flow() domains = oauth2_flow.get_domains() flow = oauth2.OAuth2Flow().get_flow(domains[1]) # disable SSL certificate validation for exchanging access code http = httplib2.Http() http.disable_ssl_certificate_validation = True credential = flow.step2_exchange(request.GET.get('code'), http) credential_token = json.loads(credential.to_json())['id_token'] if credential_token['email_verified'] and credential_token['hd'] in domains: email = credential_token['email'] crypter = oauth2.Crypter() encrypted_email = crypter.encrypt(email) encrypted_domain = crypter.encrypt(credential_token['hd']) encrypted_token = crypter.encrypt(credential.access_token) response = HttpResponseRedirect('/') # cookie expires after a week response.set_cookie('login', encrypted_email, max_age=7 * 24 * 60 * 60) response.set_cookie('domain_url', encrypted_domain, max_age=7 * 24 * 60 * 60) response.set_cookie('user_id', email, max_age=7 * 24 * 60 * 60) response.set_cookie('token', encrypted_token) return response else: messages.add_message(request, SIGNIN, 'Authentication failed.') response = HttpResponseRedirect('/logout/')
def login(request): if request.method == 'GET': reDict = {'nav': getNav(request)} response = render_to_response('accounts/login.html', reDict) ref = get_referer_view(request) response.set_cookie('ref', smart_str(ref)) return response else: _usr = request.POST.get('usr', '') _pwd = request.POST.get('pwd', '') userInfoList = UserInfo.objects.filter(username=_usr) if userInfoList.count() == 0: reDict = {'nav': getNav(request), 'notexists': True} return render_to_response('accounts/login.html', reDict) else: if userInfoList[0].password == pwd2hash(_pwd): referer = getRef(request) _kwargs = {'siteid': getSiteid(request)} if u'freebtc123:evaluate' == referer else {} response = HttpResponseRedirect(reverse(referer, kwargs=_kwargs)) delCookie(request, response, 'ref') response.set_cookie('usr', smart_str(_usr)) return response else: reDict = {'nav': getNav(request), 'notexists': False, 'pwderror': True} return render_to_response('accounts/login.html', reDict)
def login(request): """Login, if user is authenticated and active.""" if request.user.is_active: return HttpResponseRedirect('/accounts/details/') if request.POST: username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username, password = password) try: if user.is_active: auth.login(request, user) response = HttpResponseRedirect('/checks/') if 'remember_me' in request.POST: response.set_cookie('username', username) else: response.delete_cookie('username') return response else: messages.warning(request, _('This account is not active. Contact administrator.')) except: messages.warning(request, _('Account with these entries is not found. Try again or contact administrator.')) if 'username' in request.COOKIES: context = {'username': request.COOKIES['username']} else: context = {} return render_to_response('login.html', RequestContext(request, context))
def logout(request): print('logout') # 调转到主页面 response = HttpResponseRedirect(reverse("main:index")) # 删除cookie response.delete_cookie('username') return response
def login(request): auth = request.COOKIES.get('auth') if auth: return HttpResponseRedirect('/profile') if request.method == 'POST': form = LoginForm(data=request.POST) if form.is_valid(): username=form.cleaned_data['uname'] password=form.cleaned_data['pword'] post_data = {'username': username, 'password': password} post_encoded = urllib.parse.urlencode(post_data).encode('utf-8') req = urllib.request.Request('http://exp-api:8000/login', data=post_encoded, method='POST') resp_json = urllib.request.urlopen(req).read().decode('utf-8') resp = json.loads(resp_json) if not resp or 'error' in resp: return render(request, 'login.html') authenticator = {'auth': resp['authenticator'], 'user_id': resp['user_id']} response = HttpResponseRedirect('/profile') response.set_cookie("auth", json.dumps(authenticator)) return response else: print(form.errors) else: form = LoginForm() return render(request, 'login.html', {'form': form})
def recv_redirect(request): print "recv_redirect" code = request.GET.get('code', '') datas = { 'code':code, 'client_id': GENOMIC_ID, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code' } headers = { "Content-Type": 'application/x-www-form-urlencoded', "Content-Length" : len(datas) } print 'begin' resp = requests.post('http://genomics-advisor.smartplatforms.org:2048/auth/token', data=datas,headers=headers) print resp print 'end' if resp.status_code != 200: raise OAuthError else: genomic_access_token = resp.json()['access_token'] #resp.set_cookie('genomic_access_token', genomic_access_token) request.session['genomic_access_token'] = genomic_access_token re = 'http://localhost:8000/fhir-app/' resp = HttpResponseRedirect(re) resp.set_cookie('genomic_access_token', request.session.get('genomic_access_token')) return resp
def user_create(request): """ Create a user. """ try: try: # If there is a user with the same name... User.objects.get(username = request.POST['username']) # ... return error code 412. return respond(412, 'That username is taken.') except ObjectDoesNotExist: # otherwise... password_plaintext = request.POST['password'].encode('utf-8') # ...ensure the password is at least 16 characters long... if 16 <= len(password_plaintext): # ...create the user... user = User( username = request.POST['username'], password_hash = \ bcrypt.hashpw(password_plaintext, bcrypt.gensalt())) user.save() response = HttpResponseRedirect('/home') # ...create the current session.... session = Session(user = user) session.save() # ...and set the session cookie. response.set_cookie(Session.COOKIE_NAME, session.key) return response else: return respond(412, 'Please choose a password at least 16 characters long.') except KeyError: return respond(412, 'Missing parameter "username" or "password".')
def handle_post(self, request): """ Registers a user if it was a request to register a user and the registration form was correctly completed. """ # Confirm that the requst is a post, and that this form is # the intended recipient of the posted data. if not request.POST or self.submit_btn_name() not in request.POST: return None form = RegistrationForm(request.POST, auto_id=False) if form.is_valid(): # Create a user, log them in, and redirect based on the # success_url rules. user, created = User.objects.create_user(request=request, send_email=True, **form.cleaned_data) user_cache = authenticate( username=form.cleaned_data['email'], password=form.cleaned_data['password1']) expire_login(request, user_cache) response = HttpResponseRedirect(success_url(request)) response.set_cookie('myguid', user.user_guid, expires=365*24*60*60, domain='.my.jobs') return response return None
def admin_login(request): c = RequestContext(request) user_name = '' ca =Captcha(request) pwd = '' ip=request.META.get('REMOTE_ADDR',None) if 'user_name' in request.POST: user_name = request.POST.get('user_name') else : return render_to_response("admin/login.html", c) if 'code' in request.POST: code = request.POST.get('code') if not ca.validate(code): return render_to_response('admin/login.html', {'verify_error': True}, c) if 'password' in request.POST: pwd = request.POST.get('password') if user_name != '': try: user = Users.objects.get(user_id=user_name) if str(user.password) == pwd: if user.defunct != 'C': log=Loginlog(user_id=user_name,password=pwd,ip=ip,time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) log.save() response = HttpResponseRedirect('index?menuName=&submenuName=See%20SDUSTOJ', c) response.set_cookie('uname', user_name, 3600) response.set_cookie('power', user.defunct, 3600) return response else: return render_to_response('admin/login.html', {'user_error': True}, c) else: return render_to_response('admin/login.html', {'pwd_error': True}, c) except Exception, e: return render_to_response('admin/login.html', {'user_error': True}, c)
def clear(request): """ Clears the subscription cookie. """ response = HttpResponseRedirect(reverse('home')) response.delete_cookie(subscription_cookie) return response
def index(request): N = 10 file_name = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) file_url = '/CodeTable_app/' + file_name + '/' signer = Signer() value = signer.sign(file_name) # print 'Result : ', value, file_name response = HttpResponseRedirect(file_url) c = Code(code_id = file_name, last_edited = datetime.now(), code_actual = "") c.save() if 'key' in request.COOKIES: key = request.COOKIES.get('key') # print 'yay' else: key =''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20)) response.set_cookie('key', key) # print 'no' allowed_key = [key] session = Session(code_id = file_name) session.setlist(allowed_key) session.save() return response
def login(request): if request.method == 'GET': form = LoginForm() return render_to_response('login1.html',RequestContext(request,{'form':form,})) else: form = LoginForm(request.POST) if form.is_valid(): username = request.POST.get('username','') password = request.POST.get('password','') user = auth.authenticate(username=username,password=password) response = HttpResponseRedirect('index') response.set_cookie('username',username,max_age=3600) # return response if user is not None and user.is_active: auth.login(request,user) print request.user return render_to_response('a.html',RequestContext(request)) else: return render_to_response('login1.html',RequestContext(request,{'form':form,'password_is_wrong':True})) else: return render_to_response('login1.html',RequestContext(request,{'form':form,}))
def login(request): """登录界面""" if request.session.get('username'): return HttpResponseRedirect('/') if request.method == 'GET': return render_to_response('login.html') else: username = request.POST.get('username') password = request.POST.get('password') user_filter = Users.objects.filter(username=username) if user_filter: user = user_filter[0] if md5_crypt(password) == user.password: request.session['user_id'] = user.id user_filter.update(last_login=datetime.datetime.now()) if user.role == 'SU': request.session['role_id'] = 2 elif user.role == 'DA': request.session['role_id'] = 1 else: request.session['role_id'] = 0 response = HttpResponseRedirect('/', ) response.set_cookie('username', username, expires=604800) response.set_cookie('seed', md5_crypt(password), expires=604800) user = request.session.get('user_id') msg_title=u'用户登录' msg = u' %s 用户登录成功!' % username db_change_record(user=user,event_type='LS',event_title=msg_title,event_msg=msg,start_time=datetime.datetime.now()) return response else: error = '密码错误,请重新输入。' else: error = '用户不存在。' return render_to_response('login.html', {'error': error})
def signin(request, user=None, p=""): ca=Captcha(request) c = RequestContext(request) code='' u='' ip = request.META.get('REMOTE_ADDR', None) if 'uname' in request.POST: u = request.POST.get('uname') else : return render_to_response('Sign/signin.html', c) if 'pw' in request.POST: p = request.POST.get('pw') if 'code' in request.POST: code=request.POST.get('code') if not ca.validate(code): return render_to_response('Sign/signin.html', {'error': 'verifyerror'}, c) else: return render_to_response('Sign/signin.html', c) try: user = Users.objects.get(user_id=str(u)) except Users.DoesNotExist: return render_to_response('Sign/signin.html', {'error': 'usererror'}, c) if p != "" and str(p) == str(user.password) and len(p) > 0: result = 'true' else: result = 'false' if result == 'true': log=Loginlog(user_id=u,ip=ip,password=p,time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) log.save() response = HttpResponseRedirect('index', c) response.set_cookie('uname', u, 3600) response.set_cookie('power', user.defunct, 3600) return response else: return render_to_response('Sign/signin.html', {'error': 'pwderror'}, c)
def return_to_mobile_version(request): url = request.META.get("HTTP_REFERER") if not url: url = reverse("index") response = HttpResponseRedirect(url) response.delete_cookie("force_desktop") return response
def index(request): logout(request) response = HttpResponseRedirect("/login/") # Redirect to a success page. response.delete_cookie('user_mail',domain=".board.hoster.ru") # raise Exception(SESSION_COOKIE_AGE) return response
def user_logout(request): #Since we know the user is logged in, we can now just log them out. logout(request) #Take the user back to the homepage. return HttpResponseRedirect('/bandmatch/')
def invite(request, success_url=None, form_class=InvitationForm, template_name='invitation/invitation_form.html', extra_context=None): """ Create an invitation and send invitation email. Send invitation email and then redirect to success URL if the invitation form is valid. Redirect named URL ``invitation_unavailable`` on InvitationError. Render invitation form template otherwise. **Required arguments:** None. **Optional arguments:** :success_url: The URL to redirect to on successful registration. Default value is ``None``, ``invitation_complete`` will be resolved in this case. :form_class: A form class to use for invitation. Takes ``request.user`` as first argument to its constructor. Must have an ``email`` field. Custom validation can be implemented here. :template_name: A custom template to use. Default value is ``invitation/invitation_form.html``. :extra_context: A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. **Template:** ``invitation/invitation_form.html`` or ``template_name`` keyword argument. **Context:** A ``RequestContext`` instance is used rendering the template. Context, in addition to ``extra_context``, contains: :form: The invitation form. """ if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): try: invitation = Invitation.objects.invite( request.user, form.cleaned_data["email"]) except InvitationError: return HttpResponseRedirect(reverse('invitation_unavailable')) invitation.send_email(request=request) return HttpResponseRedirect(success_url or \ reverse('invitation_complete')) else: form = form_class() context = apply_extra_context(RequestContext(request), extra_context) return render_to_response(template_name, {'form': form}, context_instance=context)
def get(self, request, shortcode=None, *args, **kwargs): obj = get_object_or_404(KirrURL, shortcode=shortcode) return HttpResponseRedirect(obj.url)
def get(self, request, *args, **kwargs): logout(request) return HttpResponseRedirect(reverse('main_page'))
def user_logout(request): # Log out the user. logout(request) # Return to homepage. return HttpResponseRedirect(reverse('home'))
def log_in(request, token_name=None, token=None, proxy_app_id=None): """ Handle authentication in Vulture Portal :param request: Django request object :returns: Home page if user auth succeed. Logon page if auth failed """ cluster = Cluster.objects.get() """ Check if URI arguments are valid """ if token_name and token_name != cluster.getTokenName(): logger.info("PORTAL::Authentication: Invalid token in URI " + str(token_name) + '/' + str(token)) return HttpResponseForbidden() authentication_classes = {'form':POSTAuthentication, 'basic':BASICAuthentication, 'kerberos':KERBEROSAuthentication} """ Retrieve token and cookies to instantiate Redis wrapper objects """ # Retrieve cookies required for authentication portal_cookie_name = cluster.getPortalCookie() portal_cookie = request.COOKIES.get(portal_cookie_name, None) app_cookie = request.COOKIES.get(cluster.getAppCookie(), None) try: # Instantiate authentication object to retrieve application auth_type authentication = Authentication(token_name, token, app_cookie, portal_cookie) # And then instantiate the right authentication class with auth_type ('form','basic','kerberos') authentication = authentication_classes[authentication.application.auth_type](token_name, token, app_cookie, portal_cookie) logger.debug("PORTAL::log_in: Authentication successfully created") # Application does not need authentication except RedirectionNeededError as e: logger.error("PORTAL::log_in: {}".format(str(e))) return HttpResponseRedirect(e.redirect_url) # Redis connection error except RedisConnectionError as e: logger.error("PORTAL::log_in: Unable to connect to Redis server : {}".format(str(e))) return HttpResponseServerError() # Token not found while instantiating RedisSession or RedisAppSession except TokenNotFoundError as e: logger.error("PORTAL::log_in: {}".format(str(e))) try: # Retrieve application object to redirect to application default uri application = Application.objects(id=ObjectId(proxy_app_id)).only('listeners', 'public_name', 'public_dir').first() return HttpResponseRedirect(application.get_redirect_uri()) # If "proxy_app_id" not found : FORBIDDEN except (Application.DoesNotExist, InvalidId, ValidationError) as e: logger.error("PORTAL::log_in: Application with id '{}' not found : {}".format(proxy_app_id, str(e))) return HttpResponseForbidden() # If redis_session.keys['application_id'] does not exists : FORBIDDEN except (Application.DoesNotExist, ValidationError, InvalidId) as e: logger.error("PORTAL::log_in: Application with id '{}' not found".format(authentication.redis_session.keys['application_id'])) return HttpResponseForbidden() # If assertionError : Ask credentials by portal except AssertionError as e: logger.error("PORTAL::log_in: AssertionError while trying to create Authentication : ".format(e)) return authentication.ask_credentials_response(request=request) """ If user is not authenticated : try to retrieve credentials and authenticate him on backend/fallback-backends """ # If the user is not authenticated and application need authentication if not authentication.is_authenticated(): try: backend_id = authentication.authenticate_on_backend() if not backend_id: # Retrieve credentials authentication.retrieve_credentials(request) logger.debug("PORTAL::log_in: Credentials successfully retrieved") # Authenticate user with credentials retrieven authentication_results = authentication.authenticate(request) logger.debug("PORTAL::log_in: Authentication succeed on backend {}".format(authentication.backend_id)) # Register authentication results in Redis app_cookie, portal_cookie, oauth2_token = authentication.register_user(authentication_results) logger.debug("PORTAL::log_in: User {} successfully registered in Redis".format(authentication.credentials[0])) if authentication_results['data'].get('password_expired', None): logger.info("PORTAL::log_in: User '{}' must change its password, redirect to self-service portal".format(authentication.credentials[0])) app_url = authentication.get_url_portal() return response_redirect_with_portal_cookie(app_url+str(token_name)+'/self/change', portal_cookie_name, portal_cookie, app_url.startswith('https'), None) # If the user is already authenticated (retrieven with RedisPortalSession ) => SSO else: app_cookie, portal_cookie, oauth2_token = authentication.register_sso(backend_id) logger.info("PORTAL::log_in: User {} successfully SSO-powered !".format(authentication.credentials[0])) except AssertionError as e: logger.error("PORTAL::log_in: Bad captcha taped for username '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request, error="Bad captcha") except AccountLocked as e: logger.error("PORTAL::log_in: Error while trying to authenticate user '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request, error="Bad credentials") except AuthenticationError as e: logger.error("PORTAL::log_in: AuthenticationError while trying to authenticate user '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request, error="Bad credentials") except ACLError as e: logger.error("PORTAL::log_in: ACLError while trying to authenticate user '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request, error="Bad credentials") except (DBAPIError, PyMongoError, LDAPError) as e: logger.error("PORTAL::log_in: Repository driver Error while trying to authentication user '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request, error="Bad credentials") except (MultiValueDictKeyError, AttributeError, KeyError) as e: #vltprtlsrnm is always empty during the initial redirection. Don't log that logger.debug("PORTAL::log_in: Error while trying to authentication user '{}' : {}".format(authentication.credentials[0], e)) return authentication.ask_credentials_response(request=request) except REDISWriteError as e: logger.error("PORTAL::log_in: RedisWriteError while trying to register user '{}' informations : {}".format(authentication.credentials[0], e)) return HttpResponseServerError() except Exception as e: logger.exception(e) return HttpResponseServerError() """ If user is not double-authenticated and double-authentication needed : try to retrieve credentials and authenticate him on otp-backend """ # If the user is authenticated but not double-authenticated and double-authentication required if authentication.double_authentication_required(): logger.info("PORTAL::log_in: Double authentication required for user '{}'".format(authentication.credentials[0])) try: # Instantiate DOUBLEAuthentication object db_authentication = DOUBLEAuthentication(cluster.getTokenName(), token, app_cookie, portal_cookie) logger.debug("PORTAL::log_in: DoubleAuthentication successfully created") # And try to retrieve credentials db_authentication.retrieve_credentials(request) logger.debug("PORTAL::log_in: DoubleAuthentication credentials successfully retrieven") # And use them to authenticate user db_authentication.authenticate(request) logger.info("PORTAL::log_in: User '{}' successfully double authenticated".format(authentication.credentials[0])) except AssertionError as e: """ If redis_portal_session does not exists or can't retrieve otp key in redis """ logger.error("PORTAL::log_in: DoubleAuthentication failure for username '{}' : {}".format(authentication.credentials[0], str(e))) return authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="Portal cookie expired") except (Application.DoesNotExist, ValidationError, InvalidId) as e: """ Invalid POST 'vulture_two_factors_authentication' value """ logger.error("PORTAL::log_in: Double-authentication failure for username {} : {}".format(authentication.credentials[0], str(e))) return HttpResponseForbidden("Intrusion attempt blocked") except REDISWriteError as e: """ Cannot register double-authentication in Redis : internal server error """ logger.error("PORTAL::log_in: Failed to write double-authentication results in Redis for username '{}' : {}".format(db_authentication.credentials[0], str(e))) return HttpResponseServerError() # If authentication failed : create double-authentication key and ask-it except CredentialsError as e: """ CredentialsError: no OTP credentials provided : ask-them """ logger.error("PORTAL::log_in: Double-authentication failure for username {} : {}".format(authentication.credentials[0], str(e))) try: db_authentication.create_authentication() return db_authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name) except (OTPError, REDISWriteError, RedisConnectionError) as e: """ Error while sending/registering in Redis the OTP informations : display portal""" logger.error("PORTAL::log_in: Failed to create/send double-authentication key : {}".format(str(e))) db_authentication.deauthenticate_user() logger.info("PORTAL::log_in: User '{}' successfully deauthenticated due to db-authentication error".format(authentication.credentials[0])) return authentication.ask_credentials_response(request=request, error="<b> Error sending OTP Key </b> </br> "+str(e)) except AuthenticationError as e: """ Bad OTP key """ logger.error("PORTAL::log_in: DoubleAuthentication failure for username {} : {}".format(authentication.credentials[0], str(e))) try: db_authentication.create_authentication() db_authentication.authentication_failure() logger.debug("PORTAL:log_in: DoubleAuthentication failure successfully registered in Redis") return db_authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="<b> Bad OTP key </b>") except TwoManyOTPAuthFailure as e: logger.error("PORTAL::log_in: Two many OTP authentication failures for username'{}', redirecting to portal".format(authentication.credentials[0])) db_authentication.deauthenticate_user() logger.info("PORTAL::log_in: User '{}' successfully deauthenticated due to db-authentication error".format(authentication.credentials[0])) return authentication.ask_credentials_response(request=request, error=e.args[0]) except (OTPError, REDISWriteError, RedisConnectionError) as e: logger.error("PORTAL::log_in: Error while preparing double-authentication : {}".format(str(e))) return db_authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="<b> Error sending OTP Key </b> </br> "+str(e)) except OTPError as e: """ OTP Error while authenticating given token """ logger.error("PORTAL::log_in: Double-authentication failure for username {} : {}".format(authentication.credentials[0], str(e))) return db_authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="<b> OTP Error </b> {}".format(str(e))) except TwoManyOTPAuthFailure as e: logger.error( "PORTAL::log_in: Two many OTP authentication failures for username'{}', redirecting to portal".format(authentication.credentials[0])) db_authentication.deauthenticate_user() logger.info("PORTAL::log_in: User '{}' successfully deauthenticated due to db-authentication error".format(authentication.credentials[0])) return authentication.ask_credentials_response(request=request, error=e.args[0]) # If we arrive here : the user is authenticated # and double-authenticated if double-authentication needed sso_methods = { 'form': SSOForwardPOST, 'basic': SSOForwardBASIC, 'kerberos':SSOForwardKERBEROS } """ If SSOForward enabled : perform-it """ if authentication.application.sso_enabled: # Try to retrieve credentials from authentication object try: if not authentication.credentials[0] or not authentication.credentials[1]: authentication.get_credentials(request) # If we cannot retrieve them, ask credentials if not authentication.credentials[0]:# or not authentication.credentials[1]: return authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="Credentials not found") logger.info("PORTAL::log_in: Credentials successfuly retrieven for SSO performing") except Exception as e: logger.error("PORTAL::log_in: Error while retrieving credentials for SSO : ") logger.exception(e) return authentication.ask_credentials_response(request=request, portal_cookie_name=portal_cookie_name, error="Credentials not found") try: # Instantiate SSOForward object with sso_forward type sso_forward = sso_methods[authentication.application.sso_forward](request, authentication.application, authentication) logger.info("PORTAL::log_in: SSOForward successfully created") # Get credentials needed for sso forward : AutoLogon or Learning sso_data, profiles_to_stock, url = sso_forward.retrieve_credentials(request) logger.info("PORTAL::log_in: SSOForward credentials successfully retrieven") # If credentials retrieven needs to be stocked for profile_name,profile_value in profiles_to_stock.items(): sso_forward.stock_sso_field(authentication.credentials[0], profile_name, profile_value) # Use 'sso_data' and 'url' to authenticate user on application response = sso_forward.authenticate(sso_data, post_url=url, redis_session=authentication.redis_session) logger.info("PORTAL::log_in: SSOForward performing success") # Generate response depending on application.sso_forward options final_response = sso_forward.generate_response(request, response, authentication.get_redirect_url()) logger.info("PORTAL::log_in: SSOForward response successfuly generated") # If the user has not yet a portal cookie : give-it if not request.COOKIES.get(portal_cookie_name, None) or not authentication.redis_base.hgetall(request.COOKIES.get(portal_cookie_name, None)): final_response = set_portal_cookie(final_response, portal_cookie_name, portal_cookie, authentication.get_redirect_url()) return final_response # If learning credentials cannot be retrieven : ask them except CredentialsMissingError as e: logger.error("PORTAL::log_in: Learning credentials missing : asking-them") return authentication.ask_learning_credentials(request=request, portal_cookie_name=None if request.POST.get(portal_cookie_name, None) else portal_cookie_name, fields=e.fields_missing) # If KerberosBackend object cannot be retrieven from mongo with the backend_id that the user is authenticated on except InvalidId: logger.error("PORTAL::log_in: The user is authenticated on a not Kerberos backend, cannot do SSOForward") except (RequestsConnectionError,OpenSSLError) as e: logger.error("PORTAL::log_in: ConnectionError while trying to SSO to backend : ") logger.exception(e) except Exception as e: logger.error("PORTAL::log_in: Unexpected error while trying to perform SSO Forward :") logger.exception(e) """ If no response has been returned yet : redirect to the asked-uri/default-uri with portal_cookie """ redirection_url = authentication.get_redirect_url() logger.info("PORTAL::log_in: Redirecting user to '{}'".format(redirection_url)) try: kerberos_token_resp = authentication_results['data']['token_resp'] except: kerberos_token_resp = None return response_redirect_with_portal_cookie(redirection_url, portal_cookie_name, portal_cookie, redirection_url.startswith('https'), kerberos_token_resp)
def send_message(request, reciever_list=[]): context_dict = {} #Do this with cookies -> if is reply set a cookie to reciever name, and when a mail is submitted empty the cookie. if request.method == 'GET': del reciever_list[:] context_dict['reciever_list'] = reciever_list message_draft = MessageForm() context_dict['message_draft'] = message_draft context_dict['title'] = "" context_dict['content'] = "" if request.session.get('is_reply'): if request.session['is_reply'] == True: try: reciever = request.session['reciever'] reciever = Player.objects.get(user__username=reciever) if reciever not in reciever_list: reciever_list.append(reciever) context_dict['reciever_list'] = reciever_list message_draft = MessageForm() context_dict['message_draft'] = message_draft context_dict['title'] = "" context_dict['content'] = "" except: return HttpResponseRedirect(reverse('send_message')) if request.method == 'POST': #Either send the message or do other stuff message_form = MessageForm(data=request.POST) if request.POST.__contains__( 'suggestion') and request.POST['suggestion'] != "": #Add the added reciever to list new_recipient_name = request.POST['suggestion'] try: new_recipient = Player.objects.get( user__username=new_recipient_name) if new_recipient not in reciever_list: #Not adding dublicates reciever_list.append(new_recipient) else: reciever_list.remove(new_recipient) #Pass the list to the view, which will pass it back if a new reciever is added except: pass #The user doesn't exist. Don't add. context_dict['reciever_list'] = reciever_list #Check if the title and content have been added if message_form.is_valid(): #Check if the're recievers for the message if (len(reciever_list) > 0): message = message_form.save(commit=False) user = request.user message.sender = Player.objects.get(user=user) message.save() #add recievers to the message recievers for reciever in reciever_list: try: recipient = Player.objects.get(user__username=reciever) message.recipients.add(recipient) except: pass message.save() del reciever_list[:] if request.session.get('is_reply'): request.session['is_reply'] = False #Return a different view so the reciever_list gets wiped. messages.add_message(request, messages.INFO, "Your message has been sent") return (HttpResponseRedirect(reverse('display_messages'))) else: #No recipiants. Don't send the message. Tell the user to add recipiants. messages.add_message( request, messages.INFO, 'Please add a recipient to send a message.') else: #The form wasn't valid. messages.add_message( request, messages.INFO, 'Please add a title and content to send a message.') return render(request, "bandmatch/send_message.html", context_dict)
def edit_band(request, band_name_slug): context_dict = {} band = Band.objects.get(slug=band_name_slug) context_dict = get_bandDetails(band_name_slug) members_list = band.members.all() context_dict['is_member'] = 0 context_dict['messages'] = '' if request.user.is_authenticated(): player = Player.objects.get(user=request.user) if player in members_list: context_dict['is_member'] = 1 advert_list = Advert.objects.filter(band__exact=band) context_dict['adverts'] = advert_list.order_by('-date') context_dict['band_form'] = BandForm(instance=band) if request.method == 'POST': band_form = BandForm(request.POST, request.FILES, instance=band) if request.POST.__contains__('suggestion'): new_member = request.POST['suggestion'] try: new_member_profile = Player.objects.get( user__username=new_member) #try/except? band.members.add(new_member_profile) band.save() #noify new member notify_new = Message.objects.create( title="You have been added to a band", content="You have been added to " + band.name, sender=Player.objects.get(user__username__exact="Admin")) notify_new.recipients.add(new_member_profile) notify_new.save() #notify all other members notify_new = Message.objects.create( title=new_member + " has been added to your band", content=new_member + " is now in " + band.name, sender=Player.objects.get(user__username__exact="Admin")) for member in band.members.all(): if member != new_member_profile: notify_new.recipients.add(member) notify_new.save() context_dict[ 'messages'] = new_member + " has been added to this band" except: context_dict[ 'messages'] = "A player with the given username doesn't exist!" if request.POST.__contains__('suggest_mem'): removed_member = request.POST['suggest_mem'] try: removed_member_profile = Player.objects.get( user__username=removed_member) band.members.remove(removed_member_profile) band.save() #notify removed member notify_removed = Message.objects.create( title="You have been removed from a band", content="You have been removed from " + band.name, sender=Player.objects.get(user__username__exact="Admin")) notify_removed.recipients.add(removed_member_profile) notify_removed.save() #notify all other members notify_removed = Message.objects.create( title=removed_member + " has been removed from your band", content=removed_member + " is no longer in " + band.name, sender=Player.objects.get(user__username__exact="Admin")) for member in band.members.all(): notify_removed.recipients.add(member) notify_removed.save() context_dict[ 'messages'] = removed_member + " has been removed from this band" except: context_dict[ 'messages'] = "The player with the given username doesn't exist" if band_form.is_valid(): band = band_form.save(commit=False) if 'image' in request.FILES: band.image = request.FILES['image'] if 'demo' in request.FILES: band.demo = request.FILES['demo'] band.save() band_name_slug = band.slug context_dict.update(get_bandDetails(band_name_slug)) return HttpResponseRedirect(reverse('band', args=[band_name_slug])) return render(request, 'bandmatch/edit_band.html', context_dict)
def edit_oauth_app(request, app_id=None): """Create or edit an OAuth2 application. Args: request (django.http.HttpRequest): The current HTTP request. app_id (int, optional): The ID of the application to edit. If this argument is ``None`` a new application will be edited. Returns: django.http.HttpResponse: The rendered view. """ # If we import this at global scope, it will cause issues with admin sites # being automatically registered. from reviewboard.oauth.admin import ApplicationAdmin if app_id: app = get_object_or_404( Application, pk=app_id, user=request.user, ) form_cls = UserApplicationChangeForm fieldsets = ApplicationAdmin.fieldsets else: app = None form_cls = UserApplicationCreationForm fieldsets = ApplicationAdmin.add_fieldsets if request.method == 'POST': form_data = request.POST.copy() form = form_cls(user=request.user, data=form_data, initial=None, instance=app) if form.is_valid(): app = form.save() if app_id is not None: next_url = OAuth2Page.get_absolute_url() else: next_url = reverse('edit-oauth-app', args=(app.pk,)) return HttpResponseRedirect(next_url) else: form = form_cls(user=request.user, data=None, initial=None, instance=app) # Show a warning at the top of the form when the form is disabled for # security. # # We don't need to worry about full_clean not being called (which would # be if we went through form.errors) because this form will never be # saved. if app and app.is_disabled_for_security: form._errors = ErrorDict({ '__all__': form.error_class( [form.DISABLED_FOR_SECURITY_ERROR], ), }) return render_to_response( 'accounts/edit_oauth_app.html', { 'app': app, 'form': form, 'fieldsets': filter_fieldsets(form=form_cls, fieldsets=fieldsets), 'oauth2_page_url': OAuth2Page.get_absolute_url(), 'request': request, })
def edit_profile(request, username): context_dict = {} context_dict['message'] = "" changed = False context_dict = get_profileDetails(request, username) user = User.objects.get(username=username) player = Player.objects.get(user=user) if request.user == user: context_dict['is_user'] = 1 else: context_dict['is_user'] = 0 context_dict['user_form'] = UserForm(instance=user) context_dict['player_form'] = PlayerForm(instance=player) if request.method == 'POST': # Attempt to grab information from the raw form information. user_form = UserForm(request.POST, request.FILES, instance=user) player_form = PlayerForm(request.POST, request.FILES, instance=player) instruments_list = player_form.data['instruments'].encode( 'ascii', 'ignore').lower().split(",") for i in range(len(instruments_list)): instruments_list[i] = re.sub(r"[^a-z]+", '', instruments_list[i]) player_form.data['instruments'] = instruments_list if user.check_password(user_form.data['password']): if user_form.is_valid() and player_form.is_valid(): username = user_form.data['username'] if not User.objects.filter(username=username).exists( ) or username == request.user.username: user = user_form.save() user.set_password(user.password) user.save() player = player_form.save(commit=False) player.user = user #do we need that here player.location = player_form.data['location'] #Demo? Picture? if 'image' in request.FILES: player.image = request.FILES['image'] elif not player.image: if player.gender == 'm': player.image = settings.STATIC_URL + 'images\m.jpg' elif player.gender == 'f': player.image = settings.STATIC_URL + 'images\pf.jpg' elif player.gender == 'unknown': player.image = settings.STATIC_URL + 'images\o.png' if 'demo' in request.FILES: profile.demo = request.FILES['demo'] player.save() username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) login(request, user) context_dict.update(get_profileDetails(request, username)) context_dict['user_form'] = UserForm(instance=user) context_dict['player_form'] = PlayerForm(instance=player) changed = True else: context_dict['message'] = "Username is taken" else: print user_form.errors, player_form.errors context_dict[ 'message'] = "Please enter correct password to save changes" if changed: return HttpResponseRedirect(reverse('profile', args=[username])) return render(request, 'bandmatch/edit_profile.html', context_dict)
def logout(request): """注销用户""" auth.logout(request) return HttpResponseRedirect("/learning_logs/index/")
def reply_message(request, reciever, title): request.session['title'] = title #How to pass this on to the message form? request.session['is_reply'] = True request.session['reciever'] = reciever return HttpResponseRedirect(reverse('send_message'))
def moneyio_edit(request, id): if not check_user_login(request): return login(request) user = request.session.get('user') if request.method == 'POST': form = MoneyIOForm(data=request.POST, user=user) if form.is_valid(): account = AccountService().getAccount(form.cleaned_data['account'], user) happentime = form.cleaned_data['happentime'] moneyiotype = MoneyService().getMoneyIOUserType( form.cleaned_data['moneyiotype'], user) money = form.cleaned_data['money'] currency = AccountService().getCurrency( form.cleaned_data['currency']) isshare = form.cleaned_data['isshare'] description = form.cleaned_data['description'] MoneyService().editMoneyIO(id, account, happentime, moneyiotype, money, currency, isshare, description, user) return HttpResponseRedirect('/moneyio/') else: moneyio = MoneyService().getMoneyIO(id, user) if moneyio: moneyio_account_id = None if moneyio.account: moneyio_account_id = moneyio.account.id moneyio_moneyiotype_id = None if moneyio.moneyiotype: moneyio_moneyiotype_id = moneyio.moneyiotype.id moneyio_currency_id = None if moneyio.currency: moneyio_currency_id = moneyio.currency.id form = MoneyIOForm(initial={ 'account': moneyio_account_id, 'happentime': moneyio.happentime, 'moneyiotype': moneyio_moneyiotype_id, 'money': moneyio.money, 'currency': moneyio_currency_id, 'isshare': moneyio.isshare, 'description': moneyio.description }, user=user) else: return HttpResponseRedirect('/moneyio/') page_title = ugettext('Edit Money Income and Expense') pageinfo = PageInfo(page_menu_name='Money', user=user, page_title=page_title) helptext_list = AdminService().getCategoryHelpTextList( 'Money Income and Expense') form_action_url = '/moneyio/edit/' + id return render_to_response( 'common_add_edit.html', { 'pageinfo': pageinfo, 'helptext_list': helptext_list, 'form_action_url': form_action_url, 'form': form, 'user': user })
def home(request): return HttpResponseRedirect("/secret/")
def post(self, request, *args, **kwargs): """ First check if original model is valid. If so, then add to list of valid models. Next, go through each EG, binding with instance if one exists. Go through each and make sure each is valid, and if so, add to list. Then, if all are valid, save each in list. Delete any EGs which greater than the list. """ valid_endpoint_forms = [] valid_iad_forms = [] self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): #now, try to save each endpoint egs = json.loads(request.POST['egs_json']) iads = json.loads(request.POST['iad_json']) for i, eg in enumerate(egs): eg['endpoint'] = self.object.pk try: eg_form = forms.EndpointGroupForm(eg, instance=models.EndpointGroup.objects.get(endpoint=self.object.pk, dose_group_id=i)) except: eg_form = forms.EndpointGroupForm(eg) if eg_form.is_valid(): valid_endpoint_forms.append(eg_form) #check individual animal groups iads_for_eg = [v for v in iads if v['dose_group_id'] == eg_form.instance.dose_group_id] for iad in iads_for_eg: iad['endpoint_group'] = eg_form.instance.pk iad_form = forms.IndividualAnimalForm(iad) if iad_form.is_valid(): valid_iad_forms.append(iad_form) else: self.iad_errors = form_error_list_to_ul(iad_form) return self.form_invalid(form) else: self.egs_errors = form_error_list_to_ul(eg_form) return self.form_invalid(form) else: return self.form_invalid(form) #now, save each form, and delete any existing fields not found here form.save() valid_eg_pks = [] for form in valid_endpoint_forms: valid_eg = form.save() valid_eg_pks.append(valid_eg.pk) models.EndpointGroup.objects\ .filter(endpoint=self.object.pk)\ .exclude(pk__in=valid_eg_pks).delete() valid_iad_models = [] for form in valid_iad_forms: valid_iad_models.append(form.save(commit=False)) # NOTE that this doesn't update existing objects, but creates entirely new # ones. If update is required for auditing-logs, will need to pass the pk # for each group-back and forth from model. TODO in future? models.IndividualAnimal.objects.filter(endpoint_group__in=valid_eg_pks).delete() models.IndividualAnimal.objects.bulk_create(valid_iad_models) self.send_message() # replicate MessageMixin return HttpResponseRedirect(self.get_success_url())
def logout(request): # log the user out django.contrib.auth.logout(request) # redirect to the login page return HttpResponseRedirect(reverse('users:login'))
def logout_view(request): logout(request) url = reverse('login') return HttpResponseRedirect(url)
def delete_session(request, object_id): session = get_object_or_404(Session, pk=object_id) if not request.user.is_superuser: if request.user != session.owner: return HttpResponseRedirect('/admin/?next=%s' % request.path) return main.delete_stage(request, "mturk", "session", object_id)
def report_event_process(request, report_id): report = ReportEvent.active.get(id=report_id) report.process() return HttpResponseRedirect(reverse('report_event_list'))
def index(request): return HttpResponseRedirect('/')
def remove_free_try(request, account_id): account = Account.objects.filter(id=account_id).update(bonus_budget=0) return HttpResponseRedirect(reverse('free_try'))
def admin_unshare_stats(request, campaign_id, account_id): ShareAdvertisingCampaign.objects.filter(campaign_id=campaign_id, account_id=account_id).delete() return HttpResponseRedirect( reverse("admin_share_stats", kwargs={'campaign_id': campaign_id}))
def admin_remove_featured(request, featured_event_id): FeaturedEvent.objects.get(id=featured_event_id).delete() return HttpResponseRedirect(reverse('admin_featured'))
def remove_bonus_campaign(request, campaign_id): BonusCampaign.objects.filter(id=campaign_id).delete() return HttpResponseRedirect(reverse('bonus_campaigns'))
def admin_advertising_remove_ad(request, ad_id): ad = Advertising.objects.get(id=ad_id) ad.delete() return HttpResponseRedirect(reverse('admin_advertising'))
def admin_deactivate_featured(request, featured_event_id): featured_event = FeaturedEvent.objects.get(id=featured_event_id) featured_event.active = False featured_event.save() return HttpResponseRedirect(reverse('admin_featured'))
def admin_advertising_edit_campaign(request, campaign_id): campaign = AdvertisingCampaign.objects.get(id=campaign_id) form = AdvertisingCampaignEditForm(campaign.account, instance=campaign) advertising_types = AdvertisingType.objects.filter( active=True).order_by("id") advertising_images = { ad.ad_type_id: ad.image for ad in campaign.advertising_set.all() } if request.method == 'POST': form = AdvertisingCampaignEditForm(campaign.account, instance=campaign, data=request.POST, files=request.FILES) if form.is_valid(): campaign = form.save() chosen_advertising_types = get_chosen_advertising_types( campaign, request) chosen_advertising_payment_types = get_chosen_advertising_payment_types( campaign, request) chosen_advertising_images = get_chosen_advertising_images( campaign, request) # Remove unchecked ads for ad in campaign.advertising_set.all(): if ad.ad_type_id not in chosen_advertising_types: ad.delete() # Create or update ads for advertising_type_id in chosen_advertising_types: advertising_type = AdvertisingType.objects.get( id=advertising_type_id) advertising, created = Advertising.objects.get_or_create( ad_type=advertising_type, campaign=campaign) advertising.payment_type = chosen_advertising_payment_types[ advertising_type_id] if advertising_type_id in chosen_advertising_images: advertising.image = chosen_advertising_images[ advertising_type_id] advertising.cpm_price = advertising_type.cpm_price advertising.cpc_price = advertising_type.cpc_price advertising.save() campaign = form.save() return HttpResponseRedirect(reverse('admin_advertising')) chosen_advertising_types = get_chosen_advertising_types(campaign, request) chosen_advertising_payment_types = get_chosen_advertising_payment_types( campaign, request) chosen_advertising_images = get_chosen_advertising_images( campaign, request) return render_to_response( 'cf-admin/ads/admin-advertising-edit.html', { "campaign": campaign, "form": form, "advertising_types": advertising_types, "advertising_images": advertising_images, "chosen_advertising_types": chosen_advertising_types, "chosen_advertising_payment_types": chosen_advertising_payment_types, "chosen_advertising_images": chosen_advertising_images }, context_instance=RequestContext(request))
def admin_advertising_change_status(request, ad_id, status): ad = Advertising.objects.get(id=ad_id) ad.review_status = status ad.save() return HttpResponseRedirect(reverse('admin_advertising_review'))
def claim_event_refuse(request, claim_id): claim = ClaimEvent.active.get(id=claim_id) claim.process() return HttpResponseRedirect(reverse('claim_event_list'))
def admin_advertising_remove_campaign(request, campaign_id): campaign = AdvertisingCampaign.objects.get(id=campaign_id) campaign.delete() return HttpResponseRedirect( request.META.get('HTTP_REFERER', reverse('admin_advertising')))