Compare commits

...

5 Commits

Author SHA1 Message Date
2cc3219b30 add astro login page
Some checks failed
Build Docker Image / run (pull_request) Failing after 31s
2024-04-25 18:34:49 +02:00
b48c842e41 auth utile 2024-04-25 18:33:20 +02:00
313c197096 env var WIP 2024-04-25 18:33:01 +02:00
5776fe08d9 feat: user model 2024-04-25 18:32:25 +02:00
b1fce87215 add eslint config 2024-04-25 18:26:06 +02:00
9 changed files with 500 additions and 50 deletions

8
front/.eslintignore Normal file
View File

@ -0,0 +1,8 @@
node_modules
out
.next
next-env.d.ts
*.js
__tests__

324
front/.eslintrc.json Normal file
View File

@ -0,0 +1,324 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:astro/recommended",
"plugin:@typescript-eslint/strict",
"plugin:@typescript-eslint/stylistic"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"overrides": [
{
"files": [
"*.astro"
],
"parser": "astro-eslint-parser",
"parserOptions": {
"extraFileExtensions": [
".astro"
],
"parser": "@typescript-eslint/parser"
}
},
{
"files": [
"*.ts",
"*.tsx",
"*.astro"
],
"rules": {
"no-extra-parens": "off",
"no-unused-expressions": "off",
"no-shadow": "off",
"quotes": "off",
"semi": "off",
"space-before-function-paren": "off"
}
}
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true,
"project": "tsconfig.json",
"sourceType": "module",
"ecmaVersion": 2018
}
},
"plugins": [
"@typescript-eslint"
],
"root": true,
"rules": {
"@typescript-eslint/prefer-for-of": "error",
"@typescript-eslint/prefer-function-type": "error",
"@typescript-eslint/prefer-namespace-keyword": "error",
"@typescript-eslint/space-before-function-paren": [
"error",
{
"anonymous": "never",
"asyncArrow": "always",
"named": "never"
}
],
"@typescript-eslint/triple-slash-reference": "error",
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unified-signatures": "error",
"@typescript-eslint/adjacent-overload-signatures": "error",
"@typescript-eslint/array-type": [
"error",
{
"default": "generic"
}
],
"arrow-body-style": "error",
"arrow-parens": [
"error",
"always"
],
"@typescript-eslint/ban-types": [
"error",
{
"types": {
"{}": false
}
}
],
"complexity": [
"warn",
10
],
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/consistent-type-definitions": "error",
"constructor-super": "error",
"curly": "error",
"dot-notation": "error",
"eol-last": "error",
"eqeqeq": [
"error",
"smart"
],
"@typescript-eslint/explicit-member-accessibility": [
"error",
{
"accessibility": "explicit"
}
],
"for-direction": "error",
"getter-return": "error",
"guard-for-in": "error",
"id-blacklist": [
"error",
"any",
"Number",
"number",
"String",
"string",
"Boolean",
"boolean",
"Undefined"
],
"id-length": [
"warn",
{
"exceptions": [
"_"
]
}
],
"id-match": "error",
"indent": [
"error",
"tab",
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"max-classes-per-file": [
"error",
1
],
"max-depth": [
"warn",
2
],
"max-len": [
"warn",
{
"code": 256
}
],
"@typescript-eslint/member-delimiter-style": [
"error",
{
"multiline": {
"delimiter": "none",
"requireLast": true
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/member-ordering": "error",
"new-parens": "error",
"no-async-promise-executor": "error",
"no-await-in-loop": "warn",
"no-bitwise": "error",
"no-caller": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-console": "off",
"no-constant-condition": "error",
"no-control-regex": "warn",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-args": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"no-empty-character-class": "error",
"@typescript-eslint/no-empty-function": "error",
"@typescript-eslint/no-empty-interface": "error",
"no-eval": "error",
"no-ex-assign": "error",
"@typescript-eslint/no-explicit-any": "off",
"no-extra-boolean-cast": "error",
"no-extra-parens": "off",
"@typescript-eslint/no-extra-parens": [
"error",
"all",
{
"ignoreJSX": "all"
}
],
"no-extra-semi": "error",
"no-fallthrough": "off",
"no-func-assign": "error",
"no-import-assign": "error",
"no-inner-declarations": "error",
"no-invalid-regexp": "error",
"no-irregular-whitespace": "error",
"no-label-var": "error",
"no-loss-of-precision": "error",
"no-misleading-character-class": "error",
"@typescript-eslint/no-misused-new": "error",
"no-multiple-empty-lines": "error",
"@typescript-eslint/no-namespace": "error",
"no-new-wrappers": "error",
"no-obj-calls": "error",
"no-promise-executor-return": "error",
"@typescript-eslint/no-parameter-properties": "off",
"no-prototype-builtins": "error",
"no-regex-spaces": "error",
"no-setter-return": "error",
"@typescript-eslint/no-shadow": "error",
"no-shadow": [
"error",
{
"builtinGlobals": false,
"hoist": "all"
}
],
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-template-curly-in-string": "warn",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef": "error",
"no-undef-init": "error",
"no-underscore-dangle": "off",
"no-unexpected-multiline": "error",
"no-unreachable": "warn",
"no-unreachable-loop": "warn",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-expressions": [
"error",
{
"allowTernary": true
}
],
"@typescript-eslint/no-unused-expressions": [
"error",
{
"allowTernary": true
}
],
"no-unused-labels": "error",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", {
"args": "all",
"argsIgnorePattern": "^_",
"caughtErrors": "all",
"caughtErrorsIgnorePattern": "^_",
"destructuredArrayIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true
}],
"@typescript-eslint/no-non-null-assertion": ["warn"],
"no-var": "error",
"object-shorthand": [
"warn",
"methods"
],
"one-var": [
"error",
"never"
],
"prefer-const": "error",
"quote-props": [
"error",
"consistent-as-needed"
],
"quotes": "off",
"@typescript-eslint/quotes": [
"error",
"single",
{
"avoidEscape": true
}
],
"radix": "error",
"require-atomic-updates": "warn",
"semi": "off",
"@typescript-eslint/semi": [
"error",
"never"
],
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"asyncArrow": "always",
"named": "never"
}
],
"spaced-comment": ["error", "always", { "block": { "exceptions": ["*"] } }],
"use-isnan": "error",
"valid-typeof": "warn"
}
}

21
front/src/env.d.ts vendored
View File

@ -1 +1,22 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
export interface ImportMetaEnv {
NODE_ENV: string
APP_URL: string
POCKETBASEURL: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
declare namespace App {
/**
* Middlewares variables
*/
interface Locals {}
}

View File

@ -1,30 +1,82 @@
import { AstroCookies } from "astro";
import { PocketBase } from "PocketBase";
import { AstroCookies } from 'astro'
import PocketBase from 'pocketbase'
import UserObj from 'models/User'
import { getEnv } from 'libs/Env'
const pb = new PocketBase('https://pb-tweb.cb85.fr');
const pb = new PocketBase(getEnv('POCKET_BASE','https://pb-tweb.cb85.fr')) // XXX: 'https://pb-tweb.cb85.fr'
export async function getUser(cookies:AstroCookies): Promise<UserObj | null> {
const sessionID = cookies.get('session')?value
export async function clearUser(cookies: AstroCookies): Promise<void> {
const sessionID = cookies.get('session')?.value
if(!sessionID){
return
}
if(!sessionID){
return
}
const authData = await pb.collection('users').authRefresh();
console.log(pb.authStore.isValid);
console.log(pb.authStore.token);
console.log(pb.authStore.model.id);
cookies.delete('session',{
path: '/'
})
}
//référence a loop
//fonction get user pour récupéré un utilisateur (notament coté client)
//sessionID = JWS
export async function login(cookies: AstroCookies, user: {user: string, password: string}): boolean {
//fonction set user crée un cookies de session
//passé le cookies astro dans les paramètre
const authData = await pb.collection('users').authWithPassword(user.user, user.password)
//utiliser cookie.set pour crée un nouveau cookies
let secure = true
if (getEnv('NODE_ENV', 'production') !== 'production') {
secure = false
}
if(authData){
cookies.set('session', authData.token,{
httpOnly: true,
path: '/',
secure: secure,
sameSite: 'Strict',
maxAge: 365000,
})
return true
}
return false
}
export async function getUser(cookies: AstroCookies): Promise<UserObj | null> {
const sessionID = cookies.get('session')?.value
if(!sessionID){
return
}
if(!pb.authStore.isValid){
return
}
console.log(pb.authStore.model)
return pb.authStore.model
}
export async function setUser(cookies: AstroCookies, user: UserObj): Promise<void>{
const record = await pb.collection('users').create(user)
console.log(record)
const session = pb.authStore.token
console.log(session)
let secure = true
if (getEnv('NODE_ENV', 'production') !== 'production') {
secure = false
}
cookies.set('session', session,{
httpOnly: true,
path: '/',
secure: secure,
sameSite: 'Strict',
maxAge: 365000,
})
}

17
front/src/libs/Env.ts Normal file
View File

@ -0,0 +1,17 @@
import type { ImportMetaEnv } from 'env'
/**
* Get the environment variable
*
* @param key the env variable key
* @param defaultValue a default value if applicable
* @returns the environment value or undefined if not found
*/
export function getEnv(key: keyof ImportMetaEnv, defaultValue: string): string
export function getEnv(key: keyof ImportMetaEnv, defaultValue?: string | undefined): string | undefined
export function getEnv(key: keyof ImportMetaEnv, defaultValue?: string | undefined): string | undefined {
// get the env variable through Astro > NodeJS > input
const res = import.meta.env[key] ?? process.env[key] ?? defaultValue
return res ?? undefined
}

View File

@ -0,0 +1,19 @@
export interface PBData{
id: string | null
collectionId: string | null
collectionName: string | null
created: string | null // TODO: passé ca en date auto
updated: string | null // TODO: passé ca en date auto
}
export default interface UserObj extends PBData{
avatar: string | null
username: string
email: string
emailVisibility: false
password: string | null
passwordConfirm: string | null
name: string | null
}

View File

@ -0,0 +1,16 @@
---
import Layout from 'layouts/Layout.astro';
import { getUser } from 'libs/AuthUtils';
const user = await getUser(Astro.cookies);
if(!user){
return Astro.redirect("/account/login");
}
---
<Layout title="Account setting">
<h1>Bonjour {user.name}</h1>
</Layout>

View File

@ -2,13 +2,14 @@
import Layout from "../../layouts/Layout.astro";
import PocketBase from 'pocketbase';
import AstroUtils from "../../libs/AstroUtils";
import Schema from 'models/Schema'
import { getUser, login } from "libs/AuthUtils";
// const usr = await getUser(Astro.cookies)
// if (usr) {
// return Astro.redirect(route('/', {message: 'Vous êtes déjà connecté !'}))
// }
const usr = await getUser(Astro.cookies)
if (usr) {
// return Astro.redirect(route('/', {message: 'Vous êtes déjà connecté !'}))
}
const res = await AstroUtils.wrap(async () => {
@ -17,20 +18,14 @@ const res = await AstroUtils.wrap(async () => {
}
const form = await Astro.request.formData();
const request = {
email: form.get("username") as String,
password: form.get("password") as String
user: form.get("username") as string,
password: form.get("password") as string
}
const pb = new PocketBase('http://127.0.0.1:3001');
const authData = await pb.collection('users').authWithPassword(
request.email,
request.password,
);
// after the above you can also access the auth data from the authStore
console.log(pb.authStore.isValid);
console.log(pb.authStore.token);
console.log(pb.authStore.model.id);
await login(Astro.cookies, request)
return Astro.redirect("/account")
})
---

View File

@ -2,12 +2,14 @@
import PocketBase from 'pocketbase';
import Layout from '../../layouts/Layout.astro';
import AstroUtils from '../../libs/AstroUtils';
import { getUser, setUser } from 'libs/AuthUtils';
import UserObj from 'models/User';
//const connected = await getUser(Astro.cookies)
const connected = await getUser(Astro.cookies)
// if(connected) {
// return Astro.redirect(route('/'))
// }
if(connected) {
return Astro.redirect(route('/'))
}
const res = await AstroUtils.wrap(async () => {
@ -15,19 +17,15 @@ const res = await AstroUtils.wrap(async () => {
return
}
const form = await Astro.request.formData()
const request = {
username: form.get("username") as String,
name: form.get("name") as String,
email: form.get("email") as String,
password: form.get("password") as String,
passwordConfirm: form.get("passwordConfirm") as String,
const request : UserObj = {
username: form.get("username") as string,
name: form.get("name") as string,
email: form.get("email") as string,
password: form.get("password") as string,
passwordConfirm: form.get("passwordConfirm") as string,
emailVisibility: false
}
const pb = new PocketBase('http://127.0.0.1:3001');
console.log(request);
const record = await pb.collection('users').create(request);
console.log(record);
await setUser(Astro.cookies, request);
})
---