La version 5 de Planète Casio. Regroupe le forum, les programmes, les tutoriel, les sprites et tous les autres outils développés par nos soins.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

users.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. from datetime import date
  2. from app import db
  3. from flask import flash
  4. from flask_login import UserMixin
  5. from app.models.post import Post
  6. from app.models.privs import SpecialPrivilege, Group, GroupMember, \
  7. GroupPrivilege
  8. from app.models.trophies import Trophy, TrophyMember
  9. import app.utils.unicode_names as unicode_names
  10. from config import V5Config
  11. import werkzeug.security
  12. import re
  13. import math
  14. import app
  15. # User: Website user that performs actions on the post
  16. class User(UserMixin, db.Model):
  17. __tablename__ = 'user'
  18. # User ID, should be used to refer to any user. Thea actual user can either
  19. # be a guest (with IP as key) or a member (with this ID as key).
  20. id = db.Column(db.Integer, primary_key=True)
  21. # User type (polymorphic discriminator)
  22. type = db.Column(db.String(30))
  23. # TODO: add good relation
  24. posts = db.relationship('Post', backref="author", lazy=False)
  25. __mapper_args__ = {
  26. 'polymorphic_identity': __tablename__,
  27. 'polymorphic_on': type
  28. }
  29. def __repr__(self):
  30. return f'<User: #{self.id}>'
  31. # Guest: Unregistered user with minimal privileges
  32. class Guest(User, db.Model):
  33. __tablename__ = 'guest'
  34. __mapper_args__ = {'polymorphic_identity': __tablename__}
  35. # ID of the [User] entry
  36. id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
  37. # Reusable username, can be the name of a member (will be distinguished at
  38. # rendering time)
  39. username = db.Column(db.Unicode(64), index=True)
  40. # IP address, 47 characters is the max for an IPv6 address
  41. ip = db.Column(db.String(47))
  42. def __repr__(self):
  43. return f'<Guest: {self.username} ({self.ip})>'
  44. # Member: Registered user with full access to the website's services
  45. class Member(User, db.Model):
  46. __tablename__ = 'member'
  47. __mapper_args__ = {'polymorphic_identity': __tablename__}
  48. # Id of the [User] entry
  49. id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
  50. # Primary attributes (needed for the system to work)
  51. name = db.Column(db.Unicode(V5Config.USER_NAME_MAXLEN), index=True)
  52. norm = db.Column(db.Unicode(V5Config.USER_NAME_MAXLEN), index=True,
  53. unique=True)
  54. email = db.Column(db.Unicode(120), index=True, unique=True)
  55. password_hash = db.Column(db.String(255))
  56. xp = db.Column(db.Integer)
  57. register_date = db.Column(db.Date, default=date.today)
  58. # Avatars # TODO: rendre ça un peu plus propre
  59. @property
  60. def avatar(self):
  61. return 'avatars/' + str(self.id) + '.png'
  62. @property
  63. def level(self):
  64. level = math.asinh(self.xp / 1000) * (100 / math.asinh(10))
  65. return int(level), int(level * 100) % 100
  66. # Groups and related privileges
  67. groups = db.relationship('Group', secondary=GroupMember,
  68. back_populates='members')
  69. # Personal information, all optional
  70. bio = db.Column(db.UnicodeText)
  71. signature = db.Column(db.UnicodeText)
  72. birthday = db.Column(db.Date)
  73. # Settings
  74. newsletter = db.Column(db.Boolean, default=False)
  75. # Relations
  76. trophies = db.relationship('Trophy', secondary=TrophyMember,
  77. back_populates='owners')
  78. def __init__(self, name, email, password):
  79. """Register a new user."""
  80. self.name = name
  81. self.norm = unicode_names.normalize(name)
  82. self.email = email
  83. self.set_password(password)
  84. self.xp = 0
  85. self.bio = ""
  86. self.signature = ""
  87. self.birthday = None
  88. def delete(self):
  89. """
  90. Deletes the user and the associated information:
  91. * Special privileges
  92. """
  93. for sp in SpecialPrivilege.query.filter_by(mid=self.id).all():
  94. db.session.delete(sp)
  95. db.session.commit()
  96. db.session.delete(self)
  97. db.session.commit()
  98. def priv(self, priv):
  99. """Check whether the member has the specified privilege."""
  100. if SpecialPrivilege.query.filter_by(mid=self.id, priv=priv).first():
  101. return True
  102. return db.session.query(Group, GroupPrivilege).filter(
  103. Group.id.in_([ g.id for g in self.groups ]),
  104. GroupPrivilege.gid==Group.id,
  105. GroupPrivilege.priv==priv).first() is not None
  106. def special_privileges(self):
  107. """List member's special privileges."""
  108. sp = SpecialPrivilege.query.filter_by(mid=self.id).all()
  109. return sorted(row.priv for row in sp)
  110. def update(self, **data):
  111. """
  112. Update all or part of the user's metadata. The [data] dictionary
  113. accepts the following keys:
  114. "email" str User mail ddress
  115. "password" str Raw password
  116. "bio" str Biograpy
  117. "signature" str Post signature
  118. "birthday" date Birthday date
  119. "newsletter" bool Newsletter setting
  120. For future compatibility, other attributes are silently ignored. None
  121. values can be specified and are ignored.
  122. It is the caller's responsibility to check that the request sender has
  123. the right to change user names, password... otherwise this method will
  124. turn out dangerous!
  125. """
  126. data = {key: data[key] for key in data if data[key] is not None}
  127. # TODO: verify good type of those args, think about the password mgt
  128. if "email" in data:
  129. self.email = data["email"]
  130. if "password" in data:
  131. self.set_password(data["password"])
  132. if "bio" in data:
  133. self.bio = data["bio"]
  134. if "signature" in data:
  135. self.signature = data["signature"]
  136. if "birthday" in data:
  137. self.birthday = data["birthday"]
  138. if "newsletter" in data:
  139. self.newsletter = data["newsletter"]
  140. # For admins only
  141. if "xp" in data:
  142. self.xp = data["xp"]
  143. def get_public_data(self):
  144. """Returns the public information of the member."""
  145. return {
  146. "name": self.name,
  147. "xp": self.xp,
  148. "register_date": self.register_date,
  149. "bio": self.bio,
  150. "signature": self.signature,
  151. "birthday": self.birthday,
  152. }
  153. def add_xp(self, amount):
  154. """
  155. Reward xp to a member. If [amount] is negative, the xp total of the
  156. member will decrease, down to zero.
  157. """
  158. self.xp_points = min(max(self.xp_points + amount, 0), 1000000000)
  159. def set_password(self, password):
  160. """
  161. Set the user's password. Check whether the request sender has the right
  162. to do this!
  163. """
  164. self.password_hash = werkzeug.security.generate_password_hash(password,
  165. method='pbkdf2:sha512', salt_length=10)
  166. def check_password(self, password):
  167. """Compares password against member hash."""
  168. return werkzeug.security.check_password_hash(self.password_hash,
  169. password)
  170. def add_trophy(self, t):
  171. """
  172. Add a trophy to the current user. Check whether the request sender has
  173. the right to do this!
  174. """
  175. if type(t) == int:
  176. t = Trophy.query.get(t)
  177. if type(t) == str:
  178. t = Trophy.query.filter_by(name=t).first()
  179. if t not in self.trophies:
  180. self.trophies.append(t)
  181. # TODO: implement the notification system
  182. # self.notify(f"Vous venez de débloquer le trophée '{t.name}'")
  183. def del_trophy(self, t):
  184. """
  185. Add a trophy to the current user. Check whether the request sender has
  186. the right to do this!
  187. """
  188. if type(t) == int:
  189. t = Trophy.query.get(t)
  190. if type(t) == str:
  191. t = Trophy.query.filter_by(name=name).first()
  192. if t in self.trophies:
  193. self.trophies.remove(t)
  194. def update_trophies(self, context=None):
  195. """
  196. Auto-update trophies for the current user. Please use one of the
  197. following contexts when possible:
  198. - new-post
  199. - new-program
  200. - new-tutorial
  201. - new-test
  202. - new-event-participation
  203. - new-art
  204. - on-program-tested
  205. - on-program-rewarded
  206. - on-login
  207. - on-profile-update
  208. """
  209. def progress(trophies, value):
  210. """Award or delete all trophies from a progressive category."""
  211. for level in trophies:
  212. if value >= level:
  213. self.add_trophy(trophies[level])
  214. else:
  215. self.del_trophy(trophies[level])
  216. if context in ["new-post", "new-program", "new-tutorial", "new-test",
  217. None]:
  218. # TODO: Amount of posts by the user
  219. post_count = 0
  220. levels = {
  221. 20: "Premiers mots",
  222. 500: "Beau parleur",
  223. 1500: "Plume infaillible",
  224. 5000: "Romancier émérite",
  225. }
  226. progress(levels, post_count)
  227. if context in ["new-program", None]:
  228. # TODO: Amount of programs by the user
  229. program_count = 0
  230. levels = {
  231. 5: "Programmeur du dimanche",
  232. 10: "Codeur invétéré",
  233. 20: "Je code donc je suis",
  234. }
  235. progress(levels, program_count)
  236. if context in ["new-tutorial", None]:
  237. # TODO: Number of tutorials by user
  238. tutorial_count = 0
  239. levels = {
  240. 5: "Pédagogue",
  241. 10: "Encyclopédie vivante",
  242. 25: "Guerrier du savoir",
  243. }
  244. progress(levels, tutorial_count)
  245. if context in ["new-test", None]:
  246. # TODO: Number of tests by user
  247. test_count = 0
  248. levels = {
  249. 5: "Testeur",
  250. 25: "Grand joueur",
  251. 100: "Hard tester",
  252. }
  253. progress(levels, test_count)
  254. if context in ["new-event-participation", None]:
  255. # TODO: Number of event participations by user
  256. event_participations = 0
  257. levels = {
  258. 1: "Participant",
  259. 5: "Concourant encore",
  260. 15: "Concurrent de l'extrême",
  261. }
  262. progress(levels, event_participations)
  263. if context in ["new-art", None]:
  264. # TODO: Number of art posts by user
  265. art_count = 0
  266. levels = {
  267. 5: "Dessinateur en herbe",
  268. 30: "Open pixel",
  269. 100: "Roi du pixel",
  270. }
  271. progress(levels, art_count)
  272. if context in ["on-program-tested", None]:
  273. # TODO: Number of "coups de coeur" of user
  274. heart_count = 0
  275. levels = {
  276. 5: "Bourreau des cœurs",
  277. }
  278. progress(levels, heart_count)
  279. if context in ["on-program-rewarded", None]:
  280. # TODO: Number of programs with labels
  281. label_count = 0
  282. levels = {
  283. 5: "Maître du code",
  284. }
  285. progress(levels, label_count)
  286. if context in ["on-login", None]:
  287. # Seniority-based trophies
  288. age = date.today() - self.register_date
  289. levels = {
  290. 30: "Initié",
  291. 365.25: "Aficionado",
  292. 365.25 * 2: "Veni, vidi, casii",
  293. 365.25 * 5: "Papy Casio",
  294. 365.25 * 10: "Vétéran mythique",
  295. }
  296. progress(levels, age.days)
  297. # TODO: Trophy "actif"
  298. if context in ["on-profile-update", None]:
  299. # TODO: add a better condition (this is for test)
  300. self.add_trophy("Artiste")
  301. db.session.merge(self)
  302. db.session.commit()
  303. def __repr__(self):
  304. return f'<Member: {self.name} ({self.norm})>'
  305. @app.login.user_loader
  306. def load_user(id):
  307. return User.query.get(int(id))