Commit 29ad9f84 authored by Beno Sons's avatar Beno Sons

login register

parent 1ee74bf2
...@@ -10,6 +10,7 @@ from .config import Config ...@@ -10,6 +10,7 @@ from .config import Config
from flask_mail import Mail from flask_mail import Mail
from itsdangerous import URLSafeTimedSerializer from itsdangerous import URLSafeTimedSerializer
from flasgger import Swagger from flasgger import Swagger
from datetime import datetime
db = SQLAlchemy() db = SQLAlchemy()
migrate = Migrate() migrate = Migrate()
...@@ -101,4 +102,12 @@ def create_app(): ...@@ -101,4 +102,12 @@ def create_app():
from app.seeder import seed_users from app.seeder import seed_users
seed_users() seed_users()
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jsonify({
"status": 401,
"message": "The token has expired",
"expired_at": datetime.fromtimestamp(jwt_payload['exp']).isoformat()
}), 401
return app return app
...@@ -12,7 +12,7 @@ class Config: ...@@ -12,7 +12,7 @@ class Config:
DEBUG = os.getenv('FLASK_ENV') == 'development' DEBUG = os.getenv('FLASK_ENV') == 'development'
PORT = int(os.getenv('PORT', 8000)) PORT = int(os.getenv('PORT', 8000))
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'myjwtsecretkey') JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'myjwtsecretkey')
JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(minutes=15) JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(minutes=1440)
JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=7) JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=7)
MAIL_SERVER = os.getenv('MAIL_SERVER', 'smtp.example.com') MAIL_SERVER = os.getenv('MAIL_SERVER', 'smtp.example.com')
MAIL_PORT = os.getenv('MAIL_PORT', 587) MAIL_PORT = os.getenv('MAIL_PORT', 587)
......
...@@ -19,7 +19,6 @@ from Crypto.Cipher import AES ...@@ -19,7 +19,6 @@ from Crypto.Cipher import AES
import json import json
import sys import sys
# PHRASE = 'AygqrawSf1GI2FFzUX8AnRjLxb0V1paOuwMR22UR_1I=' # PHRASE = 'AygqrawSf1GI2FFzUX8AnRjLxb0V1paOuwMR22UR_1I='
PHRASE_KY = b'0123456789abcdef' # Key should be 16 bytes (128 bits) PHRASE_KY = b'0123456789abcdef' # Key should be 16 bytes (128 bits)
PHRASE_IV = b'abcdef9876543210' # IV should be 16 bytes PHRASE_IV = b'abcdef9876543210' # IV should be 16 bytes
...@@ -266,3 +265,10 @@ class Master(object): ...@@ -266,3 +265,10 @@ class Master(object):
# iv_b64 = base64.b64encode(iv).decode() # iv_b64 = base64.b64encode(iv).decode()
return encrypted_data_b64 return encrypted_data_b64
def row2dict(row):
d = {}
for column in row.__table__.columns:
d[column.name] = str(getattr(row, column.name))
return d
from app import db from app import db
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from app.config import Config from app.config import Config
from datetime import datetime
import pytz
jakarta_timezone = pytz.timezone('Asia/Jakarta')
current_time = datetime.now(jakarta_timezone)
class User(db.Model): class User(db.Model):
__tablename__ = 'user' __tablename__ = 'auth_user'
__table_args__ = {'schema': Config.SCHEMA_NAME } __table_args__ = {'schema': Config.SCHEMA_NAME }
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
created_date = db.Column(db.DateTime, nullable=False)
updated_date = db.Column(db.DateTime, nullable=False)
telegram_id = db.Column(db.Integer, nullable=False)
role_id = db.Column(db.Integer, nullable=False)
password = db.Column(db.String(500), nullable=False)
file_path = db.Column(db.String(500), nullable=True)
username = db.Column(db.String(150), unique=True, nullable=False) username = db.Column(db.String(150), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=False) first_name = db.Column(db.String(150), unique=True, nullable=False)
email = db.Column(db.String(150), unique=True, nullable=True, default='no-reply@example.com') last_name = db.Column(db.String(150), unique=True, nullable=False)
email = db.Column(db.String(150), unique=True, nullable=True, default='admin@admin.com')
current_refresh_token = db.Column(db.String(500), nullable=True) current_refresh_token = db.Column(db.String(500), nullable=True)
# roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic')) # roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic'))
def set_password(self, password): def set_password(self, password):
self.password_hash = generate_password_hash(password) self.password = generate_password_hash(password)
def check_password(self, password): def check_password(self, password):
return check_password_hash(self.password_hash, password) return check_password_hash(self.password, password)
# Role model # Role model
class Role(db.Model): # class Role(db.Model):
__tablename__ = 'role' # __tablename__ = 'role'
__table_args__ = {'schema': Config.SCHEMA_NAME } # __table_args__ = {'schema': Config.SCHEMA_NAME }
id = db.Column(db.Integer, primary_key=True) # id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True) # name = db.Column(db.String(50), unique=True)
# privileges = db.relationship('Privilege', secondary='role_privileges', backref=db.backref('roles', lazy='dynamic')) # privileges = db.relationship('Privilege', secondary='role_privileges', backref=db.backref('roles', lazy='dynamic'))
# Privilege model # Privilege model
class Privilege(db.Model): # class Privilege(db.Model):
__tablename__ = 'privilege' # __tablename__ = 'privilege'
__table_args__ = {'schema': Config.SCHEMA_NAME } # __table_args__ = {'schema': Config.SCHEMA_NAME }
id = db.Column(db.Integer, primary_key=True) # id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True) # name = db.Column(db.String(50), unique=True)
# # Association tables # # Association tables
# user_roles = db.Table('user_roles', # user_roles = db.Table('user_roles',
......
...@@ -4,9 +4,15 @@ from app.models.user import User ...@@ -4,9 +4,15 @@ from app.models.user import User
from app.utils.response import success_response, error_response from app.utils.response import success_response, error_response
from app import db, jwt from app import db, jwt
import datetime import datetime
from datetime import datetime as dtm
from flask_mail import Message from flask_mail import Message
from itsdangerous import URLSafeTimedSerializer from itsdangerous import URLSafeTimedSerializer
from flasgger import swag_from from flasgger import swag_from
import json
import pytz
jakarta_timezone = pytz.timezone('Asia/Jakarta')
current_time = dtm.now(jakarta_timezone)
auth_bp = Blueprint('auth', __name__) auth_bp = Blueprint('auth', __name__)
...@@ -30,14 +36,18 @@ auth_bp = Blueprint('auth', __name__) ...@@ -30,14 +36,18 @@ auth_bp = Blueprint('auth', __name__)
}) })
def register(): def register():
data = request.get_json() data = request.get_json()
created_date = current_time
first_name = data.get('first_name')
last_name = data.get('last_name')
username = data.get('username') username = data.get('username')
password = data.get('password') password = data.get('password')
email = data.get('email') email = data.get('email')
role_id = data.get('role')
if User.query.filter_by(username=username).first(): if User.query.filter_by(username=username).first():
return error_response(message="User already exists", code=400) return error_response(message="User already exists", code=400)
new_user = User(username=username, email=email) new_user = User(username=username, email=email, created_date=created_date, first_name=first_name, last_name=last_name, role_id=role_id)
new_user.set_password(password) new_user.set_password(password)
db.session.add(new_user) db.session.add(new_user)
db.session.commit() db.session.commit()
...@@ -70,8 +80,20 @@ def login(): ...@@ -70,8 +80,20 @@ def login():
# Update user with the new refresh token # Update user with the new refresh token
user.current_refresh_token = refresh_token user.current_refresh_token = refresh_token
db.session.commit() db.session.commit()
usr = {
'id': user.id,
'username': user.username,
'created_date': user.created_date,
'updated_date': user.updated_date,
'role_id': user.role_id,
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
"access_token": access_token,
"refresh_token": refresh_token
}
return success_response(data={"access_token": access_token, "refresh_token": refresh_token}) return success_response(data=usr)
@auth_bp.route('/logout', methods=['GET']) @auth_bp.route('/logout', methods=['GET'])
@jwt_required(refresh=True) @jwt_required(refresh=True)
......
...@@ -3,6 +3,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identity ...@@ -3,6 +3,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.user import User from app.models.user import User
from app.utils.response import success_response, error_response from app.utils.response import success_response, error_response
from app import db, jwt from app import db, jwt
from app.helper.Master import Master
user_bp = Blueprint('user', __name__) user_bp = Blueprint('user', __name__)
...@@ -11,11 +12,14 @@ user_bp = Blueprint('user', __name__) ...@@ -11,11 +12,14 @@ user_bp = Blueprint('user', __name__)
def profile(): def profile():
current_user = get_jwt_identity() # This should be a string (username) current_user = get_jwt_identity() # This should be a string (username)
user = User.query.filter_by(username=current_user).first() user = User.query.filter_by(username=current_user).first()
if user.current_refresh_token is None: if user.current_refresh_token is None:
return error_response("User is not Loggin", code=403) return error_response("User is not Loggin", code=403)
if user: if user:
return success_response(data={"username": user.username, "email": user.email}) if 'password' in Master.row2dict(user):
del Master.row2dict(user)['password']
return success_response(data= Master.row2dict(user))
return error_response("User not found", code=404) return error_response("User not found", code=404)
...@@ -23,14 +27,14 @@ def profile(): ...@@ -23,14 +27,14 @@ def profile():
@jwt_required() @jwt_required()
def get_users(): def get_users():
users = User.query.all() users = User.query.all()
users_data = [{"id": user.id, "username": user.username, "email": user.email, "roles": [role.name for role in user.roles]} for user in users] users_data = [{"id": user.id, "username": user.username, "email": user.email, "role_id": [role.name for role in user.roles]} for user in users]
return success_response(data=users_data) return success_response(data=users_data)
@user_bp.route('/<int:user_id>', methods=['GET']) @user_bp.route('/<int:user_id>', methods=['GET'])
@jwt_required() @jwt_required()
def get_user(user_id): def get_user(user_id):
user = User.query.get_or_404(user_id) user = User.query.get_or_404(user_id)
user_data = {"id": user.id, "username": user.username, "email": user.email, "roles": [role.name for role in user.roles]} user_data = {"id": user.id, "username": user.username, "email": user.email, "role_id": [role.name for role in user.roles]}
return success_response(data=user_data) return success_response(data=user_data)
@user_bp.route('/create', methods=['POST']) @user_bp.route('/create', methods=['POST'])
......
from app import db from app import db
from app.models.user import User from app.models.user import User
from datetime import datetime
import pytz
jakarta_timezone = pytz.timezone('Asia/Jakarta')
current_time = datetime.now(jakarta_timezone)
def seed_users(): def seed_users():
if not User.query.filter_by(username='admin').first(): if not User.query.filter_by(username='superadmin').first():
admin = User(username='admin') admin = User(username='superadmin')
admin.email = 'admin@example.com' admin.created_date = current_time
admin.updated_date = current_time
admin.role_id = '0'
admin.set_password('password') admin.set_password('password')
admin.username = 'superadmin'
admin.first_name = 'super'
admin.last_name = 'admin'
admin.email = 'superadmin@admin.com'
db.session.add(admin) db.session.add(admin)
db.session.commit() db.session.commit()
...@@ -30,6 +30,7 @@ pycryptodome==3.20.0 ...@@ -30,6 +30,7 @@ pycryptodome==3.20.0
PyJWT==2.8.0 PyJWT==2.8.0
python-dateutil==2.9.0.post0 python-dateutil==2.9.0.post0
python-dotenv==1.0.1 python-dotenv==1.0.1
pytz==2024.1
PyYAML==6.0.1 PyYAML==6.0.1
referencing==0.35.1 referencing==0.35.1
requests==2.32.3 requests==2.32.3
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment