Skip to content

Commit

Permalink
implement register and authenticator handler in api; implement regist…
Browse files Browse the repository at this point in the history
…er and login in app b00tc4mp#84
  • Loading branch information
Eden23 committed Aug 12, 2024
1 parent 69213cf commit 75fd61d
Show file tree
Hide file tree
Showing 37 changed files with 312 additions and 114 deletions.
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
export default {}
import 'dotenv/config'
import jwt from 'jsonwebtoken'

import { logic } from 'core'
import { errors } from 'com'

const { SessionError } = errors

export default (req, res, next) => {
const { username, password } = req.body

try {
logic.authenticateUser(username, password)
.then(userId =>
jwt.sign({ sub: userId }, process.env.JWT_SECRET, (error, token) => {
if (error) {
next(new SessionError(error.message))

return
}

res.json(token)
})
)
.catch(error => next(error))
} catch (error) {
next(error)
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
export default {}
import { logic } from 'core'

export default (req, res, next) => {
const { username, email, password, role } = req.body

try {
logic.registerUser(username, email, password, role)
.then(() => res.status(201).send())
.catch(error => next(error))
} catch (error) {
next(error)
}
}
4 changes: 2 additions & 2 deletions staff/marti-herms/project/V-HUB/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import express from 'express'

import { mongoose } from 'core'

import { cors, jsonBodyParser, jwtVerifier, errorHandler } from './middleware'
import { cors, jsonBodyParser, jwtVerifier, errorHandler } from './middleware/index.js'

import handle from './handlers'
import handle from './handlers/index.js'

mongoose.connect(process.env.MONGODB_URI)
.then(() => {
Expand Down
5 changes: 1 addition & 4 deletions staff/marti-herms/project/V-HUB/api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions staff/marti-herms/project/V-HUB/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@
"dependencies": {
"com": "file:../com",
"core": "file:../core",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2"
},
"devDependencies": {
"dotenv": "^16.4.5"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
curl -v http://localhost:8080/users/auth -X POST -d '{"username":"eden","password":"123123123"}' -H "Content-Type: application/json"
1 change: 1 addition & 0 deletions staff/marti-herms/project/V-HUB/api/test/register-user.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
curl -v http://localhost:8080/users -X POST -d '{"username":"eden","email":"[email protected]","password":"123123123","dev":"false"}' -H "Content-Type: application/json"
2 changes: 1 addition & 1 deletion staff/marti-herms/project/V-HUB/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<body>
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
<script type="module" src="/index.jsx"></script>
</body>

</html>
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ReactDOM from 'react-dom/client'
import { BrowserRouter as Router } from 'react-router-dom'

import App from './App.jsx'
import App from './src/App.jsx'

import './index.css'

Expand Down
16 changes: 11 additions & 5 deletions staff/marti-herms/project/V-HUB/app/logic/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import loginUser from "./loginUser";
import registerUser from "./registerUser";
import loginUser from './loginUser';
import logoutUser from './logoutUser';
import registerUser from './registerUser';
import isUserLoggedIn from './isUserLoggedIn';

export default logic = {
const logic = {
loginUser,
registerUser
}
logoutUser,
registerUser,
isUserLoggedIn
}

export default logic
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default () => !!sessionStorage.token
33 changes: 31 additions & 2 deletions staff/marti-herms/project/V-HUB/app/logic/loginUser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
import { validate, errors } from 'com'

const { SystemError } = errors

export default (username, password) => {
//validation
validate.username(username)
validate.password(password)

return fetch(`${import.meta.env.VITE_API_URL}/users/auth`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
})
.catch(error => { throw new SystemError(error.message) })
.then(response => {
const { status } = response

if (status === 200) {
return response.json()
.then(token => sessionStorage.token = token)
}

return response.json()
.then(body => {
const { error, message } = body

const constructor = errors[error]

//fetch
throw new constructor(message)
})
})
}
1 change: 1 addition & 0 deletions staff/marti-herms/project/V-HUB/app/logic/logoutUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default () => delete sessionStorage.token
36 changes: 33 additions & 3 deletions staff/marti-herms/project/V-HUB/app/logic/registerUser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
export default (username, email, password) => {
//validation
import { validate, errors } from "com"

//fetch
const { SystemError, ValidationError } = errors

export default (username, email, password, rePassword, role) => {
validate.username(username)
validate.email(email)
validate.password(password)
validate.string(role, 'role')

if (password !== rePassword) throw new ValidationError('passwords do not match')

return fetch(`${import.meta.env.VITE_API_URL}/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, email, password, role })
})
.catch(error => { throw new SystemError(error.message) })
.then(response => {
const { status } = response

if (status === 201) return

return response.json()
.then(body => {
const { error, message } = body

const constructor = errors[error]

throw new constructor(message)
})
})
}
13 changes: 11 additions & 2 deletions staff/marti-herms/project/V-HUB/app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion staff/marti-herms/project/V-HUB/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"com": "file:../com",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
Expand All @@ -27,4 +28,4 @@
"tailwindcss": "^3.4.7",
"vite": "^5.3.4"
}
}
}
36 changes: 28 additions & 8 deletions staff/marti-herms/project/V-HUB/app/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import { useState, useEffect } from 'react'
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'

import Home from './Home'
import Register from './Register'
import Login from './Login'
import Home from './home'
import Register from './register'
import Login from './login'
import Alert from './common/Alert'

import { Context } from './context'

import logic from '../logic'

export default function App() {
const navigate = useNavigate()

const { theme, setTheme } = useState(localStorage.theme)
const { alertMessage, setAlertMessage } = useState(null)

useEffect(() => {
document.documentElement.className = theme
localStorage.theme = theme
}, [theme])

const handleLogin = () => {
navigate('/')
}
Expand All @@ -27,9 +41,15 @@ export default function App() {
navigate('/login')
}

return <Routes>
<Route path='/login' element={<Login onLogin={handleLogin} onRegisterClick={handleRegisterClick} />} />
<Route path='/register' element={<Register onRegister={handleRegister} onLoginClick={handleLoginClick} />} />
<Route path='/*' element={<Home onLogout={handleLogout} />} />
</Routes>
const handleAlertAccept = () => setAlertMessage(null)

return <Context.Provider value={{ theme, setTheme, alert: setAlertMessage }}>
<Routes>
<Route path='/login' element={logic.isUserLoggedIn() ? <Navigate to='/' /> : <Login onLogin={handleLogin} onRegisterClick={handleRegisterClick} />} />
<Route path='/register' element={logic.isUserLoggedIn() ? <Navigate to='/' /> : <Register onRegister={handleRegister} onLoginClick={handleLoginClick} />} />
<Route path='/*' element={logic.isUserLoggedIn() ? <Home onLogout={handleLogout} /> : <Navigate to='/login' />} />
</Routes>

{alertMessage && <Alert message={alertMessage} onAccept={handleAlertAccept} />}
</Context.Provider>
}
42 changes: 0 additions & 42 deletions staff/marti-herms/project/V-HUB/app/src/Login.jsx

This file was deleted.

16 changes: 16 additions & 0 deletions staff/marti-herms/project/V-HUB/app/src/common/Alert.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Button from '../library/Button'
import Paragraph from '../library/Paragraph'
import Container from '../library/Container'

export default function Alert({ message, onAccept }) {
return <>
<Container className='fixed w-screen top-0 h-screen bg-black opacity-50'></Container>

<Container className='fixed w-screen top-0 h-screen flex items-center justify-center'>
<Container className='p-4 border bg-white dark:bg-black dark: text-white flex-col'>
<Paragraph>{message}</Paragraph>
<Button onClick={onAccept}>Accept</Button>
</Container>
</Container>
</>
}
Loading

0 comments on commit 75fd61d

Please sign in to comment.