Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registration page #1143

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#DATABASE = "mongodb://localhost:27017"
#RESEND_API = "your resend_api"
DATABASE = "mongodb+srv://lohahussain0:[email protected]/idurtest?retryWrites=true&w=majority"
H9660 marked this conversation as resolved.
Show resolved Hide resolved
RESEND_API = "re_iNBb6fxD_MGUSfxesy3rJQQTENYWrfDaC"
#OPENAI_API_KEY = "your open_ai api key"
JWT_SECRET= "your_private_jwt_secret_key"
NODE_ENV = "production"
Expand Down
4 changes: 2 additions & 2 deletions backend/package-lock.json

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

6 changes: 3 additions & 3 deletions backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ app.use(compression());

// Here our API Routes

app.use('/api', coreAuthRouter);
app.use('/api', adminAuth.isValidAuthToken, coreApiRouter);
app.use('/api', adminAuth.isValidAuthToken, erpApiRouter);
app.use('/api', coreAuthRouter); // This is for common users
app.use('/api', adminAuth.isValidAuthToken, coreApiRouter); // This is for admins
app.use('/api', adminAuth.isValidAuthToken, erpApiRouter); // This is for erps
app.use('/download', coreDownloadRouter);
app.use('/public', corePublicRouter);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const isValidAuthToken = require('./isValidAuthToken');
const login = require('./login');
const logout = require('./logout');
const register = require('./register');
const forgetPassword = require('./forgetPassword');
const resetPassword = require('./resetPassword');

Expand All @@ -17,6 +18,11 @@ const createAuthMiddleware = (userModel) => {
userModel,
});

authMethods.register = (req, res) =>
register(req, res, {
userModel,
});

authMethods.forgetPassword = (req, res) =>
forgetPassword(req, res, {
userModel,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const Joi = require('joi');

const mongoose = require('mongoose');
const checkAndCorrectURL = require('./checkAndCorrectURL');
const sendMail = require('./sendMail');
const { loadSettings } = require('@/middlewares/settings');
const { useAppSettings } = require('@/settings');
const AdminPassword = require('@/models/coreModels/AdminPassword');

const register = async (req, res, { userModel }) => {
const UserModel = new mongoose.model(userModel);
const PasswordInstance = new AdminPassword();

const { name, email, password, country } = req.body;

// validate
const objectSchema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: true } })
.required(),
name: Joi.string().required(),
country: Joi.string().required(),
password: Joi.string().required(),
});

const { error, value } = objectSchema.validate({ name, email, password, country });
if (error) {
return res.status(409).json({
success: false,
result: null,
error: error,
message: 'Invalid/Missing credentials.',
errorMessage: error.message,
});
}

const user = await UserModel.findOne({ email: email, removed: false });
if (user)
return res.status(409).json({
success: false,
result: null,
message: 'An account with this email already exists.',
});

const salt = await bcrypt.genSalt(10);
const hashedPassword = await PasswordInstance.generateHash(salt, password);
const newUser = {
name: name,
email: email,
country: country,
enabled: true,
};

const createdUser = await UserModel.create(newUser);
const newUserPassword = new AdminPassword({
removed: false,
user: createdUser,
password: hashedPassword,
salt: salt,
emailVerified: false,
authType: 'email',
loggedSessions: [],
});

const newPassword = await newUserPassword.save();
const settings = useAppSettings();
const idurar_app_email = settings['idurar_app_email'];
const idurar_base_url = settings['idurar_base_url'];
const url = checkAndCorrectURL(idurar_base_url);
const link = url + '/verify/' + createdUser._id + '/' + newPassword.emailToken;
await sendMail({
email,
name,
link,
idurar_app_email,
emailToken: newPassword.emailToken,
});

if (!createdUser || !newUserPassword) {
return res.status(500).json({
success: false,
result: null,
message: 'Error creating your account.',
});
} else {
const success = {
success: true,
};
const newUser = { ...createdUser, ...success };
return res.status(200).json(newUser);
}
};

module.exports = register;
2 changes: 1 addition & 1 deletion backend/src/routes/coreRoutes/coreAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { catchErrors } = require('@/handlers/errorHandlers');
const adminAuth = require('@/controllers/coreControllers/adminAuth');

router.route('/login').post(catchErrors(adminAuth.login));

router.route('/register').post(catchErrors(adminAuth.register));
router.route('/forgetpassword').post(catchErrors(adminAuth.forgetPassword));
router.route('/resetpassword').post(catchErrors(adminAuth.resetPassword));

Expand Down
1 change: 1 addition & 0 deletions frontend/src/auth/auth.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const login = async ({ loginData }) => {

export const register = async ({ registerData }) => {
try {

const response = await axios.post(API_BASE_URL + `register`, registerData);

const { status, data } = response;
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ const LoginPage = () => {
>
{translate('Log in')}
</Button>
<Button
type="primary"
htmlType="button"
className="login-form-button"
loading={isLoading}
size="large"
onClick = {()=>{ navigate('/register')}}
>
{translate('Register')}
</Button>
</Form.Item>
</Form>
</Loading>
Expand Down
60 changes: 60 additions & 0 deletions frontend/src/pages/Register.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useEffect } from 'react';

import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import useLanguage from '@/locale/useLanguage';

import { Form, Button } from 'antd';

import { selectAuth } from '@/redux/auth/selectors';
import RegisterForm from '@/forms/RegisterForm';
import Loading from '@/components/Loading';
import AuthModule from '@/modules/AuthModule';
import { register } from '@/redux/auth/actions';
const RegisterPage = () => {
const translate = useLanguage();
const { isLoading, isSuccess } = useSelector(selectAuth);
const navigate = useNavigate();
// const size = useSize();

const dispatch = useDispatch();
const onFinish = (values) => {
console.log(values);
dispatch(register({ registerData: values }));
navigate('/');
};

const FormContainer = () => {
return (
<Loading isLoading={isLoading}>
<Form
layout="vertical"
name="normal_login"
className="login-form"
initialValues={{
remember: true,
}}
onFinish={onFinish}
>
<RegisterForm />
<Form.Item>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
loading={isLoading}
size="large"
>
{translate('Register')}
</Button>
</Form.Item>
</Form>
</Loading>
);
};

return <AuthModule authContent={<FormContainer />} AUTH_TITLE="Sign Up" />;
};

export default RegisterPage;
2 changes: 2 additions & 0 deletions frontend/src/router/AuthRouter.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Routes, Route, Navigate } from 'react-router-dom';

import Login from '@/pages/Login';
import Register from '@/pages/Register';
import NotFound from '@/pages/NotFound';

import ForgetPassword from '@/pages/ForgetPassword';
Expand All @@ -15,6 +16,7 @@ export default function AuthRouter() {
<Routes>
<Route element={<Login />} path="/" />
<Route element={<Login />} path="/login" />
<Route element={<Register/>} path="/register"/>
<Route element={<Navigate to="/login" replace />} path="/logout" />
<Route element={<ForgetPassword />} path="/forgetpassword" />
<Route element={<ResetPassword />} path="/resetpassword/:userId/:resetToken" />
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/router/routes.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Navigate } from 'react-router-dom';

const Logout = lazy(() => import('@/pages/Logout.jsx'));
const NotFound = lazy(() => import('@/pages/NotFound.jsx'));

const Register = lazy(()=> import('@/pages/Register.jsx'));
const Dashboard = lazy(() => import('@/pages/Dashboard'));
const Customer = lazy(() => import('@/pages/Customer'));
const Invoice = lazy(() => import('@/pages/Invoice'));
Expand Down Expand Up @@ -61,6 +61,10 @@ let routes = {
path: '/logout',
element: <Logout />,
},
{
path: '/register',
element: <Register/>
},
{
path: '/about',
element: <About />,
Expand Down