|
| 1 | +import pandas as pd |
| 2 | +import six |
| 3 | +import secrets |
| 4 | +import ujson |
| 5 | +import validators |
| 6 | +from datetime import datetime, timedelta |
| 7 | +from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON, ForeignKey |
| 8 | +from sqlalchemy.ext.hybrid import hybrid_property |
| 9 | +from sqlalchemy.orm import relationship |
| 10 | +from sqlalchemy.ext.declarative import declarative_base |
| 11 | + |
| 12 | +TOKEN_WIDTH = 64 |
| 13 | +Base = declarative_base() |
| 14 | + |
| 15 | + |
| 16 | +class User(Base): |
| 17 | + __tablename__ = 'users' |
| 18 | + id = Column(Integer, primary_key=True) |
| 19 | + username = Column(String(100), nullable=False, unique=True) |
| 20 | + password = Column(String(100), nullable=False) |
| 21 | + |
| 22 | + _email = Column("email", String, nullable=False, unique=True) |
| 23 | + |
| 24 | + apikeys = relationship('APIKey', back_populates='client') |
| 25 | + admin = Column(Boolean, default=False) |
| 26 | + |
| 27 | + @hybrid_property |
| 28 | + def email(self): |
| 29 | + return self._email |
| 30 | + |
| 31 | + @email.setter |
| 32 | + def email(self, email): |
| 33 | + # TODO validate |
| 34 | + self._email = email |
| 35 | + |
| 36 | + def __repr__(self): |
| 37 | + return "<User(id='{}', username='{}')>".format(self.id, self.username) |
| 38 | + |
| 39 | + def to_dict(self): |
| 40 | + ret = {} |
| 41 | + for item in ("id", "username", "email"): |
| 42 | + ret[item] = getattr(self, item) |
| 43 | + return ret |
| 44 | + |
| 45 | + def from_dict(self, d): |
| 46 | + raise NotImplementedError() |
| 47 | + |
| 48 | + |
| 49 | +class APIKey(Base): |
| 50 | + __tablename__ = 'apikeys' |
| 51 | + id = Column(Integer, primary_key=True) |
| 52 | + user_id = Column(Integer, ForeignKey('users.id', ondelete='cascade')) |
| 53 | + user = relationship('User', back_populates='apikeys') |
| 54 | + key = Column(String(100), nullable=False, default=lambda: secrets.token_urlsafe(TOKEN_WIDTH)) |
| 55 | + secret = Column(String(100), nullable=False, default=lambda: secrets.token_urlsafe(TOKEN_WIDTH)) |
| 56 | + |
| 57 | + @staticmethod |
| 58 | + def generateKey(): |
| 59 | + return {'key': secrets.token_urlsafe(TOKEN_WIDTH), |
| 60 | + 'secret': secrets.token_urlsafe(TOKEN_WIDTH)} |
| 61 | + |
| 62 | + def __repr__(self): |
| 63 | + return "<Key(id='{}', key='{}', secret='***')>".format(self.id, self.key) |
| 64 | + |
| 65 | + def to_dict(self): |
| 66 | + ret = {} |
| 67 | + for item in ("id", "user_id", "key", "secret"): |
| 68 | + ret[item] = getattr(self, item) |
| 69 | + return ret |
| 70 | + |
| 71 | + def from_dict(self, d): |
| 72 | + raise NotImplementedError() |
0 commit comments