cant coonect flask-app to keycloak client - flask

I have a small app with flask.
I want to connect it to keycloak server using docker-compose
here is the main code:
keycloak = KeycloakOpenID(server_url='http://localhost:8080/auth/',
client_id='guess-app',
realm_name='guess',
client_secret_key='')
# Define views
#app.route('/')
def index():
if keycloak.token:
return redirect('/home')
else:
return (keycloak.auth_url())
#app.route('/logout')
def logout():
keycloak.logout()
return redirect('/')
# Handle redirect from Keycloak
#app.route('/callback')
def callback():
keycloak.callback()
return redirect('/home')
and here is the screenshot from the client page in keycloak:
screenshot
the connection didn't work and im not getting the login screen and I really don't understand why

Related

how can I make specific routes accessible only for specific users in flask?

I'm using flask and mongodb, I have a user table where it has a boolean attribute is_admin and I want to make specefic views and routes accessible only for admin users, I have read about Flask-admin and Flask-Principal but they seemed complicated to me since I am very beginner and its just a school project, is there a way to achieve that without using Flask-Principle?.
for example I want only admin to access this route
#users.route('/add', methods=['GET', 'POST'])
#login_required
def add():
form = UserForm(request.form)
if request.method == 'POST':
if form.validate():
user = User(username=form.username.data, password= generate_password_hash(form.password.data), vorname=form.vorname.data, nachname=form.nachname.data, geburtsdatum=form.geburtsdatum.data, email=form.email.data, admin=form.admin.data, aktiv=form.aktiv.data)
user.save()
flash("user added successfully.", "success")
return redirect(url_for('.index'))
return render_template('form.html', users=users, form=form, info=session)
If I understand your question correctly, something like this might be what you're looking for:
from flask_login import current_user
# use the suggested pattern to login user then..
#users.route('/add', methods=['GET', 'POST'])
#login_required
def add():
if not current_user.is_admin:
abort(403)
# rest of your route
This will return HTTP 403 - Forbidden
as per wikipedia:
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.

DJANGO ALL AUTHEMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL

I am trying to have two different redirects...one for normal login and another for redirect after email confirmation
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/profile'
LOGIN_REDIRECT_URL = '/'
But when I enable login, AUTHENTICATED REDIRECT goes to LOGIN_REDIRECT but when I disable Login it goes to the EMAIL_CONFIRMATION_REDIRECT route.
When I try printing the adapter settings for email_confirmation redirect url below it shows only the LOGIN_REDIRECT
def get_email_confirmation_redirect_url(self, request):
""" The URL to return to after successful e-mail confirmation. """
if request.user.is_authenticated:
if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
return \
app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
else:
return self.get_login_redirect_url(request)
else:
return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL
I tried overriding this get_email_confirmation_redirect_url in the adapter but still wont work. It is not picking the REDIRECT before I login and reverify.
Since ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/profile' was not working if the user is not logged in, I decided to override DefaultAccountAdapter in Django Allauth. My login was that if the time the user joined the app and the time logged in exceeds a certain threshold, then the redirection would be different. So I created an adapter in my users app as below:
class AccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
expiry = 90 #seconds
assert request.user.is_authenticated
if (request.user.last_login - request.user.date_joined).seconds < expiry:
url = 'profile/'
else:
url = settings.LOGIN_REDIRECT_URL
return resolve_url(url)
I then passed this adapter in my settings.py

Flask Python URL Stacking

I am currently trying to host a simple login form on a2hosting using Flask but im having issues with urls redirecting and stacking on top of each other.
For example I have www.site.com/index ask for a login or to create one. but when a user logs in or tries to register, the url will do something like www.site.com/login/index instead of just redirecting to /index
Here is a snippet from my routes code
#app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
#submit to database
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
route snippet
#app.route('/')
#app.route('/index')
def index():
# variable containing a test text
return render_template('home.html', title='Home')
Please send code snippet for index routing - #app.route('/index') ...

Flask-login redirecting back to login page

I am writing a simple flask app using flask-login and flask-mongoengine, everything was working fine until I updated all of the python plugins that I need for the project. Now flask won't log me in. When I login and the form is validated, it returns me to the login page, with the url: http://localhost:5000/auth/login?next=%2Findex ... I think the %2F might have something to do with the issue.
Here is my login view:
#bp.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = LoginForm()
if form.validate_on_submit():
user = User.objects(username__exact=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash(_('Invalid username or password'))
return redirect(url_for('auth.login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('main.index')
return redirect(next_page)
return render_template('auth/login.html', title=_('Sign In'), form=form)
I'm using WTForms and I can confirm that the form action=""
This is adapted from the flask megatutorial, but I'm using MongoDB.
Problem solved!
When I was converting the app from using SQL to MongoDB, I incorrectly made the load_user function like:
#login.user_loader
def load_user(username):
return User.objects(username__exact=username).first()
But in reality the load_user function needs to accept the id field as an interface, so the function should look like:
#login.user_loader
def load_user(id):
return User.objects.get(id=id)

Django, How to detect login success event?

I have built a crm system using django, and I want to record the login information(the login user, the login time, the login ip address) of the successfully-logged-in user, how to detect the successfully logging event? So I can save the login_record table.My view code is like this:
def custom_login(request, **kwargs):
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL, **kwargs)
else:
return login(request, **kwargs)