Registration completed
This commit is contained in:
parent
f2600a3012
commit
edf23bdbaa
|
|
@ -23,3 +23,5 @@ logs
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
|
db.sqlite-*
|
||||||
|
|
@ -192,13 +192,19 @@ html.light-mode .light-block {
|
||||||
|
|
||||||
.input-form.input-form-wide {
|
.input-form.input-form-wide {
|
||||||
width: 600px;
|
width: 600px;
|
||||||
|
min-height: 300px;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: stretch;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-form {
|
.input-form {
|
||||||
width: 400px;
|
width: 400px;
|
||||||
|
min-height: 200px;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
padding: 0 2em 2em 2em;
|
padding: 2em 2em 2em 2em;
|
||||||
border: 1px solid var(--background-modifier-border);
|
border: 1px solid var(--background-modifier-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -209,6 +215,7 @@ html.light-mode .light-block {
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-form h1 {
|
.input-form h1 {
|
||||||
|
margin-top: 0px;
|
||||||
font-size: x-large;
|
font-size: x-large;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -254,3 +261,13 @@ html.light-mode .light-block {
|
||||||
.password-validation-item.validation-error {
|
.password-validation-item.validation-error {
|
||||||
color: var(--text-error);
|
color: var(--text-error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.input-form .loading {
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border: 4px solid var(--color-purple);
|
||||||
|
border-right-color: transparent;
|
||||||
|
border-radius: 50%;
|
||||||
|
box-sizing: content-box;
|
||||||
|
animation: rotate 1s linear infinite;
|
||||||
|
}
|
||||||
|
|
@ -6,12 +6,15 @@ interface Prop
|
||||||
}
|
}
|
||||||
const props = defineProps<Prop>();
|
const props = defineProps<Prop>();
|
||||||
const model = defineModel<string>();
|
const model = defineModel<string>();
|
||||||
|
|
||||||
|
const err = ref<string | boolean | undefined>(props.error);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label v-if="title" class="input-label">{{ title }}</label>
|
<label v-if="title" class="input-label">{{ title }}</label>
|
||||||
<input class="input-input" :class="{'input-has-error': !!error}" v-model="model" v-bind="$attrs" />
|
<input @input="err = false" class="input-input" :class="{ 'input-has-error': !!err }" v-model="model"
|
||||||
<span v-if="error && typeof error === 'string'" class="input-error">{{ error }}</span>
|
v-bind="$attrs" />
|
||||||
|
<span v-if="err && typeof err === 'string'" class="input-error">{{ err }}</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
@ -6,49 +6,91 @@ export interface Auth
|
||||||
{
|
{
|
||||||
id: Ref<number>;
|
id: Ref<number>;
|
||||||
data: Ref<Record<string, any>>;
|
data: Ref<Record<string, any>>;
|
||||||
token: Ref<string>;
|
sessionId: Ref<string>;
|
||||||
session_id: Ref<number>;
|
|
||||||
status: Ref<AuthStatus>;
|
status: Ref<AuthStatus>;
|
||||||
|
|
||||||
lastRefresh: Ref<Date>;
|
lastRefresh: Ref<Date>;
|
||||||
|
|
||||||
register: (username: string, email: string, password: string, data?: Record<string, any>) => AuthStatus;
|
register: (username: string, email: string, password: string, data?: Record<string, any>) => Promise<any>;
|
||||||
login: (usernameOrEmail: string, password: string) => AuthStatus;
|
login: (usernameOrEmail: string, password: string) => Promise<void>;
|
||||||
logout: () => AuthStatus;
|
logout: () => Promise<void>;
|
||||||
|
|
||||||
refresh: () => AuthStatus;
|
refresh: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = useState<number>("auth:id", () => 0);
|
|
||||||
const data = useState<any>("auth:data", () => {});
|
|
||||||
const token = useState<string>("auth:token", () => '');
|
|
||||||
const session_id = useState<number>("auth:session_id", () => 0);
|
|
||||||
const status = useState<AuthStatus>("auth:status", () => 0);
|
|
||||||
|
|
||||||
const lastRefresh = useState<Date>("auth:date", () => new Date());
|
async function register(username: string, email: string, password: string, additionalData?: Record<string, any>): Promise<any>
|
||||||
|
|
||||||
function register(username: string, email: string, password: string, data?: Record<string, any>): AuthStatus
|
|
||||||
{
|
{
|
||||||
|
const id = useState<number>("auth:id");
|
||||||
|
const data = useState<any>("auth:data");
|
||||||
|
const sessionId = useState<string>("auth:sessionId");
|
||||||
|
const status = useState<AuthStatus>("auth:status");
|
||||||
|
const lastRefresh = useState<Date>("auth:date");
|
||||||
|
status.value = AuthStatus.loading;
|
||||||
|
|
||||||
return AuthStatus.disconnected;
|
try
|
||||||
|
{
|
||||||
|
const result = await $fetch("/api/auth/register", {
|
||||||
|
method: 'POST',
|
||||||
|
body: { username, email, password, additionalData },
|
||||||
|
ignoreResponseError: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if(result.success)
|
||||||
|
{
|
||||||
|
id.value = result.id!;
|
||||||
|
data.value = { ...additionalData, username: username, email: email };
|
||||||
|
sessionId.value = result.sessionId!;
|
||||||
|
status.value = AuthStatus.connected;
|
||||||
|
lastRefresh.value = new Date();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if(result.error)
|
||||||
|
{
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
|
|
||||||
|
return result.error;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(e) {
|
||||||
|
console.log(JSON.stringify(e));
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
function login(usernameOrEmail: string, password: string): AuthStatus
|
async function login(usernameOrEmail: string, password: string): Promise<void>
|
||||||
{
|
{
|
||||||
return AuthStatus.disconnected;
|
const status = useState<AuthStatus>("auth:status");
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
}
|
}
|
||||||
function logout(): AuthStatus
|
async function logout(): Promise<void>
|
||||||
{
|
{
|
||||||
return AuthStatus.disconnected;
|
const status = useState<AuthStatus>("auth:status");
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
function refresh(): AuthStatus
|
async function refresh(): Promise<void>
|
||||||
{
|
{
|
||||||
return AuthStatus.disconnected;
|
const status = useState<AuthStatus>("auth:status");
|
||||||
|
status.value = AuthStatus.disconnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function useAuth(): Auth {
|
export default function useAuth(): Auth {
|
||||||
|
const id = useState<number>("auth:id", () => 0);
|
||||||
|
const data = useState<any>("auth:data", () => { });
|
||||||
|
const sessionId = useState<string>("auth:sessionId", () => '');
|
||||||
|
const status = useState<AuthStatus>("auth:status", () => AuthStatus.disconnected);
|
||||||
|
|
||||||
|
const lastRefresh = useState<Date>("auth:date", () => new Date());
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id, data, token, session_id, status, lastRefresh,
|
id, data, sessionId, status, lastRefresh,
|
||||||
register, login, logout, refresh
|
register, login, logout, refresh
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
export default defineNuxtRouteMiddleware((to) => {
|
export default defineNuxtRouteMiddleware((to) => {
|
||||||
const meta = to.meta.auth;
|
const meta = to.meta.auth;
|
||||||
|
|
||||||
//to.
|
//useSession(to.)
|
||||||
|
|
||||||
|
return to;
|
||||||
})
|
})
|
||||||
|
|
@ -5,7 +5,8 @@ export default defineNuxtConfig({
|
||||||
modules: [CanvasModule, "@nuxt/content", "@nuxtjs/color-mode"],
|
modules: [CanvasModule, "@nuxt/content", "@nuxtjs/color-mode"],
|
||||||
css: ['~/assets/common.css', '~/assets/global.css'],
|
css: ['~/assets/common.css', '~/assets/global.css'],
|
||||||
runtimeConfig: {
|
runtimeConfig: {
|
||||||
dbFile: ''
|
dbFile: '',
|
||||||
|
sessionPassword: '699c46bd-9aaa-4364-ad01-510ee4fe7013'
|
||||||
},
|
},
|
||||||
components: [
|
components: [
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ const state = reactive<Registration>({
|
||||||
|
|
||||||
const confirmPassword = ref("");
|
const confirmPassword = ref("");
|
||||||
|
|
||||||
const { status, signUp } = useAuth();
|
const { status, register } = useAuth();
|
||||||
|
|
||||||
const checkedLength = computed(() => state.password.length >= 8 && state.password.length <= 128);
|
const checkedLength = computed(() => state.password.length >= 8 && state.password.length <= 128);
|
||||||
const checkedLowerUpper = computed(() => state.password.toLowerCase() !== state.password && state.password.toUpperCase() !== state.password);
|
const checkedLowerUpper = computed(() => state.password.toLowerCase() !== state.password && state.password.toUpperCase() !== state.password);
|
||||||
|
|
@ -26,17 +26,23 @@ const checkedSymbol = computed(() => " !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~".split("
|
||||||
const usernameError = ref("");
|
const usernameError = ref("");
|
||||||
const emailError = ref("");
|
const emailError = ref("");
|
||||||
|
|
||||||
function register(): void
|
async function submit()
|
||||||
{
|
{
|
||||||
const data = schema.safeParse(state);
|
const data = schema.safeParse(state);
|
||||||
|
|
||||||
if(data.success && state.password !== "" && confirmPassword.value === state.password)
|
if(data.success && state.password !== "" && confirmPassword.value === state.password)
|
||||||
{
|
{
|
||||||
try {
|
let errors = await register(data.data.username, data.data.email, data.data.password, {});
|
||||||
signUp({ ...data.data }, { redirect: true, callbackUrl: '/' });
|
|
||||||
} catch(e) {
|
if(status.value === AuthStatus.connected)
|
||||||
usernameError.value = e?.data?.find(e => e.path.includes("username"))?.message ?? "";
|
{
|
||||||
emailError.value = e?.data?.find(e => e.path.includes("email"))?.message ?? "";
|
await navigateTo('/');
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
errors = errors?.issues ?? errors;
|
||||||
|
usernameError.value = errors?.find((e: any) => e.path.includes("username"))?.message ?? "";
|
||||||
|
emailError.value = errors?.find((e: any) => e.path.includes("email"))?.message ?? "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
@ -48,27 +54,41 @@ function register(): void
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
||||||
<Head>
|
<Head>
|
||||||
<Title>S'inscrire</Title>
|
<Title>S'inscrire</Title>
|
||||||
</Head>
|
</Head>
|
||||||
<div class="site-body-center-column">
|
<div class="site-body-center-column">
|
||||||
<div class="render-container flex align-center justify-center">
|
<div class="render-container flex align-center justify-center">
|
||||||
<form v-if="status === 'unauthenticated'" @submit.prevent="register" class="input-form input-form-wide">
|
<form v-if="status === AuthStatus.disconnected" @submit.prevent="submit" class="input-form input-form-wide">
|
||||||
<h1>Inscription</h1>
|
<h1>Inscription</h1>
|
||||||
<Input type="text" v-model="state.username" placeholder="Entrez un nom d'utiliateur" title="Nom d'utilisateur" :error="usernameError"/>
|
<Input type="text" autocomplete="username" v-model="state.username"
|
||||||
<Input type="text" v-model="state.email" placeholder="Entrez une addresse mail" title="Adresse mail" :error="emailError"/>
|
placeholder="Entrez un nom d'utiliateur" title="Nom d'utilisateur" :error="usernameError" />
|
||||||
<Input type="password" v-model="state.password" placeholder="Entrez un mot de passe" title="Mot de passe" :error="!(checkedLength && checkedLowerUpper && checkedDigit && checkedSymbol)"/>
|
<Input type="text" autocomplete="email" v-model="state.email" placeholder="Entrez une addresse mail"
|
||||||
|
title="Adresse mail" :error="emailError" />
|
||||||
|
<Input type="password" autocomplete="new-password" v-model="state.password"
|
||||||
|
placeholder="Entrez un mot de passe" title="Mot de passe"
|
||||||
|
:error="!(checkedLength && checkedLowerUpper && checkedDigit && checkedSymbol)" />
|
||||||
<div class="password-validation-group">
|
<div class="password-validation-group">
|
||||||
<span class="password-validation-title">Votre mot de passe doit respecter les critères suivants :</span>
|
<span class="password-validation-title">Votre mot de passe doit respecter les critères suivants
|
||||||
<span class="password-validation-item" :class="{'validation-error': !checkedLength}">Entre 8 et 128 caractères</span>
|
:</span>
|
||||||
<span class="password-validation-item" :class="{'validation-error': !checkedLowerUpper}">Au moins une minuscule et une majuscule</span>
|
<span class="password-validation-item" :class="{'validation-error': !checkedLength}">Entre 8 et 128
|
||||||
<span class="password-validation-item" :class="{'validation-error': !checkedDigit}">Au moins un chiffre</span>
|
caractères</span>
|
||||||
<span class="password-validation-item" :class="{'validation-error': !checkedSymbol}">Au moins un caractère spécial parmis la liste suivante: <pre>! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre></span>
|
<span class="password-validation-item" :class="{'validation-error': !checkedLowerUpper}">Au moins
|
||||||
|
une minuscule et une majuscule</span>
|
||||||
|
<span class="password-validation-item" :class="{'validation-error': !checkedDigit}">Au moins un
|
||||||
|
chiffre</span>
|
||||||
|
<span class="password-validation-item" :class="{'validation-error': !checkedSymbol}">Au moins un
|
||||||
|
caractère spécial parmis la liste suivante:
|
||||||
|
<pre>! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Input type="password" v-model="confirmPassword" placeholder="Confirmer le mot de passe" title="Confirmer le mot de passe" :error="confirmPassword === '' || confirmPassword === state.password ? '' : 'Les mots de passe saisies ne sont pas identique'"/>
|
<Input type="password" v-model="confirmPassword" placeholder="Confirmer le mot de passe"
|
||||||
|
title="Confirmer le mot de passe"
|
||||||
|
:error="confirmPassword === '' || confirmPassword === state.password ? '' : 'Les mots de passe saisies ne sont pas identique'" />
|
||||||
<button>Valider</button>
|
<button>Valider</button>
|
||||||
</form>
|
</form>
|
||||||
<div v-else-if="status === 'loading'"></div>
|
<div v-else-if="status === AuthStatus.loading" class="input-form"><div class="loading"></div></div>
|
||||||
<div v-else class="not-found-container">
|
<div v-else class="not-found-container">
|
||||||
<div class="not-found-title">👀 Vous n'avez rien à faire ici. 👀</div>
|
<div class="not-found-title">👀 Vous n'avez rien à faire ici. 👀</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,9 @@ export const schema = z.object({
|
||||||
username: z.string({ required_error: "Nom d'utilisateur obligatoire" }).min(3, "Votre nom d'utilisateur doit contenir au moins 3 caractères").max(32, "Votre nom d'utilisateur doit contenir au plus 32 caractères"),
|
username: z.string({ required_error: "Nom d'utilisateur obligatoire" }).min(3, "Votre nom d'utilisateur doit contenir au moins 3 caractères").max(32, "Votre nom d'utilisateur doit contenir au plus 32 caractères"),
|
||||||
email: z.string({ required_error: "Email obligatoire" }).email("Adresse mail invalide"),
|
email: z.string({ required_error: "Email obligatoire" }).email("Adresse mail invalide"),
|
||||||
password: z.string({ required_error: "Mot de passe obligatoire" }).min(8, "Votre mot de passe doit contenir au moins 8 caractères").max(128, "Votre mot de passe doit contenir au moins 8 caractères").superRefine(securePassword),
|
password: z.string({ required_error: "Mot de passe obligatoire" }).min(8, "Votre mot de passe doit contenir au moins 8 caractères").max(128, "Votre mot de passe doit contenir au moins 8 caractères").superRefine(securePassword),
|
||||||
|
data: z.object({
|
||||||
|
|
||||||
|
}).partial().nullish(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type Registration = z.infer<typeof schema>;
|
export type Registration = z.infer<typeof schema>;
|
||||||
|
|
@ -1,2 +1,3 @@
|
||||||
export default defineEventHandler(async (e) => {
|
export default defineEventHandler(async (e) => {
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
@ -2,34 +2,61 @@ import useDatabase from '~/composables/useDatabase';
|
||||||
import { schema } from '~/schemas/registration';
|
import { schema } from '~/schemas/registration';
|
||||||
|
|
||||||
export default defineEventHandler(async (e) => {
|
export default defineEventHandler(async (e) => {
|
||||||
const body = await readValidatedBody(e, schema.safeParse);
|
try
|
||||||
|
|
||||||
if(!body.success)
|
|
||||||
return body.error;
|
|
||||||
|
|
||||||
const db = useDatabase();
|
|
||||||
|
|
||||||
const usernameQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE username = ?1`);
|
|
||||||
const checkUsername = usernameQuery.get(body.data.username);
|
|
||||||
|
|
||||||
const emailQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE email = ?1`);
|
|
||||||
const checkEmail = emailQuery.get(body.data.email);
|
|
||||||
|
|
||||||
const errors = [];
|
|
||||||
if(checkUsername.count !== 0)
|
|
||||||
errors.push({ path: ['username'], message: "Ce nom d'utilisateur est déjà utilisé" });
|
|
||||||
if(checkEmail.count !== 0)
|
|
||||||
errors.push({ path: ['email'], message: "Cette adresse mail est déjà utilisée" });
|
|
||||||
|
|
||||||
if(errors.length > 0)
|
|
||||||
throw createError({ status: 406, message: "duplicates", data: errors });
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
const hash = await Bun.password.hash(body.data.password);
|
const { sessionPassword } = useRuntimeConfig();
|
||||||
const registration = db.query(`INSERT INTO users(username, email, hash) VALUES(?1, ?2, ?3)`);
|
const body = await readValidatedBody(e, schema.safeParse);
|
||||||
const result = registration.get(body.data.username, body.data.email, hash);
|
|
||||||
|
|
||||||
setResponseStatus(e, 201, "Created");
|
if (!body.success)
|
||||||
return { success: true };
|
{
|
||||||
|
setResponseStatus(e, 406);
|
||||||
|
return { success: false, error: body.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = useDatabase();
|
||||||
|
|
||||||
|
const usernameQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE username = ?1`);
|
||||||
|
const checkUsername = usernameQuery.get(body.data.username) as any;
|
||||||
|
|
||||||
|
const emailQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE email = ?1`);
|
||||||
|
const checkEmail = emailQuery.get(body.data.email) as any;
|
||||||
|
|
||||||
|
const errors = [];
|
||||||
|
if(checkUsername.count !== 0)
|
||||||
|
errors.push({ path: ['username'], message: "Ce nom d'utilisateur est déjà utilisé" });
|
||||||
|
if(checkEmail.count !== 0)
|
||||||
|
errors.push({ path: ['email'], message: "Cette adresse mail est déjà utilisée" });
|
||||||
|
|
||||||
|
if(errors.length > 0)
|
||||||
|
{
|
||||||
|
setResponseStatus(e, 406);
|
||||||
|
return { success: false, error: errors };
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
const hash = await Bun.password.hash(body.data.password);
|
||||||
|
const registration = db.query(`INSERT INTO users(username, email, hash, email_valid) VALUES(?1, ?2, ?3, 0)`);
|
||||||
|
registration.get(body.data.username, body.data.email, hash) as any;
|
||||||
|
|
||||||
|
const userIdQuery = db.query(`SELECT id FROM users WHERE username = ?1`);
|
||||||
|
const id = (userIdQuery.get(body.data.username) as any).id;
|
||||||
|
|
||||||
|
const registeringData = db.query(`INSERT INTO users_data(user_id) VALUES(?1)`);
|
||||||
|
registeringData.get(id);
|
||||||
|
|
||||||
|
const session = await useSession(e, {
|
||||||
|
password: sessionPassword,
|
||||||
|
});
|
||||||
|
|
||||||
|
const loggingIn = db.query(`INSERT INTO user_sessions(id, user_id, ip, agent, lastRefresh) VALUES(?1, ?2, ?3, ?4, ?5)`);
|
||||||
|
loggingIn.get(session.id, id, getRequestIP(e), getRequestHeader(e, 'User-Agent'), Date.now());
|
||||||
|
|
||||||
|
setResponseStatus(e, 201);
|
||||||
|
return { success: true, id: id, sessionId: session.id };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(e)
|
||||||
|
{
|
||||||
|
return { success: false, error: e };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Loading…
Reference in New Issue