Compare commits

..

No commits in common. "af9595c447d98a906919e05575d2280ff11b6f48" and "b12c03074af1d9ec0c66aa55e52d60bf862bb231" have entirely different histories.

32 changed files with 146 additions and 338 deletions

View File

@ -0,0 +1,7 @@
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 .register import *
from .login import * from .login import *
from .edit import * from .change_password import *
from .delete import * from .delete import *

View File

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

View File

@ -1,49 +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 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): def setUp(self):
self.client = Client() self.client = Client()
self.url = "/api/accounts/login" self.url = "/accounts/login"
self.username: str = str(uuid.uuid4()) self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4()) self.password: str = str(uuid.uuid4())

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
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): class DeleteView(APIView):
permission_classes = (permissions.IsAuthenticated,) permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,) authentication_classes = (SessionAuthentication,)
def delete(self, request: HttpRequest): def post(self, request: HttpRequest):
request.user.delete() request.user.delete()
return Response("user deleted", status=status.HTTP_200_OK) return Response("user deleted", status=status.HTTP_200_OK)

View File

@ -1,42 +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
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")

View File

@ -1,16 +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 ..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): class LogoutView(APIView):
permission_classes = (permissions.IsAuthenticated,) permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,) authentication_classes = (SessionAuthentication,)
def get(self, request: HttpRequest): def post(self, request: HttpRequest):
logout(request) logout(request)
return Response("user unlogged", status=status.HTTP_200_OK) return Response("user unlogged", status=status.HTTP_200_OK)

View File

@ -1,27 +1,26 @@
import { Accounts } from "./accounts.js"; 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 class Client
{ {
constructor(url) constructor(url)
{ {
this._url = url; this._url = url;
this.accounts = new Accounts(this); this.accounts = new Accounts(this);
this._logged = undefined; this._token = undefined;
} }
async isAuthentificate() get isAuthentificate()
{ {
if (this._logged == undefined) return this.token != 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) async _post(uri, data)
@ -30,35 +29,19 @@ class Client
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(data), body: JSON.stringify(data),
}); });
let token = extract_token(response);
if (token != null)
this.token = token;
return response; return response;
} }
async login(username, password) async login(username, password)
{ {
let response = await this._post("/api/accounts/login", {username: username, password: password}) let response = await this._post("/api/accounts/login", {username: username, password: password})
let data = await response.json(); return response
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,14 +3,10 @@ import Dashboard from "./views/Dashboard.js";
import Posts from "./views/Posts.js"; import Posts from "./views/Posts.js";
import PostView from "./views/PostView.js"; import PostView from "./views/PostView.js";
import Settings from "./views/Settings.js"; import Settings from "./views/Settings.js";
import Search from "./views/Search.js";
import Chat from "./views/Chat.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 { Client } from "./api/client.js";
import AbstractRedirectView from "./views/AbstractRedirectView.js"; import RegisterView from "./views/accounts/RegisterView.js";
let client = new Client(location.protocol + "//" + location.host) let client = new Client(location.protocol + "//" + location.host)
@ -27,30 +23,27 @@ const getParams = match => {
})); }));
}; };
const navigateTo = async (uri) => { const navigateTo = url => {
if (await router(uri) === 0) history.pushState(null, null, url);
history.pushState(null, null, uri); router();
}; };
const router = async (uri = "") => { const router = async () => {
const routes = [ const routes = [
{ path: "/", view: Dashboard }, { path: "/", view: Dashboard },
{ path: "/posts", view: Posts }, { path: "/posts", view: Posts },
{ path: "/posts/:id", view: PostView }, { path: "/posts/:id", view: PostView },
{ path: "/settings", view: Settings }, { path: "/settings", view: Settings },
{ path: "/login", view: LoginView }, { path: "/login", view: LoginView },
{ path: "/logout", view: LogoutView },
{ path: "/register", view: RegisterView }, { path: "/register", view: RegisterView },
{ path: "/search", view: Search },
{ path: "/chat", view: Chat }, { path: "/chat", view: Chat },
{ path: "/home", view: HomeView },
]; ];
// Test each route for potential match // Test each route for potential match
const potentialMatches = routes.map(route => { const potentialMatches = routes.map(route => {
return { return {
route: route, route: route,
result: uri.match(pathToRegex(route.path)) result: location.pathname.match(pathToRegex(route.path))
}; };
}); });
@ -59,29 +52,18 @@ const router = async (uri = "") => {
if (!match) { if (!match) {
match = { match = {
route: routes[0], route: routes[0],
result: [uri] result: [location.pathname]
}; };
} }
if (lastView !== undefined) if (lastView !== undefined)
await lastView.leavePage(); await lastView.leavePage();
const view = new match.route.view(getParams(match)); const view = new match.route.view(getParams(match));
if (view instanceof AbstractRedirectView && await view.redirect())
return 1;
lastView = view; lastView = view;
let content = await view.getHtml(); document.querySelector("#app").innerHTML = await view.getHtml();
if (content == null)
return 1;
view.setTitle();
document.querySelector("#app").innerHTML = content
await view.postInit(); await view.postInit();
return 0;
}; };
window.addEventListener("popstate", router); window.addEventListener("popstate", router);
@ -90,10 +72,11 @@ document.addEventListener("DOMContentLoaded", () => {
document.body.addEventListener("click", e => { document.body.addEventListener("click", e => {
if (e.target.matches("[data-link]")) { if (e.target.matches("[data-link]")) {
e.preventDefault(); e.preventDefault();
navigateTo(e.target.href.slice(location.origin.length)); navigateTo(e.target.href);
} }
}); });
router(location.pathname);
router();
}); });
export { client, navigateTo } export { client }

View File

@ -1,18 +0,0 @@
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

@ -1,16 +0,0 @@
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

@ -1,15 +0,0 @@
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,7 +1,6 @@
export default class { export default class {
constructor(params, title) { constructor(params) {
this.params = params; this.params = params;
this.title = title;
} }
async postInit() { async postInit() {
@ -10,8 +9,8 @@ export default class {
async leavePage() { async leavePage() {
} }
setTitle() { setTitle(title) {
document.title = this.title; document.title = title;
} }
async getHtml() { async getHtml() {

View File

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

View File

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

View File

@ -1,15 +0,0 @@
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,8 +2,9 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView { export default class extends AbstractView {
constructor(params) { constructor(params) {
super(params, "Viewing Post"); super(params);
this.postId = params.id; this.postId = params.id;
this.setTitle("Viewing Post");
} }
async getHtml() { async getHtml() {

View File

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

View File

@ -1,38 +0,0 @@
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,7 +2,8 @@ import AbstractView from "./AbstractView.js";
export default class extends AbstractView { export default class extends AbstractView {
constructor(params) { constructor(params) {
super(params, "Settings"); super(params);
this.setTitle("Settings");
} }
async getHtml() { async getHtml() {

View File

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

View File

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

View File

@ -12,9 +12,8 @@
<a href="/" class="nav__link" data-link>Dashboard</a> <a href="/" class="nav__link" data-link>Dashboard</a>
<a href="/posts" class="nav__link" data-link>Posts</a> <a href="/posts" class="nav__link" data-link>Posts</a>
<a href="/settings" class="nav__link" data-link>Settings</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="/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> </nav>
<div id="app"></div> <div id="app"></div>
<script type="module" src="{% static 'js/index.js' %}"></script> <script type="module" src="{% static 'js/index.js' %}"></script>

View File

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