Compare commits

...

21 Commits

Author SHA1 Message Date
Xamora
af9595c447 Don't merge, it's prototypal 2023-11-30 16:36:21 +01:00
c2b6dbb989 api: add: edit accounts 2023-11-30 14:03:38 +01:00
086c20bddc change delete method in tests 2023-11-30 13:41:31 +01:00
a9cdde963d update url in tester 2023-11-30 13:40:04 +01:00
3403577c3e update test url 2023-11-30 13:39:22 +01:00
5d8005df44 remove settilte on child class 2023-11-30 13:05:46 +01:00
65a027014b chore: rename classs 2023-11-29 22:51:57 +01:00
bf3393e9a9 rename view 2023-11-29 20:56:32 +01:00
9ae0dd0e28 bozo 2023-11-29 20:03:48 +01:00
d64e62101a clean: remove bozo import 2023-11-29 20:00:22 +01:00
84a5a592ca add: Abstract class to simplifie the code,
AbstractRedirectView,
AbstractAuthentificateView
AbstractUnAuthentificateView
2023-11-29 19:55:44 +01:00
a6666b889f use replace ws by wss 2023-11-29 19:20:12 +01:00
9947ea37e2 Merge branch 'Chatte' into feat/accounts 2023-11-29 18:36:08 +01:00
7e34f883aa fix: click on loggin protected do not change
history
2023-11-29 17:04:00 +01:00
07d06253ba opti: do not execute postInit if getHtml is null 2023-11-29 16:19:17 +01:00
d5e692449b fix: move code to not render html when not needed 2023-11-29 16:10:55 +01:00
6dc0293455 fix: connexion 2023-11-29 16:05:49 +01:00
b5b54a98ba fix: de golmon 2023-11-27 19:16:30 +01:00
25721bdda8 add: home 2023-11-27 19:15:15 +01:00
27044e9bdb add register button 2023-11-27 19:13:47 +01:00
3f3ab52a09 use post init to onclick 2023-11-27 19:11:15 +01:00
32 changed files with 338 additions and 146 deletions

View File

@ -1,7 +0,0 @@
from rest_framework.serializers import Serializer, CharField
class ChangePasswordSerializer(Serializer):
current_password = CharField()
new_password = CharField()

View File

@ -1,4 +1,4 @@
from .register import *
from .login import *
from .change_password import *
from .edit import *
from .delete import *

View File

@ -1,31 +0,0 @@
from django.test import TestCase
# Create your tests here.
from django.test.client import Client
from django.http import HttpResponse
from django.contrib.auth.models import User
import uuid
class ChangePasswordTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/accounts/change_password"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
self.new_password: str = str(uuid.uuid4())
User.objects.create_user(username = self.username, password = self.password)
def test_normal(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.post(self.url, {"current_password": self.password, "new_password": self.new_password})
response_text: str = response.content.decode('utf-8')
self.assertEqual(response_text, '"password changed"')
def test_nologged(self):
response: HttpResponse = self.client.post(self.url, {"current_password": self.password, "new_password": self.new_password})
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'detail': 'Authentication credentials were not provided.'})

View File

@ -11,7 +11,7 @@ class DeleteTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/accounts/delete"
self.url = "/api/accounts/delete"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
@ -21,7 +21,7 @@ class DeleteTest(TestCase):
def test_normal_delete(self):
response: HttpResponse = self.client.post(self.url)
response: HttpResponse = self.client.delete(self.url)
response_text: str = response.content.decode("utf-8")
self.assertEqual(response_text, '"user deleted"')

49
accounts/tests/edit.py Normal file
View File

@ -0,0 +1,49 @@
from django.test import TestCase
# Create your tests here.
from django.test.client import Client
from django.http import HttpResponse
from django.contrib.auth.models import User
import uuid
class EditTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/accounts/edit"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
self.new_password: str = str(uuid.uuid4())
User.objects.create_user(username = self.username, password = self.password)
def test_normal(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "new_password": self.new_password, "username": "bozo"}, content_type='application/json')
response_text: str = response.content.decode('utf-8')
self.assertEqual(response_text, '"data has been alterate"')
def test_invalid_current_password(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": "bozo", "new_password": self.new_password, "username": "bozo"}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {"current_password":["Password is wrong."]})
def test_invalid_new_username_blank(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "username": " "}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'username': ['This field may not be blank.']})
def test_invalid_new_username_char(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "username": "*&"}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'username': ['Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.']})
def test_nologged(self):
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "new_password": self.new_password}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'detail': 'Authentication credentials were not provided.'})

View File

@ -10,7 +10,7 @@ class LoginTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/accounts/login"
self.url = "/api/accounts/login"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())

View File

@ -8,7 +8,7 @@ class LoginTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/accounts/logout"
self.url = "/api/accounts/logout"
self.client.login()

View File

@ -11,7 +11,7 @@ class RegisterTest(TestCase):
def setUp(self):
self.client = Client()
self.url: str = "/accounts/register"
self.url: str = "/api/accounts/register"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())

View File

@ -1,12 +1,13 @@
from django.urls import path
from .views import register, login, logout, delete, change_password
from .views import register, login, logout, delete, edit, logged
urlpatterns = [
path("register", register.RegisterView.as_view(), name="register"),
path("login", login.LoginView.as_view(), name="login"),
path("logout", logout.LogoutView.as_view(), name="logout"),
path("logged", logged.LoggedView.as_view(), name="logged"),
path("delete", delete.DeleteView.as_view(), name="delete"),
path("change_password", change_password.ChangePasswordView.as_view(), name="change_password")
path("edit", edit.EditView.as_view(), name="change_password")
]

View File

@ -1,25 +0,0 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from django.http import HttpRequest
from django.contrib.auth import login
from rest_framework.authentication import SessionAuthentication
from django.contrib.auth.models import User
from ..serializers.change_password import ChangePasswordSerializer
class ChangePasswordView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def post(self, request: HttpRequest):
data = request.data
serializer = ChangePasswordSerializer(data=data)
if serializer.is_valid(raise_exception=True):
user: User = request.user
if (user.check_password(data['current_password']) == 0):
return Response({'current_password': "The password is not right."}, status=status.HTTP_200_OK)
user.set_password(data["new_password"])
return Response('password changed', status=status.HTTP_200_OK)

View File

@ -7,6 +7,6 @@ from rest_framework.authentication import SessionAuthentication
class DeleteView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def post(self, request: HttpRequest):
def delete(self, request: HttpRequest):
request.user.delete()
return Response("user deleted", status=status.HTTP_200_OK)

42
accounts/views/edit.py Normal file
View File

@ -0,0 +1,42 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from django.http import HttpRequest
from django.contrib.auth import login
from rest_framework.authentication import SessionAuthentication
from django.contrib.auth.models import User
import re
class EditView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def patch(self, request: HttpRequest):
data: dict = request.data
current_password: str = data.get("current_password")
if (current_password is None):
return Response({"current_password": ["This field may not be blank."]})
user_object = request.user
if (user_object.check_password(current_password) == False):
return Response({"current_password": ["Password is wrong."]})
new_username = data.get("username", user_object.username)
if (new_username != user_object.username):
if (User.objects.filter(username=new_username).exists()):
return Response({"username": ["A user with that username already exists."]})
if (set(new_username) == {' '}):
return Response({"username": ["This field may not be blank."]})
if (re.search('^([a-z]||\@||\+||\-||\_)+$', new_username) is None):
return Response({"username":["Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters."]})
new_password: str = data.get("password")
if (new_password is not None):
user_object.set_password(new_password)
user_object.save()
return Response("data has been alterate")

16
accounts/views/logged.py Normal file
View File

@ -0,0 +1,16 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from django.http import HttpRequest
from django.contrib.auth import login
from rest_framework.authentication import SessionAuthentication
from ..serializers.login import LoginSerializer
class LoggedView(APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = (SessionAuthentication,)
def get(self, request: HttpRequest):
return Response(str(request.user.is_authenticated), status=status.HTTP_200_OK)

View File

@ -8,6 +8,6 @@ from rest_framework.authentication import SessionAuthentication
class LogoutView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def post(self, request: HttpRequest):
def get(self, request: HttpRequest):
logout(request)
return Response("user unlogged", status=status.HTTP_200_OK)

View File

@ -1,26 +1,27 @@
import { Accounts } from "./accounts.js";
function extract_token(response)
{
let cookies = response.headers.get("set-cookie");
if (cookies == null)
return null;
token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
return token;
}
class Client
{
constructor(url)
{
this._url = url;
this.accounts = new Accounts(this);
this._token = undefined;
this._logged = undefined;
}
get isAuthentificate()
async isAuthentificate()
{
return this.token != undefined;
if (this._logged == undefined)
this.logged = await this._test_logged();
return this.logged;
}
async _get(uri)
{
let response = await fetch(this._url + uri, {
method: "GET",
});
return response;
}
async _post(uri, data)
@ -32,16 +33,32 @@ class Client
},
body: JSON.stringify(data),
});
let token = extract_token(response);
if (token != null)
this.token = token;
return response;
}
async login(username, password)
{
let response = await this._post("/api/accounts/login", {username: username, password: password})
return response
let data = await response.json();
if (data == "user connected")
{
this.logged = true;
return null;
}
return data;
}
async logout()
{
await this._get("/api/accounts/logout");
this.logged = false;
}
async _test_logged()
{
let response = await this._get("/api/accounts/logged");
let data = await response.json();
return data === "True";
}
}

View File

@ -3,10 +3,14 @@ import Dashboard from "./views/Dashboard.js";
import Posts from "./views/Posts.js";
import PostView from "./views/PostView.js";
import Settings from "./views/Settings.js";
import Search from "./views/Search.js";
import Chat from "./views/Chat.js";
import HomeView from "./views/HomeView.js";
import RegisterView from "./views/accounts/RegisterView.js";
import LogoutView from "./views/accounts/LogoutView.js";
import { Client } from "./api/client.js";
import RegisterView from "./views/accounts/RegisterView.js";
import AbstractRedirectView from "./views/AbstractRedirectView.js";
let client = new Client(location.protocol + "//" + location.host)
@ -23,27 +27,30 @@ const getParams = match => {
}));
};
const navigateTo = url => {
history.pushState(null, null, url);
router();
const navigateTo = async (uri) => {
if (await router(uri) === 0)
history.pushState(null, null, uri);
};
const router = async () => {
const router = async (uri = "") => {
const routes = [
{ path: "/", view: Dashboard },
{ path: "/posts", view: Posts },
{ path: "/posts/:id", view: PostView },
{ path: "/settings", view: Settings },
{ path: "/login", view: LoginView },
{ path: "/logout", view: LogoutView },
{ path: "/register", view: RegisterView },
{ path: "/search", view: Search },
{ path: "/chat", view: Chat },
{ path: "/home", view: HomeView },
];
// Test each route for potential match
const potentialMatches = routes.map(route => {
return {
route: route,
result: location.pathname.match(pathToRegex(route.path))
result: uri.match(pathToRegex(route.path))
};
});
@ -52,18 +59,29 @@ const router = async () => {
if (!match) {
match = {
route: routes[0],
result: [location.pathname]
result: [uri]
};
}
if (lastView !== undefined)
await lastView.leavePage();
const view = new match.route.view(getParams(match));
if (view instanceof AbstractRedirectView && await view.redirect())
return 1;
lastView = view;
document.querySelector("#app").innerHTML = await view.getHtml();
let content = await view.getHtml();
if (content == null)
return 1;
view.setTitle();
document.querySelector("#app").innerHTML = content
await view.postInit();
return 0;
};
window.addEventListener("popstate", router);
@ -72,11 +90,10 @@ document.addEventListener("DOMContentLoaded", () => {
document.body.addEventListener("click", e => {
if (e.target.matches("[data-link]")) {
e.preventDefault();
navigateTo(e.target.href);
navigateTo(e.target.href.slice(location.origin.length));
}
});
router();
router(location.pathname);
});
export { client }
export { client, navigateTo }

View File

@ -0,0 +1,18 @@
import { client, navigateTo } from "../index.js";
import AbstractRedirectView from "./AbstractRedirectView.js";
export default class extends AbstractRedirectView{
constructor(params, title) {
super(params, title, "/login");
}
async redirect()
{
if (await client.isAuthentificate() === false)
{
navigateTo(this.redirect_url);
return 1;
}
return 0;
}
}

View File

@ -0,0 +1,16 @@
import { client, navigateTo } from "../index.js";
import AbstractRedirectView from "./AbstractRedirectView.js";
export default class extends AbstractRedirectView{
constructor(params, title, url) {
super(params, title, url);
}
async redirect()
{
if (await client.isAuthentificate() === false)
return 0;
navigateTo(this.redirect_url);
return 1;
}
}

View File

@ -0,0 +1,15 @@
import { navigateTo } from "../index.js";
import AbstractView from "./AbstractView.js";
export default class extends AbstractView{
constructor(params, title, url)
{
super(params, title);
this.redirect_url = url;
}
async redirect()
{
navigateTo(url);
}
}

View File

@ -1,6 +1,7 @@
export default class {
constructor(params) {
constructor(params, title) {
this.params = params;
this.title = title;
}
async postInit() {
@ -9,8 +10,8 @@ export default class {
async leavePage() {
}
setTitle(title) {
document.title = title;
setTitle() {
document.title = this.title;
}
async getHtml() {

View File

@ -1,9 +1,8 @@
import AbstractView from "./AbstractView.js";
import AbstractAuthentifiedView from "./AbstractAuthentifiedView.js";
export default class extends AbstractView {
export default class extends AbstractAuthentifiedView {
constructor(params) {
super(params);
this.setTitle("Chat");
super(params, "Chat");
let url = `ws://${window.location.host}/ws/socket-server/`
@ -45,7 +44,7 @@ export default class extends AbstractView {
<h1>Chat</h1>
<form id="form">
<input type="text" name="message" />
<input type="text" name="message" placeholder="message"/>
</form>
<div id="messages">

View File

@ -2,8 +2,7 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
this.setTitle("Dashboard");
super(params, "Dashboard");
}
async getHtml() {

View File

@ -0,0 +1,15 @@
import AbstractAuthentificateView from "./AbstractAuthentifiedView.js";
export default class extends AbstractAuthentificateView {
constructor(params) {
super(params, "Home");
this.redirect_url = "/login"
}
async getHtml() {
return `
<h1>HOME</h1>
<a href="/logout" class="nav__link" data-link>Logout</a>
`;
}
}

View File

@ -2,9 +2,8 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
super(params, "Viewing Post");
this.postId = params.id;
this.setTitle("Viewing Post");
}
async getHtml() {

View File

@ -2,8 +2,7 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
this.setTitle("Posts");
super(params, "Posts");
}
async getHtml() {

View File

@ -0,0 +1,38 @@
import AbstractAuthentifiedView from "./AbstractAuthentifiedView.js";
export default class extends AbstractAuthentifiedView {
constructor(params) {
super(params, "Search");
}
async postInit() {
let users = ["cramptéMan", "cacaMan", "chatteWomen"]
let list_users = document.getElementById('list_users');
for (const user of users) {
var new_user = document.createElement("li");
new_user.appendChild(document.createTextNode(user));
list_users.appendChild(new_user);
}
console.log(list_users);
}
async leavePage() {
}
async getHtml() {
return `
<h1>Search</h1>
<form id="form">
<input type="text" name="message" placeholder="user name to crampte"/>
</form>
<div id="users">
<ul id="list_users">
</ul>
</div>
`;
}
}

View File

@ -2,8 +2,7 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
this.setTitle("Settings");
super(params, "Settings");
}
async getHtml() {

View File

@ -1,13 +1,18 @@
import AbstractView from "../AbstractView.js";
import { client } from "../../index.js";
import { client, navigateTo } from "../../index.js";
import AbstractNonAuthentifiedView from "../AbstractNonAuthentified.js";
async function login()
{
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let response = await client.login(username, password);
let response_data = await response.json();
let response_data = await client.login(username, password);
if (response_data == null)
{
navigateTo("/home");
return;
}
["username", "user", "password"].forEach(error_field => {
let error_display = document.getElementById(`error_${error_field}`);
@ -22,15 +27,14 @@ async function login()
});
}
export default class extends AbstractView {
export default class extends AbstractNonAuthentifiedView {
constructor(params) {
super(params);
this.setTitle("Login");
document.body.addEventListener("click", e => {
e.preventDefault();
if (e.target.type == "button")
login();
});
super(params, "Login", "/home");
}
async postInit()
{
document.getElementById("button").onclick = login;
}
async getHtml() {
@ -42,7 +46,7 @@ export default class extends AbstractView {
<span id="error_username"></span>
<input type="password" id="password" placeholder="password">
<span id="error_password"></span>
<input type="button" value="login">
<input type="button" value="login" id="button">
<span id="error_user"></span>
<a href="/register" class="nav__link" data-link>Register</a>
</div>

View File

@ -0,0 +1,11 @@
import { client, navigateTo } from "../../index.js";
import AbstractAuthentifiedView from "../AbstractAuthentifiedView.js";
export default class extends AbstractAuthentifiedView
{
constructor(params) {
super(params, "Logout");
client.logout();
navigateTo("/login")
}
}

View File

@ -1,5 +1,5 @@
import AbstractView from "../AbstractView.js";
import { client } from "../../index.js";
import { client, navigateTo } from "../../index.js";
import AbstractAuthentifiedView from "../AbstractNonAuthentified.js";
async function register()
{
@ -22,15 +22,14 @@ async function register()
});
}
export default class extends AbstractView {
export default class extends AbstractAuthentifiedView {
constructor(params) {
super(params);
this.setTitle("register");
document.body.addEventListener("click", e => {
e.preventDefault();
if (e.target.type == "button")
register();
});
super(params, "Register", "/home");
}
async postInit()
{
document.getElementById("button").onclick = register;
}
async getHtml() {
@ -42,7 +41,7 @@ export default class extends AbstractView {
<span id="error_username"></span>
<input type="password" id="password" placeholder="password">
<span id="error_password"></span>
<input type="button" value="register">
<input type="button" value="register" id="button">
<span id="error_user"></span>
<a href="/login" class="nav__link" data-link>Login</a>
</div>

View File

@ -12,8 +12,9 @@
<a href="/" class="nav__link" data-link>Dashboard</a>
<a href="/posts" class="nav__link" data-link>Posts</a>
<a href="/settings" class="nav__link" data-link>Settings</a>
<a href="/chat" class="nav__link" data-link>Chat</a>
<a href="/login" class="nav__link" data-link>Login</a>
<a href="/register" class="nav__link" data-link>Register</a>
<a href="/search" class="nav__link" data-link>Search</a>
</nav>
<div id="app"></div>
<script type="module" src="{% static 'js/index.js' %}"></script>

View File

@ -9,7 +9,7 @@ class ProfileTest(TestCase):
self.user.save()
self.expected_response = {"name": "bozo",
"title": ""}
self.url = "/profiles/"
self.url = "/api/profiles/"
def test_profile_create_on_user_created(self):
response: HttpResponse = self.client.get(self.url + str(self.user.pk))