Register, Login, Logout with django class based views - python-3.8

I am trying to make an authentication system with django class based views
What I have tried so far:
This is my views.py file:
from django.shortcuts import render
from django.views import generic
from .forms import UserRegistrationForm
from django.urls import reverse_lazy
class UserCreationView(generic.CreateView):
form_class = UserRegistrationForm
template_name = 'registration/register.html'
success_url = reverse_lazy('login')
This is forms.py file
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2',)
widgets = {
'email': forms.EmailInput(attrs={'class':'input', 'placeholder': 'Email Address'})
}
This the urls.py file:
from django.urls import path
from .views import UserCreationView
urlpatterns = [
path('register/', UserCreationView.as_view(), name = 'register'),
]
Other urls.py file(urls.py file present in project folder)
path('users/', include(urls)),
path('users/', include('authentication.urls')),
The problem with this code is Whenever I login I can still login and register by going to the login url(login url in this case:http://localhost:8000/users/login/), How can I restrict user to log in again

I found out that the default LoginView() class on
django.contrib.auth import views
has a boolean attribute called
redirect_authenticated_user
And I believe this is what you are looking for.
Just look for class LoginView in https://docs.djangoproject.com/en/3.2/topics/auth/default/ and you will see it.

Related

How to write url pattern for login() with an template name argument in django4

TypeError at /users/login/
login() got an unexpected keyword argument 'template_name'
from django.contrib.auth import login
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
# Login page
path('login/', login, {'template_name': 'login.html'}, name='login'),
# Registering page
path('register/', views.register, name='register'),
]
I tried this url pattern but it gives me TypeError...
Any other way of passing template name in django login() function url pattern

How do I create a module above App module in angular 12?

i have a Login module which contains login.html.
i want login to be the default module and login.html as the default opening page.
in main.ts file you will have something like this
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
replace this with
import { LoginModule } from './login.module';
platformBrowserDynamic().bootstrapModule(LoginModule);

Authenticating a dash app within a flask app using firebase

I am using firebase authentication to authenticate my flask app. This works perfectly for all the flask views. However I can't manage for this to work with the dash view. I have attached below a very simple minimal example without firebase where I have one flask page hello and one dashboard page. I wrap the views with the decorator check_token() which currently should just redirect all views to the login page. This works for the flask views /hello and /, but not for the dash view dashboard.
Confusingly, the decorator isn't even being run for the dashboard view as evidenced by the print statements.
routes.py
from flask import current_app as app
def check_token(f):
print("RUNNING check_token")
def wrap(*args,**kwargs):
print("RUNNING wrap")
token = request.cookies.get("token")
if not token:
return redirect(url_for('login'))
return f(*args, **kwargs)
wrap.__name__ = f.__name__
return wrap
#app.route('/')
#app.route('/hello')
#check_token
def hello():
return 'hello world!'
#app.route('/login')
def login():
return "This is the login page"
#app.route('/dashboard')
#check_token
def render_dashboard():
return redirect('/dash1')
application.py
from dash import Dash
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
import dash_html_components as html
from flask import Flask, request,render_template, url_for, redirect
def init_dash(dash_app1):
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for dashboards')])
return dash_app1
def init_app():
server = Flask(__name__)
dash_app1 = Dash(__name__, server = server, url_base_pathname='/dashboard/' )
dash_app1 = init_dash(dash_app1)
with server.app_context():
import routes
app = DispatcherMiddleware(server, {
'/dash1': dash_app1.server,
})
return app
if __name__ == "__main__":
run_simple('0.0.0.0', 8090, init_app(), use_reloader=True, use_debugger=True)
Any help would be much appreciated! I have been struggling for the last two days to try and get this work
I finally got it to work with this code snippet that I found from an obscure github thread
from dash import Dash
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
import dash_html_components as html
from flask import Flask, request,render_template, url_for, redirect
from utils import check_token
def protect_views(app,bpn):
for view_func in app.server.view_functions:
print(view_func)
if view_func.startswith(bpn):
app.server.view_functions[view_func] = check_token(app.server.view_functions[view_func])
return app
def init_dash(dash_app1):
dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for dashboards')])
return dash_app1
def init_app():
server = Flask(__name__)
bpn = '/dashboard/'
dash_app1 = Dash(__name__, server = server, url_base_pathname=bpn )
dash_app1 = init_dash(dash_app1)
dash_app1 = protect_views(dash_app1, bpn)
with server.app_context():
# dash_app1 = protect_views(dash_app1)
import routes
app = DispatcherMiddleware(server, {
'/dash1': dash_app1.server,
})
return app
if __name__ == "__main__":
run_simple('0.0.0.0', 8090, init_app(), use_reloader=True, use_debugger=True)

How to use POST method to list data in RA

I have tried to use ra-jsonapi-client to make POST call to my api and list retrieved data. Is it possible? My code is
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Admin, Resource, ListGuesser } from 'react-admin';
const dataProviders = [
{ dataProvider: jsonapiClient('http://my.api.com:1234'), resources: ['get_info'] }]
const App = () => (
<Admin dataProvider={dataProviders}>
<Resource name="get_info" list={ListGuesser} />
</Admin>
);
export default App;
I know how to pass resource to dataprovider, but I can't figure out how to pass data and type in Resource. Is it possible or I need to write my own dataprovider?
I am pretty new to RA.
Thank you
You need to write your own custom data provider. A data provider abstracts the details of your API away from react-admin.
React admin doesn't care what you need to do to get data from your API.

Mailbox not in the scope

I am trying to create a frontend using elm with elm-router in order to manage the routing.
I have this main file :
-- Main.elm
import Router exposing (Route, match, (:->))
import History exposing (path)
import Routing as Routing exposing (route)
import Signal exposing ((<~))
import Html exposing (Html)
import Signal exposing (Mailbox, mailbox, Signal)
import Task exposing (Task)
import Test as Test exposing (pathChangeMailbox)
main : Signal Html
main = route <~ path
port runTask : Signal (Task error())
port runTask =
pathChangeMailbox.signal
This module to handle a mailbox. I could use a mailbox by page but it's ugly so I tried make a module to handle all the common code.
module Test where
import Signal exposing (Mailbox, mailbox, Signal)
import Task exposing (Task)
pathChangeMailbox : Mailbox (Task error ())
pathChangeMailbox = mailbox (Task.succeed())
I also have a module Routing to list the route and associate action to them.
And here is the module to handle the menu, and so the navigation.
module Menu where
import Html exposing (a, text, Html, div)
import Html.Events exposing (onClick)
import Task exposing (Task)
import History exposing (setPath)
import Test as Test exposing (pathChangeMailbox)
display : String -> Html
display _ =
div []
[
a []
[ onClick Test.pathChangeMailbox.address (setPath "/CV.elm") ]
[ text "Mon CV" ]
]
When I try to run the program I got the following error :
Error in .\src\Menu.elm:
Error on line 14, column 22 to 47:
Could not find variable 'Test.pathChangeMailbox.address'.
Looks like the prefix 'Test.pathChangeMailbox' is not in scope. Is it spelled correctly?
Is it imported correctly?
You can read about how imports work at the following address:
Do you have anyidea, why even if I import the Test module it's keep saying that Test.pathChangeMailbox is not in scope ?
Edit : Add Routing.elm
module Routing where
import Html exposing (Html, div, text, br)
import Signal exposing (Mailbox, mailbox, Signal)
import Task exposing (Task)
import Router exposing (match, (:->), Route)
-- Import displays
import CV as CV exposing (display)
import Home as Home exposing (display)
route : Route Html
route = match
[
"/src/Main.elm" :-> Home.display
, "/CV.elm" :-> CV.display
] display404
display404 : String -> Html
display404 url =
div []
[
text "Erreur 404"
, br [] []
, text ("url : " ++ url ++ " not found.")
]
I think you've found a bug here. You should file an issue.
EDIT: good job :) Summary of the link: The problem comes from mixing the . used for qualified module access and record access.
Here's a workaround for now, import the name unqualified and use it unqualified. Note I also removed an extra []:
## -4,13 +4,13 ## import Html exposing (a, text, Html, div)
import Html.Events exposing (onClick)
import Task exposing (Task)
import History exposing (setPath)
import Test as Test exposing (pathChangeMailbox)
display : String -> Html
display _ =
div []
[
- a []
- [ onClick Test.pathChangeMailbox.address (setPath "/CV.elm") ]
+ a
+ [ onClick pathChangeMailbox.address (setPath "/CV.elm") ]
[ text "Mon CV" ]
]
(Menu.elm)