Hi I have written an app using storyboards and decided to look at writing it in SwiftUI. So far so good. When it comes to showing (or not showing the login page) based on the users logged in status what is the best way to achieve this? Most examples just show the login page but never do checks if the user is already logged in.
For simplicity, you can use UserDefaults to check if the user already logged in or not. Or you can use Core Data to keep your record.
This is an example code using UserDefaults:
If the user has logged in, you can declare this when user has
entered the login data and enter
let defaults = UserDefaults.standard
defaults.setValue(true, forKey: "skipTutorialPages")
defaults.synchronize()
In the AppDelegate, add this to didFinishLaunchingWithOptions
let defaults = UserDefaults.standard
let skipTutorialPages = defaults.bool(forKey: "skipLoginPages")
if skipLoginPages
{
// Skip to your login pages
}
Related
I want an effect to be applied when a user is entering my website. So therefore I want to check for when a user is coming from outside my website so the effect isnt getting applied when the user is surfing through different urls inside the website, but only when the user is coming from outside my website
You can't really check for where a user has come from specifically. You can check if the user has just arrived on your site by setting a session variable when they load one of your pages. You can check for it before you set it, and if they don't have it, then they have just arrived and you can apply your effect. There's some good examples of how sessions work here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions
There's a couple of ways to handle this. If you are using function based views, you can just create a separate util function and include it at the top of every page, eg,
utils.py
def first_visit(request):
"""returns the answer to the question 'first visit for session?'
make sure SESSION_EXPIRE_AT_BROWSER_CLOSE set to False in settings for persistance"""
if request.session['first_visit']:
#this is not the first session because the session variable is used.
return False
else:
#This is the first visit
...#do something
#set the session variable so you only do the above once
request.session[first_visit'] = True
return True
views.py
from utils.py import first_visit
def show_page(request):
first_visit = first_visit(request)
This approach gives you some control. For example, you may not want to run it on pages that require login, because you will already have run it on the login page.
Otherwise, the best approach depends on what will happen on the first visit. If you want just to update a template (eg, perhaps to show a message or run a script on th epage) you can use a context processor which gives you extra context for your templates. If you want to interrupt the request, perhaps to redirect it to a separate page, you can create a simple piece of middleware.
docs for middleware
docs for context processors
You may also be able to handle this entirely by javascript. This uses localStorage to store whether or not this is the user's first visit to the site and displays the loading area for 5 seconds if there is nothing in localStorage. You can include this in your base template so it runs on every page.
function showMain() {
document.getElementByID("loading").style.display = "none";
document.getElementByID("main").style.display = "block";
}
const secondVisit = localStorage.getItem("secondVisit");
if (!secondVisit) {
//show loading screen
document.getElementByID("loading").style.display = "block";
document.getElementByID("main").style.display = "none";
setTimeout(5000, showMain)
localStorage.setItem("secondVisit", "true" );
} else {
showMain()
}
I have a ReactJS component inside a Django template, where a user clicks on a checkout button, posts the item_code and gets redirected to checkout:
onCheckout = () => {
fetch("/onCheckout/", {
method: "POST",
body: JSON.stringify({'item': this.props.item_info.code})
}).then(window.location.replace("/checkout"))
}
A Django view receives the request and stores it in a session.
def onCheckout(request):
if request.method == "POST":
items = request.session.get('items', [])
new_item = json.loads(request.body.decode('utf-8'))['item']
items.append(new_item)
request.session['items'] = items
I am having a issue with storing data in the session. After the first item gets stored correctly in the array, and I then checkout on a second item, the items array starts acting up:
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) new_item
'5213G-001'
(Pdb) items
['15130BC.ZZ.8042BC.01']
(Pdb) items
['5213G-001']
If I try to access request.session['item'] from any other view function, I get a KeyError.
I am fairly new to Django, any help would be appreciated. Also, I would like to know if there are better alternatives to accomplish the above.
Sessions Config
settings.SESSION_ENGINE = 'django.contrib.sessions.backends.db'
settings.SESSION_CACHE_ALIAS = 'default'
settings.CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
Some reading on change detection for Django sessions: https://docs.djangoproject.com/en/2.0/topics/http/sessions/#when-sessions-are-saved
Based on your code, it appears to me that the change detection should happen. However, let's try to brute force this, can you add the following line as the last line of your code: request.session.modified = True - see if this fixes your issue?
Update: some basic checks
Can you verify the following
Check if your db backend is configured priestly
If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.
Check if your session Middleware is enabled
Sessions are implemented via a piece of middleware. The default settings.py created by django-admin startproject has SessionMiddleware activated. To enable session functionality, edit the MIDDLEWARE_CLASSES setting and make sure it contains 'django.contrib.sessions.middleware.SessionMiddleware'.
Update 2: Test the session
Maybe modify a style existing endpoint as follows and see if you are able to store values and persist them in session :
test_keys = request.session.get('test_keys', [])
test_keys.append(random.randint())
request.session['test_keys'] = test_keys
return Response(request.session.get('test_keys', []))
You should see that each time you hit the api, you get a list with one new integer in it in addition to all past values. Lmk how this goes.
Is there any way to check if the admin is logged in at front-end in Opencart? I would like to show a notice bar with content "Admin Logged In" when I open my store.
To be precise, in the controller of my module, i would like to add:
$data['admin_logged'] = some_function;
and when I echo it in my .tpl to get 1 if admin is logged in or 0 if not.
Actually i got it done by:
// Check if admin is logged in - frontend
$this->user = new User($this->registry);
$data['admin_logged']=($this->user->isLogged())
Now you can use if($admin_logged) /* do stuff here */
Thank you anyway
Yes, you can check it, using the User class:
$data['admin_logged'] = $this->user->isLogged() ? 1 : 0;
Im new to Pimcore and I'm trying to use Zend Auth with pimcore objects. I assume this is a wise approach and it seems more or less logical to me. I've done the initial setup of the object within pimcore itself. Now I'm trying to work out how to connect it to zend auth, that is, for example when I extend zend auth and have my own login function, how do i check if the login is valid in my object?
Does someone have a guide that I could use on this perhaps? otherwise if someone could point me in the right direction that would be great
Jason
You can follow this guide: http://www.pimcore.org/forum/discussion/419/zend_auth_adapter-for-pimcore-objects , it worked well for me.
UPDATE: The link above has been taken away, so laying out the full answer here:
First, you need to put ObjectAdapter.php in website/lib/Website/Auth/ObjectAdapter.php .
Then, this is how you login your user (use as you prefer, for example in your controller init function):
$authAdapter = new Website_Auth_ObjectAdapter('Object_Users', 'o_key', 'password', '/users/');
// The parameters are 1. object you keep your users in, 2. the field that contains their username (I use o_key which is the name of the object itself, to keep unique usernames without fuzz), and 3. the password field in the user object.
// Setup auth adapter
$authAdapter->setIdentity($username)->setCredential($password);
$auth = Zend_Auth::getInstance();
// Authenticate
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// Login successful
} else {
// Login failed
}
To check for a login-session, use:
$this->auth = Zend_Auth::getInstance();
if ($this->auth->hasIdentity()) {
// We have a login session (user is logged in)
$userObject = $this->auth->getIdentity();
}
To kill a session:
Zend_Auth::getInstance()->clearIdentity();
This is my second foray into Ajax and I'm not quite sure how to pull this off.
So I have a modal window that opens when an anonymous user attempts to perform a certain task. The window contains a user signup form that I then $.post to my Django login view. If username/password are valid, user is logged in an status code of 1 is returned as the response. IF not, a status of 0 is returned.
When I try to do it outside of js, it works. However, within my script, it fails. I think that it has to do with the response content_type and how I'm interpreting it. I'm not sure.
def login_async(request):
if request.method=='POST' and len(request.POST['username'])<20 and len(request.POST['password'])<20:
username=request.POST.get('username', '') #probably need to script tags here
password=request.POST.get('password', '')
user=auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request,user)
status=1
response=HttpResponse()
response['Content_Type']="text/html"
response.write(status)
return response
else:
status=0
response=HttpResponse()
response['Content_Type']="text/html"
response.write(status)
return response
$('input#login').click(function(event){
$.post("/login_async/", {username:$('input[name=username]').val(), password:$('input[name=password]').val()}, //could also use $(this).serialize() here to capture all form inputs
function(data){
if(data==1){
$('#login').dialog("close");
}
});
});
What's the problem here? I initially tried to return the response as JSON but I couldn't figure out how to make serialize.serializers("json",status) work. I kept getting an error.
One last question...
If I get a valid status (user is signed in), that will influence the behavior of modal windows on the page. The modal windows open based on logged in status. If a user is signed in, one set of windows open on a click event, and vice versa. This toggle is dependent on Django context {% user.is_authenticated %}.
That context renders only once right, on page load? Can I do anything to communicate the status change to the modal windows that's secure from easy hacks?
It should be Content-Type. If that doesn't fix your problem, try adding a dataType parameter at the end of the $.post call.
$.post("/login_async/", {}, function(data){
// fancy stuff
}, "html");
Yeah I thought it over more and realized that I should just unbind the existing click event handlers on the modal windows and then bind new event handlers depending on the ajax response.
I love programming