diff --git a/thorunimore/database/__init__.py b/thorunimore/database/__init__.py index 7b58c00..9cd535a 100644 --- a/thorunimore/database/__init__.py +++ b/thorunimore/database/__init__.py @@ -1,7 +1,9 @@ from .students import Student from .telegram import Telegram +from .tokens import Token __all__ = ( "Student", "Telegram", + "Token", ) diff --git a/thorunimore/database/tokens.py b/thorunimore/database/tokens.py new file mode 100644 index 0000000..8a9427f --- /dev/null +++ b/thorunimore/database/tokens.py @@ -0,0 +1,20 @@ +import sqlalchemy as s +import sqlalchemy.orm as o + +from .base import Base + + +class Token(Base): + """ + A table that contains API tokens to check if an user is registered or not in the database. + """ + __tablename__ = "tokens" + + id = s.Column(s.Integer, nullable=False, primary_key=True) + token = s.Column(s.String, nullable=False) + + owner_id = s.Column(s.BigInteger, s.ForeignKey("telegram.id"), nullable=False) + owner = o.relationship("Telegram", backref="tokens") + + def __repr__(self): + return f"{self.__qualname__}({self.id=}, {self.token=}, {self.owner_id=})" diff --git a/thorunimore/web/__main__.py b/thorunimore/web/__main__.py index 7954c16..7ab0da8 100644 --- a/thorunimore/web/__main__.py +++ b/thorunimore/web/__main__.py @@ -8,7 +8,7 @@ import werkzeug.middleware.proxy_fix from royalnet.typing import * -from ..database import Student +from ..database import Student, Token, Telegram from ..database.base import Base from ..deeplinking import DeepLinking @@ -20,6 +20,7 @@ reverse_proxy_app = werkzeug.middleware.proxy_fix.ProxyFix(app=app, x_for=1, x_proto=0, x_host=1, x_port=0, x_prefix=0) db = flask_sqlalchemy.SQLAlchemy(app=app, metadata=Base.metadata) +db.create_all() oauth = authlib.integrations.flask_client.OAuth(app=app) oauth.register( @@ -106,6 +107,42 @@ def page_privacy(): return flask.render_template("privacy.html") +@app.route("/api//whois/") +def api_whois(token: str, tg_id: int): + token = db.session.query(Token).filter_by(token=token).one_or_none() + if token is None: + return flask.jsonify({ + "description": "Invalid token", + }), 403 + + tg = db.session.query(Telegram).filter_by(id=tg_id).one_or_none() + if tg is None: + return flask.jsonify({ + "description": "User was not found in Thor's database", + "found": False, + }), 404 + + if tg.st.privacy: + return flask.jsonify({ + "description": "User has a private profile in Thor's database", + "found": True, + }), 200 + + return flask.jsonify({ + "description": "User has a public profile in Thor's database", + "found": True, + "tg": { + "first_name": tg.first_name, + "last_name": tg.last_name, + "username": tg.username, + }, + "st": { + "email": f"{tg.st.email_prefix}@studenti.unimore.it", + "first_name": tg.st.first_name, + "last_name": tg.st.last_name, + } + }), 200 + + if __name__ == "__main__": - db.create_all() app.run()