mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2026-10-23 20:17:57 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ed37c30e1 | ||
|
|
c2f63ccc72 | ||
|
|
970a41c895 | ||
|
|
3fd29b3905 | ||
|
|
7f7fef3f89 | ||
|
|
90ee8023e6 | ||
|
|
c486d558ad | ||
|
|
85569af770 | ||
|
|
f97bb08c5c | ||
|
|
6f6e3f7e7b | ||
|
|
26b2d153fd | ||
|
|
2577f2dcac | ||
|
|
e4b69a406f | ||
|
|
2fdce34ffc | ||
|
|
2bf9dea771 | ||
|
|
847c078735 | ||
|
|
14e70a63b8 | ||
|
|
05872b5170 |
@@ -0,0 +1,31 @@
|
|||||||
|
NODE_ENV=dev
|
||||||
|
PORT=5000
|
||||||
|
DB_HOST=
|
||||||
|
DB_PASS=
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_NAME=
|
||||||
|
MIGRATIONS_RUN=true
|
||||||
|
SWAGGER_API_DOCS_PATH="/api-docs"
|
||||||
|
|
||||||
|
JWT_ACCESS_TOKEN_SECRET=your_access_token_secret
|
||||||
|
JWT_ACCESS_TOKEN_EXPIRY=1d
|
||||||
|
JWT_REFRESH_TOKEN_SECRET=your_refresh_token_secret
|
||||||
|
JWT_REFRESH_TOKEN_EXPIRY=1d
|
||||||
|
USE_MOCK=true
|
||||||
|
|
||||||
|
|
||||||
|
OCI_TENANCY_ID=
|
||||||
|
OCI_USER_ID=
|
||||||
|
OCI_FINGERPRINT=
|
||||||
|
OCI_PRIVATE_KEY=
|
||||||
|
OCI_PASSPHRASE=""
|
||||||
|
OCI_NAMESPACE=
|
||||||
|
OCI_REGION=
|
||||||
|
|
||||||
|
|
||||||
|
MAIL_HOST=smtp.gmail.com
|
||||||
|
MAIL_USER=[email protected]
|
||||||
|
MAIL_PASSWORD=
|
||||||
|
MAIL_PORT=587
|
||||||
|
MAIL_FROM=UBA
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/** @type {import('eslint').Linter.Config} */
|
||||||
|
module.exports = {
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
parserOptions: {
|
||||||
|
project: 'tsconfig.json',
|
||||||
|
tsconfigRootDir: __dirname,
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||||
|
extends: ['plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', 'plugin:security/recommended'],
|
||||||
|
root: true,
|
||||||
|
env: {
|
||||||
|
node: true,
|
||||||
|
jest: true,
|
||||||
|
},
|
||||||
|
ignorePatterns: ['.eslintrc.js', 'node_modules', 'dist', 'coverage', 'jest*\\.ts', 'typeorm*\\.ts'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/interface-name-prefix': 'off',
|
||||||
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'warn',
|
||||||
|
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
|
||||||
|
],
|
||||||
|
'@typescript-eslint/no-inferrable-types': 'off',
|
||||||
|
'func-names': ['error', 'as-needed'],
|
||||||
|
'no-underscore-dangle': ['error'],
|
||||||
|
'require-await': ['error'],
|
||||||
|
'no-console': ['error'],
|
||||||
|
'no-multi-assign': ['error'],
|
||||||
|
'no-magic-numbers': ['error', { ignoreArrayIndexes: true }],
|
||||||
|
'no-multiple-empty-lines': ['error', { max: 1, maxEOF: 1, maxBOF: 0 }],
|
||||||
|
'max-len': [
|
||||||
|
'error',
|
||||||
|
{ code: 120, tabWidth: 2, ignoreUrls: true, ignoreStrings: true, ignoreTemplateLiterals: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
overrides: [
|
||||||
|
{
|
||||||
|
files: ['*spec.ts'],
|
||||||
|
rules: {
|
||||||
|
'no-magic-numbers': ['off'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
name: CI Zod
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
- main
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_ENV: development
|
||||||
|
TAG: dev
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
install_dependencies:
|
||||||
|
name: Install Dependencies
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Cache Node Modules
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-node_modules-
|
||||||
|
|
||||||
|
run_tests:
|
||||||
|
name: Run Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: install_dependencies
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Run Lint
|
||||||
|
run: npm run lint
|
||||||
|
|
||||||
|
- name: Run Tests with Coverage
|
||||||
|
run: npm run test:cov
|
||||||
|
|
||||||
|
build_app:
|
||||||
|
name: Build Application
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: run_tests
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Build Application
|
||||||
|
run: npm run build
|
||||||
|
|
||||||
|
- name: Upload Build Artifacts
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: dist
|
||||||
|
path: dist/
|
||||||
+52
-21
@@ -1,24 +1,55 @@
|
|||||||
/static
|
# compiled output
|
||||||
/media
|
/dist
|
||||||
.idea/
|
/node_modules
|
||||||
*.pyc
|
/build
|
||||||
media/
|
|
||||||
*.name
|
# Logs
|
||||||
*.iml
|
logs
|
||||||
*.log
|
*.log
|
||||||
*.xml
|
npm-debug.log*
|
||||||
*.pyo
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.idea
|
|
||||||
venv/*
|
# Tests
|
||||||
static/*
|
/coverage
|
||||||
*.pem
|
/.nyc_output
|
||||||
*.sqlite3
|
|
||||||
/migrations/__pycache__/
|
# IDEs and editors
|
||||||
/__pycache__/
|
/.idea
|
||||||
/*.pyc
|
.project
|
||||||
*/__pycache__/*.pyc
|
.classpath
|
||||||
__pycache__/
|
.c9/
|
||||||
*.env
|
*.launch
|
||||||
ve/*
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
|
||||||
|
|
||||||
|
# dotenv environment variable files
|
||||||
|
.env
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# temp directory
|
||||||
|
.temp
|
||||||
|
.tmp
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
pids
|
||||||
|
*.pid
|
||||||
|
*.seed
|
||||||
|
*.pid.lock
|
||||||
|
|
||||||
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"printWidth": 120
|
||||||
|
}
|
||||||
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"editor.codeActionsOnSave": {
|
||||||
|
"source.organizeImports": "explicit"
|
||||||
|
}
|
||||||
|
}
|
||||||
-11
@@ -1,11 +0,0 @@
|
|||||||
FROM python:3.9
|
|
||||||
ENV PYTHONUNBUFFERED 1
|
|
||||||
RUN mkdir /usr/src/app
|
|
||||||
WORKDIR /usr/src/app
|
|
||||||
COPY . .
|
|
||||||
RUN apt-get update
|
|
||||||
RUN apt-get install wkhtmltopdf -y
|
|
||||||
RUN apt install -y gdal-bin python3-gdal
|
|
||||||
RUN pip install -r requirements.txt
|
|
||||||
WORKDIR /usr/src/app
|
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Base image
|
||||||
|
FROM node:22.4.1-alpine
|
||||||
|
RUN apk update && \
|
||||||
|
apk upgrade && \
|
||||||
|
apk add ca-certificates curl && \
|
||||||
|
update-ca-certificates
|
||||||
|
|
||||||
|
#saudi timezone
|
||||||
|
ENV TZ=Asia/Riyadh
|
||||||
|
|
||||||
|
# Create app directory
|
||||||
|
RUN mkdir /app && chown node:node /app
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# finally switch user to node
|
||||||
|
USER node
|
||||||
|
|
||||||
|
|
||||||
|
# A wildcard is used to ensure both package.json, package-lock.json and package-lock.json are copied
|
||||||
|
COPY --chown=node:node package*.json ./
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Install app dependencies
|
||||||
|
RUN npm install --frozen-lockfile
|
||||||
|
# Bundle app source
|
||||||
|
COPY --chown=node:node . .
|
||||||
|
|
||||||
|
# Creates a "dist" folder with the production build
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Start the server using the production build
|
||||||
|
CMD [ "node", "dist/main" ]
|
||||||
@@ -1 +1,99 @@
|
|||||||
# ZODBank-Backend
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"""Account admin"""
|
|
||||||
from django.contrib import admin
|
|
||||||
|
|
||||||
"""Import django app"""
|
|
||||||
from .models import UserProfile, UserEmailOtp, UserPhoneOtp
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(UserProfile)
|
|
||||||
class UserProfileAdmin(admin.ModelAdmin):
|
|
||||||
"""User profile admin"""
|
|
||||||
list_display = ['user']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.user__email
|
|
||||||
|
|
||||||
@admin.register(UserEmailOtp)
|
|
||||||
class UserEmailOtpAdmin(admin.ModelAdmin):
|
|
||||||
"""User Email otp admin"""
|
|
||||||
list_display = ['email']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return object in email and otp format"""
|
|
||||||
return self.email + '-' + self.otp
|
|
||||||
|
|
||||||
@admin.register(UserPhoneOtp)
|
|
||||||
class UserPhoneOtpAdmin(admin.ModelAdmin):
|
|
||||||
"""User Phone otp admin"""
|
|
||||||
list_display = ['phone']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return object in phone number and otp format"""
|
|
||||||
return self.phone + '-' + self.otp
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class AccountConfig(AppConfig):
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'account'
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserEmailOtp',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('email', models.EmailField(max_length=254)),
|
|
||||||
('otp', models.CharField(max_length=10)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_email_otp',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserPhoneOtp',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('country_code', models.IntegerField()),
|
|
||||||
('phone', models.CharField(max_length=17)),
|
|
||||||
('otp', models.CharField(max_length=10)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_phone_otp',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserProfile',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('user_type', models.CharField(blank=True, choices=[('1', 'junior'), ('2', 'guardian'), ('3', 'superuser')], default=None, max_length=15, null=True)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('is_active', models.BooleanField(default=False)),
|
|
||||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_profile', to=settings.AUTH_USER_MODEL)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_profile',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('account', '0001_initial'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='useremailotp',
|
|
||||||
name='user_type',
|
|
||||||
field=models.CharField(blank=True, choices=[('1', 'junior'), ('2', 'guardian'), ('3', 'superuser')], default=None, max_length=15, null=True),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
from django.db import models
|
|
||||||
import random
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from base.constants import USER_TYPE
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class UserProfile(models.Model):
|
|
||||||
"""
|
|
||||||
User details
|
|
||||||
"""
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile')
|
|
||||||
user_type = models.CharField(max_length=15, choices=USER_TYPE, null=True, blank=True, default=None)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
is_active = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_profile'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return f'{self.user}'
|
|
||||||
|
|
||||||
class UserPhoneOtp(models.Model):
|
|
||||||
"""
|
|
||||||
This class is used to verify user email and their contact no.
|
|
||||||
"""
|
|
||||||
"""user details"""
|
|
||||||
country_code = models.IntegerField()
|
|
||||||
phone = models.CharField(max_length=17)
|
|
||||||
"""otp details"""
|
|
||||||
otp = models.CharField(max_length=10)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
expired_at = models.DateTimeField(blank=True, null=True)
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_phone_otp'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return self.phone
|
|
||||||
|
|
||||||
class UserEmailOtp(models.Model):
|
|
||||||
"""
|
|
||||||
This class is used to verify user email and their contact no.
|
|
||||||
"""
|
|
||||||
"""user details"""
|
|
||||||
email = models.EmailField()
|
|
||||||
"""otp details"""
|
|
||||||
otp = models.CharField(max_length=10)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
user_type = models.CharField(max_length=15, choices=USER_TYPE, null=True, blank=True, default=None)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
expired_at = models.DateTimeField(blank=True, null=True)
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_email_otp'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return self.email
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
from rest_framework import serializers
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from junior.models import Junior
|
|
||||||
from account.models import UserProfile, UserEmailOtp, UserPhoneOtp
|
|
||||||
from base.constants import GUARDIAN, JUNIOR, SUPERUSER
|
|
||||||
from django.db import transaction
|
|
||||||
from base.messages import ERROR_CODE_REQUIRED, ERROR_CODE, SUCCESS_CODE, STATUS_CODE_ERROR
|
|
||||||
from django.core.exceptions import ObjectDoesNotExist
|
|
||||||
from django.contrib.auth import authenticate
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.decorators import action
|
|
||||||
from django.contrib.auth import authenticate, login
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
from guardian.utils import upload_image_to_alibaba
|
|
||||||
from .utils import get_token
|
|
||||||
|
|
||||||
|
|
||||||
class GoogleLoginSerializer(serializers.Serializer):
|
|
||||||
access_token = serializers.CharField(max_length=5000, required=True)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
"""meta class"""
|
|
||||||
fields = ('access_token',)
|
|
||||||
|
|
||||||
class UpdateGuardianImageSerializer(serializers.ModelSerializer):
|
|
||||||
"""Reset Password after verification"""
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Guardian
|
|
||||||
fields = '__all__'
|
|
||||||
|
|
||||||
def update(self, instance, validated_data):
|
|
||||||
"""update image """
|
|
||||||
instance.image = validated_data.get('image', instance.image)
|
|
||||||
instance.save()
|
|
||||||
return instance
|
|
||||||
|
|
||||||
class UpdateJuniorProfileImageSerializer(serializers.ModelSerializer):
|
|
||||||
"""Reset Password after verification"""
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Junior
|
|
||||||
fields = '__all__'
|
|
||||||
|
|
||||||
def update(self, instance, validated_data):
|
|
||||||
"""update image """
|
|
||||||
image = validated_data.get('image', instance.image)
|
|
||||||
filename = f"images/{image.name}"
|
|
||||||
image_url = upload_image_to_alibaba(image, filename)
|
|
||||||
instance.image = image_url
|
|
||||||
instance.save()
|
|
||||||
return instance
|
|
||||||
class ResetPasswordSerializer(serializers.Serializer):
|
|
||||||
"""Reset Password after verification"""
|
|
||||||
verification_code = serializers.CharField(max_length=10)
|
|
||||||
password = serializers.CharField(required=True)
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
verification_code = validated_data.pop('verification_code')
|
|
||||||
password = validated_data.pop('password')
|
|
||||||
user_opt_details = UserEmailOtp.objects.filter(otp=verification_code, is_verified=True).last()
|
|
||||||
if user_opt_details:
|
|
||||||
user_details = User.objects.filter(email=user_opt_details.email).last()
|
|
||||||
if user_details:
|
|
||||||
if user_details.check_password(password):
|
|
||||||
raise serializers.ValidationError({"details":ERROR_CODE['2001'],"code":"400", "status":"failed"})
|
|
||||||
user_details.set_password(password)
|
|
||||||
user_details.save()
|
|
||||||
return {'password':password}
|
|
||||||
return user_opt_details
|
|
||||||
return ''
|
|
||||||
|
|
||||||
class ChangePasswordSerializer(serializers.Serializer):
|
|
||||||
"""Update Password after verification"""
|
|
||||||
current_password = serializers.CharField(max_length=100)
|
|
||||||
new_password = serializers.CharField(required=True)
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
|
|
||||||
def validate_current_password(self, value):
|
|
||||||
user = self.context
|
|
||||||
if self.context.password not in ('', None):
|
|
||||||
if user.check_password(value):
|
|
||||||
return value
|
|
||||||
raise serializers.ValidationError({"details":ERROR_CODE['2015']})
|
|
||||||
def create(self, validated_data):
|
|
||||||
new_password = validated_data.pop('new_password')
|
|
||||||
current_password = validated_data.pop('current_password')
|
|
||||||
if new_password == current_password:
|
|
||||||
raise serializers.ValidationError({"details": ERROR_CODE['2026']})
|
|
||||||
user_details = User.objects.filter(email=self.context).last()
|
|
||||||
if user_details:
|
|
||||||
user_details.set_password(new_password)
|
|
||||||
user_details.save()
|
|
||||||
return {'password':new_password}
|
|
||||||
return ''
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class ForgotPasswordSerializer(serializers.Serializer):
|
|
||||||
"""Forget password serializer"""
|
|
||||||
email = serializers.EmailField()
|
|
||||||
|
|
||||||
class SuperUserSerializer(serializers.ModelSerializer):
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
"""user type"""
|
|
||||||
return SUPERUSER
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
fields = ['id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'user_type']
|
|
||||||
|
|
||||||
|
|
||||||
class GuardianSerializer(serializers.ModelSerializer):
|
|
||||||
"""guardian serializer"""
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
email = serializers.SerializerMethodField('get_auth')
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
refresh_token = serializers.SerializerMethodField('get_refresh_token')
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
return get_token()['access']
|
|
||||||
def get_refresh_token(self, obj):
|
|
||||||
return get_token()['refresh']
|
|
||||||
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
"""user type"""
|
|
||||||
return GUARDIAN
|
|
||||||
|
|
||||||
def get_auth(self, obj):
|
|
||||||
"""user email address"""
|
|
||||||
return obj.user.username
|
|
||||||
|
|
||||||
def get_first_name(self, obj):
|
|
||||||
"""user first name"""
|
|
||||||
return obj.user.first_name
|
|
||||||
|
|
||||||
def get_last_name(self, obj):
|
|
||||||
"""user last name"""
|
|
||||||
return obj.user.last_name
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Guardian
|
|
||||||
fields = ['auth_token', 'refresh_token', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'family_name', 'gender', 'dob',
|
|
||||||
'referral_code', 'is_active', 'is_complete_profile', 'passcode', 'image',
|
|
||||||
'created_at', 'updated_at', 'user_type']
|
|
||||||
|
|
||||||
|
|
||||||
class JuniorSerializer(serializers.ModelSerializer):
|
|
||||||
"""junior serializer"""
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
email = serializers.SerializerMethodField('get_auth')
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
refresh_token = serializers.SerializerMethodField('get_refresh_token')
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
return get_token()['access']
|
|
||||||
def get_refresh_token(self, obj):
|
|
||||||
return get_token()['refresh']
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
return JUNIOR
|
|
||||||
|
|
||||||
def get_auth(self, obj):
|
|
||||||
return obj.auth.username
|
|
||||||
|
|
||||||
def get_first_name(self, obj):
|
|
||||||
return obj.auth.first_name
|
|
||||||
|
|
||||||
def get_last_name(self, obj):
|
|
||||||
return obj.auth.last_name
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Junior
|
|
||||||
fields = ['auth_token', 'refresh_token', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'gender', 'dob',
|
|
||||||
'guardian_code', 'referral_code','is_active', 'is_complete_profile', 'created_at', 'image',
|
|
||||||
'updated_at', 'user_type']
|
|
||||||
|
|
||||||
class EmailVerificationSerializer(serializers.ModelSerializer):
|
|
||||||
"""Email verification serializer"""
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = UserEmailOtp
|
|
||||||
fields = '__all__'
|
|
||||||
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<!DOCTYPE HTML>
|
|
||||||
{% block subject %}DinDin{% endblock %}
|
|
||||||
{% load static %}
|
|
||||||
|
|
||||||
{% block html %}
|
|
||||||
<html lang="en" style="height: 100%;">
|
|
||||||
<head>
|
|
||||||
<meta http-equiv="Content-Type"
|
|
||||||
content="text/html; charset=UTF-8">
|
|
||||||
<meta name="viewport"
|
|
||||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
|
|
||||||
<title>Zod Bank | OTP</title>
|
|
||||||
<style type="text/css">
|
|
||||||
@media all and (max-width: 599px) {
|
|
||||||
.block {
|
|
||||||
display: block !important;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
.top-space {
|
|
||||||
padding: 15px 0 0 !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body style="margin: 0; padding: 0; background: #f7f8f9; height: 100%;">
|
|
||||||
<!-- begin template body -->
|
|
||||||
<table style="background:#f7f8f9; border: 0; border-collapse: separate; border-spacing: 0px; margin: auto; width: 100%; font-family: Arial, Helvetica, sans-serif; height: 100%;" aria-describedby="email-data-wrapper">
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0;">
|
|
||||||
<table style="background-color: white; border-collapse: separate; border-spacing: 0px; border: 1px solid #e4e8eb; width: 100%; max-width: 600px; margin-right:auto; margin-left: auto;
|
|
||||||
font-family: Arial, Helvetica, sans-serif;" aria-describedby="email-data-wrapper">
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 41px 30px 40px; height: 39px; background: url({% static 'images/backgrounds/email_template.png' %}) left center no-repeat; background-size: cover;">
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% block plain %}
|
|
||||||
{% endblock %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px;">
|
|
||||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">-</p>
|
|
||||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">Cheers!</p>
|
|
||||||
<p style="margin: 0 0 30px; font-size: 14px; line-height: 20px; color: #505050; font-weight: 700;">Zod Bank Team</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<!-- end template body -->
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{% extends "templated_email/email_base.email" %}
|
|
||||||
|
|
||||||
{% block subject %}
|
|
||||||
OTP Verification
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block plain %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 15px;">
|
|
||||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
|
||||||
Hi User,
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 22px;">
|
|
||||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
|
||||||
You are receiving this email for email verification. Please use <b>{{ otp }} </b>as the verification code for your email address & username.
|
|
||||||
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{% extends "templated_email/email_base.email" %}
|
|
||||||
|
|
||||||
{% block subject %}
|
|
||||||
Password Reset Verification Code
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block plain %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 15px;">
|
|
||||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
|
||||||
Hi User,
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 22px;">
|
|
||||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
|
||||||
You are receiving this email for reset password verification. Please use <b>{{ verification_code }} </b>as the verification code.
|
|
||||||
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from rest_framework.decorators import api_view
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
from .views import (UserLogin, SendPhoneOtp, UserPhoneVerification, UserEmailVerification, ReSendEmailOtp,
|
|
||||||
ForgotPasswordAPIView, ResetPasswordAPIView, ChangePasswordAPIView, UpdateProfileImage,
|
|
||||||
GoogleLoginViewSet, SigninWithApple)
|
|
||||||
"""Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
router.register('user', UserLogin, basename='user')
|
|
||||||
router.register('admin', UserLogin, basename='admin')
|
|
||||||
router.register('google-login', GoogleLoginViewSet, basename='admin')
|
|
||||||
router.register('send-phone-otp', SendPhoneOtp, basename='send-phone-otp')
|
|
||||||
router.register('user-phone-verification', UserPhoneVerification, basename='user-phone-verification')
|
|
||||||
router.register('user-email-verification', UserEmailVerification, basename='user-email-verification')
|
|
||||||
router.register('resend-email-otp', ReSendEmailOtp, basename='resend-email-otp')
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
path('api/v1/forgot-password/', ForgotPasswordAPIView.as_view()),
|
|
||||||
path('api/v1/reset-password/', ResetPasswordAPIView.as_view()),
|
|
||||||
path('api/v1/change-password/', ChangePasswordAPIView.as_view()),
|
|
||||||
path('api/v1/update-profile-image/', UpdateProfileImage.as_view()),
|
|
||||||
path('api/v1/apple-login/', SigninWithApple.as_view(), name='signup_with_apple'),
|
|
||||||
]
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
"""Account utils"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.conf import settings
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.response import Response
|
|
||||||
from templated_email import send_templated_mail
|
|
||||||
import jwt
|
|
||||||
from datetime import datetime
|
|
||||||
from calendar import timegm
|
|
||||||
from uuid import uuid4
|
|
||||||
import secrets
|
|
||||||
|
|
||||||
def send_otp_email(recipient_email, otp):
|
|
||||||
from_email = settings.EMAIL_FROM_ADDRESS
|
|
||||||
recipient_list = [recipient_email]
|
|
||||||
send_templated_mail(
|
|
||||||
template_name='email_otp_verification.email',
|
|
||||||
from_email=from_email,
|
|
||||||
recipient_list=recipient_list,
|
|
||||||
context={
|
|
||||||
'otp': otp
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return otp
|
|
||||||
|
|
||||||
def custom_response(detail, data=None, response_status=status.HTTP_200_OK):
|
|
||||||
"""Custom response code"""
|
|
||||||
if not data:
|
|
||||||
data = None
|
|
||||||
|
|
||||||
return Response({"data": data, "message": detail, "status": "success", "code": response_status})
|
|
||||||
|
|
||||||
|
|
||||||
def custom_error_response(detail, response_status):
|
|
||||||
"""
|
|
||||||
function is used for getting same global error response for all
|
|
||||||
:param detail: error message .
|
|
||||||
:param response_status: http status.
|
|
||||||
:return: Json response
|
|
||||||
"""
|
|
||||||
if not detail:
|
|
||||||
detail = {}
|
|
||||||
return Response({"error": detail, "status": "failed", "code": response_status})
|
|
||||||
|
|
||||||
|
|
||||||
def get_user_data(attrs):
|
|
||||||
"""
|
|
||||||
used to decode token
|
|
||||||
"""
|
|
||||||
user_data = jwt.decode(jwt=attrs['token'], options={'verify_signature': False},
|
|
||||||
algorithms=['RS256'])
|
|
||||||
return user_data
|
|
||||||
|
|
||||||
|
|
||||||
def generate_jwt_token(token_type: str, now_time: int, data: dict = dict):
|
|
||||||
"""
|
|
||||||
used to generate jwt token
|
|
||||||
"""
|
|
||||||
if type(data) == type:
|
|
||||||
data = {}
|
|
||||||
data.update({
|
|
||||||
'token_type': token_type,
|
|
||||||
'iss': 'your_site_url',
|
|
||||||
'iat': timegm(datetime.utcnow().utctimetuple()),
|
|
||||||
'jti': uuid4().hex
|
|
||||||
})
|
|
||||||
TOKEN_TYPE = ["access", "refresh"]
|
|
||||||
if token_type == TOKEN_TYPE[1]:
|
|
||||||
exp = now_time + settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME']
|
|
||||||
else:
|
|
||||||
exp = now_time + settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']
|
|
||||||
|
|
||||||
data.update({
|
|
||||||
"exp": timegm(exp.utctimetuple())
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
signing_key = secrets.token_hex(32)
|
|
||||||
|
|
||||||
return jwt.encode(payload=data, key=signing_key,
|
|
||||||
algorithm='HS256')
|
|
||||||
|
|
||||||
|
|
||||||
def get_token(data: dict = dict):
|
|
||||||
""" create access and refresh token """
|
|
||||||
now_time = datetime.utcnow()
|
|
||||||
access = generate_jwt_token('access', now_time, data)
|
|
||||||
refresh = generate_jwt_token('refresh', now_time, data)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'access': access,
|
|
||||||
'refresh': refresh
|
|
||||||
}
|
|
||||||
@@ -1,328 +0,0 @@
|
|||||||
from rest_framework import viewsets, status, views
|
|
||||||
from rest_framework.decorators import action
|
|
||||||
import random
|
|
||||||
import logging
|
|
||||||
import jwt
|
|
||||||
from django.contrib.auth import authenticate, login
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from junior.models import Junior
|
|
||||||
from account.models import UserProfile, UserPhoneOtp, UserEmailOtp
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from .serializers import (SuperUserSerializer, GuardianSerializer, JuniorSerializer, EmailVerificationSerializer,
|
|
||||||
ForgotPasswordSerializer, ResetPasswordSerializer, ChangePasswordSerializer,
|
|
||||||
GoogleLoginSerializer, UpdateGuardianImageSerializer, UpdateJuniorProfileImageSerializer)
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from guardian.tasks import generate_otp
|
|
||||||
from account.utils import send_otp_email
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
from templated_email import send_templated_mail
|
|
||||||
import google.oauth2.credentials
|
|
||||||
import google.auth.transport.requests
|
|
||||||
from rest_framework import status
|
|
||||||
from rest_framework.response import Response
|
|
||||||
import requests
|
|
||||||
from django.conf import settings
|
|
||||||
from .utils import get_token
|
|
||||||
|
|
||||||
|
|
||||||
class GoogleLoginMixin:
|
|
||||||
def google_login(self, request):
|
|
||||||
access_token = request.data.get('access_token')
|
|
||||||
user_type = request.data.get('user_type')
|
|
||||||
if not access_token:
|
|
||||||
return Response({'error': 'Access token is required.'}, status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Validate the access token and obtain the user's email and name
|
|
||||||
credentials = google.oauth2.credentials.Credentials.from_authorized_user_info(
|
|
||||||
info={
|
|
||||||
'access_token': access_token,
|
|
||||||
'token_uri': 'https://oauth2.googleapis.com/token',
|
|
||||||
'client_id': settings.GOOGLE_CLIENT_ID,
|
|
||||||
'client_secret': settings.GOOGLE_CLIENT_SECRET,
|
|
||||||
'refresh_token': None,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
user_info_endpoint = f'https://www.googleapis.com/oauth2/v3/userinfo?access_token={access_token}'
|
|
||||||
headers = {'Authorization': f'Bearer {credentials.token}'}
|
|
||||||
response = requests.get(user_info_endpoint, headers=headers)
|
|
||||||
response.raise_for_status()
|
|
||||||
user_info = response.json()
|
|
||||||
email = user_info['email']
|
|
||||||
first_name = user_info['given_name']
|
|
||||||
last_name = user_info['family_name']
|
|
||||||
profile_picture = user_info['picture']
|
|
||||||
except Exception as e:
|
|
||||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
# Check if the user exists in your database or create a new user
|
|
||||||
# ...
|
|
||||||
user_data = User.objects.filter(email__iexact=email)
|
|
||||||
if user_data.exists():
|
|
||||||
if str(user_type) == '1':
|
|
||||||
junior_query = Junior.objects.filter(auth=user_data.last()).last()
|
|
||||||
serializer = JuniorSerializer(junior_query)
|
|
||||||
if str(user_type) == '2':
|
|
||||||
guardian_query = Guardian.objects.filter(user=user_data.last()).last()
|
|
||||||
serializer = GuardianSerializer(guardian_query)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
if not User.objects.filter(email__iexact=email).exists():
|
|
||||||
user_obj = User.objects.create(username=email, email=email, first_name=first_name, last_name=last_name)
|
|
||||||
if str(user_type) == '1':
|
|
||||||
junior_query = Junior.objects.create(auth=user_obj, is_verified=True, is_active=True,
|
|
||||||
image=profile_picture)
|
|
||||||
serializer = JuniorSerializer(junior_query)
|
|
||||||
if str(user_type) == '2':
|
|
||||||
guardian_query = Guardian.objects.create(user=user_obj, is_verified=True, is_active=True,
|
|
||||||
image=profile_picture)
|
|
||||||
serializer = GuardianSerializer(guardian_query)
|
|
||||||
# Return a JSON response with the user's email and name
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
|
|
||||||
class GoogleLoginViewSet(GoogleLoginMixin, viewsets.GenericViewSet):
|
|
||||||
serializer_class = GoogleLoginSerializer
|
|
||||||
|
|
||||||
def create(self, request):
|
|
||||||
serializer = self.get_serializer(data=request.data)
|
|
||||||
serializer.is_valid(raise_exception=True)
|
|
||||||
return self.google_login(request)
|
|
||||||
|
|
||||||
class SigninWithApple(views.APIView):
|
|
||||||
"""This API is for sign in with Apple for app."""
|
|
||||||
def post(self, request):
|
|
||||||
token = request.data.get("access_token")
|
|
||||||
user_type = request.data.get("user_type")
|
|
||||||
if not token:
|
|
||||||
return custom_error_response(ERROR_CODE['2027'], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
try:
|
|
||||||
decoded_data = jwt.decode(token, options={"verify_signature": False})
|
|
||||||
user_data = {"email": decoded_data.get('email'), "username": decoded_data.get('email'), "is_active": True}
|
|
||||||
if decoded_data.get("email"):
|
|
||||||
try:
|
|
||||||
user = User.objects.get(email=decoded_data.get("email"))
|
|
||||||
if str(user_type) == '1':
|
|
||||||
junior_query = Junior.objects.filter(auth=user).last()
|
|
||||||
serializer = JuniorSerializer(junior_query)
|
|
||||||
if str(user_type) == '2':
|
|
||||||
guardian_query = Guardian.objects.filter(user=user).last()
|
|
||||||
serializer = GuardianSerializer(guardian_query)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
except User.DoesNotExist:
|
|
||||||
user = User.objects.create(**user_data)
|
|
||||||
if str(user_type) == '1':
|
|
||||||
junior_query = Junior.objects.create(auth=user, is_verified=True, is_active=True)
|
|
||||||
serializer = JuniorSerializer(junior_query)
|
|
||||||
if str(user_type) == '2':
|
|
||||||
guardian_query = Guardian.objects.create(user=user, is_verified=True, is_active=True)
|
|
||||||
serializer = GuardianSerializer(guardian_query)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
class UpdateProfileImage(views.APIView):
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
def put(self, request, format=None):
|
|
||||||
if request.data['user_type'] == '1':
|
|
||||||
junior_query = Junior.objects.filter(auth=request.user).last()
|
|
||||||
serializer = UpdateJuniorProfileImageSerializer(junior_query, data=request.data, partial=True)
|
|
||||||
else:
|
|
||||||
guardian_query = Guardian.objects.filter(user=request.user).last()
|
|
||||||
serializer = UpdateGuardianImageSerializer(guardian_query, data=request.data, partial=True)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3017'], serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ChangePasswordAPIView(views.APIView):
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ChangePasswordSerializer(context=request.user, data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3007'], response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ResetPasswordAPIView(views.APIView):
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ResetPasswordSerializer(data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3006'], response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ForgotPasswordAPIView(views.APIView):
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ForgotPasswordSerializer(data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
email = serializer.validated_data['email']
|
|
||||||
try:
|
|
||||||
User.objects.get(email=email)
|
|
||||||
except User.DoesNotExist:
|
|
||||||
return custom_error_response(ERROR_CODE['2004'], response_status=status.HTTP_404_NOT_FOUND)
|
|
||||||
verification_code = ''.join([str(random.randrange(9)) for _ in range(6)])
|
|
||||||
# Send the verification code to the user's email
|
|
||||||
from_email = settings.EMAIL_FROM_ADDRESS
|
|
||||||
recipient_list = [email]
|
|
||||||
send_templated_mail(
|
|
||||||
template_name='email_reset_verification.email',
|
|
||||||
from_email=from_email,
|
|
||||||
recipient_list=recipient_list,
|
|
||||||
context={
|
|
||||||
'verification_code': verification_code
|
|
||||||
}
|
|
||||||
)
|
|
||||||
user_data, created = UserEmailOtp.objects.get_or_create(email=email)
|
|
||||||
if user_data:
|
|
||||||
user_data.otp = verification_code
|
|
||||||
user_data.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3015'],
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class SendPhoneOtp(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
otp = generate_otp()
|
|
||||||
phone_number = self.request.data['phone']
|
|
||||||
if phone_number.isdigit() and len(phone_number) == 10:
|
|
||||||
phone_otp, created = UserPhoneOtp.objects.get_or_create(country_code=self.request.data['country_code'],
|
|
||||||
phone=self.request.data['phone'])
|
|
||||||
if phone_otp:
|
|
||||||
phone_otp.otp = otp
|
|
||||||
phone_otp.save()
|
|
||||||
return custom_response(None, {'phone_otp':otp}, response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(ERROR_CODE['2020'], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
class UserPhoneVerification(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
phone_data = UserPhoneOtp.objects.filter(phone=self.request.GET.get('phone'),
|
|
||||||
otp=self.request.GET.get('otp')).last()
|
|
||||||
if phone_data:
|
|
||||||
phone_data.is_verified = True
|
|
||||||
phone_data.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3012'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
except Exception:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class UserLogin(viewsets.ViewSet):
|
|
||||||
@action(methods=['post'], detail=False)
|
|
||||||
def login(self, request):
|
|
||||||
username = request.data.get('username')
|
|
||||||
password = request.data.get('password')
|
|
||||||
user = authenticate(request, username=username, password=password)
|
|
||||||
|
|
||||||
try:
|
|
||||||
if user is not None:
|
|
||||||
login(request, user)
|
|
||||||
guardian_data = Guardian.objects.filter(user__username=username, is_verified=True).last()
|
|
||||||
if guardian_data:
|
|
||||||
serializer = GuardianSerializer(guardian_data).data
|
|
||||||
junior_data = Junior.objects.filter(auth__username=username, is_verified=True).last()
|
|
||||||
if junior_data:
|
|
||||||
serializer = JuniorSerializer(junior_data).data
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_401_UNAUTHORIZED)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
email_verified = UserEmailOtp.objects.filter(email=username).last()
|
|
||||||
refresh = RefreshToken.for_user(user)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
data = {"auth_token":access_token, "is_profile_complete": False,
|
|
||||||
"user_type": email_verified.user_type,
|
|
||||||
}
|
|
||||||
is_verified = False
|
|
||||||
if email_verified:
|
|
||||||
is_verified = email_verified.is_verified
|
|
||||||
if not is_verified:
|
|
||||||
otp = generate_otp()
|
|
||||||
email_verified.otp = otp
|
|
||||||
email_verified.save()
|
|
||||||
data.update({"email_otp":otp})
|
|
||||||
return custom_response(ERROR_CODE['2024'], {"email_otp": otp, "is_email_verified": is_verified},
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
data.update({"is_email_verified": is_verified})
|
|
||||||
return custom_response(None, data, response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
@action(methods=['post'], detail=False)
|
|
||||||
def admin_login(self, request):
|
|
||||||
username = request.data.get('username')
|
|
||||||
password = request.data.get('password')
|
|
||||||
user = authenticate(request, username=username, password=password)
|
|
||||||
try:
|
|
||||||
if user is not None:
|
|
||||||
login(request, user)
|
|
||||||
if user.is_superuser:
|
|
||||||
serializer = SuperUserSerializer(user)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_401_UNAUTHORIZED)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
refresh = RefreshToken.for_user(user)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
data = {"auth_token": access_token, "user_role": '3'}
|
|
||||||
return custom_response(None, data, response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
class UserEmailVerification(viewsets.ModelViewSet):
|
|
||||||
"""User Email verification"""
|
|
||||||
serializer_class = EmailVerificationSerializer
|
|
||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
user_obj = User.objects.filter(username=self.request.GET.get('email')).last()
|
|
||||||
email_data = UserEmailOtp.objects.filter(email=self.request.GET.get('email'),
|
|
||||||
otp=self.request.GET.get('otp')).last()
|
|
||||||
if email_data:
|
|
||||||
email_data.is_verified = True
|
|
||||||
email_data.save()
|
|
||||||
if email_data.user_type == '1':
|
|
||||||
junior_data = Junior.objects.filter(auth__email=self.request.GET.get('email')).last()
|
|
||||||
if junior_data:
|
|
||||||
junior_data.is_verified = True
|
|
||||||
junior_data.save()
|
|
||||||
else:
|
|
||||||
guardian_data = Guardian.objects.filter(user__email=self.request.GET.get('email')).last()
|
|
||||||
if guardian_data:
|
|
||||||
guardian_data.is_verified = True
|
|
||||||
guardian_data.save()
|
|
||||||
refresh = RefreshToken.for_user(user_obj)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return custom_response(SUCCESS_CODE['3011'], {"auth_token":access_token}, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ReSendEmailOtp(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
otp = generate_otp()
|
|
||||||
if User.objects.filter(email=request.data['email']):
|
|
||||||
email_data, created = UserEmailOtp.objects.get_or_create(email=request.data['email'])
|
|
||||||
if email_data:
|
|
||||||
email_data.otp = otp
|
|
||||||
email_data.save()
|
|
||||||
send_otp_email(request.data['email'], otp)
|
|
||||||
return custom_response(SUCCESS_CODE['3016'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2023"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
"""
|
|
||||||
This is init module of the Project Zod Bank
|
|
||||||
"""
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
"""
|
|
||||||
Common send_mail function
|
|
||||||
"""
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from django.core.mail import EmailMultiAlternatives
|
|
||||||
|
|
||||||
|
|
||||||
def send_mail(subject, message, from_email, recipient_list, html_message=None, cc=None,
|
|
||||||
fail_silently=False):
|
|
||||||
"""
|
|
||||||
Send Email
|
|
||||||
:param subject:
|
|
||||||
:param message:
|
|
||||||
:param from_email:
|
|
||||||
:param recipient_list:
|
|
||||||
:param html_message:
|
|
||||||
:param cc:
|
|
||||||
:param fail_silently:
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, cc)
|
|
||||||
if html_message:
|
|
||||||
mail.attach_alternative(html_message, 'text/html')
|
|
||||||
|
|
||||||
return mail.send(fail_silently)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return False
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains constants used throughout the project
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
|
|
||||||
# GOOGLE_URL used for interact with google server to verify user existence.
|
|
||||||
#GOOGLE_URL = "https://www.googleapis.com/plus/v1/"
|
|
||||||
|
|
||||||
|
|
||||||
# Super Admin string constant for 'role'
|
|
||||||
SUPER_ADMIN = "Super Admin"
|
|
||||||
|
|
||||||
# Define jwt_token_expiration time in minutes for now token will expire after 3 days
|
|
||||||
JWT_TOKEN_EXPIRATION = 3 * 24 * 60
|
|
||||||
|
|
||||||
# Define common file extention
|
|
||||||
FILE_EXTENSION = ("gif", "jpeg", "jpg", "png", "svg")
|
|
||||||
|
|
||||||
# Define file size in bytes(5MB = 5 * 1024 * 1024)
|
|
||||||
FILE_SIZE = 5 * 1024 * 1024
|
|
||||||
|
|
||||||
# String constant for configurable date for allocation lock period
|
|
||||||
ALLOCATION_LOCK_DATE = 1
|
|
||||||
|
|
||||||
sort_dict = {
|
|
||||||
'1': 'name',
|
|
||||||
'2': '-name'
|
|
||||||
}
|
|
||||||
USER_TYPE = (
|
|
||||||
('1', 'junior'),
|
|
||||||
('2', 'guardian'),
|
|
||||||
('3', 'superuser')
|
|
||||||
)
|
|
||||||
GENDERS = (
|
|
||||||
('1', 'Male'),
|
|
||||||
('2', 'Female')
|
|
||||||
)
|
|
||||||
# duplicate name used defined in constant PROJECT_NAME
|
|
||||||
PROJECT_NAME = 'Zod Bank'
|
|
||||||
GUARDIAN = 'guardian'
|
|
||||||
JUNIOR = 'junior'
|
|
||||||
SUPERUSER = 'superuser'
|
|
||||||
# numbers used as a constant
|
|
||||||
|
|
||||||
# Define the byte into kb
|
|
||||||
BYTE_IMAGE_SIZE = 1024
|
|
||||||
|
|
||||||
# validate file size
|
|
||||||
MAX_FILE_SIZE = 1024 * 1024 * 5
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains constants used throughout the project
|
|
||||||
"""
|
|
||||||
from zod_bank.settings import BUCKET_NAME
|
|
||||||
|
|
||||||
# Define S3 folder url
|
|
||||||
S3_FOLDER_DIR = {
|
|
||||||
'user_image': 'user_image/',
|
|
||||||
}
|
|
||||||
|
|
||||||
# S3 bucket url
|
|
||||||
S3_URL = "https://"+BUCKET_NAME+".s3.amazonaws.com/"
|
|
||||||
|
|
||||||
S3_FOLDER_URL = {
|
|
||||||
'user_image_file': S3_URL+S3_FOLDER_DIR['user_image'],
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains all the messages used all across the project
|
|
||||||
"""
|
|
||||||
|
|
||||||
ERROR_CODE_REQUIRED = {
|
|
||||||
# Error code for email address
|
|
||||||
"1000": ["Required email address not found."],
|
|
||||||
# Error code for password
|
|
||||||
"1001": ["Required password not found."],
|
|
||||||
# Error code for Required Post parameters
|
|
||||||
"1002": ["Required POST parameters not found."],
|
|
||||||
# Error code for Required Get parameters
|
|
||||||
"1003": ["Required GET parameters not found."],
|
|
||||||
# Error code for Required Headers
|
|
||||||
"1004": ["Required headers were not found."],
|
|
||||||
# Error code for Required Put parameters
|
|
||||||
"1005": ["Required PUT parameters not found."],
|
|
||||||
# Error code for Required query parameters
|
|
||||||
"1006": ["Required query parameters is not valid."],
|
|
||||||
# Error code for Required Head parameters
|
|
||||||
"1008": ["Required HEAD parameters not found."]
|
|
||||||
}
|
|
||||||
|
|
||||||
# Error code
|
|
||||||
ERROR_CODE = {
|
|
||||||
"2000": "Email not found.",
|
|
||||||
"2001": "This is your existing password. Please choose other one",
|
|
||||||
"2002": "Invalid login credentials.",
|
|
||||||
"2003": "An account already exists with this email address.",
|
|
||||||
"2004": "User not found.",
|
|
||||||
"2005": "Your account has been activated.",
|
|
||||||
"2006": "Your account is not activated.",
|
|
||||||
"2007": "Your account already activated.",
|
|
||||||
"2008": "Invalid OTP.",
|
|
||||||
"2009": "The user provided cannot be found or the reset password token has become invalid/timed out.",
|
|
||||||
"2010": "Invalid Link.",
|
|
||||||
"2011": "Your profile has not been completed yet.",
|
|
||||||
"2012": "Phone number already used",
|
|
||||||
"2013": "Invalid token.",
|
|
||||||
"2014": "Your old password doesn't match.",
|
|
||||||
"2015": "Invalid old password.",
|
|
||||||
"2016": "Invalid search.",
|
|
||||||
"2017": "{model} object with {pk} does not exist",
|
|
||||||
"2018": "Attached File not found",
|
|
||||||
"2019": "Either File extension or File size doesn't meet the requirements",
|
|
||||||
"2020": "Enter valid mobile number",
|
|
||||||
"2021": "Already register",
|
|
||||||
"2022": "Invalid Guardian code",
|
|
||||||
"2023": "Invalid user",
|
|
||||||
"2024": "Email not verified",
|
|
||||||
"2025": "Invalid input. Expected a list of strings.",
|
|
||||||
"2026": "New password should not same as old password",
|
|
||||||
"2027": "data should contain `identityToken`"
|
|
||||||
}
|
|
||||||
SUCCESS_CODE = {
|
|
||||||
# Success code for password
|
|
||||||
"3001": "Sign up successfully",
|
|
||||||
# Success code for Thank you
|
|
||||||
"3002": "Thank you for contacting us! Our Consumer Experience Team will reach out to you shortly.",
|
|
||||||
# Success code for account activation
|
|
||||||
"3003": "Log in successfully",
|
|
||||||
# Success code for password reset
|
|
||||||
"3004": "Password reset link has been sent to your email address",
|
|
||||||
# Success code for link verified
|
|
||||||
"3005": "Your link has been verified, it's valid",
|
|
||||||
# Success code for password reset
|
|
||||||
"3006": "Your password has been reset successfully.",
|
|
||||||
# Success code for password update
|
|
||||||
"3007": "Your password has been changed successfully.",
|
|
||||||
# Success code for valid link
|
|
||||||
"3008": "You have a valid link.",
|
|
||||||
# Success code for logged out
|
|
||||||
"3009": "You have successfully logged out!",
|
|
||||||
# Success code for check all fields
|
|
||||||
"3010": "All fields are valid",
|
|
||||||
"3011": "Email OTP Verified successfully",
|
|
||||||
"3012": "Phone OTP Verified successfully",
|
|
||||||
"3013": "Valid Guardian code",
|
|
||||||
"3014": "Password has been updated successfully.",
|
|
||||||
"3015": "Verification code sent on your email.",
|
|
||||||
"3016": "Send otp on your Email successfully",
|
|
||||||
"3017": "Profile image update successfully"
|
|
||||||
}
|
|
||||||
|
|
||||||
STATUS_CODE_ERROR = {
|
|
||||||
# Status code for Invalid Input
|
|
||||||
"4001": ["Invalid input."],
|
|
||||||
# Status code for Authentication credentials
|
|
||||||
"4002": ["Authentication credentials were not provided."],
|
|
||||||
# Status code for Permission
|
|
||||||
"4003": ["You do not have permission to perform this action."],
|
|
||||||
# Status code for not found
|
|
||||||
"4004": ["Not found."],
|
|
||||||
# Status code for method not allowed
|
|
||||||
"4005": ["Method not allowed."]
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
"""
|
|
||||||
Custom routers for job sourcing .
|
|
||||||
"""
|
|
||||||
# third party imports
|
|
||||||
from rest_framework.routers import DefaultRouter
|
|
||||||
|
|
||||||
|
|
||||||
class OptionalSlashRouter(DefaultRouter):
|
|
||||||
"""
|
|
||||||
optional slash router class
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
|
||||||
"""
|
|
||||||
explicitly appending '/' in urls if '/' doesn't exists for making common url patterns .
|
|
||||||
"""
|
|
||||||
super(OptionalSlashRouter, self).__init__()
|
|
||||||
self.trailing_slash = '/?'
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
"""
|
|
||||||
This file used for file uploaded
|
|
||||||
"""
|
|
||||||
import datetime
|
|
||||||
# python imports
|
|
||||||
import logging
|
|
||||||
import mimetypes
|
|
||||||
import os
|
|
||||||
|
|
||||||
import boto3
|
|
||||||
from django.core.files.storage import FileSystemStorage
|
|
||||||
# django imports
|
|
||||||
from django.utils.crypto import get_random_string
|
|
||||||
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
|
|
||||||
|
|
||||||
from base import constants
|
|
||||||
from base.constants import NUMBER
|
|
||||||
# local import
|
|
||||||
from zod_bank.settings import base_settings as settings
|
|
||||||
from zod_bank.settings.base_settings import BASE_DIR
|
|
||||||
|
|
||||||
|
|
||||||
def image_upload(folder, file_name, data):
|
|
||||||
"""
|
|
||||||
Function to upload files
|
|
||||||
:param folder:folder location string
|
|
||||||
:param file_name:file_name without ext string
|
|
||||||
:param data:data file obj
|
|
||||||
:return:Dictionary
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
img_name = None
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
bucket_name = settings.BUCKET_NAME
|
|
||||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
|
||||||
fss = FileSystemStorage()
|
|
||||||
file = fss.save('tmp/' + str(file_name), data)
|
|
||||||
fss.url(file)
|
|
||||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
|
||||||
s3_client.upload_file(
|
|
||||||
tmp_file, bucket_name, folder + str(file_name),
|
|
||||||
ExtraArgs={'ACL': 'public-read', 'ContentType': data.content_type}
|
|
||||||
)
|
|
||||||
os.unlink(tmp_file)
|
|
||||||
img_name = file_name
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
logging.error(e)
|
|
||||||
return status, error, img_name
|
|
||||||
|
|
||||||
|
|
||||||
def file_delete(folder, file_name):
|
|
||||||
"""
|
|
||||||
To delete common file
|
|
||||||
:param folder: folder name str
|
|
||||||
:param file_name: file_name string type
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
s3_client.delete_object(Bucket=settings.BUCKET_NAME, Key=str(folder) + str(file_name))
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
return status, error
|
|
||||||
|
|
||||||
|
|
||||||
def get_aws_obj(folder, file_name):
|
|
||||||
"""
|
|
||||||
To get aws file obj
|
|
||||||
:param folder: folder string type
|
|
||||||
:param file_name: file_name string type
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
obj = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
file_name = folder + file_name
|
|
||||||
obj = s3_client.get_object(Bucket=settings.BUCKET_NAME, Key=file_name)
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return status, obj
|
|
||||||
|
|
||||||
|
|
||||||
def upload_image(post_data, folder):
|
|
||||||
"""
|
|
||||||
:param post_data:
|
|
||||||
:param folder: string type
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
upload_obj = None
|
|
||||||
# Check Post data
|
|
||||||
if post_data:
|
|
||||||
date_now = datetime.datetime.now()
|
|
||||||
file_extension = os.path.splitext(str(post_data.name))
|
|
||||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
|
||||||
rand = get_random_string(NUMBER['twelve'])
|
|
||||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
|
||||||
upload_obj = image_upload(folder, image_name, post_data)
|
|
||||||
return upload_obj
|
|
||||||
|
|
||||||
|
|
||||||
def upload_voice_kit_image(post_data, folder, image_dir):
|
|
||||||
"""
|
|
||||||
:param post_data:
|
|
||||||
:param folder: string type
|
|
||||||
:param image_dir: image_dir
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
upload_obj = None
|
|
||||||
# Check Post data
|
|
||||||
if post_data:
|
|
||||||
date_now = datetime.datetime.now()
|
|
||||||
file_extension = os.path.splitext(str(post_data))
|
|
||||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
|
||||||
rand = get_random_string(NUMBER['twelve'])
|
|
||||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
|
||||||
upload_obj = voice_kit_image_upload(folder, image_name, post_data, image_dir)
|
|
||||||
return upload_obj
|
|
||||||
|
|
||||||
|
|
||||||
def voice_kit_image_upload(folder, file_name, data, image_dir):
|
|
||||||
"""
|
|
||||||
Function to upload files
|
|
||||||
:param folder:folder location string
|
|
||||||
:param file_name:file_name without ext string
|
|
||||||
:param data:data file obj
|
|
||||||
:return:Dictionary
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
img_name = None
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
bucket_name = settings.BUCKET_NAME
|
|
||||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
|
||||||
fss = FileSystemStorage()
|
|
||||||
with open(image_dir+data, 'rb') as f:
|
|
||||||
file = fss.save('tmp/' + str(file_name), f)
|
|
||||||
fss.url(file)
|
|
||||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
|
||||||
s3_client.upload_file(
|
|
||||||
tmp_file, bucket_name, folder + str(file_name),
|
|
||||||
ExtraArgs={'ACL': 'public-read', 'ContentType': mimetypes.guess_type(file_name)[0]}
|
|
||||||
)
|
|
||||||
os.unlink(tmp_file)
|
|
||||||
img_name = file_name
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
logging.error(e)
|
|
||||||
return status, error, img_name
|
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
version: '3'
|
|
||||||
services:
|
|
||||||
nginx:
|
|
||||||
image: nginx:latest
|
|
||||||
container_name: nginx
|
|
||||||
ports:
|
|
||||||
- "8000:8000"
|
|
||||||
volumes:
|
|
||||||
- ./nginx:/etc/nginx/conf.d
|
|
||||||
- .:/usr/src/app
|
|
||||||
depends_on:
|
|
||||||
- web
|
|
||||||
web:
|
|
||||||
build: .
|
|
||||||
container_name: django
|
|
||||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
|
||||||
volumes:
|
|
||||||
- .:/usr/src/app
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
"""Guardian admin"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.contrib import admin
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Guardian
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(Guardian)
|
|
||||||
class GuardianAdmin(admin.ModelAdmin):
|
|
||||||
"""Junior Admin"""
|
|
||||||
list_display = ['user', 'family_name']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return self.user__email
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
"""Guardian app file"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class CustodianConfig(AppConfig):
|
|
||||||
"""Guardian config"""
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'guardian'
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
import django.contrib.postgres.fields
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='Guardian',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('country_code', models.IntegerField(blank=True, null=True)),
|
|
||||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
|
||||||
('family_name', models.CharField(blank=True, default=None, max_length=50, null=True)),
|
|
||||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=15, null=True)),
|
|
||||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
|
||||||
('guardian_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('junior_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
|
||||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
('is_complete_profile', models.BooleanField(default=False)),
|
|
||||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='guardian_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'verbose_name': 'Guardian',
|
|
||||||
'db_table': 'guardians',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-27 06:15
|
|
||||||
|
|
||||||
from django.db import migrations
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0001_initial'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.RemoveField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='junior_code',
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-27 13:59
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0002_remove_guardian_junior_code'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='country_name',
|
|
||||||
field=models.CharField(blank=True, default=None, max_length=30, null=True),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-28 06:52
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0003_guardian_country_name'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='image',
|
|
||||||
field=models.ImageField(blank=True, default=None, null=True, upload_to='images/'),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-29 06:14
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0004_guardian_image'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='image',
|
|
||||||
field=models.ImageField(blank=True, default=None, null=True, upload_to=''),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0005_alter_guardian_image'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='is_verified',
|
|
||||||
field=models.BooleanField(default=False),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"""Guardian model file"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
"""Import Django app"""
|
|
||||||
from base.constants import GENDERS
|
|
||||||
User = get_user_model()
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class Guardian(models.Model):
|
|
||||||
"""Guardian model"""
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='guardian_profile', verbose_name='Email')
|
|
||||||
"""Contact details"""
|
|
||||||
country_code = models.IntegerField(blank=True, null=True)
|
|
||||||
phone = models.CharField(max_length=31, null=True, blank=True, default=None)
|
|
||||||
country_name = models.CharField(max_length=30, null=True, blank=True, default=None)
|
|
||||||
"""Image info"""
|
|
||||||
image = models.ImageField(null=True, blank=True, default=None)
|
|
||||||
"""Personal info"""
|
|
||||||
family_name = models.CharField(max_length=50, null=True, blank=True, default=None)
|
|
||||||
gender = models.CharField(choices=GENDERS, max_length=15, null=True, blank=True, default=None)
|
|
||||||
dob = models.DateField(max_length=15, null=True, blank=True, default=None)
|
|
||||||
"""Profile activity"""
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
is_complete_profile = models.BooleanField(default=False)
|
|
||||||
passcode = models.IntegerField(null=True, blank=True, default=None)
|
|
||||||
"""Codes"""
|
|
||||||
guardian_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code_used = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
"""Profile created and updated time"""
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta class """
|
|
||||||
db_table = 'guardians'
|
|
||||||
verbose_name = 'Guardian'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return f'{self.user}'
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
"""Serializer of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
import logging
|
|
||||||
import random
|
|
||||||
from rest_framework import serializers
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
from django.db import transaction
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Guardian
|
|
||||||
from account.models import UserProfile, UserEmailOtp
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from .utils import upload_image_to_alibaba
|
|
||||||
from junior.models import Junior
|
|
||||||
class UserSerializer(serializers.ModelSerializer):
|
|
||||||
"""User serializer"""
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
fields = ['email', 'password', 'auth_token']
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
"""generate auth token"""
|
|
||||||
refresh = RefreshToken.for_user(obj)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return access_token
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""fetch data"""
|
|
||||||
email = validated_data.get('email')
|
|
||||||
user_type = self.context
|
|
||||||
password = validated_data.get('password')
|
|
||||||
try:
|
|
||||||
"""Create user profile"""
|
|
||||||
user = User.objects.create_user(username=email, email=email, password=password)
|
|
||||||
UserProfile.objects.create(user=user, user_type=user_type)
|
|
||||||
if user_type == '1':
|
|
||||||
Junior.objects.create(auth=user)
|
|
||||||
if user_type == '2':
|
|
||||||
Guardian.objects.create(user=user)
|
|
||||||
return user
|
|
||||||
except Exception as e:
|
|
||||||
"""Error handling"""
|
|
||||||
logging.error(e)
|
|
||||||
otp = UserEmailOtp.objects.filter(email=email).last()
|
|
||||||
otp_verified = False
|
|
||||||
if otp and otp.is_verified:
|
|
||||||
otp_verified = True
|
|
||||||
raise serializers.ValidationError({"details":ERROR_CODE['2021'], "otp_verified":bool(otp_verified),
|
|
||||||
"code": 400, "status":"failed",
|
|
||||||
})
|
|
||||||
|
|
||||||
class CreateGuardianSerializer(serializers.ModelSerializer):
|
|
||||||
"""Create guardian serializer"""
|
|
||||||
"""Basic info"""
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
email = serializers.SerializerMethodField('get_email')
|
|
||||||
"""Contact details"""
|
|
||||||
phone = serializers.CharField(max_length=20, required=False)
|
|
||||||
country_code = serializers.IntegerField(required=False)
|
|
||||||
family_name = serializers.CharField(max_length=100, required=False)
|
|
||||||
dob = serializers.DateField(required=False)
|
|
||||||
referral_code = serializers.CharField(max_length=100, required=False)
|
|
||||||
image = serializers.ImageField(required=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Guardian
|
|
||||||
fields = ['first_name', 'last_name', 'email', 'phone', 'family_name', 'gender', 'country_code',
|
|
||||||
'dob', 'referral_code', 'passcode', 'is_complete_profile', 'referral_code_used',
|
|
||||||
'country_name', 'image']
|
|
||||||
|
|
||||||
def get_first_name(self,obj):
|
|
||||||
"""first name of guardian"""
|
|
||||||
return obj.user.first_name
|
|
||||||
|
|
||||||
def get_last_name(self,obj):
|
|
||||||
"""last name of guardian"""
|
|
||||||
return obj.user.last_name
|
|
||||||
|
|
||||||
def get_email(self,obj):
|
|
||||||
"""emailof guardian"""
|
|
||||||
return obj.user.email
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""Create guardian profile"""
|
|
||||||
# phone_number = validated_data.get('phone', None)
|
|
||||||
# guardian_data = Guardian.objects.filter(phone=phone_number)
|
|
||||||
# junior_data = Junior.objects.filter(phone=phone_number)
|
|
||||||
# if phone_number and (guardian_data or junior_data):
|
|
||||||
# raise serializers.ValidationError({"details": ERROR_CODE['2012']})
|
|
||||||
user = User.objects.filter(username=self.context['user']).last()
|
|
||||||
if user:
|
|
||||||
"""Save first and last name of guardian"""
|
|
||||||
if self.context.get('first_name') != '' and self.context.get('last_name') != '':
|
|
||||||
user.first_name = self.context.get('first_name', user.first_name)
|
|
||||||
user.last_name = self.context.get('last_name', user.last_name)
|
|
||||||
user.save()
|
|
||||||
"""Create guardian data"""
|
|
||||||
guardian, created = Guardian.objects.get_or_create(user=self.context['user'])
|
|
||||||
if created:
|
|
||||||
"""Create referral code and guardian code"""
|
|
||||||
guardian.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
guardian.guardian_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
if guardian:
|
|
||||||
"""update details according to the data get from request"""
|
|
||||||
guardian.gender = validated_data.get('gender',guardian.gender)
|
|
||||||
guardian.family_name = validated_data.get('family_name', guardian.family_name)
|
|
||||||
guardian.dob = validated_data.get('dob',guardian.dob)
|
|
||||||
"""Update country code and phone number"""
|
|
||||||
guardian.phone = validated_data.get('phone', guardian.phone)
|
|
||||||
guardian.country_code = validated_data.get('country_code', guardian.country_code)
|
|
||||||
guardian.passcode = validated_data.get('passcode', guardian.passcode)
|
|
||||||
guardian.country_name = validated_data.get('country_name', guardian.country_name)
|
|
||||||
guardian.referral_code_used = validated_data.get('referral_code_used', guardian.referral_code_used)
|
|
||||||
"""Complete profile of the junior if below all data are filled"""
|
|
||||||
complete_profile_field = all([guardian.phone, guardian.gender, guardian.family_name, guardian.country_name,
|
|
||||||
guardian.dob, guardian.country_code, user.first_name, user.last_name])
|
|
||||||
guardian.is_complete_profile = False
|
|
||||||
if complete_profile_field:
|
|
||||||
guardian.is_complete_profile = True
|
|
||||||
image = validated_data.pop('image', None)
|
|
||||||
if image:
|
|
||||||
filename = f"images/{image.name}"
|
|
||||||
image_url = upload_image_to_alibaba(image, filename)
|
|
||||||
guardian.image = image_url
|
|
||||||
guardian.save()
|
|
||||||
return guardian
|
|
||||||
|
|
||||||
def save(self, **kwargs):
|
|
||||||
"""Save the data into junior table"""
|
|
||||||
with transaction.atomic():
|
|
||||||
instance = super().save(**kwargs)
|
|
||||||
return instance
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
"""task files"""
|
|
||||||
"""Django import"""
|
|
||||||
import random
|
|
||||||
def generate_otp():
|
|
||||||
"""generate random otp"""
|
|
||||||
return ''.join([str(random.randrange(9)) for _ in range(6)])
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
"""Test file of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from .views import SignupViewset, UpdateGuardianProfile
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
|
|
||||||
"""Define Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
"""Sign up API"""
|
|
||||||
router.register('sign-up', SignupViewset, basename='sign-up')
|
|
||||||
"""Create guardian profile API"""
|
|
||||||
router.register('create-guardian-profile', UpdateGuardianProfile, basename='update-guardian-profile')
|
|
||||||
"""Define Url pattern"""
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
]
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import oss2
|
|
||||||
from django.conf import settings
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
def upload_image_to_alibaba(image, filename):
|
|
||||||
# Save the image object to a temporary file
|
|
||||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
|
||||||
temp_file.write(image.read())
|
|
||||||
auth = oss2.Auth(settings.ALIYUN_OSS_ACCESS_KEY_ID, settings.ALIYUN_OSS_ACCESS_KEY_SECRET)
|
|
||||||
bucket = oss2.Bucket(auth, settings.ALIYUN_OSS_ENDPOINT, settings.ALIYUN_OSS_BUCKET_NAME)
|
|
||||||
# Upload the temporary file to Alibaba OSS
|
|
||||||
bucket.put_object_from_file(filename, temp_file.name)
|
|
||||||
return f"https://{settings.ALIYUN_OSS_BUCKET_NAME}.{settings.ALIYUN_OSS_ENDPOINT}/{filename}"
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
"""Views of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
"""Import Django app"""
|
|
||||||
from .serializers import UserSerializer, CreateGuardianSerializer
|
|
||||||
from .models import Guardian
|
|
||||||
from junior.models import Junior
|
|
||||||
from account.models import UserEmailOtp
|
|
||||||
from .tasks import generate_otp
|
|
||||||
from account.utils import send_otp_email
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
# Create your views here.
|
|
||||||
class SignupViewset(viewsets.ModelViewSet):
|
|
||||||
"""Signup view set"""
|
|
||||||
serializer_class = UserSerializer
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Create user profile"""
|
|
||||||
serializer = UserSerializer(context=request.data['user_type'], data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
"""Generate otp"""
|
|
||||||
otp = generate_otp()
|
|
||||||
UserEmailOtp.objects.create(email=request.data['email'], otp=otp, user_type=str(request.data['user_type']))
|
|
||||||
"""Send email to the register user"""
|
|
||||||
send_otp_email(request.data['email'], otp)
|
|
||||||
return custom_response(SUCCESS_CODE['3001'], {"email_otp": otp},
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class UpdateGuardianProfile(viewsets.ViewSet):
|
|
||||||
"""Update guardian profile"""
|
|
||||||
serializer_class = CreateGuardianSerializer
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Create guardian profile"""
|
|
||||||
serializer = CreateGuardianSerializer(context={"user":request.user,
|
|
||||||
"first_name":request.data.get('first_name', ''),
|
|
||||||
"last_name": request.data.get('last_name',' ')},
|
|
||||||
data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
"""save serializer"""
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(None, serializer.data,response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { Config as JestConfig } from 'jest';
|
||||||
|
import { pathsToModuleNameMapper } from 'ts-jest';
|
||||||
|
import { compilerOptions as tsConfigCompilerOptions } from './tsconfig.json';
|
||||||
|
|
||||||
|
type ArrayElement<A> = A extends readonly (infer T)[] ? T : never;
|
||||||
|
type JestProjectConfig = Exclude<ArrayElement<JestConfig['projects']>, string>;
|
||||||
|
|
||||||
|
const baseJestConfig: JestConfig = {
|
||||||
|
// ...
|
||||||
|
};
|
||||||
|
const baseJestProjectConfig: JestProjectConfig = {
|
||||||
|
testEnvironment: 'node',
|
||||||
|
transform: {
|
||||||
|
'^.+\\.(t|j)s$': 'ts-jest',
|
||||||
|
},
|
||||||
|
moduleNameMapper: pathsToModuleNameMapper(tsConfigCompilerOptions.paths, { prefix: '<rootDir>' }),
|
||||||
|
globalSetup: '<rootDir>/test/global-setup.ts',
|
||||||
|
};
|
||||||
|
const projects: { name?: string; rootDir: string }[] = [{ rootDir: '.' }];
|
||||||
|
|
||||||
|
export function buildJestConfig(config?: {
|
||||||
|
jestConfigs?: JestConfig;
|
||||||
|
jestProjectConfigs?: JestProjectConfig;
|
||||||
|
}): JestConfig {
|
||||||
|
return {
|
||||||
|
...baseJestConfig,
|
||||||
|
...config?.jestConfigs,
|
||||||
|
projects: projects.map(({ name, rootDir }) => ({
|
||||||
|
...baseJestProjectConfig,
|
||||||
|
...config?.jestProjectConfigs,
|
||||||
|
...(name && { displayName: name }),
|
||||||
|
rootDir,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import type { Config } from 'jest';
|
||||||
|
import { buildJestConfig } from './jest.base.config';
|
||||||
|
|
||||||
|
const config: Config = buildJestConfig({
|
||||||
|
jestProjectConfigs: {
|
||||||
|
testRegex: '.*\\.spec\\.ts$',
|
||||||
|
coveragePathIgnorePatterns: ['__testing__', 'entities', '<rootDir>/src/db', 'index.ts'],
|
||||||
|
},
|
||||||
|
jestConfigs: {
|
||||||
|
coverageDirectory: 'coverage',
|
||||||
|
collectCoverageFrom: ['<rootDir>/src/**/*.(t|j)s'],
|
||||||
|
coverageReporters: ['clover', 'json', 'lcov', 'text', 'text-summary', 'cobertura'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
"""Junior admin"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.contrib import admin
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Junior
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(Junior)
|
|
||||||
class JuniorAdmin(admin.ModelAdmin):
|
|
||||||
"""Junior Admin"""
|
|
||||||
list_display = ['auth']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return self.auth__email
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
"""App file"""
|
|
||||||
"""Import AppConfig"""
|
|
||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
class JuniorConfig(AppConfig):
|
|
||||||
"""Junior config"""
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'junior'
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
import django.contrib.postgres.fields
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='Junior',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
|
||||||
('country_code', models.IntegerField(blank=True, null=True)),
|
|
||||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=10, null=True)),
|
|
||||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
|
||||||
('junior_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('guardian_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
|
||||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
('is_complete_profile', models.BooleanField(default=False)),
|
|
||||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('auth', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='junior_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'verbose_name': 'Junior',
|
|
||||||
'db_table': 'junior',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-27 13:59
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('junior', '0001_initial'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='junior',
|
|
||||||
name='country_name',
|
|
||||||
field=models.CharField(blank=True, default=None, max_length=30, null=True),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-28 10:16
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('junior', '0002_junior_country_name'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='junior',
|
|
||||||
name='image',
|
|
||||||
field=models.ImageField(blank=True, default=None, null=True, upload_to='images/'),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-29 06:14
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('junior', '0003_junior_image'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name='junior',
|
|
||||||
name='image',
|
|
||||||
field=models.ImageField(blank=True, default=None, null=True, upload_to=''),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('junior', '0004_alter_junior_image'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='junior',
|
|
||||||
name='is_verified',
|
|
||||||
field=models.BooleanField(default=False),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"""Junior model """
|
|
||||||
"""Import django"""
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
from django.contrib.postgres.fields import ArrayField
|
|
||||||
"""Import django app"""
|
|
||||||
from base.constants import GENDERS
|
|
||||||
User = get_user_model()
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class Junior(models.Model):
|
|
||||||
"""Junior model"""
|
|
||||||
auth = models.ForeignKey(User, on_delete=models.CASCADE, related_name='junior_profile', verbose_name='Email')
|
|
||||||
"""Contact details"""
|
|
||||||
phone = models.CharField(max_length=31, null=True, blank=True, default=None)
|
|
||||||
country_code = models.IntegerField(blank=True, null=True)
|
|
||||||
country_name = models.CharField(max_length=30, null=True, blank=True, default=None)
|
|
||||||
"""Personal info"""
|
|
||||||
gender = models.CharField(max_length=10, choices=GENDERS, null=True, blank=True, default=None)
|
|
||||||
dob = models.DateField(max_length=15, null=True, blank=True, default=None)
|
|
||||||
image = models.ImageField(null=True, blank=True, default=None)
|
|
||||||
"""Codes"""
|
|
||||||
junior_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
guardian_code = ArrayField(models.CharField(max_length=10, null=True, blank=True, default=None),null=True)
|
|
||||||
referral_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code_used = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
"""Profile activity"""
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
is_complete_profile = models.BooleanField(default=False)
|
|
||||||
passcode = models.IntegerField(null=True, blank=True, default=None)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
"""Profile created and updated time"""
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta class """
|
|
||||||
db_table = 'junior'
|
|
||||||
verbose_name = 'Junior'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return f'{self.auth}'
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
"""Serializer file for junior"""
|
|
||||||
"""Import Django 3rd party app"""
|
|
||||||
from rest_framework import serializers
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from django.db import transaction
|
|
||||||
import random
|
|
||||||
"""Import django app"""
|
|
||||||
from junior.models import Junior
|
|
||||||
from guardian.utils import upload_image_to_alibaba
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from guardian.models import Guardian
|
|
||||||
|
|
||||||
class ListCharField(serializers.ListField):
|
|
||||||
"""Serializer for Array field"""
|
|
||||||
child = serializers.CharField()
|
|
||||||
|
|
||||||
def to_representation(self, data):
|
|
||||||
"""to represent the data"""
|
|
||||||
return data
|
|
||||||
|
|
||||||
def to_internal_value(self, data):
|
|
||||||
"""internal value"""
|
|
||||||
if isinstance(data, list):
|
|
||||||
return data
|
|
||||||
raise serializers.ValidationError({"details":ERROR_CODE['2025']})
|
|
||||||
|
|
||||||
|
|
||||||
class CreateJuniorSerializer(serializers.ModelSerializer):
|
|
||||||
"""Create junior serializer"""
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
email = serializers.SerializerMethodField('get_email')
|
|
||||||
phone = serializers.CharField(max_length=20, required=False)
|
|
||||||
country_code = serializers.IntegerField(required=False)
|
|
||||||
dob = serializers.DateField(required=False)
|
|
||||||
referral_code = serializers.CharField(max_length=100, required=False)
|
|
||||||
guardian_code = ListCharField(required=False)
|
|
||||||
image = serializers.ImageField(required=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Junior
|
|
||||||
fields = ['first_name', 'last_name', 'email', 'phone', 'gender', 'country_code', 'dob', 'referral_code',
|
|
||||||
'passcode', 'is_complete_profile', 'guardian_code', 'referral_code_used',
|
|
||||||
'country_name', 'image']
|
|
||||||
|
|
||||||
def get_first_name(self,obj):
|
|
||||||
"""first name of junior"""
|
|
||||||
return obj.auth.first_name
|
|
||||||
|
|
||||||
def get_last_name(self,obj):
|
|
||||||
"""last name of junior"""
|
|
||||||
return obj.auth.last_name
|
|
||||||
|
|
||||||
def get_email(self,obj):
|
|
||||||
"""email of junior"""
|
|
||||||
return obj.auth.email
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""Create junior profile"""
|
|
||||||
image = validated_data.get('image', None)
|
|
||||||
# phone_number = validated_data.get('phone', None)
|
|
||||||
# guardian_data = Guardian.objects.filter(phone=phone_number)
|
|
||||||
# junior_data = Junior.objects.filter(phone=phone_number)
|
|
||||||
# if phone_number and (junior_data or guardian_data):
|
|
||||||
# raise serializers.ValidationError({"details":ERROR_CODE['2012']})
|
|
||||||
user = User.objects.filter(username=self.context['user']).last()
|
|
||||||
if user:
|
|
||||||
"""Save first and last name of junior"""
|
|
||||||
if self.context.get('first_name') != '' and self.context.get('last_name') != '':
|
|
||||||
user.first_name = self.context.get('first_name', user.first_name)
|
|
||||||
user.last_name = self.context.get('last_name', user.last_name)
|
|
||||||
user.save()
|
|
||||||
"""Create junior data"""
|
|
||||||
junior, created = Junior.objects.get_or_create(auth=self.context['user'])
|
|
||||||
if created:
|
|
||||||
"""Create referral code and junior code"""
|
|
||||||
junior.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
junior.junior_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
if junior:
|
|
||||||
"""update details according to the data get from request"""
|
|
||||||
junior.gender = validated_data.get('gender',junior.gender)
|
|
||||||
"""Update guardian code"""
|
|
||||||
junior.guardian_code = validated_data.get('guardian_code', junior.guardian_code)
|
|
||||||
junior.dob = validated_data.get('dob',junior.dob)
|
|
||||||
junior.passcode = validated_data.get('passcode', junior.passcode)
|
|
||||||
junior.country_name = validated_data.get('country_name', junior.country_name)
|
|
||||||
"""Update country code and phone number"""
|
|
||||||
junior.phone = validated_data.get('phone', junior.phone)
|
|
||||||
junior.country_code = validated_data.get('country_code', junior.country_code)
|
|
||||||
junior.referral_code_used = validated_data.get('referral_code_used', junior.referral_code_used)
|
|
||||||
"""Complete profile of the junior if below all data are filled"""
|
|
||||||
complete_profile_field = all([junior.phone, junior.gender, junior.country_name,
|
|
||||||
junior.dob, junior.country_code, user.first_name, user.last_name])
|
|
||||||
junior.is_complete_profile = False
|
|
||||||
if complete_profile_field:
|
|
||||||
junior.is_complete_profile = True
|
|
||||||
if image:
|
|
||||||
filename = f"images/{image.name}"
|
|
||||||
image_url = upload_image_to_alibaba(image, filename)
|
|
||||||
junior.image = image_url
|
|
||||||
junior.save()
|
|
||||||
return junior
|
|
||||||
|
|
||||||
def save(self, **kwargs):
|
|
||||||
"""Save the data into junior table"""
|
|
||||||
with transaction.atomic():
|
|
||||||
instance = super().save(**kwargs)
|
|
||||||
return instance
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
"""Junior test file"""
|
|
||||||
"""Import TestCase"""
|
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from .views import UpdateJuniorProfile, ValidateGuardianCode
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
|
|
||||||
"""Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
"""Create junior profile API"""
|
|
||||||
router.register('create-junior-profile', UpdateJuniorProfile, basename='profile-update')
|
|
||||||
"""validate guardian code API"""
|
|
||||||
router.register('validate-guardian-code', ValidateGuardianCode, basename='validate-guardian-code')
|
|
||||||
"""Define url pattern"""
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
]
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
"""Junior view file"""
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
"""Django app import"""
|
|
||||||
from junior.models import Junior
|
|
||||||
from .serializers import CreateJuniorSerializer
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
# Create your views here.
|
|
||||||
class UpdateJuniorProfile(viewsets.ViewSet):
|
|
||||||
"""Update junior profile"""
|
|
||||||
serializer_class = CreateJuniorSerializer
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Use CreateJuniorSerializer"""
|
|
||||||
serializer = CreateJuniorSerializer(context={"user":request.user,
|
|
||||||
"first_name":request.data.get('first_name', ''),
|
|
||||||
"last_name": request.data.get('last_name',' ')},
|
|
||||||
data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
"""save serializer"""
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ValidateGuardianCode(viewsets.ViewSet):
|
|
||||||
"""Check guardian code exist or not"""
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
"""check guardian code"""
|
|
||||||
guardian_code = self.request.GET.get('guardian_code').split(',')
|
|
||||||
for code in guardian_code:
|
|
||||||
guardian_data = Guardian.objects.filter(guardian_code=code).exists()
|
|
||||||
if guardian_data:
|
|
||||||
return custom_response(SUCCESS_CODE['3013'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2022"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
"""Django's command-line utility for administrative tasks."""
|
|
||||||
"""Django import"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""Main function"""
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zod_bank.settings')
|
|
||||||
try:
|
|
||||||
"""Import execute from command line function"""
|
|
||||||
from django.core.management import execute_from_command_line
|
|
||||||
except ImportError as exc:
|
|
||||||
"""Show Exception error"""
|
|
||||||
raise ImportError(
|
|
||||||
"Couldn't import Django. Are you sure it's installed and "
|
|
||||||
"available on your PYTHONPATH environment variable? Did you "
|
|
||||||
"forget to activate a virtual environment?"
|
|
||||||
) from exc
|
|
||||||
execute_from_command_line(sys.argv)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true,
|
||||||
|
"watchAssets": true,
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"include": "config",
|
||||||
|
"exclude": "**/*.md"
|
||||||
|
},
|
||||||
|
"i18n",
|
||||||
|
"files"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
upstream web {
|
|
||||||
ip_hash;
|
|
||||||
server web:8000;
|
|
||||||
}
|
|
||||||
|
|
||||||
# portal
|
|
||||||
server {
|
|
||||||
location / {
|
|
||||||
proxy_pass http://web/;
|
|
||||||
proxy_set_header Host $http_host;
|
|
||||||
}
|
|
||||||
listen 8000;
|
|
||||||
client_max_body_size 512M;
|
|
||||||
server_name localhost;
|
|
||||||
proxy_read_timeout 900;
|
|
||||||
proxy_connect_timeout 900;
|
|
||||||
proxy_send_timeout 900;
|
|
||||||
#proxy_set_header Host $http_host;
|
|
||||||
|
|
||||||
location /static {
|
|
||||||
autoindex on;
|
|
||||||
alias /usr/src/app/static/;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Generated
+16468
File diff suppressed because it is too large
Load Diff
+111
@@ -0,0 +1,111 @@
|
|||||||
|
{
|
||||||
|
"name": "test",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"typeorm:cli": "./node_modules/.bin/ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
|
||||||
|
"typeorm:cli-d": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm -d typeorm.cli.ts",
|
||||||
|
"migration:generate": "npm run typeorm:cli-d migration:generate",
|
||||||
|
"migration:create": "npm run typeorm:cli migration:create",
|
||||||
|
"migration:up": "npm run typeorm:cli-d migration:run",
|
||||||
|
"migration:down": "npm run typeorm:cli-d migration:revert"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@abdalhamid/hello": "^2.0.0",
|
||||||
|
"@hamid/hello": "file:../libraries/test-package",
|
||||||
|
"@nestjs-modules/mailer": "^2.0.2",
|
||||||
|
"@nestjs/axios": "^3.1.2",
|
||||||
|
"@nestjs/common": "^10.0.0",
|
||||||
|
"@nestjs/config": "^3.3.0",
|
||||||
|
"@nestjs/core": "^10.0.0",
|
||||||
|
"@nestjs/event-emitter": "^2.1.1",
|
||||||
|
"@nestjs/jwt": "^10.2.0",
|
||||||
|
"@nestjs/microservices": "^10.4.7",
|
||||||
|
"@nestjs/passport": "^10.0.3",
|
||||||
|
"@nestjs/platform-express": "^10.4.8",
|
||||||
|
"@nestjs/swagger": "^8.0.5",
|
||||||
|
"@nestjs/terminus": "^10.2.3",
|
||||||
|
"@nestjs/throttler": "^6.2.1",
|
||||||
|
"@nestjs/typeorm": "^10.0.2",
|
||||||
|
"amqp-connection-manager": "^4.1.14",
|
||||||
|
"amqplib": "^0.10.4",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.1",
|
||||||
|
"google-libphonenumber": "^3.2.39",
|
||||||
|
"handlebars": "^4.7.8",
|
||||||
|
"ioredis": "^5.4.1",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"moment": "^2.30.1",
|
||||||
|
"nestjs-i18n": "^10.4.9",
|
||||||
|
"nestjs-pino": "^4.1.0",
|
||||||
|
"nodemailer": "^6.9.16",
|
||||||
|
"oci-common": "^2.99.0",
|
||||||
|
"oci-sdk": "^2.99.0",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"pg": "^8.13.1",
|
||||||
|
"pino-http": "^10.3.0",
|
||||||
|
"pino-pretty": "^13.0.0",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"typeorm": "^0.3.20",
|
||||||
|
"typeorm-transactional": "^0.5.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@golevelup/ts-jest": "^0.6.0",
|
||||||
|
"@nestjs/cli": "^10.0.0",
|
||||||
|
"@nestjs/schematics": "^10.0.0",
|
||||||
|
"@nestjs/testing": "^10.0.0",
|
||||||
|
"@types/bcrypt": "^5.0.2",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/google-libphonenumber": "^7.4.30",
|
||||||
|
"@types/jest": "^29.5.2",
|
||||||
|
"@types/lodash": "^4.17.13",
|
||||||
|
"@types/multer": "^1.4.12",
|
||||||
|
"@types/node": "^20.3.1",
|
||||||
|
"@types/nodemailer": "^6.4.16",
|
||||||
|
"@types/passport-jwt": "^4.0.1",
|
||||||
|
"@types/supertest": "^6.0.0",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^5.59.2",
|
||||||
|
"@typescript-eslint/parser": "^5.59.2",
|
||||||
|
"eslint": "^8.39.0",
|
||||||
|
"eslint-config-prettier": "^8.8.0",
|
||||||
|
"eslint-plugin-prettier": "^4.0.0",
|
||||||
|
"eslint-plugin-security": "^1.7.1",
|
||||||
|
"jest": "^29.5.0",
|
||||||
|
"lint-staged": "^13.2.2",
|
||||||
|
"prettier": "^2.8.8",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.1.0",
|
||||||
|
"ts-loader": "^9.4.3",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.1.3"
|
||||||
|
},
|
||||||
|
"lint-staged": {
|
||||||
|
"*.{js,ts}": [
|
||||||
|
"eslint --fix"
|
||||||
|
],
|
||||||
|
"*.{js,ts,json,md}": [
|
||||||
|
"prettier --write"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
aliyun-python-sdk-core==2.13.36
|
|
||||||
aliyun-python-sdk-dysmsapi==2.1.2
|
|
||||||
aliyun-python-sdk-kms==2.16.1
|
|
||||||
aliyun-python-sdk-sts==3.1.1
|
|
||||||
amqp==5.1.1
|
|
||||||
asgiref==3.7.2
|
|
||||||
async-timeout==4.0.2
|
|
||||||
billiard==4.1.0
|
|
||||||
boto3==1.26.157
|
|
||||||
botocore==1.29.157
|
|
||||||
cachetools==5.3.1
|
|
||||||
celery==5.3.1
|
|
||||||
certifi==2023.5.7
|
|
||||||
cffi==1.15.1
|
|
||||||
channels==4.0.0
|
|
||||||
channels-redis==4.1.0
|
|
||||||
charset-normalizer==3.1.0
|
|
||||||
click==8.1.3
|
|
||||||
click-didyoumean==0.3.0
|
|
||||||
click-plugins==1.1.1
|
|
||||||
click-repl==0.3.0
|
|
||||||
crcmod==1.7
|
|
||||||
cron-descriptor==1.4.0
|
|
||||||
cryptography==41.0.1
|
|
||||||
decouple==0.0.7
|
|
||||||
Django==4.2.2
|
|
||||||
django-celery-beat==2.5.0
|
|
||||||
django-celery-results==2.5.1
|
|
||||||
django-cors-headers==4.1.0
|
|
||||||
django-dotenv==1.4.2
|
|
||||||
django-extensions==3.2.3
|
|
||||||
django-phonenumber-field==7.1.0
|
|
||||||
django-render-block==0.9.2
|
|
||||||
django-ses==3.5.0
|
|
||||||
django-smtp-ssl==1.0
|
|
||||||
django-storages==1.13.2
|
|
||||||
django-templated-email==3.0.1
|
|
||||||
django-timezone-field==5.1
|
|
||||||
djangorestframework==3.14.0
|
|
||||||
djangorestframework-simplejwt==5.2.2
|
|
||||||
drf-yasg==1.21.6
|
|
||||||
google-auth==2.21.0
|
|
||||||
gunicorn==20.1.0
|
|
||||||
idna==3.4
|
|
||||||
inflection==0.5.1
|
|
||||||
jmespath==0.10.0
|
|
||||||
kombu==5.3.1
|
|
||||||
msgpack==1.0.5
|
|
||||||
oss2==2.18.0
|
|
||||||
packaging==23.1
|
|
||||||
phonenumbers==8.13.15
|
|
||||||
Pillow==9.5.0
|
|
||||||
prompt-toolkit==3.0.38
|
|
||||||
psycopg==3.1.9
|
|
||||||
pyasn1==0.5.0
|
|
||||||
pyasn1-modules==0.3.0
|
|
||||||
pycparser==2.21
|
|
||||||
pycryptodome==3.18.0
|
|
||||||
PyJWT==2.7.0
|
|
||||||
python-crontab==2.7.1
|
|
||||||
python-dateutil==2.8.2
|
|
||||||
python-dotenv==1.0.0
|
|
||||||
pytz==2023.3
|
|
||||||
PyYAML==6.0
|
|
||||||
redis==4.5.5
|
|
||||||
requests==2.31.0
|
|
||||||
rsa==4.9
|
|
||||||
s3transfer==0.6.1
|
|
||||||
six==1.16.0
|
|
||||||
sqlparse==0.4.4
|
|
||||||
typing_extensions==4.6.3
|
|
||||||
tzdata==2023.3
|
|
||||||
uritemplate==4.1.1
|
|
||||||
urllib3==1.26.16
|
|
||||||
vine==5.0.0
|
|
||||||
wcwidth==0.2.6
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { MiddlewareConsumer, Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { APP_FILTER, APP_PIPE } from '@nestjs/core';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { I18nMiddleware, I18nModule } from 'nestjs-i18n';
|
||||||
|
import { LoggerModule } from 'nestjs-pino';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
import { addTransactionalDataSource } from 'typeorm-transactional';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { OtpModule } from './common/modules/otp/otp.module';
|
||||||
|
import { AllExceptionsFilter, buildI18nValidationExceptionFilter } from './core/filters';
|
||||||
|
import { buildConfigOptions, buildLoggerOptions, buildTypeormOptions } from './core/module-options';
|
||||||
|
import { buildI18nOptions } from './core/module-options/i18n-options';
|
||||||
|
import { buildValidationPipe } from './core/pipes';
|
||||||
|
import { CustomerModule } from './customer/customer.module';
|
||||||
|
import { migrations } from './db';
|
||||||
|
import { DocumentModule } from './document/document.module';
|
||||||
|
import { GuardianModule } from './guardian/guardian.module';
|
||||||
|
import { HealthModule } from './health/health.module';
|
||||||
|
import { JuniorModule } from './junior/junior.module';
|
||||||
|
import { LookupModule } from './common/modules/lookup/lookup.module';
|
||||||
|
@Module({
|
||||||
|
controllers: [],
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot(buildConfigOptions()),
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
imports: [],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: (config: ConfigService) => {
|
||||||
|
return buildTypeormOptions(config, migrations);
|
||||||
|
},
|
||||||
|
/* eslint-disable require-await */
|
||||||
|
async dataSourceFactory(options) {
|
||||||
|
if (!options) {
|
||||||
|
throw new Error('Invalid options passed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return addTransactionalDataSource(new DataSource(options));
|
||||||
|
},
|
||||||
|
/* eslint-enable require-await */
|
||||||
|
}),
|
||||||
|
LoggerModule.forRootAsync({
|
||||||
|
useFactory: (config: ConfigService) => buildLoggerOptions(config),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
I18nModule.forRoot(buildI18nOptions()),
|
||||||
|
// App modules
|
||||||
|
AuthModule,
|
||||||
|
CustomerModule,
|
||||||
|
JuniorModule,
|
||||||
|
GuardianModule,
|
||||||
|
OtpModule,
|
||||||
|
DocumentModule,
|
||||||
|
HealthModule,
|
||||||
|
LookupModule,
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
// Global Pipes
|
||||||
|
{
|
||||||
|
inject: [ConfigService],
|
||||||
|
provide: APP_PIPE,
|
||||||
|
useFactory: (config: ConfigService) => buildValidationPipe(config),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Global Filters (order matters)
|
||||||
|
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
|
||||||
|
{ provide: APP_FILTER, useValue: buildI18nValidationExceptionFilter() },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {
|
||||||
|
configure(consumer: MiddlewareConsumer) {
|
||||||
|
consumer.apply(I18nMiddleware).forRoutes('*');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { forwardRef, Module } from '@nestjs/common';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { CustomerModule } from '~/customer/customer.module';
|
||||||
|
import { AuthController } from './controllers';
|
||||||
|
import { Device, User, UserNotificationSettings } from './entities';
|
||||||
|
import { DeviceRepository, UserRepository } from './repositories';
|
||||||
|
import { AuthService, DeviceService } from './services';
|
||||||
|
import { UserService } from './services/user.service';
|
||||||
|
import { AccessTokenStrategy } from './strategies';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([User, UserNotificationSettings, Device]),
|
||||||
|
JwtModule.register({}),
|
||||||
|
forwardRef(() => CustomerModule),
|
||||||
|
],
|
||||||
|
providers: [AuthService, UserRepository, UserService, DeviceService, DeviceRepository, AccessTokenStrategy],
|
||||||
|
controllers: [AuthController],
|
||||||
|
exports: [UserService],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const COUNTRY_CODE_REGEX = /^\+\d{1,3}$/;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './country-code-regex.constant.';
|
||||||
|
export * from './passcode-regext.constant';
|
||||||
|
export * from './password-regex.constant';
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const PASSCODE_REGEX = /^\d{6}$/;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const PASSWORD_REGEX = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&#\-_])[A-Za-z\d@$!%*?&#\-_]{8,}$/;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Body, Controller, Headers, HttpCode, HttpStatus, Post, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { DEVICE_ID_HEADER } from '~/common/constants';
|
||||||
|
import { AuthenticatedUser } from '~/common/decorators';
|
||||||
|
import { AccessTokenGuard } from '~/common/guards';
|
||||||
|
import { ResponseFactory } from '~/core/utils';
|
||||||
|
import {
|
||||||
|
CreateUnverifiedUserRequestDto,
|
||||||
|
DisableBiometricRequestDto,
|
||||||
|
EnableBiometricRequestDto,
|
||||||
|
ForgetPasswordRequestDto,
|
||||||
|
LoginRequestDto,
|
||||||
|
SendForgetPasswordOtpRequestDto,
|
||||||
|
SetEmailRequestDto,
|
||||||
|
SetPasscodeRequestDto,
|
||||||
|
VerifyUserRequestDto,
|
||||||
|
} from '../dtos/request';
|
||||||
|
import { SendForgetPasswordOtpResponseDto, SendRegisterOtpResponseDto } from '../dtos/response';
|
||||||
|
import { LoginResponseDto } from '../dtos/response/login.response.dto';
|
||||||
|
import { IJwtPayload } from '../interfaces';
|
||||||
|
import { AuthService } from '../services';
|
||||||
|
|
||||||
|
@Controller('auth')
|
||||||
|
@ApiTags('Auth')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
@Post('register/otp')
|
||||||
|
async register(@Body() createUnverifiedUserDto: CreateUnverifiedUserRequestDto) {
|
||||||
|
const phoneNumber = await this.authService.sendRegisterOtp(createUnverifiedUserDto);
|
||||||
|
return ResponseFactory.data(new SendRegisterOtpResponseDto(phoneNumber));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('register/verify')
|
||||||
|
async verifyUser(@Body() verifyUserDto: VerifyUserRequestDto) {
|
||||||
|
const [res, user] = await this.authService.verifyUser(verifyUserDto);
|
||||||
|
return ResponseFactory.data(new LoginResponseDto(res, user));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('register/set-email')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
async setEmail(@AuthenticatedUser() { sub }: IJwtPayload, @Body() setEmailDto: SetEmailRequestDto) {
|
||||||
|
await this.authService.setEmail(sub, setEmailDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('register/set-passcode')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
async setPasscode(@AuthenticatedUser() { sub }: IJwtPayload, @Body() { passcode }: SetPasscodeRequestDto) {
|
||||||
|
await this.authService.setPasscode(sub, passcode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('biometric/enable')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
enableBiometric(@AuthenticatedUser() { sub }: IJwtPayload, @Body() enableBiometricDto: EnableBiometricRequestDto) {
|
||||||
|
return this.authService.enableBiometric(sub, enableBiometricDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('biometric/disable')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
disableBiometric(@AuthenticatedUser() { sub }: IJwtPayload, @Body() disableBiometricDto: DisableBiometricRequestDto) {
|
||||||
|
return this.authService.disableBiometric(sub, disableBiometricDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('forget-password/otp')
|
||||||
|
async forgetPassword(@Body() sendForgetPasswordOtpDto: SendForgetPasswordOtpRequestDto) {
|
||||||
|
const email = await this.authService.sendForgetPasswordOtp(sendForgetPasswordOtpDto);
|
||||||
|
return ResponseFactory.data(new SendForgetPasswordOtpResponseDto(email));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('forget-password/reset')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
resetPassword(@Body() forgetPasswordDto: ForgetPasswordRequestDto) {
|
||||||
|
return this.authService.verifyForgetPasswordOtp(forgetPasswordDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
async login(@Body() loginDto: LoginRequestDto, @Headers(DEVICE_ID_HEADER) deviceId: string) {
|
||||||
|
const [res, user] = await this.authService.login(loginDto, deviceId);
|
||||||
|
return ResponseFactory.data(new LoginResponseDto(res, user));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from './auth.controller';
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Matches } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
import { COUNTRY_CODE_REGEX } from '~/auth/constants';
|
||||||
|
import { IsValidPhoneNumber } from '~/core/decorators/validations';
|
||||||
|
|
||||||
|
export class CreateUnverifiedUserRequestDto {
|
||||||
|
@ApiProperty({ example: '+962' })
|
||||||
|
@Matches(COUNTRY_CODE_REGEX, {
|
||||||
|
message: i18n('validation.Matches', { path: 'general', property: 'auth.countryCode' }),
|
||||||
|
})
|
||||||
|
countryCode: string = '+966';
|
||||||
|
|
||||||
|
@ApiProperty({ example: '787259134' })
|
||||||
|
@IsValidPhoneNumber({
|
||||||
|
message: i18n('validation.IsValidPhoneNumber', { path: 'general', property: 'auth.phoneNumber' }),
|
||||||
|
})
|
||||||
|
phoneNumber!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { PickType } from '@nestjs/swagger';
|
||||||
|
import { EnableBiometricRequestDto } from './enable-biometric.request.dto';
|
||||||
|
|
||||||
|
export class DisableBiometricRequestDto extends PickType(EnableBiometricRequestDto, ['deviceId']) {}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsString } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
export class EnableBiometricRequestDto {
|
||||||
|
@ApiProperty({ example: 'device-id' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceId' }) })
|
||||||
|
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.deviceId' }) })
|
||||||
|
deviceId!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'publicKey' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.publicKey' }) })
|
||||||
|
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.publicKey' }) })
|
||||||
|
publicKey!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEmail, IsNotEmpty, IsNumberString, IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
|
||||||
|
export class ForgetPasswordRequestDto {
|
||||||
|
@ApiProperty({ example: '[email protected]' })
|
||||||
|
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }) })
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'password' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||||
|
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.password' }) })
|
||||||
|
password!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'password' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.confirmPassword' }) })
|
||||||
|
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.confirmPassword' }) })
|
||||||
|
confirmPassword!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '111111' })
|
||||||
|
@IsNumberString(
|
||||||
|
{ no_symbols: true },
|
||||||
|
{ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.otp' }) },
|
||||||
|
)
|
||||||
|
@MaxLength(DEFAULT_OTP_LENGTH, {
|
||||||
|
message: i18n('validation.MaxLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||||
|
})
|
||||||
|
@MinLength(DEFAULT_OTP_LENGTH, {
|
||||||
|
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||||
|
})
|
||||||
|
otp!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export * from './create-unverified-user.request.dto';
|
||||||
|
export * from './disable-biometric.request.dto';
|
||||||
|
export * from './enable-biometric.request.dto';
|
||||||
|
export * from './forget-password.request.dto';
|
||||||
|
export * from './login.request.dto';
|
||||||
|
export * from './send-forget-password-otp.request.dto';
|
||||||
|
export * from './set-email.request.dto';
|
||||||
|
export * from './set-passcode.request.dto';
|
||||||
|
export * from './verify-user.request.dto';
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEmail, IsEnum, IsString, ValidateIf } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
import { GrantType } from '~/auth/enums';
|
||||||
|
export class LoginRequestDto {
|
||||||
|
@ApiProperty({ example: GrantType.PASSWORD })
|
||||||
|
@IsEnum(GrantType, { message: i18n('validation.IsEnum', { path: 'general', property: 'auth.grantType' }) })
|
||||||
|
grantType!: GrantType;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '[email protected]' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.email' }) })
|
||||||
|
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }) })
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '123456' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||||
|
@ValidateIf((o) => o.grantType === GrantType.PASSWORD)
|
||||||
|
password!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'device-token' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceToken' }) })
|
||||||
|
@ValidateIf((o) => o.grantType === GrantType.BIOMETRIC)
|
||||||
|
deviceToken!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { PickType } from '@nestjs/swagger';
|
||||||
|
import { LoginRequestDto } from './login.request.dto';
|
||||||
|
|
||||||
|
export class SendForgetPasswordOtpRequestDto extends PickType(LoginRequestDto, ['email']) {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEmail } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
export class SetEmailRequestDto {
|
||||||
|
@ApiProperty({ example: '[email protected]' })
|
||||||
|
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }) })
|
||||||
|
email!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNumberString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
const PASSCODE_LENGTH = 6;
|
||||||
|
|
||||||
|
export class SetPasscodeRequestDto {
|
||||||
|
@ApiProperty({ example: '123456' })
|
||||||
|
@IsNumberString(
|
||||||
|
{ no_symbols: true },
|
||||||
|
{ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.passcode' }) },
|
||||||
|
)
|
||||||
|
@MinLength(PASSCODE_LENGTH, { message: i18n('validation.MinLength', { path: 'general', property: 'auth.passcode' }) })
|
||||||
|
@MaxLength(PASSCODE_LENGTH, { message: i18n('validation.MaxLength', { path: 'general', property: 'auth.passcode' }) })
|
||||||
|
passcode!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNumberString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
|
||||||
|
import { CreateUnverifiedUserRequestDto } from './create-unverified-user.request.dto';
|
||||||
|
|
||||||
|
export class VerifyUserRequestDto extends CreateUnverifiedUserRequestDto {
|
||||||
|
@ApiProperty({ example: '111111' })
|
||||||
|
@IsNumberString(
|
||||||
|
{ no_symbols: true },
|
||||||
|
{ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.otp' }) },
|
||||||
|
)
|
||||||
|
@MaxLength(DEFAULT_OTP_LENGTH, {
|
||||||
|
message: i18n('validation.MaxLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||||
|
})
|
||||||
|
@MinLength(DEFAULT_OTP_LENGTH, {
|
||||||
|
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||||
|
})
|
||||||
|
otp!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export * from './send-forget-password.response.dto';
|
||||||
|
export * from './send-register-otp.response.dto';
|
||||||
|
export * from './user.response.dto';
|
||||||
|
export * from './verify-user.response.dto';
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { User } from '~/auth/entities';
|
||||||
|
import { ILoginResponse } from '~/auth/interfaces';
|
||||||
|
import { CustomerResponseDto } from '~/customer/dtos/response';
|
||||||
|
import { UserResponseDto } from './user.response.dto';
|
||||||
|
|
||||||
|
export class LoginResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
accessToken!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
refreshToken!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
expiresAt!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: UserResponseDto })
|
||||||
|
user!: UserResponseDto;
|
||||||
|
|
||||||
|
@ApiProperty({ example: CustomerResponseDto })
|
||||||
|
customer!: CustomerResponseDto;
|
||||||
|
|
||||||
|
constructor(IVerifyUserResponse: ILoginResponse, user: User) {
|
||||||
|
this.user = new UserResponseDto(user);
|
||||||
|
this.customer = new CustomerResponseDto(user.customer);
|
||||||
|
this.accessToken = IVerifyUserResponse.accessToken;
|
||||||
|
this.refreshToken = IVerifyUserResponse.refreshToken;
|
||||||
|
this.expiresAt = IVerifyUserResponse.expiresAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export class SendForgetPasswordOtpResponseDto {
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
constructor(email: string) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class SendRegisterOtpResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
phoneNumber!: string;
|
||||||
|
|
||||||
|
constructor(phoneNumber: string) {
|
||||||
|
this.phoneNumber = phoneNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { User } from '~/auth/entities';
|
||||||
|
import { Roles } from '~/auth/enums';
|
||||||
|
|
||||||
|
export class UserResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
phoneNumber!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
countryCode!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
isPasswordSet!: boolean;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
isProfileCompleted!: boolean;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
roles!: Roles[];
|
||||||
|
|
||||||
|
constructor(user: User) {
|
||||||
|
this.id = user.id;
|
||||||
|
this.email = user.email;
|
||||||
|
this.phoneNumber = user.phoneNumber;
|
||||||
|
this.countryCode = user.countryCode;
|
||||||
|
this.isPasswordSet = user.isPasswordSet;
|
||||||
|
this.isProfileCompleted = user.isProfileCompleted;
|
||||||
|
this.roles = user.roles;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { User } from '~/auth/entities';
|
||||||
|
import { ILoginResponse } from '~/auth/interfaces';
|
||||||
|
|
||||||
|
export class VerifyUserResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
accessToken!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
refreshToken!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
expiresAt!: Date;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
user!: User;
|
||||||
|
|
||||||
|
constructor(data: ILoginResponse, user: User) {
|
||||||
|
this.accessToken = data.accessToken;
|
||||||
|
this.refreshToken = data.refreshToken;
|
||||||
|
this.expiresAt = data.expiresAt;
|
||||||
|
this.user = user;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryColumn, UpdateDateColumn } from 'typeorm';
|
||||||
|
import { User } from './user.entity';
|
||||||
|
|
||||||
|
@Entity('devices')
|
||||||
|
export class Device {
|
||||||
|
@PrimaryColumn('varchar', { length: 255 })
|
||||||
|
deviceId!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'user_id' })
|
||||||
|
userId!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'device_name', nullable: true })
|
||||||
|
deviceName?: string | null;
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'public_key', nullable: true })
|
||||||
|
publicKey?: string | null;
|
||||||
|
|
||||||
|
@Column('timestamp with time zone', { name: 'last_access_on', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
lastAccessOn!: Date;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, (user) => user.devices, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user!: User;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './device.entity';
|
||||||
|
export * from './user-notification-settings.entity';
|
||||||
|
export * from './user.entity';
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import {
|
||||||
|
BaseEntity,
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
OneToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from './user.entity';
|
||||||
|
|
||||||
|
@Entity('user_notification_settings')
|
||||||
|
export class UserNotificationSettings extends BaseEntity {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@Column({ name: 'is_email_enabled', default: false })
|
||||||
|
isEmailEnabled!: boolean;
|
||||||
|
|
||||||
|
@Column({ name: 'is_push_enabled', default: false })
|
||||||
|
isPushEnabled!: boolean;
|
||||||
|
|
||||||
|
@Column({ name: 'is_sms_enabled', default: false })
|
||||||
|
isSmsEnabled!: boolean;
|
||||||
|
|
||||||
|
@OneToOne(() => User, (user) => user.notificationSettings, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user!: User;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone' })
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone' })
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import {
|
||||||
|
BaseEntity,
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
OneToMany,
|
||||||
|
OneToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { Otp } from '~/common/modules/otp/entities';
|
||||||
|
import { Customer } from '~/customer/entities/customer.entity';
|
||||||
|
import { Document } from '~/document/entities';
|
||||||
|
import { Roles } from '../enums';
|
||||||
|
import { Device } from './device.entity';
|
||||||
|
import { UserNotificationSettings } from './user-notification-settings.entity';
|
||||||
|
|
||||||
|
@Entity('users')
|
||||||
|
export class User extends BaseEntity {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, nullable: true, name: 'email' })
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, name: 'phone_number' })
|
||||||
|
phoneNumber!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 10, name: 'country_code' })
|
||||||
|
countryCode!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, name: 'password', nullable: true })
|
||||||
|
password!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, name: 'salt', nullable: true })
|
||||||
|
salt!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, nullable: true, name: 'google_id' })
|
||||||
|
googleId!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, nullable: true, name: 'apple_id' })
|
||||||
|
appleId!: string;
|
||||||
|
|
||||||
|
@Column('boolean', { default: false, name: 'is_profile_completed' })
|
||||||
|
isProfileCompleted!: boolean;
|
||||||
|
|
||||||
|
@Column('text', { nullable: true, array: true, name: 'roles' })
|
||||||
|
roles!: Roles[];
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'profile_picture_id', nullable: true })
|
||||||
|
profilePictureId!: string;
|
||||||
|
|
||||||
|
@OneToOne(() => Document, (document) => document.user, { cascade: true, nullable: true })
|
||||||
|
@JoinColumn({ name: 'profile_picture_id' })
|
||||||
|
profilePicture!: Document;
|
||||||
|
|
||||||
|
@OneToMany(() => Otp, (otp) => otp.user)
|
||||||
|
otp!: Otp[];
|
||||||
|
|
||||||
|
@OneToOne(() => UserNotificationSettings, (notificationSettings) => notificationSettings.user, {
|
||||||
|
cascade: true,
|
||||||
|
eager: true,
|
||||||
|
})
|
||||||
|
notificationSettings!: UserNotificationSettings;
|
||||||
|
|
||||||
|
@OneToOne(() => Customer, (customer) => customer.user, { cascade: true, eager: true })
|
||||||
|
customer!: Customer;
|
||||||
|
|
||||||
|
@OneToMany(() => Device, (device) => device.user)
|
||||||
|
devices!: Device[];
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone' })
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone' })
|
||||||
|
updatedAt!: Date;
|
||||||
|
|
||||||
|
get isPasswordSet(): boolean {
|
||||||
|
return !!this.password;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export enum GrantType {
|
||||||
|
PASSWORD = 'PASSWORD',
|
||||||
|
BIOMETRIC = 'BIOMETRIC',
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './grant-type.enum';
|
||||||
|
export * from './roles.enum';
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export enum Roles {
|
||||||
|
JUNIOR = 'JUNIOR',
|
||||||
|
GUARDIAN = 'GUARDIAN',
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user