2022-11-21 12:30:38 +01:00
|
|
|
import base64
|
2019-07-15 14:12:00 +02:00
|
|
|
import datetime
|
|
|
|
import hashlib
|
2022-11-21 12:30:38 +01:00
|
|
|
import json
|
2019-07-15 14:12:00 +02:00
|
|
|
import random
|
2021-02-12 22:43:34 +01:00
|
|
|
import time
|
|
|
|
from typing import Optional, Dict
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
import bcrypt
|
2023-04-25 10:36:27 +02:00
|
|
|
import rsa
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
|
2022-11-12 15:36:17 +01:00
|
|
|
from sqlalchemy.orm import make_transient
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-11-12 15:36:17 +01:00
|
|
|
from platypush.common.db import Base
|
2019-07-15 14:12:00 +02:00
|
|
|
from platypush.context import get_plugin
|
2022-04-05 22:47:44 +02:00
|
|
|
from platypush.exceptions.user import (
|
|
|
|
InvalidJWTTokenException,
|
|
|
|
InvalidCredentialsException,
|
|
|
|
)
|
2021-02-12 22:43:34 +01:00
|
|
|
from platypush.utils import get_or_generate_jwt_rsa_key_pair
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
|
|
|
|
class UserManager:
|
|
|
|
"""
|
|
|
|
Main class for managing platform users
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
2022-11-12 15:36:17 +01:00
|
|
|
db_plugin = get_plugin('db')
|
|
|
|
assert db_plugin, 'Database plugin not configured'
|
|
|
|
self.db = db_plugin
|
|
|
|
self.db.create_all(self.db.get_engine(), Base)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
@staticmethod
|
|
|
|
def _mask_password(user):
|
|
|
|
make_transient(user)
|
|
|
|
user.password = None
|
|
|
|
return user
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-11-12 15:36:17 +01:00
|
|
|
def _get_session(self, *args, **kwargs):
|
|
|
|
return self.db.get_session(self.db.get_engine(), *args, **kwargs)
|
|
|
|
|
2019-07-15 14:12:00 +02:00
|
|
|
def get_user(self, username):
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
user = self._get_user(session, username)
|
|
|
|
if not user:
|
|
|
|
return None
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
session.expunge(user)
|
|
|
|
return self._mask_password(user)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def get_user_count(self):
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
return session.query(User).count()
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2019-07-19 00:50:45 +02:00
|
|
|
def get_users(self):
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-11-21 00:57:00 +01:00
|
|
|
return session.query(User).all()
|
2019-07-19 00:50:45 +02:00
|
|
|
|
2019-07-15 14:12:00 +02:00
|
|
|
def create_user(self, username, password, **kwargs):
|
|
|
|
if not username:
|
|
|
|
raise ValueError('Invalid or empty username')
|
|
|
|
if not password:
|
|
|
|
raise ValueError('Please provide a password for the user')
|
|
|
|
|
2022-11-12 16:10:57 +01:00
|
|
|
with self._get_session(locked=True) as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
user = self._get_user(session, username)
|
|
|
|
if user:
|
|
|
|
raise NameError('The user {} already exists'.format(username))
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-05 22:47:44 +02:00
|
|
|
record = User(
|
|
|
|
username=username,
|
|
|
|
password=self._encrypt_password(password),
|
|
|
|
created_at=datetime.datetime.utcnow(),
|
2023-04-25 10:36:27 +02:00
|
|
|
**kwargs,
|
2022-04-05 22:47:44 +02:00
|
|
|
)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
session.add(record)
|
|
|
|
session.commit()
|
|
|
|
user = self._get_user(session, username)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
return self._mask_password(user)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def update_password(self, username, old_password, new_password):
|
2022-11-12 16:10:57 +01:00
|
|
|
with self._get_session(locked=True) as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
if not self._authenticate_user(session, username, old_password):
|
|
|
|
return False
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
user = self._get_user(session, username)
|
|
|
|
user.password = self._encrypt_password(new_password)
|
|
|
|
session.commit()
|
|
|
|
return True
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def authenticate_user(self, username, password):
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
return self._authenticate_user(session, username, password)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def authenticate_user_session(self, session_token):
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-04-05 22:47:44 +02:00
|
|
|
user_session = (
|
|
|
|
session.query(UserSession)
|
|
|
|
.filter_by(session_token=session_token)
|
|
|
|
.first()
|
|
|
|
)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
if not user_session or (
|
2022-04-05 22:47:44 +02:00
|
|
|
user_session.expires_at
|
|
|
|
and user_session.expires_at < datetime.datetime.utcnow()
|
|
|
|
):
|
2022-04-04 16:50:17 +02:00
|
|
|
return None, None
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
user = session.query(User).filter_by(user_id=user_session.user_id).first()
|
|
|
|
return self._mask_password(user), user_session
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def delete_user(self, username):
|
2022-11-12 16:10:57 +01:00
|
|
|
with self._get_session(locked=True) as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
user = self._get_user(session, username)
|
|
|
|
if not user:
|
|
|
|
raise NameError('No such user: {}'.format(username))
|
2019-07-19 00:50:45 +02:00
|
|
|
|
2022-04-05 22:47:44 +02:00
|
|
|
user_sessions = (
|
|
|
|
session.query(UserSession).filter_by(user_id=user.user_id).all()
|
|
|
|
)
|
2022-04-04 16:50:17 +02:00
|
|
|
for user_session in user_sessions:
|
|
|
|
session.delete(user_session)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
session.delete(user)
|
|
|
|
session.commit()
|
|
|
|
return True
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def delete_user_session(self, session_token):
|
2022-11-12 16:10:57 +01:00
|
|
|
with self._get_session(locked=True) as session:
|
2022-04-05 22:47:44 +02:00
|
|
|
user_session = (
|
|
|
|
session.query(UserSession)
|
|
|
|
.filter_by(session_token=session_token)
|
|
|
|
.first()
|
|
|
|
)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
if not user_session:
|
|
|
|
return False
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
session.delete(user_session)
|
|
|
|
session.commit()
|
|
|
|
return True
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
def create_user_session(self, username, password, expires_at=None):
|
2022-11-12 16:10:57 +01:00
|
|
|
with self._get_session(locked=True) as session:
|
2022-04-04 16:50:17 +02:00
|
|
|
user = self._authenticate_user(session, username, password)
|
|
|
|
if not user:
|
|
|
|
return None
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
if expires_at:
|
2022-04-05 22:47:44 +02:00
|
|
|
if isinstance(expires_at, (int, float)):
|
2022-04-04 16:50:17 +02:00
|
|
|
expires_at = datetime.datetime.fromtimestamp(expires_at)
|
|
|
|
elif isinstance(expires_at, str):
|
|
|
|
expires_at = datetime.datetime.fromisoformat(expires_at)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-05 22:47:44 +02:00
|
|
|
user_session = UserSession(
|
|
|
|
user_id=user.user_id,
|
|
|
|
session_token=self.generate_session_token(),
|
|
|
|
csrf_token=self.generate_session_token(),
|
|
|
|
created_at=datetime.datetime.utcnow(),
|
|
|
|
expires_at=expires_at,
|
|
|
|
)
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2022-04-04 16:50:17 +02:00
|
|
|
session.add(user_session)
|
|
|
|
session.commit()
|
|
|
|
return user_session
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_user(session, username):
|
|
|
|
return session.query(User).filter_by(username=username).first()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _encrypt_password(pwd):
|
2021-09-16 17:53:40 +02:00
|
|
|
if isinstance(pwd, str):
|
|
|
|
pwd = pwd.encode()
|
|
|
|
return bcrypt.hashpw(pwd, bcrypt.gensalt(12)).decode()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _check_password(cls, pwd, hashed_pwd):
|
|
|
|
return bcrypt.checkpw(cls._to_bytes(pwd), cls._to_bytes(hashed_pwd))
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2021-09-16 17:53:40 +02:00
|
|
|
def _to_bytes(data) -> bytes:
|
|
|
|
if isinstance(data, str):
|
|
|
|
data = data.encode()
|
|
|
|
return data
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2021-02-12 22:43:34 +01:00
|
|
|
def generate_session_token():
|
2019-07-15 14:12:00 +02:00
|
|
|
rand = bytes(random.randint(0, 255) for _ in range(0, 255))
|
|
|
|
return hashlib.sha256(rand).hexdigest()
|
|
|
|
|
2021-02-15 22:49:13 +01:00
|
|
|
def get_user_by_session(self, session_token: str):
|
|
|
|
"""
|
|
|
|
Get a user associated to a session token.
|
|
|
|
|
|
|
|
:param session_token: Session token.
|
|
|
|
"""
|
2022-11-12 15:36:17 +01:00
|
|
|
with self._get_session() as session:
|
2022-04-05 22:47:44 +02:00
|
|
|
return (
|
|
|
|
session.query(User)
|
|
|
|
.join(UserSession)
|
|
|
|
.filter_by(session_token=session_token)
|
|
|
|
.first()
|
|
|
|
)
|
|
|
|
|
|
|
|
def generate_jwt_token(
|
|
|
|
self,
|
|
|
|
username: str,
|
|
|
|
password: str,
|
|
|
|
expires_at: Optional[datetime.datetime] = None,
|
|
|
|
) -> str:
|
2021-02-12 22:43:34 +01:00
|
|
|
"""
|
|
|
|
Create a user JWT token for API usage.
|
|
|
|
|
|
|
|
:param username: User name.
|
|
|
|
:param password: Password.
|
|
|
|
:param expires_at: Expiration datetime of the token.
|
|
|
|
:return: The generated JWT token as a string.
|
|
|
|
:raises: :class:`platypush.exceptions.user.InvalidCredentialsException` in case of invalid credentials.
|
|
|
|
"""
|
|
|
|
user = self.authenticate_user(username, password)
|
|
|
|
if not user:
|
|
|
|
raise InvalidCredentialsException()
|
|
|
|
|
2022-11-21 12:30:38 +01:00
|
|
|
pub_key, _ = get_or_generate_jwt_rsa_key_pair()
|
|
|
|
payload = json.dumps(
|
|
|
|
{
|
|
|
|
'username': username,
|
2022-11-21 13:16:09 +01:00
|
|
|
'password': password,
|
2022-11-21 12:30:38 +01:00
|
|
|
'created_at': datetime.datetime.now().timestamp(),
|
|
|
|
'expires_at': expires_at.timestamp() if expires_at else None,
|
|
|
|
},
|
|
|
|
sort_keys=True,
|
|
|
|
indent=None,
|
|
|
|
)
|
|
|
|
|
2023-04-25 10:36:27 +02:00
|
|
|
return base64.b64encode(rsa.encrypt(payload.encode('ascii'), pub_key)).decode()
|
2021-02-12 22:43:34 +01:00
|
|
|
|
2022-11-21 13:16:09 +01:00
|
|
|
def validate_jwt_token(self, token: str) -> Dict[str, str]:
|
2021-02-12 22:43:34 +01:00
|
|
|
"""
|
|
|
|
Validate a JWT token.
|
|
|
|
|
|
|
|
:param token: Token to validate.
|
|
|
|
:return: On success, it returns the JWT payload with the following structure:
|
|
|
|
|
|
|
|
.. code-block:: json
|
|
|
|
|
|
|
|
{
|
|
|
|
"username": "user ID/name",
|
|
|
|
"created_at": "token creation timestamp",
|
|
|
|
"expires_at": "token expiration timestamp"
|
|
|
|
}
|
|
|
|
|
|
|
|
:raises: :class:`platypush.exceptions.user.InvalidJWTTokenException` in case of invalid token.
|
|
|
|
"""
|
2022-11-21 12:30:38 +01:00
|
|
|
_, priv_key = get_or_generate_jwt_rsa_key_pair()
|
2021-02-12 22:43:34 +01:00
|
|
|
|
|
|
|
try:
|
2022-11-21 12:30:38 +01:00
|
|
|
payload = json.loads(
|
2023-04-25 10:36:27 +02:00
|
|
|
rsa.decrypt(base64.b64decode(token.encode('ascii')), priv_key).decode(
|
|
|
|
'ascii'
|
|
|
|
)
|
2022-11-21 12:30:38 +01:00
|
|
|
)
|
|
|
|
except (TypeError, ValueError) as e:
|
2023-04-25 10:36:27 +02:00
|
|
|
raise InvalidJWTTokenException(f'Could not decode JWT token: {e}') from e
|
2021-02-12 22:43:34 +01:00
|
|
|
|
|
|
|
expires_at = payload.get('expires_at')
|
|
|
|
if expires_at and time.time() > expires_at:
|
|
|
|
raise InvalidJWTTokenException('Expired JWT token')
|
|
|
|
|
2022-11-21 13:16:09 +01:00
|
|
|
user = self.authenticate_user(
|
2023-04-25 10:36:27 +02:00
|
|
|
payload.get('username', ''), payload.get('password', '')
|
2022-11-21 13:16:09 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
if not user:
|
|
|
|
raise InvalidCredentialsException()
|
|
|
|
|
2021-02-12 22:43:34 +01:00
|
|
|
return payload
|
|
|
|
|
2019-07-15 14:12:00 +02:00
|
|
|
def _authenticate_user(self, session, username, password):
|
2021-02-12 22:43:34 +01:00
|
|
|
"""
|
|
|
|
:return: :class:`platypush.user.User` instance if the user exists and the password is valid, ``None`` otherwise.
|
|
|
|
"""
|
2019-07-15 14:12:00 +02:00
|
|
|
user = self._get_user(session, username)
|
|
|
|
if not user:
|
2021-02-12 22:43:34 +01:00
|
|
|
return None
|
2019-07-15 14:12:00 +02:00
|
|
|
|
2021-02-12 22:43:34 +01:00
|
|
|
if not self._check_password(password, user.password):
|
|
|
|
return None
|
|
|
|
|
|
|
|
return user
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
|
|
|
|
class User(Base):
|
2022-04-05 22:47:44 +02:00
|
|
|
"""Models the User table"""
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
__tablename__ = 'user'
|
2022-04-05 22:47:44 +02:00
|
|
|
__table_args__ = {'sqlite_autoincrement': True}
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
user_id = Column(Integer, primary_key=True)
|
|
|
|
username = Column(String, unique=True, nullable=False)
|
|
|
|
password = Column(String)
|
|
|
|
created_at = Column(DateTime)
|
|
|
|
|
|
|
|
|
|
|
|
class UserSession(Base):
|
2022-04-05 22:47:44 +02:00
|
|
|
"""Models the UserSession table"""
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
__tablename__ = 'user_session'
|
2022-04-05 22:47:44 +02:00
|
|
|
__table_args__ = {'sqlite_autoincrement': True}
|
2019-07-15 14:12:00 +02:00
|
|
|
|
|
|
|
session_id = Column(Integer, primary_key=True)
|
|
|
|
session_token = Column(String, unique=True, nullable=False)
|
2019-07-19 00:50:45 +02:00
|
|
|
csrf_token = Column(String, unique=True)
|
2019-07-15 14:12:00 +02:00
|
|
|
user_id = Column(Integer, ForeignKey('user.user_id'), nullable=False)
|
|
|
|
created_at = Column(DateTime)
|
|
|
|
expires_at = Column(DateTime)
|
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|